feat(labs): add the labd provisioner with clone pool, time to live and limits

This commit is contained in:
shira committed 2026-10-11 15:43:04 +03:00
1 parent 9fdaa62b9b
commit 9385b2ddd4
53 files changed
+14675 -6

No files matched your search

+138
View File
@@ -0,0 +1,138 @@
// Package store keeps the lab records in one JSON file.
//
// labd holds a few dozen labs at most, so the whole file is rewritten on
// every change: the new content goes to a temporary file in the same
// directory, which is synced, renamed over the old file, and followed by a
// sync of the directory. A crash leaves either the old or the new file,
// never a mix. This needs no database engine, no cgo, and no extra
// dependency, and an operator can read the file during an incident. The file
// holds variant seeds, so it is created with mode 0600 in a directory that
// only the labd user can read.
package store
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sync"
"lincodex/labd/internal/lab"
)
const (
fileVersion = 1
fileMode = 0o600
// maxFileBytes refuses a state file that cannot come from labd.
maxFileBytes = 16 << 20
)
type document struct {
Version int `json:"version"`
Labs []lab.Lab `json:"labs"`
}
// Store reads and writes the state file.
type Store struct {
path string
mu sync.Mutex
}
// New returns a store for the state file at path. The directory must exist.
func New(path string) (*Store, error) {
if !filepath.IsAbs(path) {
return nil, errors.New("store.New - the state file path must be absolute")
}
info, err := os.Stat(filepath.Dir(path))
if err != nil {
return nil, fmt.Errorf("store.New - state directory: %w", err)
}
if !info.IsDir() {
return nil, errors.New("store.New - the parent of the state file is not a directory")
}
return &Store{path: path}, nil
}
// Load returns the stored labs. A missing file is an empty store; a file
// that cannot be decoded is an error, because labd must not forget labs whose
// LXD objects may still exist.
func (s *Store) Load() ([]lab.Lab, error) {
s.mu.Lock()
defer s.mu.Unlock()
content, err := os.ReadFile(s.path)
if errors.Is(err, fs.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("Store.Load - read: %w", err)
}
if len(content) > maxFileBytes {
return nil, errors.New("Store.Load - the state file is too large")
}
var decoded document
if err := json.Unmarshal(content, &decoded); err != nil {
return nil, fmt.Errorf("Store.Load - decode: %w", err)
}
if decoded.Version != fileVersion {
return nil, fmt.Errorf("Store.Load - unsupported state file version %d", decoded.Version)
}
return decoded.Labs, nil
}
// Save replaces the stored labs atomically and durably.
func (s *Store) Save(labs []lab.Lab) error {
s.mu.Lock()
defer s.mu.Unlock()
if labs == nil {
labs = []lab.Lab{}
}
content, err := json.MarshalIndent(document{Version: fileVersion, Labs: labs}, "", " ")
if err != nil {
return fmt.Errorf("Store.Save - encode: %w", err)
}
directory := filepath.Dir(s.path)
temporary, err := os.CreateTemp(directory, ".labs-*.json")
if err != nil {
return fmt.Errorf("Store.Save - create temporary file: %w", err)
}
name := temporary.Name()
committed := false
defer func() {
if !committed {
_ = temporary.Close() // Already closed on the success path.
_ = os.Remove(name) // Best effort; a stale temporary file is harmless.
}
}()
if err := temporary.Chmod(fileMode); err != nil {
return fmt.Errorf("Store.Save - chmod: %w", err)
}
if _, err := temporary.Write(append(content, '\n')); err != nil {
return fmt.Errorf("Store.Save - write: %w", err)
}
if err := temporary.Sync(); err != nil {
return fmt.Errorf("Store.Save - sync file: %w", err)
}
if err := temporary.Close(); err != nil {
return fmt.Errorf("Store.Save - close: %w", err)
}
if err := os.Rename(name, s.path); err != nil {
return fmt.Errorf("Store.Save - rename: %w", err)
}
committed = true
return syncDirectory(directory)
}
// syncDirectory makes the rename durable.
func syncDirectory(path string) error {
directory, err := os.Open(path)
if err != nil {
return fmt.Errorf("store.syncDirectory - open: %w", err)
}
defer func() { _ = directory.Close() }() // Read-only handle.
if err := directory.Sync(); err != nil {
return fmt.Errorf("store.syncDirectory - sync: %w", err)
}
return nil
}
+89
View File
@@ -0,0 +1,89 @@
package store_test
import (
"net/netip"
"os"
"path/filepath"
"testing"
"time"
"github.com/google/uuid"
"lincodex/labd/internal/lab"
"lincodex/labd/internal/store"
)
func TestSaveAndLoadKeepEveryField(t *testing.T) {
directory := t.TempDir()
path := filepath.Join(directory, "labs.json")
labs, err := mustStore(t, path).Load()
if err != nil || len(labs) != 0 {
t.Fatalf("Load() of a missing file = %v, %v; want empty", labs, err)
}
created := time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC)
record := lab.Lab{
ID: uuid.New(), TemplateID: "ubuntu-dns", TemplateVersion: 2, Seed: "ab", Fingerprint: "f",
State: lab.Failed, FailureReason: lab.FailureTimedOut, CreatedAt: created, ExpiresAt: created.Add(time.Hour),
MemoryBytes: 768 << 20,
Nodes: []lab.Node{{
Name: "srv", Kind: "ubuntu", Instance: "lcxl-0102030405-srv",
ManagementAddress: netip.MustParseAddr("10.81.0.16"), ManagementPort: 22,
}},
Bridges: []string{"lxl010203040500"},
}
if err := mustStore(t, path).Save([]lab.Lab{record}); err != nil {
t.Fatalf("Save() error = %v", err)
}
loaded, err := mustStore(t, path).Load()
if err != nil || len(loaded) != 1 {
t.Fatalf("Load() = %v, %v", loaded, err)
}
got := loaded[0]
if got.ID != record.ID || got.State != record.State || got.FailureReason != record.FailureReason ||
!got.ExpiresAt.Equal(record.ExpiresAt) || !got.ReadyAt.IsZero() || got.Nodes[0] != record.Nodes[0] ||
got.Bridges[0] != record.Bridges[0] || got.MemoryBytes != record.MemoryBytes {
t.Fatalf("Load() = %+v, want %+v", got, record)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if mode := info.Mode().Perm(); mode != 0o600 {
t.Fatalf("state file mode = %o, want 600", mode)
}
entries, err := os.ReadDir(directory)
if err != nil || len(entries) != 1 {
t.Fatalf("directory holds %d entries, want only the state file", len(entries))
}
}
func TestLoadRefusesACorruptFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "labs.json")
if err := os.WriteFile(path, []byte("{\"version\":1,\"labs\":["), 0o600); err != nil {
t.Fatal(err)
}
if _, err := mustStore(t, path).Load(); err == nil {
t.Fatal("Load() accepted a truncated file; labd would forget its labs")
}
if err := os.WriteFile(path, []byte(`{"version":9,"labs":[]}`), 0o600); err != nil {
t.Fatal(err)
}
if _, err := mustStore(t, path).Load(); err == nil {
t.Fatal("Load() accepted an unknown version")
}
}
func TestNewRefusesARelativePath(t *testing.T) {
if _, err := store.New("labs.json"); err == nil {
t.Fatal("New() accepted a relative path")
}
}
func mustStore(t *testing.T, path string) *store.Store {
t.Helper()
s, err := store.New(path)
if err != nil {
t.Fatalf("New() error = %v", err)
}
return s
}