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,662 @@
|
||||
// Package pool owns the labs of labd: admission by the host memory budget,
|
||||
// cloning nodes from prepared snapshots, readiness, console tokens, checks,
|
||||
// expiry, and guaranteed deletion.
|
||||
//
|
||||
// Every lab is written to the state file before any LXD object exists and
|
||||
// stays there until LXD confirms that all its objects are gone, so a crash at
|
||||
// any point leaves a record that the next start finishes: a lab caught while
|
||||
// provisioning fails as interrupted and is deleted, and an expired one is
|
||||
// deleted by the next sweep. Reconcile deletes objects that carry the labd
|
||||
// markers but belong to no record.
|
||||
//
|
||||
// Clones are copy-on-write snapshots on the btrfs pool and take seconds, so
|
||||
// the pool keeps no pre-started nodes: every node boots with the
|
||||
// configuration of its own variant, and "pool" is the bounded set of
|
||||
// concurrent labs that the memory budget allows.
|
||||
package pool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/labd/internal/lab"
|
||||
"lincodex/labd/internal/lxd"
|
||||
"lincodex/labd/internal/template"
|
||||
)
|
||||
|
||||
// Errors of the manager. Busy is a capacity signal; it is never reported as
|
||||
// an infrastructure failure.
|
||||
var (
|
||||
ErrBusy = errors.New("lab pool busy")
|
||||
ErrNotFound = errors.New("lab not found")
|
||||
ErrPayloadMismatch = errors.New("lab ID reused with another payload")
|
||||
ErrUnknownTemplate = errors.New("unknown lab template")
|
||||
ErrLifetimeTooLong = errors.New("lab lifetime above the maximum")
|
||||
ErrUnknownNode = errors.New("unknown lab node")
|
||||
ErrNotReady = errors.New("lab is not ready")
|
||||
ErrCheckUnavailable = errors.New("lab check unavailable")
|
||||
ErrIDCollision = errors.New("lab ID collides with the LXD names of another lab")
|
||||
)
|
||||
|
||||
const (
|
||||
consoleTokenBytes = 32
|
||||
// MaxConsoleTokenTTL is the contract bound of a console token.
|
||||
MaxConsoleTokenTTL = 120 * time.Second
|
||||
)
|
||||
|
||||
// LXD is the part of the LXD API that the manager uses.
|
||||
type LXD interface {
|
||||
ListInstances(ctx context.Context) ([]lxd.Instance, error)
|
||||
CreateInstance(ctx context.Context, spec lxd.InstanceSpec) error
|
||||
StartInstance(ctx context.Context, name string) error
|
||||
StopInstance(ctx context.Context, name string) error
|
||||
DeleteInstance(ctx context.Context, name string) error
|
||||
ListNetworks(ctx context.Context) ([]lxd.Network, error)
|
||||
CreateNetwork(ctx context.Context, spec lxd.NetworkSpec) error
|
||||
DeleteNetwork(ctx context.Context, name string) error
|
||||
}
|
||||
|
||||
// Store persists the lab records.
|
||||
type Store interface {
|
||||
Load() ([]lab.Lab, error)
|
||||
Save(labs []lab.Lab) error
|
||||
}
|
||||
|
||||
// Prober tells whether a node answers on its management port.
|
||||
type Prober interface {
|
||||
Probe(ctx context.Context, address netip.AddrPort) error
|
||||
}
|
||||
|
||||
// Config holds the limits of the manager.
|
||||
type Config struct {
|
||||
// MemoryBudgetBytes is the guest memory that all labs together may use.
|
||||
MemoryBudgetBytes int64
|
||||
// MaxLabs additionally caps the number of labs; zero means only the
|
||||
// memory budget applies.
|
||||
MaxLabs int
|
||||
MaxLifetime time.Duration
|
||||
ProvisionTimeout time.Duration
|
||||
ProbeInterval time.Duration
|
||||
DeletedRetention time.Duration
|
||||
ConsoleTokenTTL time.Duration
|
||||
CheckTimeout time.Duration
|
||||
// ManagementNetwork is the LXD bridge of the management plane.
|
||||
ManagementNetwork string
|
||||
ManagementPrefix netip.Prefix
|
||||
// ManagementHost is the host side of the management bridge, where labd
|
||||
// and the checker connect from.
|
||||
ManagementHost netip.Addr
|
||||
// ManagementFirst is the first address handed to nodes.
|
||||
ManagementFirst netip.Addr
|
||||
}
|
||||
|
||||
func (c Config) validate() error {
|
||||
var errs []error
|
||||
if c.MemoryBudgetBytes <= 0 || c.MaxLabs < 0 {
|
||||
errs = append(errs, errors.New("pool.Config - the memory budget must be positive and the lab cap not negative"))
|
||||
}
|
||||
for _, value := range []time.Duration{c.MaxLifetime, c.ProvisionTimeout, c.ProbeInterval, c.DeletedRetention, c.CheckTimeout} {
|
||||
if value <= 0 {
|
||||
errs = append(errs, errors.New("pool.Config - durations must be positive"))
|
||||
break
|
||||
}
|
||||
}
|
||||
if c.ConsoleTokenTTL <= 0 || c.ConsoleTokenTTL > MaxConsoleTokenTTL {
|
||||
errs = append(errs, errors.New("pool.Config - the console token TTL must be 1 to 120 seconds"))
|
||||
}
|
||||
if c.ManagementNetwork == "" || !c.ManagementPrefix.IsValid() || !c.ManagementPrefix.Addr().Is4() ||
|
||||
!c.ManagementPrefix.Contains(c.ManagementHost) || !c.ManagementPrefix.Contains(c.ManagementFirst) {
|
||||
errs = append(errs, errors.New("pool.Config - the management network, host, and first address must form one IPv4 subnet"))
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// CreateRequest is a lab of one template variant.
|
||||
type CreateRequest struct {
|
||||
TemplateID string
|
||||
TemplateVersion int
|
||||
Seed [template.SeedBytes]byte
|
||||
Lifetime time.Duration
|
||||
}
|
||||
|
||||
// Fingerprint identifies the payload of a request for idempotency.
|
||||
func (r CreateRequest) Fingerprint() string {
|
||||
sum := sha256.Sum256(fmt.Appendf(nil, "%s\x00%d\x00%x\x00%d", r.TemplateID, r.TemplateVersion, r.Seed, r.Lifetime))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// CheckResult is the outcome of one check.
|
||||
type CheckResult struct {
|
||||
CheckedAt time.Time
|
||||
Criteria []template.Criterion
|
||||
}
|
||||
|
||||
type consoleGrant struct {
|
||||
lab uuid.UUID
|
||||
node string
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
// Manager owns every lab of the process. It is safe for concurrent use.
|
||||
type Manager struct {
|
||||
cfg Config
|
||||
lxd LXD
|
||||
store Store
|
||||
templates *template.Registry
|
||||
prober Prober
|
||||
now func() time.Time
|
||||
logger *slog.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
labs map[uuid.UUID]*lab.Lab
|
||||
workers map[uuid.UUID]context.CancelFunc
|
||||
grants map[[sha256.Size]byte]consoleGrant
|
||||
started bool
|
||||
draining bool
|
||||
// base is the lifetime of the background workers; Close cancels it.
|
||||
base context.Context
|
||||
stop context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// New returns a manager. It refuses a template that can never fit the memory
|
||||
// budget, so a configuration error does not look like a busy pool forever.
|
||||
func New(cfg Config, client LXD, store Store, templates *template.Registry, prober Prober, now func() time.Time, logger *slog.Logger) (*Manager, error) {
|
||||
if err := cfg.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, candidate := range templates.All() {
|
||||
if candidate.MemoryBytes() > cfg.MemoryBudgetBytes {
|
||||
return nil, fmt.Errorf("pool.New - template %s version %d needs more memory than the budget", candidate.ID, candidate.Version)
|
||||
}
|
||||
}
|
||||
return &Manager{
|
||||
cfg: cfg, lxd: client, store: store, templates: templates, prober: prober, now: now, logger: logger,
|
||||
labs: make(map[uuid.UUID]*lab.Lab),
|
||||
workers: make(map[uuid.UUID]context.CancelFunc),
|
||||
grants: make(map[[sha256.Size]byte]consoleGrant),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Start loads the records and resumes unfinished work. A lab that was
|
||||
// provisioning when the previous process stopped fails as interrupted and is
|
||||
// deleted, because its partial objects cannot be trusted.
|
||||
func (m *Manager) Start(ctx context.Context) error {
|
||||
records, err := m.store.Load()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Manager.Start - load: %w", err)
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.started {
|
||||
return errors.New("Manager.Start - already started")
|
||||
}
|
||||
interrupted := false
|
||||
for index := range records {
|
||||
record := records[index]
|
||||
if record.State == lab.Provisioning {
|
||||
record.State = lab.Failed
|
||||
record.FailureReason = lab.FailureInterrupted
|
||||
interrupted = true
|
||||
}
|
||||
m.labs[record.ID] = &record
|
||||
}
|
||||
if interrupted {
|
||||
if err := m.persistLocked(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
m.base, m.stop = context.WithCancel(context.WithoutCancel(ctx))
|
||||
m.started = true
|
||||
for id, record := range m.labs {
|
||||
if record.NeedsTeardown() {
|
||||
m.startWorkerLocked(id)
|
||||
}
|
||||
}
|
||||
m.logger.InfoContext(ctx, "lab records loaded", slog.Int("labs", len(m.labs)))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ready reports whether the manager accepts labs.
|
||||
func (m *Manager) Ready() bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.started && !m.draining
|
||||
}
|
||||
|
||||
// Usage returns the memory in use and the number of labs that hold LXD
|
||||
// objects.
|
||||
func (m *Manager) Usage() (int64, int) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.usageLocked()
|
||||
}
|
||||
|
||||
// Create admits and stores a lab and starts its provisioning. It is
|
||||
// idempotent by id: the same payload returns the stored lab with created
|
||||
// false.
|
||||
func (m *Manager) Create(id uuid.UUID, request CreateRequest) (lab.Lab, bool, error) {
|
||||
chosen, ok := m.templates.Lookup(request.TemplateID, request.TemplateVersion)
|
||||
if !ok {
|
||||
return lab.Lab{}, false, ErrUnknownTemplate
|
||||
}
|
||||
if request.Lifetime > m.cfg.MaxLifetime {
|
||||
return lab.Lab{}, false, ErrLifetimeTooLong
|
||||
}
|
||||
fingerprint := request.Fingerprint()
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if existing, found := m.labs[id]; found {
|
||||
if existing.Fingerprint != fingerprint {
|
||||
return lab.Lab{}, false, ErrPayloadMismatch
|
||||
}
|
||||
return existing.Clone(), false, nil
|
||||
}
|
||||
if !m.started || m.draining {
|
||||
return lab.Lab{}, false, ErrBusy
|
||||
}
|
||||
if m.collidesLocked(id) {
|
||||
return lab.Lab{}, false, ErrIDCollision
|
||||
}
|
||||
used, count := m.usageLocked()
|
||||
cost := chosen.MemoryBytes()
|
||||
if used+cost > m.cfg.MemoryBudgetBytes || (m.cfg.MaxLabs > 0 && count >= m.cfg.MaxLabs) {
|
||||
return lab.Lab{}, false, ErrBusy
|
||||
}
|
||||
addresses, ok := m.allocateLocked(len(chosen.Nodes))
|
||||
if !ok {
|
||||
return lab.Lab{}, false, ErrBusy
|
||||
}
|
||||
|
||||
now := m.now().UTC()
|
||||
record := &lab.Lab{
|
||||
ID: id, TemplateID: chosen.ID, TemplateVersion: chosen.Version,
|
||||
Seed: hex.EncodeToString(request.Seed[:]), Fingerprint: fingerprint,
|
||||
State: lab.Provisioning, CreatedAt: now, ExpiresAt: now.Add(request.Lifetime),
|
||||
MemoryBytes: cost,
|
||||
}
|
||||
for index, node := range chosen.Nodes {
|
||||
record.Nodes = append(record.Nodes, lab.Node{
|
||||
Name: node.Name, Kind: string(node.Kind), Instance: lab.InstanceName(id, node.Name),
|
||||
ManagementAddress: addresses[index], ManagementPort: node.Port(),
|
||||
})
|
||||
}
|
||||
for index := range chosen.Links {
|
||||
record.Bridges = append(record.Bridges, lab.BridgeName(id, index))
|
||||
}
|
||||
m.labs[id] = record
|
||||
if err := m.persistLocked(); err != nil {
|
||||
delete(m.labs, id)
|
||||
return lab.Lab{}, false, err
|
||||
}
|
||||
m.startWorkerLocked(id)
|
||||
m.logger.Info("lab admitted", slog.String("lab_id", id.String()), slog.String("template", chosen.ID),
|
||||
slog.Int64("memory_bytes", cost), slog.Int64("used_bytes", used+cost))
|
||||
return record.Clone(), true, nil
|
||||
}
|
||||
|
||||
// Get returns a lab.
|
||||
func (m *Manager) Get(id uuid.UUID) (lab.Lab, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
record, ok := m.labs[id]
|
||||
if !ok {
|
||||
return lab.Lab{}, ErrNotFound
|
||||
}
|
||||
return record.Clone(), nil
|
||||
}
|
||||
|
||||
// Delete ends a lab before its timer. It returns changed false for a lab that
|
||||
// is already ending.
|
||||
func (m *Manager) Delete(id uuid.UUID) (lab.Lab, bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
record, ok := m.labs[id]
|
||||
if !ok {
|
||||
return lab.Lab{}, false, ErrNotFound
|
||||
}
|
||||
if !record.Active() {
|
||||
return record.Clone(), false, nil
|
||||
}
|
||||
m.endLocked(id, record)
|
||||
if err := m.persistLocked(); err != nil {
|
||||
// The deletion proceeds; the next successful save records it, and a
|
||||
// restart before that deletes the lab at its timer.
|
||||
m.logger.Error("lab state not saved", slog.String("lab_id", id.String()), slog.String("error", err.Error()))
|
||||
}
|
||||
return record.Clone(), true, nil
|
||||
}
|
||||
|
||||
// endLocked moves an active lab to deleting and makes sure a worker removes
|
||||
// it.
|
||||
func (m *Manager) endLocked(id uuid.UUID, record *lab.Lab) {
|
||||
record.State = lab.Deleting
|
||||
if cancel, running := m.workers[id]; running {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
m.startWorkerLocked(id)
|
||||
}
|
||||
|
||||
// ConsoleToken issues a single-use console token for a node of a ready lab.
|
||||
func (m *Manager) ConsoleToken(id uuid.UUID, node string) (string, time.Time, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
record, err := m.readyLocked(id)
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
if _, known := record.Node(node); !known {
|
||||
return "", time.Time{}, ErrUnknownNode
|
||||
}
|
||||
raw := make([]byte, consoleTokenBytes)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("Manager.ConsoleToken - random: %w", err)
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
expiresAt := m.now().UTC().Add(m.cfg.ConsoleTokenTTL)
|
||||
m.grants[sha256.Sum256([]byte(token))] = consoleGrant{lab: id, node: node, expiresAt: expiresAt}
|
||||
return token, expiresAt, nil
|
||||
}
|
||||
|
||||
// ConsumeConsoleToken redeems a console token once. The console attach uses
|
||||
// it; an unknown, used, or expired token and a lab that is no longer ready
|
||||
// all fail alike.
|
||||
func (m *Manager) ConsumeConsoleToken(token string) (uuid.UUID, string, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
grant, ok := m.grants[digest]
|
||||
delete(m.grants, digest)
|
||||
if !ok || !m.now().Before(grant.expiresAt) {
|
||||
return uuid.Nil, "", ErrNotFound
|
||||
}
|
||||
if _, err := m.readyLocked(grant.lab); err != nil {
|
||||
return uuid.Nil, "", err
|
||||
}
|
||||
return grant.lab, grant.node, nil
|
||||
}
|
||||
|
||||
// Check runs the checker of the template against a ready lab.
|
||||
func (m *Manager) Check(ctx context.Context, id uuid.UUID) (CheckResult, error) {
|
||||
m.mu.Lock()
|
||||
record, err := m.readyLocked(id)
|
||||
if err != nil {
|
||||
m.mu.Unlock()
|
||||
return CheckResult{}, err
|
||||
}
|
||||
snapshot := record.Clone()
|
||||
m.mu.Unlock()
|
||||
|
||||
chosen, ok := m.templates.Lookup(snapshot.TemplateID, snapshot.TemplateVersion)
|
||||
if !ok {
|
||||
return CheckResult{}, fmt.Errorf("Manager.Check - template of lab %s is gone: %w", id, ErrCheckUnavailable)
|
||||
}
|
||||
variant, err := m.plan(snapshot, chosen)
|
||||
if err != nil {
|
||||
return CheckResult{}, fmt.Errorf("Manager.Check - plan: %w: %w", ErrCheckUnavailable, err)
|
||||
}
|
||||
access := make([]template.NodeAccess, 0, len(snapshot.Nodes))
|
||||
for _, node := range snapshot.Nodes {
|
||||
access = append(access, template.NodeAccess{
|
||||
Name: node.Name, Kind: template.Kind(node.Kind),
|
||||
Address: netip.AddrPortFrom(node.ManagementAddress, node.ManagementPort),
|
||||
})
|
||||
}
|
||||
checkCtx, cancel := context.WithTimeout(ctx, m.cfg.CheckTimeout)
|
||||
defer cancel()
|
||||
criteria, err := chosen.Check(checkCtx, variant, access)
|
||||
if err != nil {
|
||||
return CheckResult{}, fmt.Errorf("Manager.Check - checker: %w: %w", ErrCheckUnavailable, err)
|
||||
}
|
||||
if err := template.ValidateCriteria(criteria); err != nil {
|
||||
return CheckResult{}, fmt.Errorf("Manager.Check - checker output: %w: %w", ErrCheckUnavailable, err)
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
// A lab that ended during the check may have been read half deleted.
|
||||
if _, err := m.readyLocked(id); err != nil {
|
||||
return CheckResult{}, err
|
||||
}
|
||||
return CheckResult{CheckedAt: m.now().UTC(), Criteria: slices.Clone(criteria)}, nil
|
||||
}
|
||||
|
||||
func (m *Manager) readyLocked(id uuid.UUID) (*lab.Lab, error) {
|
||||
record, ok := m.labs[id]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if record.State != lab.Ready || !m.now().Before(record.ExpiresAt) {
|
||||
return nil, ErrNotReady
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
// Sweep ends expired labs, restarts pending deletions, forgets deleted
|
||||
// labs after their retention, and drops expired console tokens. The reaper
|
||||
// calls it periodically.
|
||||
func (m *Manager) Sweep(ctx context.Context) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !m.started {
|
||||
return
|
||||
}
|
||||
now := m.now()
|
||||
changed := false
|
||||
for id, record := range m.labs {
|
||||
if record.Active() && !now.Before(record.ExpiresAt) {
|
||||
m.logger.InfoContext(ctx, "lab expired", slog.String("lab_id", id.String()))
|
||||
m.endLocked(id, record)
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
if record.NeedsTeardown() {
|
||||
m.startWorkerLocked(id)
|
||||
continue
|
||||
}
|
||||
if !record.HoldsResources() && now.Sub(record.DeletedAt) >= m.cfg.DeletedRetention {
|
||||
delete(m.labs, id)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
for digest, grant := range m.grants {
|
||||
if !now.Before(grant.expiresAt) {
|
||||
delete(m.grants, digest)
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
if err := m.persistLocked(); err != nil {
|
||||
m.logger.ErrorContext(ctx, "lab state not saved", slog.String("error", err.Error()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reconcile deletes LXD objects that carry the labd markers but belong to no
|
||||
// lab that may hold objects. Objects with the name prefix but without the
|
||||
// marker are reported and left alone.
|
||||
func (m *Manager) Reconcile(ctx context.Context) error {
|
||||
// List before taking the snapshot: a lab created after the listing is
|
||||
// not in it, and a lab deleted in between only yields not-found deletes.
|
||||
instances, err := m.lxd.ListInstances(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Manager.Reconcile - list instances: %w", err)
|
||||
}
|
||||
networks, err := m.lxd.ListNetworks(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Manager.Reconcile - list networks: %w", err)
|
||||
}
|
||||
knownInstances, knownBridges := m.knownObjects()
|
||||
|
||||
var errs []error
|
||||
removed := 0
|
||||
for _, instance := range instances {
|
||||
if !strings.HasPrefix(instance.Name, lab.InstancePrefix) || knownInstances[instance.Name] {
|
||||
continue
|
||||
}
|
||||
if !lab.OwnedInstance(instance.Name, instance.Config) {
|
||||
m.logger.WarnContext(ctx, "instance with the lab prefix has no labd marker; left alone", slog.String("instance", instance.Name))
|
||||
continue
|
||||
}
|
||||
if err := m.deleteInstance(ctx, instance.Name); err != nil {
|
||||
errs = append(errs, err)
|
||||
continue
|
||||
}
|
||||
removed++
|
||||
}
|
||||
for _, network := range networks {
|
||||
if !strings.HasPrefix(network.Name, lab.BridgePrefix) || knownBridges[network.Name] {
|
||||
continue
|
||||
}
|
||||
if !lab.OwnedBridge(network.Name, network.Config) {
|
||||
m.logger.WarnContext(ctx, "network with the lab prefix has no labd marker; left alone", slog.String("network", network.Name))
|
||||
continue
|
||||
}
|
||||
if err := m.deleteNetwork(ctx, network.Name); err != nil {
|
||||
errs = append(errs, err)
|
||||
continue
|
||||
}
|
||||
removed++
|
||||
}
|
||||
if removed > 0 {
|
||||
m.logger.InfoContext(ctx, "orphaned lab objects deleted", slog.Int("objects", removed))
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (m *Manager) knownObjects() (map[string]bool, map[string]bool) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
instances := make(map[string]bool)
|
||||
bridges := make(map[string]bool)
|
||||
for _, record := range m.labs {
|
||||
if !record.HoldsResources() {
|
||||
continue
|
||||
}
|
||||
for _, node := range record.Nodes {
|
||||
instances[node.Instance] = true
|
||||
}
|
||||
for _, bridge := range record.Bridges {
|
||||
bridges[bridge] = true
|
||||
}
|
||||
}
|
||||
return instances, bridges
|
||||
}
|
||||
|
||||
// Drain stops admitting labs; existing labs keep running.
|
||||
func (m *Manager) Drain() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.draining = true
|
||||
}
|
||||
|
||||
// Close stops the workers and waits for them. Labs keep their records: the
|
||||
// next start deletes a lab that was provisioning and expires the others on
|
||||
// their timers.
|
||||
func (m *Manager) Close(ctx context.Context) error {
|
||||
m.mu.Lock()
|
||||
m.draining = true
|
||||
if m.stop != nil {
|
||||
m.stop()
|
||||
}
|
||||
m.mu.Unlock()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
m.wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("Manager.Close - wait for workers: %w", ctx.Err())
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) usageLocked() (int64, int) {
|
||||
var used int64
|
||||
count := 0
|
||||
for _, record := range m.labs {
|
||||
if record.HoldsResources() {
|
||||
used += record.MemoryBytes
|
||||
count++
|
||||
}
|
||||
}
|
||||
return used, count
|
||||
}
|
||||
|
||||
func (m *Manager) collidesLocked(id uuid.UUID) bool {
|
||||
short := lab.ShortID(id)
|
||||
for _, record := range m.labs {
|
||||
if record.HoldsResources() && lab.ShortID(record.ID) == short {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// allocateLocked picks free management addresses, skipping the host side
|
||||
// and the broadcast address.
|
||||
func (m *Manager) allocateLocked(count int) ([]netip.Addr, bool) {
|
||||
used := make(map[netip.Addr]bool)
|
||||
for _, record := range m.labs {
|
||||
if record.HoldsResources() {
|
||||
for _, node := range record.Nodes {
|
||||
used[node.ManagementAddress] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
addresses := make([]netip.Addr, 0, count)
|
||||
for address := m.cfg.ManagementFirst; len(addresses) < count; address = address.Next() {
|
||||
next := address.Next()
|
||||
if !m.cfg.ManagementPrefix.Contains(address) || !next.IsValid() || !m.cfg.ManagementPrefix.Contains(next) {
|
||||
return nil, false
|
||||
}
|
||||
if address != m.cfg.ManagementHost && !used[address] {
|
||||
addresses = append(addresses, address)
|
||||
}
|
||||
}
|
||||
return addresses, true
|
||||
}
|
||||
|
||||
func (m *Manager) persistLocked() error {
|
||||
records := make([]lab.Lab, 0, len(m.labs))
|
||||
for _, record := range m.labs {
|
||||
records = append(records, record.Clone())
|
||||
}
|
||||
slices.SortFunc(records, func(a, b lab.Lab) int {
|
||||
if order := a.CreatedAt.Compare(b.CreatedAt); order != 0 {
|
||||
return order
|
||||
}
|
||||
return strings.Compare(a.ID.String(), b.ID.String())
|
||||
})
|
||||
if err := m.store.Save(records); err != nil {
|
||||
return fmt.Errorf("Manager.persist - save: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) plan(record lab.Lab, chosen template.Template) (template.Variant, error) {
|
||||
seed, err := hex.DecodeString(record.Seed)
|
||||
if err != nil || len(seed) != template.SeedBytes {
|
||||
return template.Variant{}, errors.New("Manager.plan - the stored seed is malformed")
|
||||
}
|
||||
addresses := make([]netip.Addr, 0, len(record.Nodes))
|
||||
for _, node := range record.Nodes {
|
||||
addresses = append(addresses, node.ManagementAddress)
|
||||
}
|
||||
return chosen.Plan([template.SeedBytes]byte(seed), addresses, m.cfg.ManagementPrefix.Bits(), m.cfg.ManagementHost)
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
package pool_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/labd/internal/lab"
|
||||
"lincodex/labd/internal/lxd"
|
||||
"lincodex/labd/internal/lxd/lxdfake"
|
||||
"lincodex/labd/internal/pool"
|
||||
"lincodex/labd/internal/store"
|
||||
"lincodex/labd/internal/template"
|
||||
)
|
||||
|
||||
const (
|
||||
managementNetwork = "lxdbr-labmgmt"
|
||||
nodeMemory = 768 << 20
|
||||
labMemory = 2 * nodeMemory
|
||||
waitLimit = 5 * time.Second
|
||||
)
|
||||
|
||||
var errCheckerOffline = errors.New("checker cannot reach the node")
|
||||
|
||||
type clock struct {
|
||||
mu sync.Mutex
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func (c *clock) Now() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.now
|
||||
}
|
||||
|
||||
func (c *clock) Advance(d time.Duration) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.now = c.now.Add(d)
|
||||
}
|
||||
|
||||
type prober struct{ down atomic.Bool }
|
||||
|
||||
func (p *prober) Probe(context.Context, netip.AddrPort) error {
|
||||
if p.down.Load() {
|
||||
return errors.New("connection refused")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func testTemplate() template.Template {
|
||||
return template.Template{
|
||||
ID: "mikrotik-pair", Version: 1,
|
||||
Nodes: []template.Node{
|
||||
{Name: "r1", Kind: template.MikroTik, Profile: "lincodex-lab-small", Source: "tpl-chr/base", MemoryBytes: nodeMemory},
|
||||
{Name: "srv", Kind: template.Ubuntu, Profile: "lincodex-lab-small", Source: "tpl-ubuntu/base", MemoryBytes: nodeMemory},
|
||||
},
|
||||
Links: []template.Link{{Name: "lan", Nodes: []string{"r1", "srv"}}, {Name: "wan", Nodes: []string{"r1"}}},
|
||||
Render: func(variant template.Variant) (map[string]template.Bootstrap, error) {
|
||||
r1, _ := variant.Node("r1")
|
||||
srv, _ := variant.Node("srv")
|
||||
return map[string]template.Bootstrap{
|
||||
"r1": {UserData: template.RouterOSManagementScript(r1)},
|
||||
"srv": {NetworkConfig: template.UbuntuNetworkConfig(srv)},
|
||||
}, nil
|
||||
},
|
||||
Check: func(_ context.Context, variant template.Variant, nodes []template.NodeAccess) ([]template.Criterion, error) {
|
||||
if len(nodes) != 2 || nodes[0].Address.Port() != 8728 || nodes[1].Address.Port() != 22 {
|
||||
return nil, errCheckerOffline
|
||||
}
|
||||
// The variant decides the result, as a real checker would.
|
||||
passed := variant.Rand("criteria").IntN(2) == 0
|
||||
return []template.Criterion{{ID: "ospf", Passed: passed}, {ID: "ping", Passed: true}}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type harness struct {
|
||||
t *testing.T
|
||||
fake *lxdfake.LXD
|
||||
statePath string
|
||||
clock *clock
|
||||
prober *prober
|
||||
cfg pool.Config
|
||||
registry *template.Registry
|
||||
}
|
||||
|
||||
func newHarness(t *testing.T, change func(*pool.Config)) *harness {
|
||||
t.Helper()
|
||||
registry, err := template.NewRegistry(testTemplate())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := pool.Config{
|
||||
MemoryBudgetBytes: 2 * labMemory,
|
||||
MaxLifetime: 2 * time.Hour,
|
||||
ProvisionTimeout: waitLimit,
|
||||
ProbeInterval: time.Millisecond,
|
||||
DeletedRetention: time.Hour,
|
||||
ConsoleTokenTTL: time.Minute,
|
||||
CheckTimeout: time.Second,
|
||||
ManagementNetwork: managementNetwork,
|
||||
ManagementPrefix: netip.MustParsePrefix("10.81.0.0/24"),
|
||||
ManagementHost: netip.MustParseAddr("10.81.0.1"),
|
||||
ManagementFirst: netip.MustParseAddr("10.81.0.16"),
|
||||
}
|
||||
if change != nil {
|
||||
change(&cfg)
|
||||
}
|
||||
return &harness{
|
||||
t: t,
|
||||
fake: lxdfake.New([]string{"tpl-chr/base", "tpl-ubuntu/base"}, managementNetwork),
|
||||
statePath: filepath.Join(t.TempDir(), "labs.json"),
|
||||
clock: &clock{now: time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC)},
|
||||
prober: &prober{},
|
||||
cfg: cfg,
|
||||
registry: registry,
|
||||
}
|
||||
}
|
||||
|
||||
// start creates and starts a manager on the shared fake and state file. Two
|
||||
// managers in a row model a restart of labd.
|
||||
func (h *harness) start() *pool.Manager {
|
||||
h.t.Helper()
|
||||
states, err := store.New(h.statePath)
|
||||
if err != nil {
|
||||
h.t.Fatal(err)
|
||||
}
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
manager, err := pool.New(h.cfg, h.fake, states, h.registry, h.prober, h.clock.Now, logger)
|
||||
if err != nil {
|
||||
h.t.Fatal(err)
|
||||
}
|
||||
if err := manager.Start(context.Background()); err != nil {
|
||||
h.t.Fatal(err)
|
||||
}
|
||||
h.t.Cleanup(func() {
|
||||
if err := manager.Close(context.Background()); err != nil {
|
||||
h.t.Errorf("Close() error = %v", err)
|
||||
}
|
||||
})
|
||||
return manager
|
||||
}
|
||||
|
||||
func request(seed byte) pool.CreateRequest {
|
||||
return pool.CreateRequest{TemplateID: "mikrotik-pair", TemplateVersion: 1, Seed: [32]byte{seed}, Lifetime: 30 * time.Minute}
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, manager *pool.Manager, id uuid.UUID, done func(lab.Lab) bool) lab.Lab {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(waitLimit)
|
||||
for {
|
||||
record, err := manager.Get(id)
|
||||
if err == nil && done(record) {
|
||||
return record
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("lab %s did not reach the expected state; last %+v, %v", id, record, err)
|
||||
}
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func inState(state lab.State) func(lab.Lab) bool {
|
||||
return func(record lab.Lab) bool { return record.State == state }
|
||||
}
|
||||
|
||||
func removed(record lab.Lab) bool { return !record.HoldsResources() }
|
||||
|
||||
func (h *harness) labObjects(id uuid.UUID) (int, int) {
|
||||
short := lab.ShortID(id)
|
||||
instances, bridges := 0, 0
|
||||
for name := range h.fake.Instances() {
|
||||
if strings.Contains(name, short) {
|
||||
instances++
|
||||
}
|
||||
}
|
||||
for name := range h.fake.Networks() {
|
||||
if strings.Contains(name, short) {
|
||||
bridges++
|
||||
}
|
||||
}
|
||||
return instances, bridges
|
||||
}
|
||||
|
||||
func TestCreateClonesNodesOnIsolatedBridgesAndDeleteRemovesEverything(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
manager := h.start()
|
||||
id := uuid.New()
|
||||
|
||||
created, isNew, err := manager.Create(id, request(1))
|
||||
if err != nil || !isNew || created.State != lab.Provisioning {
|
||||
t.Fatalf("Create() = %+v, %v, %v", created, isNew, err)
|
||||
}
|
||||
ready := waitFor(t, manager, id, inState(lab.Ready))
|
||||
if ready.ReadyAt.IsZero() || !ready.ExpiresAt.Equal(ready.CreatedAt.Add(30*time.Minute)) {
|
||||
t.Fatalf("ready lab times = %+v", ready)
|
||||
}
|
||||
|
||||
instances := h.fake.Instances()
|
||||
networks := h.fake.Networks()
|
||||
if len(instances) != 2 || len(networks) != 2 {
|
||||
t.Fatalf("LXD holds %d instances and %d networks, want 2 and 2", len(instances), len(networks))
|
||||
}
|
||||
for _, bridge := range ready.Bridges {
|
||||
spec := networks[bridge]
|
||||
if len(bridge) > 15 || spec.Config["ipv4.address"] != "none" || spec.Config["ipv6.address"] != "none" ||
|
||||
spec.Config[lab.ConfigLab] != id.String() {
|
||||
t.Fatalf("bridge %s = %+v, want an L2-only bridge marked with the lab", bridge, spec)
|
||||
}
|
||||
}
|
||||
r1 := instances[lab.InstanceName(id, "r1")]
|
||||
srv := instances[lab.InstanceName(id, "srv")]
|
||||
if !r1.Running || !srv.Running || r1.Spec.Source != "tpl-chr/base" || r1.Spec.Config[lab.ConfigLab] != id.String() {
|
||||
t.Fatalf("r1 = %+v", r1)
|
||||
}
|
||||
management := r1.Spec.Devices["eth0"]
|
||||
if management["network"] != managementNetwork || management["security.port_isolation"] != "true" ||
|
||||
management["security.mac_filtering"] != "true" {
|
||||
t.Fatalf("r1 management NIC = %v", management)
|
||||
}
|
||||
// r1 is on both links, srv only on the first; no node has a NIC on a
|
||||
// bridge of another lab or on any other network.
|
||||
if r1.Spec.Devices["eth1"]["network"] != ready.Bridges[0] || r1.Spec.Devices["eth2"]["network"] != ready.Bridges[1] ||
|
||||
srv.Spec.Devices["eth1"]["network"] != ready.Bridges[0] || len(srv.Spec.Devices) != 3 {
|
||||
t.Fatalf("data NICs: r1 %v, srv %v", r1.Spec.Devices, srv.Spec.Devices)
|
||||
}
|
||||
if !strings.Contains(r1.Spec.Config["cloud-init.user-data"], "address=10.81.0.16/24") ||
|
||||
!strings.Contains(srv.Spec.Config["cloud-init.network-config"], "10.81.0.17/24") ||
|
||||
srv.Spec.Devices["cloud-init"]["source"] != "cloud-init:config" {
|
||||
t.Fatalf("bootstrap: r1 %v, srv %v", r1.Spec.Config, srv.Spec.Config)
|
||||
}
|
||||
|
||||
deleting, changed, err := manager.Delete(id)
|
||||
if err != nil || !changed || deleting.State != lab.Deleting {
|
||||
t.Fatalf("Delete() = %+v, %v, %v", deleting, changed, err)
|
||||
}
|
||||
deleted := waitFor(t, manager, id, inState(lab.Deleted))
|
||||
if deleted.DeletedAt.IsZero() {
|
||||
t.Fatal("deleted lab has no deletion time")
|
||||
}
|
||||
if got := len(h.fake.Instances()) + len(h.fake.Networks()); got != 0 {
|
||||
t.Fatalf("LXD still holds %d objects of the lab", got)
|
||||
}
|
||||
if used, count := manager.Usage(); used != 0 || count != 0 {
|
||||
t.Fatalf("Usage() = %d, %d after deletion", used, count)
|
||||
}
|
||||
again, changed, err := manager.Delete(id)
|
||||
if err != nil || changed || again.State != lab.Deleted {
|
||||
t.Fatalf("second Delete() = %+v, %v, %v", again, changed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabsBeyondTheMemoryBudgetAreBusyAndStoreNothing(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
manager := h.start()
|
||||
first, second := uuid.New(), uuid.New()
|
||||
for index, id := range []uuid.UUID{first, second} {
|
||||
if _, _, err := manager.Create(id, request(byte(index+1))); err != nil {
|
||||
t.Fatalf("Create(%d) error = %v", index, err)
|
||||
}
|
||||
}
|
||||
extra := uuid.New()
|
||||
if _, _, err := manager.Create(extra, request(9)); !errors.Is(err, pool.ErrBusy) {
|
||||
t.Fatalf("third Create() error = %v, want ErrBusy", err)
|
||||
}
|
||||
if _, err := manager.Get(extra); !errors.Is(err, pool.ErrNotFound) {
|
||||
t.Fatalf("a busy request was stored: %v", err)
|
||||
}
|
||||
if used, count := manager.Usage(); used != 2*labMemory || count != 2 {
|
||||
t.Fatalf("Usage() = %d, %d", used, count)
|
||||
}
|
||||
|
||||
waitFor(t, manager, first, inState(lab.Ready))
|
||||
if _, _, err := manager.Delete(first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor(t, manager, first, removed)
|
||||
// Capacity returns only after the objects are gone; then the same ID is
|
||||
// admitted.
|
||||
if _, isNew, err := manager.Create(extra, request(9)); err != nil || !isNew {
|
||||
t.Fatalf("Create() after a deletion = %v, %v", isNew, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabCapAppliesBesideTheMemoryBudget(t *testing.T) {
|
||||
h := newHarness(t, func(cfg *pool.Config) { cfg.MaxLabs = 1 })
|
||||
manager := h.start()
|
||||
if _, _, err := manager.Create(uuid.New(), request(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := manager.Create(uuid.New(), request(2)); !errors.Is(err, pool.ErrBusy) {
|
||||
t.Fatalf("Create() error = %v, want ErrBusy", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateIsIdempotentByID(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
manager := h.start()
|
||||
id := uuid.New()
|
||||
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repeated, isNew, err := manager.Create(id, request(1))
|
||||
if err != nil || isNew || repeated.ID != id {
|
||||
t.Fatalf("repeated Create() = %+v, %v, %v", repeated, isNew, err)
|
||||
}
|
||||
if _, _, err := manager.Create(id, request(2)); !errors.Is(err, pool.ErrPayloadMismatch) {
|
||||
t.Fatalf("Create() with another seed error = %v, want ErrPayloadMismatch", err)
|
||||
}
|
||||
if used, count := manager.Usage(); used != labMemory || count != 1 {
|
||||
t.Fatalf("a repeat reserved capacity again: %d, %d", used, count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRefusesUnknownTemplatesAndLongLifetimes(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
manager := h.start()
|
||||
unknown := request(1)
|
||||
unknown.TemplateVersion = 2
|
||||
if _, _, err := manager.Create(uuid.New(), unknown); !errors.Is(err, pool.ErrUnknownTemplate) {
|
||||
t.Fatalf("Create() error = %v, want ErrUnknownTemplate", err)
|
||||
}
|
||||
long := request(1)
|
||||
long.Lifetime = 3 * time.Hour
|
||||
if _, _, err := manager.Create(uuid.New(), long); !errors.Is(err, pool.ErrLifetimeTooLong) {
|
||||
t.Fatalf("Create() error = %v, want ErrLifetimeTooLong", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiryDeletesTheLabAfterARestart(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
first := h.start()
|
||||
id := uuid.New()
|
||||
if _, _, err := first.Create(id, request(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor(t, first, id, inState(lab.Ready))
|
||||
// The process stops in the middle of the lab's life; its timer lives in
|
||||
// the state file, not in the process.
|
||||
if err := first.Close(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
second := h.start()
|
||||
second.Sweep(context.Background())
|
||||
if record := waitFor(t, second, id, inState(lab.Ready)); h.fake.Instances()[record.Nodes[0].Instance].Spec.Name == "" {
|
||||
t.Fatal("a running lab lost its nodes across the restart")
|
||||
}
|
||||
h.clock.Advance(29 * time.Minute)
|
||||
second.Sweep(context.Background())
|
||||
if record, _ := second.Get(id); record.State != lab.Ready {
|
||||
t.Fatalf("lab ended before its timer: %s", record.State)
|
||||
}
|
||||
h.clock.Advance(time.Minute)
|
||||
second.Sweep(context.Background())
|
||||
waitFor(t, second, id, inState(lab.Deleted))
|
||||
if instances, bridges := h.labObjects(id); instances+bridges != 0 {
|
||||
t.Fatalf("LXD still holds %d instances and %d bridges after expiry", instances, bridges)
|
||||
}
|
||||
if _, _, err := second.ConsoleToken(id, "r1"); !errors.Is(err, pool.ErrNotReady) {
|
||||
t.Fatalf("ConsoleToken() for a deleted lab error = %v", err)
|
||||
}
|
||||
|
||||
h.clock.Advance(time.Hour)
|
||||
second.Sweep(context.Background())
|
||||
if _, err := second.Get(id); !errors.Is(err, pool.ErrNotFound) {
|
||||
t.Fatalf("Get() after the retention error = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestartDuringProvisioningFailsAndDeletesTheLab(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
id := uuid.New()
|
||||
created := h.clock.Now()
|
||||
// The previous process wrote the record and created one bridge and one
|
||||
// instance before it died.
|
||||
record := lab.Lab{
|
||||
ID: id, TemplateID: "mikrotik-pair", TemplateVersion: 1, Seed: strings.Repeat("01", 32), Fingerprint: "x",
|
||||
State: lab.Provisioning, CreatedAt: created, ExpiresAt: created.Add(time.Hour), MemoryBytes: labMemory,
|
||||
Nodes: []lab.Node{
|
||||
{Name: "r1", Kind: "mikrotik", Instance: lab.InstanceName(id, "r1"), ManagementAddress: netip.MustParseAddr("10.81.0.16"), ManagementPort: 8728},
|
||||
{Name: "srv", Kind: "ubuntu", Instance: lab.InstanceName(id, "srv"), ManagementAddress: netip.MustParseAddr("10.81.0.17"), ManagementPort: 22},
|
||||
},
|
||||
Bridges: []string{lab.BridgeName(id, 0), lab.BridgeName(id, 1)},
|
||||
}
|
||||
states, err := store.New(h.statePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := states.Save([]lab.Lab{record}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.fake.AddNetwork(lxd.NetworkSpec{Name: record.Bridges[0], Config: map[string]string{lab.ConfigLab: id.String()}})
|
||||
h.fake.AddInstance(lxd.InstanceSpec{
|
||||
Name: record.Nodes[0].Instance, Config: map[string]string{lab.ConfigLab: id.String()},
|
||||
Devices: map[string]map[string]string{"eth1": {"type": "nic", "network": record.Bridges[0]}},
|
||||
}, true)
|
||||
|
||||
manager := h.start()
|
||||
failed := waitFor(t, manager, id, removed)
|
||||
if failed.State != lab.Failed || failed.FailureReason != lab.FailureInterrupted {
|
||||
t.Fatalf("interrupted lab = %s %s", failed.State, failed.FailureReason)
|
||||
}
|
||||
if got := len(h.fake.Instances()) + len(h.fake.Networks()); got != 0 {
|
||||
t.Fatalf("LXD still holds %d objects of the interrupted lab", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconcileDeletesOrphansAndLeavesForeignObjects(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
manager := h.start()
|
||||
kept := uuid.New()
|
||||
if _, _, err := manager.Create(kept, request(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor(t, manager, kept, inState(lab.Ready))
|
||||
|
||||
orphan := uuid.New()
|
||||
h.fake.AddNetwork(lxd.NetworkSpec{Name: lab.BridgeName(orphan, 0), Config: map[string]string{lab.ConfigLab: orphan.String()}})
|
||||
h.fake.AddInstance(lxd.InstanceSpec{
|
||||
Name: lab.InstanceName(orphan, "r1"), Config: map[string]string{lab.ConfigLab: orphan.String()},
|
||||
Devices: map[string]map[string]string{"eth1": {"type": "nic", "network": lab.BridgeName(orphan, 0)}},
|
||||
}, true)
|
||||
// Same prefix, no marker: an object an operator made by hand.
|
||||
h.fake.AddInstance(lxd.InstanceSpec{Name: "lcxl-operator-test"}, false)
|
||||
h.fake.AddInstance(lxd.InstanceSpec{Name: "lincodex-runner", Config: map[string]string{lab.ConfigLab: "x"}}, true)
|
||||
|
||||
if err := manager.Reconcile(context.Background()); err != nil {
|
||||
t.Fatalf("Reconcile() error = %v", err)
|
||||
}
|
||||
instances := h.fake.Instances()
|
||||
if _, ok := instances[lab.InstanceName(orphan, "r1")]; ok {
|
||||
t.Fatal("the orphaned instance survived")
|
||||
}
|
||||
if _, ok := h.fake.Networks()[lab.BridgeName(orphan, 0)]; ok {
|
||||
t.Fatal("the orphaned bridge survived")
|
||||
}
|
||||
for _, name := range []string{"lcxl-operator-test", "lincodex-runner", lab.InstanceName(kept, "r1"), lab.InstanceName(kept, "srv")} {
|
||||
if _, ok := instances[name]; !ok {
|
||||
t.Fatalf("Reconcile() deleted %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvisioningFailureFailsTheLabAndReturnsItsCapacity(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
h.fake.FailCreateInstance(func(name string) error {
|
||||
if strings.HasSuffix(name, "-srv") {
|
||||
return lxdfake.ErrInjected
|
||||
}
|
||||
return nil
|
||||
})
|
||||
manager := h.start()
|
||||
id := uuid.New()
|
||||
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failed := waitFor(t, manager, id, removed)
|
||||
if failed.State != lab.Failed || failed.FailureReason != lab.FailureProvisioning {
|
||||
t.Fatalf("lab = %s %s", failed.State, failed.FailureReason)
|
||||
}
|
||||
if instances, bridges := h.labObjects(id); instances+bridges != 0 {
|
||||
t.Fatalf("a failed lab left %d instances and %d bridges", instances, bridges)
|
||||
}
|
||||
if used, count := manager.Usage(); used != 0 || count != 0 {
|
||||
t.Fatalf("Usage() = %d, %d", used, count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvisioningTimeoutFailsTheLab(t *testing.T) {
|
||||
h := newHarness(t, func(cfg *pool.Config) { cfg.ProvisionTimeout = 20 * time.Millisecond })
|
||||
h.prober.down.Store(true)
|
||||
manager := h.start()
|
||||
id := uuid.New()
|
||||
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failed := waitFor(t, manager, id, removed)
|
||||
if failed.State != lab.Failed || failed.FailureReason != lab.FailureTimedOut {
|
||||
t.Fatalf("lab = %s %s", failed.State, failed.FailureReason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletionIsRetriedUntilLXDConfirmsIt(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
manager := h.start()
|
||||
id := uuid.New()
|
||||
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor(t, manager, id, inState(lab.Ready))
|
||||
h.fake.FailDeletes(true)
|
||||
if _, _, err := manager.Delete(id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if record, _ := manager.Get(id); record.State != lab.Deleting || !record.HoldsResources() {
|
||||
t.Fatalf("lab = %s with deleted_at %v, want deleting while LXD refuses", record.State, record.DeletedAt)
|
||||
}
|
||||
if _, count := manager.Usage(); count != 1 {
|
||||
t.Fatal("capacity returned before the objects were gone")
|
||||
}
|
||||
h.fake.FailDeletes(false)
|
||||
manager.Sweep(context.Background())
|
||||
waitFor(t, manager, id, inState(lab.Deleted))
|
||||
if instances, bridges := h.labObjects(id); instances+bridges != 0 {
|
||||
t.Fatalf("LXD still holds %d instances and %d bridges", instances, bridges)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleTokensAreSingleUseAndBoundToTheNode(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
manager := h.start()
|
||||
id := uuid.New()
|
||||
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := manager.ConsoleToken(id, "r1"); !errors.Is(err, pool.ErrNotReady) && err != nil {
|
||||
t.Fatalf("ConsoleToken() while provisioning error = %v", err)
|
||||
}
|
||||
waitFor(t, manager, id, inState(lab.Ready))
|
||||
if _, _, err := manager.ConsoleToken(id, "r9"); !errors.Is(err, pool.ErrUnknownNode) {
|
||||
t.Fatalf("ConsoleToken() for an unknown node error = %v", err)
|
||||
}
|
||||
token, expiresAt, err := manager.ConsoleToken(id, "srv")
|
||||
if err != nil || len(token) != 43 || !expiresAt.Equal(h.clock.Now().Add(time.Minute)) {
|
||||
t.Fatalf("ConsoleToken() = %q, %v, %v", token, expiresAt, err)
|
||||
}
|
||||
labID, node, err := manager.ConsumeConsoleToken(token)
|
||||
if err != nil || labID != id || node != "srv" {
|
||||
t.Fatalf("ConsumeConsoleToken() = %v, %q, %v", labID, node, err)
|
||||
}
|
||||
if _, _, err := manager.ConsumeConsoleToken(token); !errors.Is(err, pool.ErrNotFound) {
|
||||
t.Fatalf("a token was accepted twice: %v", err)
|
||||
}
|
||||
expired, _, err := manager.ConsoleToken(id, "r1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.clock.Advance(time.Minute)
|
||||
if _, _, err := manager.ConsumeConsoleToken(expired); !errors.Is(err, pool.ErrNotFound) {
|
||||
t.Fatalf("an expired token was accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckRunsTheTemplateCheckerOnlyOnAReadyLab(t *testing.T) {
|
||||
h := newHarness(t, nil)
|
||||
manager := h.start()
|
||||
id := uuid.New()
|
||||
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor(t, manager, id, inState(lab.Ready))
|
||||
first, err := manager.Check(context.Background(), id)
|
||||
if err != nil || len(first.Criteria) != 2 {
|
||||
t.Fatalf("Check() = %+v, %v", first, err)
|
||||
}
|
||||
second, err := manager.Check(context.Background(), id)
|
||||
if err != nil || second.Criteria[0] != first.Criteria[0] {
|
||||
t.Fatalf("a repeated check of the same variant differs: %+v, %+v, %v", first, second, err)
|
||||
}
|
||||
if _, _, err := manager.Delete(id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := manager.Check(context.Background(), id); !errors.Is(err, pool.ErrNotReady) {
|
||||
t.Fatalf("Check() of a deleting lab error = %v, want ErrNotReady", err)
|
||||
}
|
||||
if _, err := manager.Check(context.Background(), uuid.New()); !errors.Is(err, pool.ErrNotFound) {
|
||||
t.Fatalf("Check() of an unknown lab error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRefusesATemplateThatCanNeverFit(t *testing.T) {
|
||||
h := newHarness(t, func(cfg *pool.Config) { cfg.MemoryBudgetBytes = labMemory - 1 })
|
||||
states, err := store.New(h.statePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
if _, err := pool.New(h.cfg, h.fake, states, h.registry, h.prober, h.clock.Now, logger); err == nil {
|
||||
t.Fatal("New() accepted a budget below the smallest lab")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package pool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TCPProber reports a node as reachable when its management port accepts a
|
||||
// TCP connection from the host side of the management bridge.
|
||||
type TCPProber struct {
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Probe opens and closes one connection.
|
||||
func (p TCPProber) Probe(ctx context.Context, address netip.AddrPort) error {
|
||||
dialer := net.Dialer{Timeout: p.Timeout}
|
||||
connection, err := dialer.DialContext(ctx, "tcp", address.String())
|
||||
if err != nil {
|
||||
return fmt.Errorf("TCPProber.Probe - dial: %w", err)
|
||||
}
|
||||
_ = connection.Close() // Only the accepted connection matters.
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package pool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/labd/internal/lab"
|
||||
"lincodex/labd/internal/lxd"
|
||||
"lincodex/labd/internal/template"
|
||||
)
|
||||
|
||||
// startWorkerLocked runs the provisioning and deletion of one lab in its own
|
||||
// goroutine. At most one worker exists per lab, so the provisioning and the
|
||||
// deletion of a lab never race.
|
||||
func (m *Manager) startWorkerLocked(id uuid.UUID) {
|
||||
if _, running := m.workers[id]; running || !m.started || m.base.Err() != nil {
|
||||
return
|
||||
}
|
||||
provisionCtx, cancel := context.WithCancel(m.base)
|
||||
m.workers[id] = cancel
|
||||
m.wg.Add(1)
|
||||
go m.run(provisionCtx, id)
|
||||
}
|
||||
|
||||
func (m *Manager) run(provisionCtx context.Context, id uuid.UUID) {
|
||||
defer m.wg.Done()
|
||||
tornDown := false
|
||||
defer func() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if cancel, ok := m.workers[id]; ok {
|
||||
cancel()
|
||||
delete(m.workers, id)
|
||||
}
|
||||
// A deletion requested while this worker finished provisioning
|
||||
// starts at once instead of at the next sweep.
|
||||
if record, ok := m.labs[id]; ok && !tornDown && record.NeedsTeardown() {
|
||||
m.startWorkerLocked(id)
|
||||
}
|
||||
}()
|
||||
if record, ok := m.snapshot(id); ok && record.State == lab.Provisioning {
|
||||
m.provision(provisionCtx, record)
|
||||
}
|
||||
if m.base.Err() != nil {
|
||||
return
|
||||
}
|
||||
if record, ok := m.snapshot(id); ok && record.NeedsTeardown() {
|
||||
tornDown = true
|
||||
m.teardown(m.base, record)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) snapshot(id uuid.UUID) (lab.Lab, bool) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
record, ok := m.labs[id]
|
||||
if !ok {
|
||||
return lab.Lab{}, false
|
||||
}
|
||||
return record.Clone(), true
|
||||
}
|
||||
|
||||
// provision builds the lab and records the outcome. A cancelled
|
||||
// provisioning (deletion, expiry) records nothing: the lab is already
|
||||
// deleting. A stopped process records nothing either: the next start fails
|
||||
// the lab as interrupted.
|
||||
func (m *Manager) provision(provisionCtx context.Context, record lab.Lab) {
|
||||
ctx, cancel := context.WithTimeout(provisionCtx, m.cfg.ProvisionTimeout)
|
||||
defer cancel()
|
||||
started := time.Now()
|
||||
err := m.build(ctx, record)
|
||||
switch {
|
||||
case err == nil:
|
||||
m.finishProvisioning(record.ID, "", nil)
|
||||
m.logger.Info("lab ready", slog.String("lab_id", record.ID.String()),
|
||||
slog.Int64("provision_ms", time.Since(started).Milliseconds()))
|
||||
case provisionCtx.Err() != nil:
|
||||
return
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
m.finishProvisioning(record.ID, lab.FailureTimedOut, err)
|
||||
default:
|
||||
m.finishProvisioning(record.ID, lab.FailureProvisioning, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) finishProvisioning(id uuid.UUID, reason lab.FailureReason, cause error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
record, ok := m.labs[id]
|
||||
if !ok || record.State != lab.Provisioning {
|
||||
return
|
||||
}
|
||||
if reason == "" {
|
||||
record.State = lab.Ready
|
||||
record.ReadyAt = m.now().UTC()
|
||||
} else {
|
||||
record.State = lab.Failed
|
||||
record.FailureReason = reason
|
||||
// The LXD text may name host paths; it stays in the labd log.
|
||||
m.logger.Warn("lab provisioning failed", slog.String("lab_id", id.String()),
|
||||
slog.String("reason", string(reason)), slog.String("error", cause.Error()))
|
||||
}
|
||||
if err := m.persistLocked(); err != nil {
|
||||
m.logger.Error("lab state not saved", slog.String("lab_id", id.String()), slog.String("error", err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
// build creates the bridges and instances of a lab, starts the instances,
|
||||
// and waits until every node answers on its management port.
|
||||
func (m *Manager) build(ctx context.Context, record lab.Lab) error {
|
||||
chosen, ok := m.templates.Lookup(record.TemplateID, record.TemplateVersion)
|
||||
if !ok {
|
||||
return errors.New("Manager.build - the template of the lab is not in this build")
|
||||
}
|
||||
variant, err := m.plan(record, chosen)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bootstraps, err := chosen.Render(variant)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Manager.build - render: %w", err)
|
||||
}
|
||||
for index, link := range chosen.Links {
|
||||
spec := lxd.NetworkSpec{
|
||||
Name: record.Bridges[index],
|
||||
Description: "Lincodex lab link " + link.Name,
|
||||
// No address on the host side: the bridge is L2 only, so lab
|
||||
// traffic is neither routed nor answered by the host.
|
||||
Config: map[string]string{"ipv4.address": "none", "ipv6.address": "none", lab.ConfigLab: record.ID.String()},
|
||||
}
|
||||
if err := m.lxd.CreateNetwork(ctx, spec); err != nil {
|
||||
return fmt.Errorf("Manager.build - create bridge: %w", err)
|
||||
}
|
||||
}
|
||||
for index, node := range chosen.Nodes {
|
||||
bootstrap := bootstraps[node.Name]
|
||||
if err := template.ValidateBootstrap(bootstrap); err != nil {
|
||||
return err
|
||||
}
|
||||
spec := m.instanceSpec(record, chosen, node, variant.Nodes[index], bootstrap)
|
||||
if err := m.lxd.CreateInstance(ctx, spec); err != nil {
|
||||
return fmt.Errorf("Manager.build - create instance: %w", err)
|
||||
}
|
||||
}
|
||||
for _, node := range record.Nodes {
|
||||
if err := m.lxd.StartInstance(ctx, node.Instance); err != nil {
|
||||
return fmt.Errorf("Manager.build - start instance: %w", err)
|
||||
}
|
||||
}
|
||||
return m.waitReachable(ctx, record)
|
||||
}
|
||||
|
||||
func (m *Manager) instanceSpec(record lab.Lab, chosen template.Template, node template.Node, planned template.PlannedNode, bootstrap template.Bootstrap) lxd.InstanceSpec {
|
||||
config := map[string]string{
|
||||
lab.ConfigLab: record.ID.String(),
|
||||
lab.ConfigNode: node.Name,
|
||||
lab.ConfigExpiresAt: record.ExpiresAt.Format(time.RFC3339),
|
||||
// The guest gets no LXD guest API.
|
||||
"security.devlxd": "false",
|
||||
}
|
||||
devices := map[string]map[string]string{
|
||||
// The management NIC overrides the profile NIC: a fixed MAC that
|
||||
// cloud-init matches, no MAC spoofing, and no traffic to other
|
||||
// isolated ports of the bridge, that is, to other nodes.
|
||||
"eth0": {
|
||||
"type": "nic", "network": m.cfg.ManagementNetwork, "hwaddr": planned.ManagementMAC,
|
||||
"security.mac_filtering": "true", "security.port_isolation": "true",
|
||||
},
|
||||
}
|
||||
bridges := make(map[string]string, len(chosen.Links))
|
||||
for index, link := range chosen.Links {
|
||||
bridges[link.Name] = record.Bridges[index]
|
||||
}
|
||||
for _, nic := range planned.Interfaces {
|
||||
devices[nic.Device] = map[string]string{"type": "nic", "network": bridges[nic.Link], "hwaddr": nic.MAC}
|
||||
}
|
||||
if bootstrap.UserData != "" || bootstrap.NetworkConfig != "" {
|
||||
if bootstrap.UserData != "" {
|
||||
config["cloud-init.user-data"] = bootstrap.UserData
|
||||
}
|
||||
if bootstrap.NetworkConfig != "" {
|
||||
config["cloud-init.network-config"] = bootstrap.NetworkConfig
|
||||
}
|
||||
// A VM reads its cloud-init data from this config drive.
|
||||
devices["cloud-init"] = map[string]string{"type": "disk", "source": "cloud-init:config"}
|
||||
}
|
||||
return lxd.InstanceSpec{
|
||||
Name: lab.InstanceName(record.ID, node.Name),
|
||||
Description: "Lincodex lab node " + node.Name,
|
||||
Source: node.Source,
|
||||
Profiles: []string{node.Profile},
|
||||
Config: config,
|
||||
Devices: devices,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) waitReachable(ctx context.Context, record lab.Lab) error {
|
||||
for _, node := range record.Nodes {
|
||||
address := netip.AddrPortFrom(node.ManagementAddress, node.ManagementPort)
|
||||
for {
|
||||
err := m.prober.Probe(ctx, address)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
timer := time.NewTimer(m.cfg.ProbeInterval)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return fmt.Errorf("Manager.waitReachable - node %s: %w", node.Name, ctx.Err())
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// teardown deletes every instance and bridge of a lab. LXD answers not found
|
||||
// for an object that never existed or is already gone, which counts as
|
||||
// deleted. On any other failure the lab stays deleting and the next sweep
|
||||
// tries again.
|
||||
func (m *Manager) teardown(ctx context.Context, record lab.Lab) {
|
||||
var errs []error
|
||||
for _, node := range record.Nodes {
|
||||
if err := m.deleteInstance(ctx, node.Instance); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
if len(errs) == 0 {
|
||||
for _, bridge := range record.Bridges {
|
||||
if err := m.deleteNetwork(ctx, bridge); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := errors.Join(errs...); err != nil {
|
||||
m.logger.Warn("lab deletion incomplete; retrying on the next sweep",
|
||||
slog.String("lab_id", record.ID.String()), slog.String("error", err.Error()))
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
current, ok := m.labs[record.ID]
|
||||
if !ok || !current.NeedsTeardown() {
|
||||
return
|
||||
}
|
||||
current.DeletedAt = m.now().UTC()
|
||||
if current.State == lab.Deleting {
|
||||
current.State = lab.Deleted
|
||||
}
|
||||
if err := m.persistLocked(); err != nil {
|
||||
m.logger.Error("lab state not saved", slog.String("lab_id", record.ID.String()), slog.String("error", err.Error()))
|
||||
}
|
||||
m.logger.Info("lab deleted", slog.String("lab_id", record.ID.String()), slog.String("state", string(current.State)))
|
||||
}
|
||||
|
||||
func (m *Manager) deleteInstance(ctx context.Context, name string) error {
|
||||
if err := m.lxd.StopInstance(ctx, name); err != nil {
|
||||
if errors.Is(err, lxd.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("Manager.deleteInstance - stop %s: %w", name, err)
|
||||
}
|
||||
if err := m.lxd.DeleteInstance(ctx, name); err != nil && !errors.Is(err, lxd.ErrNotFound) {
|
||||
return fmt.Errorf("Manager.deleteInstance - delete %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) deleteNetwork(ctx context.Context, name string) error {
|
||||
if err := m.lxd.DeleteNetwork(ctx, name); err != nil && !errors.Is(err, lxd.ErrNotFound) {
|
||||
return fmt.Errorf("Manager.deleteNetwork - delete %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user