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
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package lxd_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"lincodex/labd/internal/lxd"
|
||||
)
|
||||
|
||||
// apiStub answers like the LXD API: requests are recorded, and mutating
|
||||
// calls return an async operation that the client must wait for.
|
||||
type apiStub struct {
|
||||
mu sync.Mutex
|
||||
requests []string
|
||||
bodies map[string]map[string]any
|
||||
waits int
|
||||
running bool
|
||||
failOp bool
|
||||
}
|
||||
|
||||
func (s *apiStub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
key := r.Method + " " + r.URL.Path
|
||||
s.requests = append(s.requests, key+"?"+r.URL.RawQuery)
|
||||
if r.Body != nil && r.ContentLength != 0 {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body) // A stub; malformed bodies fail the assertions.
|
||||
s.bodies[key] = body
|
||||
}
|
||||
switch {
|
||||
case key == "GET /1.0/instances":
|
||||
writeSync(w, []map[string]any{{"name": "lcxl-0102030405-r1", "status": "Running", "config": map[string]string{"user.lincodex.lab": "x"}}})
|
||||
case key == "GET /1.0/instances/lcxl-0102030405-r1/state":
|
||||
status := "Stopped"
|
||||
if s.running {
|
||||
status = "Running"
|
||||
}
|
||||
writeSync(w, map[string]any{"status": status})
|
||||
case key == "DELETE /1.0/instances/missing", key == "DELETE /1.0/networks/missing":
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"type":"error","error":"Not found","error_code":404}`))
|
||||
case key == "POST /1.0/networks":
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"type":"error","error":"The network already exists","error_code":400}`))
|
||||
case strings.HasPrefix(key, "GET /1.0/operations/op-1/wait"):
|
||||
s.waits++
|
||||
code := 103
|
||||
if s.waits > 1 {
|
||||
code = 200
|
||||
if s.failOp {
|
||||
code = 400
|
||||
}
|
||||
}
|
||||
writeSync(w, map[string]any{"id": "op-1", "status_code": code, "err": "copy failed"})
|
||||
case r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodDelete:
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
_, _ = w.Write([]byte(`{"type":"async","status_code":100,"operation":"/1.0/operations/op-1","metadata":{}}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func writeSync(w http.ResponseWriter, metadata any) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"type": "sync", "status_code": 200, "metadata": metadata})
|
||||
}
|
||||
|
||||
func newStub(t *testing.T) (*apiStub, *lxd.Client) {
|
||||
t.Helper()
|
||||
stub := &apiStub{bodies: map[string]map[string]any{}}
|
||||
server := httptest.NewServer(stub)
|
||||
t.Cleanup(server.Close)
|
||||
return stub, lxd.NewWithHTTPClient(server.Client(), server.URL, "labs")
|
||||
}
|
||||
|
||||
func TestCreateInstanceCopiesTheSnapshotAndWaitsForTheOperation(t *testing.T) {
|
||||
stub, client := newStub(t)
|
||||
err := client.CreateInstance(context.Background(), lxd.InstanceSpec{
|
||||
Name: "lcxl-0102030405-r1", Source: "lincodex-tpl-chr/base", Profiles: []string{"lincodex-lab-small"},
|
||||
Config: map[string]string{"user.lincodex.lab": "x"},
|
||||
Devices: map[string]map[string]string{"eth1": {"type": "nic", "network": "lxl010203040500"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateInstance() error = %v", err)
|
||||
}
|
||||
body := stub.bodies["POST /1.0/instances"]
|
||||
source, _ := body["source"].(map[string]any)
|
||||
if body["type"] != "virtual-machine" || source["type"] != "copy" || source["source"] != "lincodex-tpl-chr/base" {
|
||||
t.Fatalf("create body = %v", body)
|
||||
}
|
||||
if stub.waits != 2 {
|
||||
t.Fatalf("operation polls = %d, want 2 (running, then success)", stub.waits)
|
||||
}
|
||||
for _, request := range stub.requests {
|
||||
if !strings.Contains(request, "project=labs") {
|
||||
t.Fatalf("request %q does not name the project", request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedOperationIsAnAPIError(t *testing.T) {
|
||||
stub, client := newStub(t)
|
||||
stub.failOp = true
|
||||
err := client.DeleteInstance(context.Background(), "lcxl-0102030405-r1")
|
||||
var apiErr *lxd.APIError
|
||||
if !errors.As(err, &apiErr) || apiErr.Code != 400 {
|
||||
t.Fatalf("DeleteInstance() error = %v, want an APIError 400", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingObjectsAreNotFound(t *testing.T) {
|
||||
_, client := newStub(t)
|
||||
if err := client.DeleteInstance(context.Background(), "missing"); !errors.Is(err, lxd.ErrNotFound) {
|
||||
t.Fatalf("DeleteInstance() error = %v, want ErrNotFound", err)
|
||||
}
|
||||
if err := client.DeleteNetwork(context.Background(), "missing"); !errors.Is(err, lxd.ErrNotFound) {
|
||||
t.Fatalf("DeleteNetwork() error = %v, want ErrNotFound", err)
|
||||
}
|
||||
var apiErr *lxd.APIError
|
||||
if err := client.CreateNetwork(context.Background(), lxd.NetworkSpec{Name: "lxl010203040500"}); !errors.As(err, &apiErr) {
|
||||
t.Fatalf("CreateNetwork() error = %v, want an APIError", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStopInstanceSkipsAStoppedInstance(t *testing.T) {
|
||||
stub, client := newStub(t)
|
||||
if err := client.StopInstance(context.Background(), "lcxl-0102030405-r1"); err != nil {
|
||||
t.Fatalf("StopInstance() error = %v", err)
|
||||
}
|
||||
if _, sent := stub.bodies["PUT /1.0/instances/lcxl-0102030405-r1/state"]; sent {
|
||||
t.Fatal("StopInstance() sent a stop for a stopped instance")
|
||||
}
|
||||
stub.running = true
|
||||
if err := client.StopInstance(context.Background(), "lcxl-0102030405-r1"); err != nil {
|
||||
t.Fatalf("StopInstance() error = %v", err)
|
||||
}
|
||||
body := stub.bodies["PUT /1.0/instances/lcxl-0102030405-r1/state"]
|
||||
if body["action"] != "stop" || body["force"] != true {
|
||||
t.Fatalf("stop body = %v", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListInstancesDecodesConfig(t *testing.T) {
|
||||
_, client := newStub(t)
|
||||
instances, err := client.ListInstances(context.Background())
|
||||
if err != nil || len(instances) != 1 || instances[0].Config["user.lincodex.lab"] != "x" {
|
||||
t.Fatalf("ListInstances() = %+v, %v", instances, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package lxd_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/labd/internal/lxd"
|
||||
)
|
||||
|
||||
const liveTimeout = 5 * time.Minute
|
||||
|
||||
// TestLiveLXD creates one lab bridge and one instance copied from a prepared
|
||||
// snapshot on a real LXD, checks that they appear, and deletes them. It runs
|
||||
// only with LABD_LIVE_SOCKET and LABD_LIVE_SOURCE set (make -C labd
|
||||
// test-live) and is meant for a test host, never the production app host.
|
||||
// LABD_LIVE_START=1 also boots the instance, which needs KVM.
|
||||
func TestLiveLXD(t *testing.T) {
|
||||
socket, source := os.Getenv("LABD_LIVE_SOCKET"), os.Getenv("LABD_LIVE_SOURCE")
|
||||
if socket == "" || source == "" {
|
||||
t.Skip("set LABD_LIVE_SOCKET and LABD_LIVE_SOURCE to run against a real LXD")
|
||||
}
|
||||
project := envOr("LABD_LIVE_PROJECT", "default")
|
||||
profile := envOr("LABD_LIVE_PROFILE", "lincodex-lab-small")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), liveTimeout)
|
||||
defer cancel()
|
||||
client := lxd.NewUnix(socket, project)
|
||||
if err := client.Ping(ctx); err != nil {
|
||||
t.Fatalf("Ping() error = %v", err)
|
||||
}
|
||||
|
||||
suffix := randomHex(t, 3)
|
||||
bridge := "lxllive" + suffix
|
||||
instance := "lcxl-live-" + suffix
|
||||
marker := map[string]string{"user.lincodex.lab": "live-test-" + suffix}
|
||||
t.Cleanup(func() {
|
||||
// Best effort if an assertion stopped the test half way.
|
||||
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), liveTimeout)
|
||||
defer cleanupCancel()
|
||||
_ = client.StopInstance(cleanupCtx, instance)
|
||||
_ = client.DeleteInstance(cleanupCtx, instance)
|
||||
_ = client.DeleteNetwork(cleanupCtx, bridge)
|
||||
})
|
||||
|
||||
if err := client.CreateNetwork(ctx, lxd.NetworkSpec{
|
||||
Name: bridge, Description: "labd live test",
|
||||
Config: map[string]string{"ipv4.address": "none", "ipv6.address": "none", "user.lincodex.lab": marker["user.lincodex.lab"]},
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateNetwork() error = %v", err)
|
||||
}
|
||||
started := time.Now()
|
||||
if err := client.CreateInstance(ctx, lxd.InstanceSpec{
|
||||
Name: instance, Description: "labd live test", Source: source, Profiles: []string{profile}, Config: marker,
|
||||
Devices: map[string]map[string]string{"eth1": {"type": "nic", "network": bridge}},
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateInstance() error = %v", err)
|
||||
}
|
||||
t.Logf("copy of %s took %s", source, time.Since(started))
|
||||
if !hasInstance(t, client, instance) || !hasNetwork(t, client, bridge) {
|
||||
t.Fatal("the created objects are not listed")
|
||||
}
|
||||
if os.Getenv("LABD_LIVE_START") == "1" {
|
||||
if err := client.StartInstance(ctx, instance); err != nil {
|
||||
t.Fatalf("StartInstance() error = %v", err)
|
||||
}
|
||||
if running, err := client.InstanceRunning(ctx, instance); err != nil || !running {
|
||||
t.Fatalf("InstanceRunning() = %v, %v", running, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := client.StopInstance(ctx, instance); err != nil {
|
||||
t.Fatalf("StopInstance() error = %v", err)
|
||||
}
|
||||
if err := client.DeleteInstance(ctx, instance); err != nil {
|
||||
t.Fatalf("DeleteInstance() error = %v", err)
|
||||
}
|
||||
if err := client.DeleteNetwork(ctx, bridge); err != nil {
|
||||
t.Fatalf("DeleteNetwork() error = %v", err)
|
||||
}
|
||||
if hasInstance(t, client, instance) || hasNetwork(t, client, bridge) {
|
||||
t.Fatal("deleted objects are still listed")
|
||||
}
|
||||
if err := client.DeleteInstance(ctx, instance); !errors.Is(err, lxd.ErrNotFound) {
|
||||
t.Fatalf("second DeleteInstance() error = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func envOr(name, fallback string) string {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func randomHex(t *testing.T, size int) string {
|
||||
t.Helper()
|
||||
raw := make([]byte, size)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return hex.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func hasInstance(t *testing.T, client *lxd.Client, name string) bool {
|
||||
t.Helper()
|
||||
instances, err := client.ListInstances(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("ListInstances() error = %v", err)
|
||||
}
|
||||
return slices.ContainsFunc(instances, func(instance lxd.Instance) bool { return instance.Name == name })
|
||||
}
|
||||
|
||||
func hasNetwork(t *testing.T, client *lxd.Client, name string) bool {
|
||||
t.Helper()
|
||||
networks, err := client.ListNetworks(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("ListNetworks() error = %v", err)
|
||||
}
|
||||
return slices.ContainsFunc(networks, func(network lxd.Network) bool { return network.Name == name })
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
// Package lxdfake is an in-memory LXD for unit tests of labd. It enforces the
|
||||
// rules of LXD that the provisioner depends on: an instance is copied only
|
||||
// from a known snapshot, its NICs need existing networks, a running instance
|
||||
// cannot be deleted, and a network in use cannot be deleted.
|
||||
package lxdfake
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"sync"
|
||||
|
||||
"lincodex/labd/internal/lxd"
|
||||
)
|
||||
|
||||
// ErrInjected is the error of an injected failure.
|
||||
var ErrInjected = errors.New("injected lxd failure")
|
||||
|
||||
// Instance is the fake state of an instance.
|
||||
type Instance struct {
|
||||
Spec lxd.InstanceSpec
|
||||
Running bool
|
||||
}
|
||||
|
||||
// LXD is the fake. It is safe for concurrent use.
|
||||
type LXD struct {
|
||||
mu sync.Mutex
|
||||
sources map[string]struct{}
|
||||
instances map[string]*Instance
|
||||
networks map[string]lxd.NetworkSpec
|
||||
// external networks exist but were not created through the fake, such
|
||||
// as the management bridge.
|
||||
external map[string]struct{}
|
||||
// failCreateInstance, when set, is called before an instance is created
|
||||
// and fails the call with its error.
|
||||
failCreateInstance func(name string) error
|
||||
failDelete bool
|
||||
unreachable bool
|
||||
}
|
||||
|
||||
// New returns a fake with the given prepared snapshots and pre-existing
|
||||
// networks.
|
||||
func New(sources []string, networks ...string) *LXD {
|
||||
fake := &LXD{
|
||||
sources: make(map[string]struct{}),
|
||||
instances: make(map[string]*Instance),
|
||||
networks: make(map[string]lxd.NetworkSpec),
|
||||
external: make(map[string]struct{}),
|
||||
}
|
||||
for _, source := range sources {
|
||||
fake.sources[source] = struct{}{}
|
||||
}
|
||||
for _, network := range networks {
|
||||
fake.external[network] = struct{}{}
|
||||
}
|
||||
return fake
|
||||
}
|
||||
|
||||
// FailCreateInstance makes CreateInstance fail for the names that fail
|
||||
// returns an error for.
|
||||
func (f *LXD) FailCreateInstance(fail func(name string) error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.failCreateInstance = fail
|
||||
}
|
||||
|
||||
// FailDeletes makes every delete fail until it is switched off.
|
||||
func (f *LXD) FailDeletes(fail bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.failDelete = fail
|
||||
}
|
||||
|
||||
// SetUnreachable makes every call fail as if the socket were gone.
|
||||
func (f *LXD) SetUnreachable(unreachable bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.unreachable = unreachable
|
||||
}
|
||||
|
||||
// AddInstance puts an instance into the fake without labd, as an operator or
|
||||
// a crashed labd would leave it.
|
||||
func (f *LXD) AddInstance(spec lxd.InstanceSpec, running bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.instances[spec.Name] = &Instance{Spec: spec, Running: running}
|
||||
}
|
||||
|
||||
// AddNetwork puts a managed network into the fake without labd.
|
||||
func (f *LXD) AddNetwork(spec lxd.NetworkSpec) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.networks[spec.Name] = spec
|
||||
}
|
||||
|
||||
// Instances returns a copy of every instance by name.
|
||||
func (f *LXD) Instances() map[string]Instance {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
result := make(map[string]Instance, len(f.instances))
|
||||
for name, instance := range f.instances {
|
||||
result[name] = *instance
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Networks returns a copy of every network created in the fake by name.
|
||||
func (f *LXD) Networks() map[string]lxd.NetworkSpec {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return maps.Clone(f.networks)
|
||||
}
|
||||
|
||||
func (f *LXD) check() error {
|
||||
if f.unreachable {
|
||||
return fmt.Errorf("lxdfake: dial: %w", ErrInjected)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *LXD) Ping(context.Context) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.check()
|
||||
}
|
||||
|
||||
func (f *LXD) ListInstances(context.Context) ([]lxd.Instance, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if err := f.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names := slices.Sorted(maps.Keys(f.instances))
|
||||
result := make([]lxd.Instance, 0, len(names))
|
||||
for _, name := range names {
|
||||
instance := f.instances[name]
|
||||
status := "Stopped"
|
||||
if instance.Running {
|
||||
status = "Running"
|
||||
}
|
||||
result = append(result, lxd.Instance{Name: name, Status: status, Config: maps.Clone(instance.Spec.Config)})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (f *LXD) CreateInstance(_ context.Context, spec lxd.InstanceSpec) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if err := f.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.failCreateInstance != nil {
|
||||
if err := f.failCreateInstance(spec.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, exists := f.instances[spec.Name]; exists {
|
||||
return &lxd.APIError{Code: 409, Message: "instance exists"}
|
||||
}
|
||||
if _, known := f.sources[spec.Source]; !known {
|
||||
return fmt.Errorf("lxdfake: source %s: %w", spec.Source, lxd.ErrNotFound)
|
||||
}
|
||||
for device, config := range spec.Devices {
|
||||
if config["type"] != "nic" {
|
||||
continue
|
||||
}
|
||||
if !f.networkExists(config["network"]) {
|
||||
return &lxd.APIError{Code: 400, Message: "device " + device + " names an unknown network"}
|
||||
}
|
||||
}
|
||||
f.instances[spec.Name] = &Instance{Spec: spec}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *LXD) networkExists(name string) bool {
|
||||
_, managed := f.networks[name]
|
||||
_, external := f.external[name]
|
||||
return managed || external
|
||||
}
|
||||
|
||||
func (f *LXD) InstanceRunning(_ context.Context, name string) (bool, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if err := f.check(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
instance, ok := f.instances[name]
|
||||
if !ok {
|
||||
return false, lxd.ErrNotFound
|
||||
}
|
||||
return instance.Running, nil
|
||||
}
|
||||
|
||||
func (f *LXD) StartInstance(_ context.Context, name string) error {
|
||||
return f.setRunning(name, true)
|
||||
}
|
||||
|
||||
func (f *LXD) StopInstance(_ context.Context, name string) error {
|
||||
return f.setRunning(name, false)
|
||||
}
|
||||
|
||||
func (f *LXD) setRunning(name string, running bool) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if err := f.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
instance, ok := f.instances[name]
|
||||
if !ok {
|
||||
return lxd.ErrNotFound
|
||||
}
|
||||
instance.Running = running
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *LXD) DeleteInstance(_ context.Context, name string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if err := f.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.failDelete {
|
||||
return fmt.Errorf("lxdfake: delete %s: %w", name, ErrInjected)
|
||||
}
|
||||
instance, ok := f.instances[name]
|
||||
if !ok {
|
||||
return lxd.ErrNotFound
|
||||
}
|
||||
if instance.Running {
|
||||
return &lxd.APIError{Code: 400, Message: "instance is running"}
|
||||
}
|
||||
delete(f.instances, name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *LXD) ListNetworks(context.Context) ([]lxd.Network, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if err := f.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names := slices.Sorted(maps.Keys(f.networks))
|
||||
result := make([]lxd.Network, 0, len(names))
|
||||
for _, name := range names {
|
||||
result = append(result, lxd.Network{Name: name, Managed: true, Config: maps.Clone(f.networks[name].Config)})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (f *LXD) CreateNetwork(_ context.Context, spec lxd.NetworkSpec) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if err := f.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(spec.Name) > 15 {
|
||||
return &lxd.APIError{Code: 400, Message: "network name too long"}
|
||||
}
|
||||
if f.networkExists(spec.Name) {
|
||||
return &lxd.APIError{Code: 409, Message: "network exists"}
|
||||
}
|
||||
f.networks[spec.Name] = spec
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *LXD) DeleteNetwork(_ context.Context, name string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if err := f.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.failDelete {
|
||||
return fmt.Errorf("lxdfake: delete %s: %w", name, ErrInjected)
|
||||
}
|
||||
if _, ok := f.networks[name]; !ok {
|
||||
return lxd.ErrNotFound
|
||||
}
|
||||
for _, instance := range f.instances {
|
||||
for _, config := range instance.Spec.Devices {
|
||||
if config["network"] == name {
|
||||
return &lxd.APIError{Code: 400, Message: "network is in use"}
|
||||
}
|
||||
}
|
||||
}
|
||||
delete(f.networks, name)
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user