Files

663 lines
20 KiB
Go

// 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)
}