feat(labs): add the labd provisioner with clone pool, time to live and limits
This commit is contained in:
1 parent
9fdaa62b9b
commit
9385b2ddd4
53 files changed
+14675
-6
No files matched your search
@@ -0,0 +1,341 @@
|
||||
// Package lxd is a small client of the LXD REST API over its unix socket.
|
||||
//
|
||||
// labd needs a dozen calls: list, create, start, stop, and delete instances
|
||||
// and bridge networks, and wait for their operations. The official client
|
||||
// (github.com/canonical/lxd/client) is AGPL-3.0 since LXD 5.20 and pulls in
|
||||
// much of the LXD tree, so this package speaks the documented REST API with
|
||||
// net/http instead.
|
||||
package lxd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxResponseBytes bounds a response body; the largest one is a list of
|
||||
// instances with their config.
|
||||
maxResponseBytes = 8 << 20
|
||||
// operationWaitSeconds is the server-side wait of one poll of an
|
||||
// operation; the context bounds the whole wait.
|
||||
operationWaitSeconds = 30
|
||||
startTimeoutSeconds = 60
|
||||
stopTimeoutSeconds = 30
|
||||
idleConnTimeout = 30 * time.Second
|
||||
maxIdleConns = 4
|
||||
operationsPrefix = "/1.0/operations/"
|
||||
statusRunning = "Running"
|
||||
// Operation status codes of the LXD API.
|
||||
operationSuccess = 200
|
||||
operationFailure = 400
|
||||
operationCancelled = 401
|
||||
)
|
||||
|
||||
// ErrNotFound means that LXD does not hold the object.
|
||||
var ErrNotFound = errors.New("lxd object not found")
|
||||
|
||||
// APIError is an error answer of the LXD API. Message is the LXD text; it may
|
||||
// name objects and paths of the host and is only logged, never returned to a
|
||||
// client of labd.
|
||||
type APIError struct {
|
||||
Code int
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string { return fmt.Sprintf("lxd error %d: %s", e.Code, e.Message) }
|
||||
|
||||
// InstanceSpec is a new instance copied from a prepared snapshot.
|
||||
type InstanceSpec struct {
|
||||
Name string
|
||||
Description string
|
||||
// Source is the snapshot to copy, as instance/snapshot.
|
||||
Source string
|
||||
Profiles []string
|
||||
Config map[string]string
|
||||
Devices map[string]map[string]string
|
||||
}
|
||||
|
||||
// NetworkSpec is a new bridge network.
|
||||
type NetworkSpec struct {
|
||||
Name string
|
||||
Description string
|
||||
Config map[string]string
|
||||
}
|
||||
|
||||
// Instance is an instance as listed by LXD.
|
||||
type Instance struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Config map[string]string `json:"config"`
|
||||
}
|
||||
|
||||
// Network is a network as listed by LXD.
|
||||
type Network struct {
|
||||
Name string `json:"name"`
|
||||
Managed bool `json:"managed"`
|
||||
Config map[string]string `json:"config"`
|
||||
}
|
||||
|
||||
// Client calls the LXD API.
|
||||
type Client struct {
|
||||
httpClient *http.Client
|
||||
baseURL string
|
||||
project string
|
||||
}
|
||||
|
||||
// NewUnix returns a client of the LXD socket at socketPath for one project.
|
||||
func NewUnix(socketPath, project string) *Client {
|
||||
transport := &http.Transport{
|
||||
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
var dialer net.Dialer
|
||||
return dialer.DialContext(ctx, "unix", socketPath)
|
||||
},
|
||||
Proxy: nil,
|
||||
MaxIdleConns: maxIdleConns,
|
||||
IdleConnTimeout: idleConnTimeout,
|
||||
DisableCompression: true,
|
||||
}
|
||||
return NewWithHTTPClient(&http.Client{Transport: transport}, "http://lxd", project)
|
||||
}
|
||||
|
||||
// NewWithHTTPClient returns a client that sends requests to baseURL with
|
||||
// httpClient. Tests use it with an httptest server.
|
||||
func NewWithHTTPClient(httpClient *http.Client, baseURL, project string) *Client {
|
||||
client := *httpClient
|
||||
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
return &Client{httpClient: &client, baseURL: strings.TrimSuffix(baseURL, "/"), project: project}
|
||||
}
|
||||
|
||||
type envelope struct {
|
||||
Type string `json:"type"`
|
||||
Operation string `json:"operation"`
|
||||
ErrorCode int `json:"error_code"`
|
||||
Error string `json:"error"`
|
||||
Metadata json.RawMessage `json:"metadata"`
|
||||
}
|
||||
|
||||
type operation struct {
|
||||
ID string `json:"id"`
|
||||
StatusCode int `json:"status_code"`
|
||||
Err string `json:"err"`
|
||||
}
|
||||
|
||||
// Ping checks that the API answers.
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
_, err := c.do(ctx, http.MethodGet, "/1.0", nil, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// ListInstances returns every instance of the project.
|
||||
func (c *Client) ListInstances(ctx context.Context) ([]Instance, error) {
|
||||
answer, err := c.do(ctx, http.MethodGet, "/1.0/instances", url.Values{"recursion": {"1"}}, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var instances []Instance
|
||||
if err := json.Unmarshal(answer.Metadata, &instances); err != nil {
|
||||
return nil, fmt.Errorf("Client.ListInstances - decode: %w", err)
|
||||
}
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
// CreateInstance copies a virtual machine from spec.Source and waits for the
|
||||
// copy to finish. The instance is not started.
|
||||
func (c *Client) CreateInstance(ctx context.Context, spec InstanceSpec) error {
|
||||
body := map[string]any{
|
||||
"name": spec.Name,
|
||||
"description": spec.Description,
|
||||
"type": "virtual-machine",
|
||||
"source": map[string]any{"type": "copy", "source": spec.Source, "instance_only": true},
|
||||
"profiles": spec.Profiles,
|
||||
"config": spec.Config,
|
||||
"devices": spec.Devices,
|
||||
}
|
||||
answer, err := c.do(ctx, http.MethodPost, "/1.0/instances", nil, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.wait(ctx, answer)
|
||||
}
|
||||
|
||||
// InstanceRunning reports whether the instance runs.
|
||||
func (c *Client) InstanceRunning(ctx context.Context, name string) (bool, error) {
|
||||
answer, err := c.do(ctx, http.MethodGet, "/1.0/instances/"+url.PathEscape(name)+"/state", nil, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var state struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(answer.Metadata, &state); err != nil {
|
||||
return false, fmt.Errorf("Client.InstanceRunning - decode: %w", err)
|
||||
}
|
||||
return state.Status == statusRunning, nil
|
||||
}
|
||||
|
||||
// StartInstance starts an instance and waits for LXD to report it started.
|
||||
func (c *Client) StartInstance(ctx context.Context, name string) error {
|
||||
return c.changeState(ctx, name, map[string]any{"action": "start", "timeout": startTimeoutSeconds})
|
||||
}
|
||||
|
||||
// StopInstance stops a running instance at once; a stopped one is left as
|
||||
// it is.
|
||||
func (c *Client) StopInstance(ctx context.Context, name string) error {
|
||||
running, err := c.InstanceRunning(ctx, name)
|
||||
if err != nil || !running {
|
||||
return err
|
||||
}
|
||||
return c.changeState(ctx, name, map[string]any{"action": "stop", "force": true, "timeout": stopTimeoutSeconds})
|
||||
}
|
||||
|
||||
func (c *Client) changeState(ctx context.Context, name string, body map[string]any) error {
|
||||
answer, err := c.do(ctx, http.MethodPut, "/1.0/instances/"+url.PathEscape(name)+"/state", nil, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.wait(ctx, answer)
|
||||
}
|
||||
|
||||
// DeleteInstance deletes a stopped instance with its root volume.
|
||||
func (c *Client) DeleteInstance(ctx context.Context, name string) error {
|
||||
answer, err := c.do(ctx, http.MethodDelete, "/1.0/instances/"+url.PathEscape(name), nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.wait(ctx, answer)
|
||||
}
|
||||
|
||||
// ListNetworks returns every network of the project.
|
||||
func (c *Client) ListNetworks(ctx context.Context) ([]Network, error) {
|
||||
answer, err := c.do(ctx, http.MethodGet, "/1.0/networks", url.Values{"recursion": {"1"}}, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var networks []Network
|
||||
if err := json.Unmarshal(answer.Metadata, &networks); err != nil {
|
||||
return nil, fmt.Errorf("Client.ListNetworks - decode: %w", err)
|
||||
}
|
||||
return networks, nil
|
||||
}
|
||||
|
||||
// CreateNetwork creates a managed bridge.
|
||||
func (c *Client) CreateNetwork(ctx context.Context, spec NetworkSpec) error {
|
||||
body := map[string]any{"name": spec.Name, "description": spec.Description, "type": "bridge", "config": spec.Config}
|
||||
answer, err := c.do(ctx, http.MethodPost, "/1.0/networks", nil, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.wait(ctx, answer)
|
||||
}
|
||||
|
||||
// DeleteNetwork deletes a managed network that no instance uses.
|
||||
func (c *Client) DeleteNetwork(ctx context.Context, name string) error {
|
||||
answer, err := c.do(ctx, http.MethodDelete, "/1.0/networks/"+url.PathEscape(name), nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.wait(ctx, answer)
|
||||
}
|
||||
|
||||
// wait follows an asynchronous answer until its operation ends.
|
||||
func (c *Client) wait(ctx context.Context, answer envelope) error {
|
||||
if answer.Type != "async" {
|
||||
return nil
|
||||
}
|
||||
id := strings.TrimPrefix(answer.Operation, operationsPrefix)
|
||||
if id == "" || strings.Contains(id, "/") {
|
||||
return errors.New("Client.wait - the answer names no operation")
|
||||
}
|
||||
query := url.Values{"timeout": {fmt.Sprint(operationWaitSeconds)}}
|
||||
for {
|
||||
result, err := c.do(ctx, http.MethodGet, operationsPrefix+url.PathEscape(id)+"/wait", query, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var state operation
|
||||
if err := json.Unmarshal(result.Metadata, &state); err != nil {
|
||||
return fmt.Errorf("Client.wait - decode: %w", err)
|
||||
}
|
||||
switch state.StatusCode {
|
||||
case operationSuccess:
|
||||
return nil
|
||||
case operationFailure, operationCancelled:
|
||||
return &APIError{Code: state.StatusCode, Message: state.Err}
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) do(ctx context.Context, method, path string, query url.Values, body any) (envelope, error) {
|
||||
request, err := c.newRequest(ctx, method, path, query, body)
|
||||
if err != nil {
|
||||
return envelope{}, err
|
||||
}
|
||||
response, err := c.httpClient.Do(request)
|
||||
if err != nil {
|
||||
return envelope{}, fmt.Errorf("Client.do - %s %s: %w", method, path, err)
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }() // The body was read or is discarded.
|
||||
content, err := io.ReadAll(io.LimitReader(response.Body, maxResponseBytes+1))
|
||||
if err != nil {
|
||||
return envelope{}, fmt.Errorf("Client.do - read: %w", err)
|
||||
}
|
||||
if len(content) > maxResponseBytes {
|
||||
return envelope{}, errors.New("Client.do - the LXD answer is too large")
|
||||
}
|
||||
var answer envelope
|
||||
if err := json.Unmarshal(content, &answer); err != nil {
|
||||
return envelope{}, fmt.Errorf("Client.do - %s %s answered %d without an LXD body", method, path, response.StatusCode)
|
||||
}
|
||||
if answer.Type != "error" && response.StatusCode < http.StatusBadRequest {
|
||||
return answer, nil
|
||||
}
|
||||
code := answer.ErrorCode
|
||||
if code == 0 {
|
||||
code = response.StatusCode
|
||||
}
|
||||
if code == http.StatusNotFound {
|
||||
return envelope{}, fmt.Errorf("Client.do - %s %s: %w", method, path, ErrNotFound)
|
||||
}
|
||||
return envelope{}, &APIError{Code: code, Message: answer.Error}
|
||||
}
|
||||
|
||||
func (c *Client) newRequest(ctx context.Context, method, path string, query url.Values, body any) (*http.Request, error) {
|
||||
if query == nil {
|
||||
query = url.Values{}
|
||||
}
|
||||
if c.project != "" {
|
||||
query.Set("project", c.project)
|
||||
}
|
||||
target := c.baseURL + path
|
||||
if encoded := query.Encode(); encoded != "" {
|
||||
target += "?" + encoded
|
||||
}
|
||||
var reader io.Reader = http.NoBody
|
||||
if body != nil {
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Client.newRequest - encode: %w", err)
|
||||
}
|
||||
reader = bytes.NewReader(encoded)
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, method, target, reader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Client.newRequest - request: %w", err)
|
||||
}
|
||||
if body != nil {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
return request, nil
|
||||
}
|
||||
Reference in new issue
Block a user