diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 0201aed4..c3355627 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -946,9 +946,13 @@ one disk and a firmware inventory. No production site registers it yet. time at least every 30 seconds while burn-in runs, and exactly when it sees the receipt appear. A worker restarted after the receipt appeared uses the stored time, so a restart can shorten the recorded burn-in but - never lengthen it. A burn-in that reported before the plan's duration, or - that no worker saw run that long, is a `Failed` result. The boot server - and the worker share the site's clock. + never lengthen it. With no stored time, the burn-in measures zero. A + burn-in shorter than the plan's duration is a `Failed` result. Its + mismatch says the image reported early when a worker watched the receipt + appear, and that the burn-in could not be proven long enough across a + worker restart when none did, so staff know a re-run may pass. The boot + server and the worker share the site's clock. The local VM worker times + burn-in the same way. - **Evidence.** Strings the BMC supplies are cut to 128 bytes, and the component lists are dropped before the verdict if the evidence would pass the kind's limit. @@ -1046,7 +1050,9 @@ inputs, and nothing else writes them. Device, which describes the guest it defines, with the plan. Burn-in is real: one network boot of the site image in burn-in mode on a scratch disk, proven by its one console receipt, after which the scratch disk is - removed. + removed. It is timed like the Redfish worker's, from the boot server's + delivery to the last sighting without the receipt, so a site that boots + its guest directly, with no boot server, refuses commissioning. - The Redfish site registers the Redfish worker against the lab emulator. The `redfish-commission-mark` step requires exactly one effective `On` to target A, one passed burn-in receipt and no effect on target B, and the diff --git a/internal/site/burnin/burnin.go b/internal/site/burnin/burnin.go new file mode 100644 index 00000000..1c7125b3 --- /dev/null +++ b/internal/site/burnin/burnin.go @@ -0,0 +1,143 @@ +// Package burnin times a commissioning's burn-in the same way at every site +// that boots its burn-in image from the network. +// +// Burn-in starts when the boot server finished delivering the image, not when +// the server or guest started, so firmware start and the network boot do not +// count. It ends at the last time a worker saw the console without the +// image's receipt, which is never after the image reported. A worker stores +// that time at least every PersistEvery while burn-in runs, and exactly when +// it sees the receipt appear, so a worker restart can shorten the measured +// burn-in but never lengthen it. +package burnin + +import ( + "errors" + "os" + "strings" + "time" + + "go.datum.net/fleet/internal/site" +) + +// Records holds, for each operation, the last time a worker saw no burn-in +// receipt on the console, on the store's clock. +const Records = "burnin-receipt" + +// PersistEvery is how often a worker stores the time it last saw no receipt +// while burn-in runs. A worker restarted after the receipt appeared uses the +// stored time, at most this much earlier than the truth plus the restart's +// gap. +const PersistEvery = 30 * time.Second + +// The two reasons a burn-in that reported a pass still fails as too short. +// Both are Failed verdicts; the second tells staff a re-run may pass. +const ( + // TooShort: a worker watched the receipt appear, so the measured length + // is exact, and it is shorter than the plan's duration. + TooShort = "the burn-in image reported before the plan's duration" + // Restarted: no worker watched the receipt appear, because a worker + // restart fell inside the burn-in, so the measured length is only a lower + // bound and that bound is shorter than the plan's duration. + Restarted = "burn-in could not be proven long enough across a worker restart" +) + +// Record is an operation's stored sighting. +type Record struct { + // AbsentAt is the last time a worker saw no receipt. + AbsentAt time.Time `json:"absentAt"` + // Exact is set by the worker that saw the receipt appear: AbsentAt is + // then its last sighting before the receipt, not a periodic one. + Exact bool `json:"exact,omitempty"` +} + +// Absence tracks one worker's sightings of the burn-in console. Its zero +// value is ready to use. +type Absence struct { + last, stored time.Time + seen bool +} + +// Observe records one read of the console: at is the store's time taken +// before the read, and receipts the number of burn-in receipts for the +// operation found on it. Taking the time first keeps a sighting of none from +// postdating a receipt written during the read. +func (a *Absence) Observe(work *site.Work, at time.Time, receipts int) error { + store := work.Store() + switch { + case a.seen: + return nil + case receipts == 0: + a.last = at + if a.stored.IsZero() || a.last.Sub(a.stored) >= PersistEvery { + a.stored = a.last + return store.PutRecord(work.Device, work.Fence, Records, work.Key(), Record{AbsentAt: a.last}) + } + return nil + } + a.seen = true + if a.last.IsZero() { + // This worker never saw the console without the receipt: keep what + // an earlier worker stored. + return nil + } + return store.PutRecord(work.Device, work.Fence, Records, work.Key(), Record{AbsentAt: a.last, Exact: true}) +} + +// Measurement is a burn-in's measured start and end, and why it is too +// short, if it is. +type Measurement struct { + StartedAt, CompletedAt time.Time + // Short is TooShort or Restarted when the burn-in is shorter than the + // plan's duration, and empty otherwise. + Short string +} + +// Measure times the operation's burn-in from the boot server's delivery log +// at deliveryLog and the stored sighting. With no sighting stored, nothing +// shows the burn-in ran at all, and it measures zero. +func Measure(work *site.Work, deliveryLog string, duration time.Duration) (Measurement, error) { + started, ok := DeliveredAt(deliveryLog) + if !ok { + return Measurement{}, errors.New("the boot log does not record when burn-in began") + } + var record Record + if _, err := work.Store().GetRecord(work.Device, Records, work.Key(), &record); err != nil { + return Measurement{}, err + } + m := Measurement{StartedAt: started, CompletedAt: record.AbsentAt} + if m.CompletedAt.Before(started) { + m.CompletedAt = started + } + if m.CompletedAt.Sub(started) < duration { + m.Short = Restarted + if record.Exact { + m.Short = TooShort + } + } + return m, nil +} + +// DeliveredAt is when the boot server finished delivering the operation's +// last boot file, rounded up to the next second because the log records +// whole seconds. The boot server and the worker share the site's clock. +func DeliveredAt(deliveryLog string) (time.Time, bool) { + data, _ := os.ReadFile(deliveryLog) + var last time.Time + for _, line := range strings.Split(string(data), "\n") { + fields := strings.Fields(line) + if len(fields) != 4 || fields[1] != "write-complete" { + continue + } + at, err := time.Parse(time.RFC3339, fields[0]) + if err != nil { + return time.Time{}, false + } + if at.After(last) { + last = at + } + } + if last.IsZero() { + return time.Time{}, false + } + return last.Add(time.Second), true +} diff --git a/internal/site/burnin/burnin_test.go b/internal/site/burnin/burnin_test.go new file mode 100644 index 00000000..ace6dd1e --- /dev/null +++ b/internal/site/burnin/burnin_test.go @@ -0,0 +1,30 @@ +package burnin + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +// The boot log records whole seconds, so a file logged at 10:00:05 may have +// finished at any point up to 10:00:06. Burn-in is timed from the next whole +// second after the last file, so the log's truncation can never shorten the +// time an image must run. +func TestDeliveryIsRoundedUpToTheNextSecond(t *testing.T) { + path := filepath.Join(t.TempDir(), "boot-delivery.log") + log := "2026-01-02T10:00:00Z admitted boot.ipxe bytes=1\n" + + "2026-01-02T10:00:00Z write-complete boot.ipxe bytes=1\n" + + "2026-01-02T10:00:05Z write-complete installer.gz bytes=1\n" + + "2026-01-02T10:00:03Z write-complete kernel bytes=1\n" + if err := os.WriteFile(path, []byte(log), 0o600); err != nil { + t.Fatal(err) + } + at, ok := DeliveredAt(path) + if want := time.Date(2026, 1, 2, 10, 0, 6, 0, time.UTC); !ok || !at.Equal(want) { + t.Fatalf("DeliveredAt = %v, %v; want %v", at, ok, want) + } + if _, ok := DeliveredAt(filepath.Join(t.TempDir(), "missing.log")); ok { + t.Fatal("a missing log records a delivery") + } +} diff --git a/internal/site/redfishwork/commissioning.go b/internal/site/redfishwork/commissioning.go index 8b5e9c56..209b184e 100644 --- a/internal/site/redfishwork/commissioning.go +++ b/internal/site/redfishwork/commissioning.go @@ -15,6 +15,7 @@ import ( "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/burnin" "k8s.io/apimachinery/pkg/api/resource" ) @@ -120,29 +121,18 @@ func (k Commissioning) Run(ctx context.Context, work *site.Work) (any, error) { return nil, err } evidence.Steps = steps - // Burn-in is timed from the boot server's delivery of the image, not from - // power-on, so firmware start and the network boot do not count towards - // it. An image that reports early fails however long the server took to - // fetch it. It ends at the last time a worker saw no receipt, which is - // never after the image reported, so a worker restarted after an early - // report cannot lengthen it. - started, delivered := k.deliveredAt(work) - if !delivered { - return nil, errors.New("the boot log does not record when burn-in began") - } - completed, err := receiptBound(work) + // Burn-in is timed from the boot server's delivery of the image to the + // last time a worker saw no receipt; see package burnin. + measured, err := burnin.Measure(work, filepath.Join(BootDirectory(k.BootRoot, work.Key()), "boot-delivery.log"), plan.BurnIn.Duration.Duration) if err != nil { return nil, err } - if completed.Before(started) { - completed = started - } - evidence.BurnIn = &ops.BurnInEvidence{Result: result, StartedAt: metaNow(started), CompletedAt: metaNow(completed)} + evidence.BurnIn = &ops.BurnInEvidence{Result: result, StartedAt: metaNow(measured.StartedAt), CompletedAt: metaNow(measured.CompletedAt)} if result != ops.BurnInPassed { return fail(evidence, ops.PhaseBurnIn, []string{"the burn-in image reported a failure"}) } - if completed.Sub(started) < plan.BurnIn.Duration.Duration { - return fail(evidence, ops.PhaseBurnIn, []string{"the burn-in image reported before the plan's duration, or no worker saw it run that long"}) + if measured.Short != "" { + return fail(evidence, ops.PhaseBurnIn, []string{measured.Short}) } after, err := conn(work).BMC.Hardware(ctx, conn(work).System) if err != nil { @@ -155,62 +145,6 @@ func (k Commissioning) Run(ctx context.Context, work *site.Work) (any, error) { return fit(evidence), nil } -// receiptRecords holds, for each operation, the last time a worker saw no -// burn-in receipt on the console, on the store's clock. -const receiptRecords = "burnin-receipt" - -// receiptPersistEvery is how often a worker stores the time it last saw no -// receipt while burn-in runs. A worker that sees the receipt appear stores -// its exact last sighting of none; one restarted after the receipt appeared -// uses the stored time, at most this much earlier, so a restart can shorten -// a burn-in's recorded length but never lengthen it. -const receiptPersistEvery = 30 * time.Second - -type receiptRecord struct { - AbsentAt time.Time `json:"absentAt"` -} - -// receiptAbsence tracks one worker's sightings of the burn-in console. -type receiptAbsence struct { - last, stored time.Time - seen bool -} - -// observe records one poll of the console: seen is the number of burn-in -// receipts found. -func (a *receiptAbsence) observe(work *site.Work, seen int) error { - store := work.Store() - switch { - case a.seen: - return nil - case seen == 0: - a.last = store.Now() - if a.stored.IsZero() || a.last.Sub(a.stored) >= receiptPersistEvery { - a.stored = a.last - return store.PutRecord(work.Device, work.Fence, receiptRecords, work.Key(), receiptRecord{AbsentAt: a.last}) - } - return nil - } - a.seen = true - if a.last.IsZero() { - // This worker never saw the console without the receipt: keep what - // an earlier worker stored. - return nil - } - return store.PutRecord(work.Device, work.Fence, receiptRecords, work.Key(), receiptRecord{AbsentAt: a.last}) -} - -// receiptBound is the stored last time a worker saw no burn-in receipt. With -// none stored, nothing shows the burn-in ran at all, and the zero time makes -// it as short as possible. -func receiptBound(work *site.Work) (time.Time, error) { - var record receiptRecord - if _, err := work.Store().GetRecord(work.Device, receiptRecords, work.Key(), &record); err != nil { - return time.Time{}, err - } - return record.AbsentAt, nil -} - // preflightRecords holds each operation's passing inspection and firmware // evidence, stored before burn-in sends anything. const preflightRecords = "commissioning" diff --git a/internal/site/redfishwork/commissioning_test.go b/internal/site/redfishwork/commissioning_test.go index 6d24d521..fb2fed47 100644 --- a/internal/site/redfishwork/commissioning_test.go +++ b/internal/site/redfishwork/commissioning_test.go @@ -15,6 +15,7 @@ import ( "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/burnin" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -295,14 +296,22 @@ func TestOversizedEvidenceKeepsTheVerdict(t *testing.T) { } } +// burnInFailed checks a proven burn-in failure with the given mismatch. +func burnInFailed(t *testing.T, result custody.SiteResult, evidence ops.CommissioningEvidence, mismatch string) { + t.Helper() + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn || + len(evidence.Mismatches) != 1 || evidence.Mismatches[0] != mismatch { + t.Fatalf("result = %+v, evidence %+v; want the burn-in to fail with %q", result, evidence, mismatch) + } +} + +// A worker that watched the receipt appear proves the burn-in too short. func TestABurnInShorterThanThePlanFails(t *testing.T) { l := newLab(t) l.burnTime = 0 r := commissioningRunner(t, l) result, evidence := commission(t, l, r, "op-short", planSpec(t, nil)) - if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn { - t.Fatalf("result = %+v, evidence %+v", result, evidence) - } + burnInFailed(t, result, evidence, burnin.TooShort) } // A burn-in is timed from the image's delivery: a slow firmware start and @@ -312,9 +321,7 @@ func TestASlowBootDoesNotLengthenTheBurnIn(t *testing.T) { l.pxeTime, l.burnTime = 5*time.Minute, 30*time.Second r := commissioningRunner(t, l) result, evidence := commission(t, l, r, "op-slow-boot", planSpec(t, nil)) - if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn { - t.Fatalf("result = %+v, evidence %+v", result, evidence) - } + burnInFailed(t, result, evidence, burnin.TooShort) } // A BMC that reports another serial number gets no verdict: a Failed one @@ -331,58 +338,102 @@ func TestCommissioningRefusesAnotherServer(t *testing.T) { } // A worker killed after the image reported early, before it journaled the -// burn-in done, is replaced later. The replacement's journal time is long -// after the plan's duration, but burn-in ends when the receipt appeared, so -// it still fails as too short. -func TestARestartAfterAnEarlyReceiptStillFailsTooShort(t *testing.T) { - l := newLab(t) - l.burnTime = 0 - r := commissioningRunner(t, l) - spec := planSpec(t, nil) - work := assignment(l, "DeviceCommissioning", "op-early-restart", 1, spec) - work.Snapshot.Extra = map[string]string{custody.SnapshotSerialNumber: "serial-001"} - ctx, cancel := context.WithCancel(context.Background()) - var once sync.Once - l.afterReceipt = func() { - once.Do(func() { - cancel() - // The replacement starts well after the plan's duration. - l.mu.Lock() - l.skew += 10 * time.Minute - l.mu.Unlock() +// burn-in done, is replaced ten minutes later. The replacement's journal +// time is long after the plan's duration, but burn-in ends at the last +// stored sighting without the receipt, so it still fails. A worker that +// watched the receipt appear proves the burn-in too short; when none did, +// the failure says a restart left the burn-in unproven. +func TestARestartAfterAnEarlyReceiptStillFails(t *testing.T) { + for name, c := range map[string]struct { + watched bool + mismatch string + }{ + "receipt seen before the restart": {watched: true, mismatch: burnin.TooShort}, + "receipt printed during the restart": {watched: false, mismatch: burnin.Restarted}, + } { + t.Run(name, func(t *testing.T) { + l := newLab(t) + l.burnTime = 0 + r := commissioningRunner(t, l) + spec := planSpec(t, nil) + work := assignment(l, "DeviceCommissioning", "op-early-restart", 1, spec) + work.Snapshot.Extra = map[string]string{custody.SnapshotSerialNumber: "serial-001"} + ctx, cancel := context.WithCancel(context.Background()) + stopped := make(chan struct{}) + restart := func() { + cancel() + <-stopped + // The replacement starts well after the plan's duration. + l.mu.Lock() + l.skew += 10 * time.Minute + l.mu.Unlock() + } + if c.watched { + // Stop the worker once it has stored its sighting of the + // receipt appearing. + l.afterReceipt = func() { + for { + var record burnin.Record + if _, err := l.store.GetRecord(device, burnin.Records, work.Key(), &record); err != nil || record.Exact { + break + } + time.Sleep(5 * time.Millisecond) + } + restart() + } + } else { + // Stop the worker before the receipt is printed. + l.beforeReceipt = restart + } + _, err := r.Run(ctx, work) + close(stopped) + if !errors.Is(err, context.Canceled) { + t.Fatalf("interrupted: %v", err) + } + // Let the server finish reporting and power off with no worker + // watching. + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(5 * time.Millisecond) { + l.mu.Lock() + off := l.power == "Off" + l.mu.Unlock() + if off { + break + } + if time.Now().After(deadline) { + t.Fatal("the server never powered off") + } + } + journal, err := r.Store.Journal(device) + if err != nil { + t.Fatal(err) + } + for _, entry := range journal { + if entry.Operation == work.Key() && entry.Step == burnInPhase.name+"-verified" && entry.State == site.StepDone { + t.Fatal("the first worker journaled the burn-in before it was stopped") + } + } + l.beforeReceipt, l.afterReceipt = nil, nil + result, err := r.Run(context.Background(), work) + if err != nil { + t.Fatal(err) + } + var evidence ops.CommissioningEvidence + if err := json.Unmarshal(result.Evidence, &evidence); err != nil { + t.Fatalf("result = %+v", result) + } + burnInFailed(t, result, evidence, c.mismatch) + if l.onCount() != 1 { + t.Fatalf("%d power-ons", l.onCount()) + } + if got := evidence.BurnIn.CompletedAt.Sub(evidence.BurnIn.StartedAt.Time); got >= time.Minute { + t.Fatalf("burn-in recorded as %s", got) + } + operation := &ops.DeviceCommissioning{Spec: spec, Status: ops.OperationStatus{Snapshot: &work.Snapshot}} + if _, err := custody.DeviceCommissioningKind().Evidence(operation, result.Evidence); err != nil { + t.Fatalf("the kind rejects the worker's evidence: %v", err) + } }) } - if _, err := r.Run(ctx, work); !errors.Is(err, context.Canceled) { - t.Fatalf("interrupted: %v", err) - } - journal, err := r.Store.Journal(device) - if err != nil { - t.Fatal(err) - } - for _, entry := range journal { - if entry.Operation == work.Key() && entry.Step == burnInPhase.name+"-verified" && entry.State == site.StepDone { - t.Fatal("the first worker journaled the burn-in before it was stopped") - } - } - l.afterReceipt = nil - result, err := r.Run(context.Background(), work) - if err != nil { - t.Fatal(err) - } - var evidence ops.CommissioningEvidence - if err := json.Unmarshal(result.Evidence, &evidence); err != nil { - t.Fatalf("result = %+v", result) - } - if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn || l.onCount() != 1 { - t.Fatalf("result = %+v, evidence %+v, %d power-ons", result, evidence, l.onCount()) - } - if got := evidence.BurnIn.CompletedAt.Sub(evidence.BurnIn.StartedAt.Time); got >= time.Minute { - t.Fatalf("burn-in recorded as %s", got) - } - operation := &ops.DeviceCommissioning{Spec: spec, Status: ops.OperationStatus{Snapshot: &work.Snapshot}} - if _, err := custody.DeviceCommissioningKind().Evidence(operation, result.Evidence); err != nil { - t.Fatalf("the kind rejects the worker's evidence: %v", err) - } } // A baseline matches the entry whose Id it names before any entry by Name, diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 9aa2c9c4..04f8f494 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -28,6 +28,7 @@ import ( "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/burnin" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -385,7 +386,7 @@ func (c Config) started(ctx context.Context, work *site.Work, boot Boot, ph phas func (c Config) complete(ctx context.Context, work *site.Work, boot Boot, ph phase) error { poll, offGrace, outage, _ := c.durations() var offSince, failingSince time.Time - var absence receiptAbsence + var absence burnin.Absence for { power, err := conn(work).Observe(ctx) switch { @@ -400,12 +401,13 @@ func (c Config) complete(ctx context.Context, work *site.Work, boot Boot, ph pha } default: failingSince = time.Time{} + at := work.Store().Now() seen, err := c.receipts(work, boot, ph) if err != nil { return err } if ph.name == burnInPhase.name { - if err := absence.observe(work, seen); err != nil { + if err := absence.Observe(work, at, seen); err != nil { return err } } @@ -490,31 +492,6 @@ func (c Config) deliveries(work *site.Work) map[string]bool { return done } -// deliveredAt is when the boot server finished delivering the operation's -// last boot file, rounded up to the next second because the log records -// whole seconds. The boot server and the worker share the site's clock. -func (c Config) deliveredAt(work *site.Work) (time.Time, bool) { - data, _ := os.ReadFile(filepath.Join(BootDirectory(c.BootRoot, work.Key()), "boot-delivery.log")) - var last time.Time - for _, line := range strings.Split(string(data), "\n") { - fields := strings.Fields(line) - if len(fields) != 4 || fields[1] != "write-complete" { - continue - } - at, err := time.Parse(time.RFC3339, fields[0]) - if err != nil { - return time.Time{}, false - } - if at.After(last) { - last = at - } - } - if last.IsZero() { - return time.Time{}, false - } - return last.Add(time.Second), true -} - func (c Config) verifyDelivery(work *site.Work) error { done := c.deliveries(work) for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 288c76cc..bc51f28a 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -80,9 +80,9 @@ type lab struct { // pxeTime is how long firmware start and the network boot take before // the boot server delivers the image. pxeTime time.Duration - // afterReceipt runs once the receipt is on the console, before the - // server powers off. - afterReceipt func() + // beforeReceipt runs just before the receipt is printed, and + // afterReceipt once it is on the console, before the server powers off. + beforeReceipt, afterReceipt func() } func newLab(t *testing.T) *lab { @@ -216,6 +216,9 @@ func (l *lab) boot(target string) { case target == "Hdd": line = "FLEET-DISK-BOOT:" + boot.Receipt } + if l.beforeReceipt != nil { + l.beforeReceipt() + } file, err := os.OpenFile(l.console, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) if err == nil { fmt.Fprintln(file, line) @@ -503,27 +506,3 @@ func TestAServerThatNeverPowersOffEndsTheStep(t *testing.T) { t.Fatalf("result = %+v, %d power-ons after %s", result, l.onCount(), time.Since(started)) } } - -// The boot log records whole seconds, so a file logged at 10:00:05 may have -// finished at any point up to 10:00:06. Burn-in is timed from the next whole -// second after the last file, so the log's truncation can never shorten the -// time an image must run. -func TestDeliveryIsRoundedUpToTheNextSecond(t *testing.T) { - cfg := Config{BootRoot: t.TempDir()} - work := &site.Work{Assignment: site.Assignment{Device: "metal/server-a", Fence: 1}} - dir := BootDirectory(cfg.BootRoot, work.Key()) - if err := os.MkdirAll(dir, 0o700); err != nil { - t.Fatal(err) - } - log := "2026-01-02T10:00:00Z admitted boot.ipxe bytes=1\n" + - "2026-01-02T10:00:00Z write-complete boot.ipxe bytes=1\n" + - "2026-01-02T10:00:05Z write-complete installer.gz bytes=1\n" + - "2026-01-02T10:00:03Z write-complete kernel bytes=1\n" - if err := os.WriteFile(filepath.Join(dir, "boot-delivery.log"), []byte(log), 0o600); err != nil { - t.Fatal(err) - } - at, ok := cfg.deliveredAt(work) - if want := time.Date(2026, 1, 2, 10, 0, 6, 0, time.UTC); !ok || !at.Equal(want) { - t.Fatalf("deliveredAt = %v, %v; want %v", at, ok, want) - } -} diff --git a/internal/site/vmwork/commissioning.go b/internal/site/vmwork/commissioning.go index aa8c7459..6fa01bb3 100644 --- a/internal/site/vmwork/commissioning.go +++ b/internal/site/vmwork/commissioning.go @@ -17,6 +17,7 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/burnin" "go.datum.net/fleet/internal/site/fixture" ) @@ -31,8 +32,9 @@ const burnInMarker = "FLEET-BURNIN:" // has no BMC, so inspection compares the hardware and firmware the site // enrolls for the Device, which describe the guest the site defines, with the // plan. Burn-in is real: one network boot of the site image in burn-in mode -// on a scratch disk, proven by its console receipt. The scratch disk is -// removed afterwards, so a commissioning leaves no disk behind. +// on a scratch disk, proven by its console receipt and timed by package +// burnin. The scratch disk is removed afterwards, so a commissioning leaves +// no disk behind. type Commissioning struct{ Config } var _ site.Kind = Commissioning{} @@ -64,6 +66,12 @@ func (k Commissioning) Check(_ context.Context, work *site.Work) *custody.Refusa if d := burnIn.Duration.Duration; d < time.Minute || d > 24*time.Hour { return &custody.Refusal{Reason: custody.ReasonInputsUnreadable, Message: "the burn-in duration is outside 1 minute to 24 hours"} } + // Burn-in is timed from the boot server's delivery of the image. A + // direct kernel boot has no boot server, so nothing would record when + // it began. + if !k.PXE { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "the site does not boot the burn-in image from the network"} + } return nil } @@ -89,14 +97,19 @@ func (k Commissioning) Run(ctx context.Context, work *site.Work) (any, error) { at, _ := work.JournaledAt(step) evidence.Steps = append(evidence.Steps, ops.StepEvidence{Name: step, CompletedAt: metav1.NewTime(at.UTC())}) } - started, _ := work.JournaledAt(burnInStage + "-start") - completed, _ := work.JournaledAt(burnInStage + "-verified") - evidence.BurnIn = &ops.BurnInEvidence{Result: result, StartedAt: metav1.NewTime(started.UTC()), CompletedAt: metav1.NewTime(completed.UTC())} + // Neither the guest's start nor the journaled verdict times the burn-in: + // the firmware and network boot would lengthen it, and a worker + // restarted after an early receipt would lengthen it further. + measured, err := burnin.Measure(work, filepath.Join(k.BootRoot, Key(work.Key()), "boot-delivery.log"), plan.BurnIn.Duration.Duration) + if err != nil { + return nil, err + } + evidence.BurnIn = &ops.BurnInEvidence{Result: result, StartedAt: metav1.NewTime(measured.StartedAt.UTC()), CompletedAt: metav1.NewTime(measured.CompletedAt.UTC())} switch { case result != ops.BurnInPassed: evidence.Result, evidence.FailedPhase, evidence.Mismatches = ops.CommissioningFailed, ops.PhaseBurnIn, []string{"the burn-in image reported a failure"} - case completed.Sub(started) < plan.BurnIn.Duration.Duration: - evidence.Result, evidence.FailedPhase, evidence.Mismatches = ops.CommissioningFailed, ops.PhaseBurnIn, []string{"the burn-in reported before the plan's duration"} + case measured.Short != "": + evidence.Result, evidence.FailedPhase, evidence.Mismatches = ops.CommissioningFailed, ops.PhaseBurnIn, []string{measured.Short} default: evidence.Result = ops.CommissioningPassed } @@ -146,7 +159,7 @@ func (k Commissioning) burnIn(ctx context.Context, work *site.Work, duration tim }); err != nil { return "", err } - if k.PXE && !work.Journaled(burnInStage+"-start") { + if !work.Journaled(burnInStage + "-start") { if boot.Closed || !k.now().Before(boot.Expires) { return "", errors.New("the boot admission expired or closed before the network boot") } @@ -165,7 +178,7 @@ func (k Commissioning) burnIn(ctx context.Context, work *site.Work, duration tim // A failed network boot closes its admission at once, as an // installer's does. fail := func(err error) error { - if k.PXE && boot.Open && (ctx.Err() == nil || site.DeadlinePassed(ctx)) { + if boot.Open && (ctx.Err() == nil || site.DeadlinePassed(ctx)) { boot.Open, boot.Closed = false, true _ = install.save(work, boot) } @@ -188,17 +201,15 @@ func (k Commissioning) burnIn(ctx context.Context, work *site.Work, duration tim }); err != nil { return "", fail(err) } - if _, err := k.waitBurnIn(ctx, work, boot); err != nil { + if err := k.waitBurnIn(ctx, work, boot); err != nil { return "", fail(err) } - if k.PXE { - if err := install.verifyNetworkBoot(ctx, work); err != nil { - return "", fail(err) - } - boot.Open, boot.Closed = false, true - if err := install.save(work, boot); err != nil { - return "", err - } + if err := install.verifyNetworkBoot(ctx, work); err != nil { + return "", fail(err) + } + boot.Open, boot.Closed = false, true + if err := install.save(work, boot); err != nil { + return "", err } if err := work.Step(ctx, site.Step{Name: burnInStage + "-verified", Send: func(context.Context) error { return nil }, Idempotent: true}); err != nil { return "", err @@ -208,10 +219,8 @@ func (k Commissioning) burnIn(ctx context.Context, work *site.Work, duration tim if err != nil { return "", err } - if k.PXE { - if err := work.Step(ctx, site.Step{Name: burnInStage + "-network-off", Send: k.stopNetwork, Idempotent: true}); err != nil { - return "", err - } + if err := work.Step(ctx, site.Step{Name: burnInStage + "-network-off", Send: k.stopNetwork, Idempotent: true}); err != nil { + return "", err } // The burn-in only reads its scratch disk; removing it leaves the Device // with no disk the commissioning made. @@ -230,30 +239,46 @@ func (k Commissioning) burnIn(ctx context.Context, work *site.Work, duration tim return result, nil } -// waitBurnIn waits for the guest to stop, then reads its result. -func (k Commissioning) waitBurnIn(ctx context.Context, work *site.Work, boot Boot) (ops.BurnInResult, error) { +// waitBurnIn waits for the guest to stop, reading its console on each poll +// so the burn-in's end is the last time this worker saw no receipt. +func (k Commissioning) waitBurnIn(ctx context.Context, work *site.Work, boot Boot) error { + var absence burnin.Absence for { + // List the domains before reading the console: a guest seen stopped + // has already written everything it will. running, err := Installation(k).running(ctx, work.Key()) if err != nil { - return "", err + return err + } + at := work.Store().Now() + results, err := k.burnInResults(work, boot) + if err != nil { + return err + } + if err := absence.Observe(work, at, len(results)); err != nil { + return err } if !running { - return k.burnInResult(work, boot) + _, err := k.burnInResult(work, boot) + return err } select { case <-ctx.Done(): - return "", context.Cause(ctx) - case <-time.After(time.Second): + return context.Cause(ctx) + case <-time.After(k.poll()): } } } -// burnInResult reads the one result line with this boot's receipt. Any other -// count proves nothing. -func (k Commissioning) burnInResult(work *site.Work, boot Boot) (ops.BurnInResult, error) { +// burnInResults reads the result lines with this boot's receipt. A console +// the guest has not created yet holds none. +func (k Commissioning) burnInResults(work *site.Work, boot Boot) ([]string, error) { data, err := os.ReadFile(filepath.Join(Installation(k).directory(work.Device, work.Key()), burnInStage+".log")) + if os.IsNotExist(err) { + return nil, nil + } if err != nil { - return "", err + return nil, err } prefix := burnInMarker + boot.Receipt + ":" var results []string @@ -262,6 +287,16 @@ func (k Commissioning) burnInResult(work *site.Work, boot Boot) (ops.BurnInResul results = append(results, strings.TrimPrefix(line, prefix)) } } + return results, nil +} + +// burnInResult reads the one result line with this boot's receipt. Any other +// count proves nothing. +func (k Commissioning) burnInResult(work *site.Work, boot Boot) (ops.BurnInResult, error) { + results, err := k.burnInResults(work, boot) + if err != nil { + return "", err + } if len(results) != 1 { return "", errors.New("the guest stopped without exactly one burn-in result") } diff --git a/internal/site/vmwork/commissioning_test.go b/internal/site/vmwork/commissioning_test.go index c3198914..b50d8ce8 100644 --- a/internal/site/vmwork/commissioning_test.go +++ b/internal/site/vmwork/commissioning_test.go @@ -3,6 +3,7 @@ package vmwork import ( "context" "encoding/json" + "errors" "os" "path/filepath" "strings" @@ -15,6 +16,7 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/burnin" "go.datum.net/fleet/internal/site/fixture" ) @@ -22,33 +24,103 @@ import ( var localHardware = &ops.InspectedHardware{CPU: ops.InspectedCPU{Architecture: "amd64", Cores: 2}, Memory: "2Gi", Disks: []ops.InspectedDisk{{Name: "disk-0", Capacity: "2Gi"}}, Interfaces: []ops.InspectedInterface{{Name: "primary", MACAddress: "02:00:00:00:00:01"}}} -// commissioningRig is a rig whose site store clock advances a minute on each -// read, so a burn-in the fake guest finishes at once spans the plan's -// duration in the journal. tick false keeps the real clock. -func commissioningRig(t *testing.T, tick bool) *rig { +// clock is the site's clock, shared by the store and the boot server. Only +// a test moves it. +type clock struct { + mu sync.Mutex + now time.Time +} + +func (c *clock) read() 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) +} + +// commissioningRig is a network-booting rig on a clock only the test moves. +// Its burn-in guest takes boot, on the site's clock, before the boot server +// delivers the image, then runs for burn before it reports. +func commissioningRig(t *testing.T, boot, burn time.Duration) *rig { r := newRig(t) - if tick { - var mu sync.Mutex - now := time.Now().UTC() - store, err := site.OpenStore(filepath.Join(filepath.Dir(r.config.Disks), "store"), func() time.Time { - mu.Lock() - defer mu.Unlock() - now = now.Add(time.Minute) - return now - }) - if err != nil { - t.Fatal(err) - } - r.store, r.runner.Store, r.runner.Results = store, store, site.NewResults(store) + // A whole second, so the boot log's whole seconds are exact. + c := &clock{now: time.Now().UTC().Truncate(time.Second)} + store, err := site.OpenStore(filepath.Join(filepath.Dir(r.config.Disks), "store"), c.read) + if err != nil { + t.Fatal(err) } + r.store, r.runner.Store, r.runner.Results = store, store, site.NewResults(store) + r.clock = c + r.config.PXE, r.config.Now, r.config.Poll = true, c.read, time.Millisecond access := r.runner.Access.(fixture.Access) target := access.Enrollment[device] target.Hardware = localHardware access.Enrollment[device] = target r.runner.Kinds["DeviceCommissioning"] = Commissioning{r.config} + r.vm.burnIn = r.burnInGuest(boot, burn) + r.vm.admission = func() (Boot, bool) { + records, err := store.Records(bootRecords) + if err != nil { + t.Error(err) + } + for _, record := range records { + var boot Boot + if json.Unmarshal(record.Data, &boot) == nil && boot.Open && !boot.Closed { + return boot, true + } + } + return Boot{}, false + } return r } +// burnInGuest is a burn-in guest the worker watches throughout: on the +// first list the boot server delivers the image after boot, on the second +// burn has passed, and on the third the guest reports and stops. +func (r *rig) burnInGuest(boot, burn time.Duration) func(int) (bool, bool) { + return func(lists int) (bool, bool) { + switch lists { + case 1: + r.clock.advance(boot) + r.deliver(r.clock.read()) + case 2: + r.clock.advance(burn) + default: + return true, true + } + return false, false + } +} + +// deliver writes the boot server's delivery log for every operation the +// site has a boot admission for, at the given time. +func (r *rig) deliver(at time.Time) { + r.t.Helper() + records, err := r.store.Records(bootRecords) + if err != nil { + r.t.Fatal(err) + } + for _, record := range records { + dir := filepath.Join(r.config.BootRoot, record.Name) + if err := os.MkdirAll(dir, 0o700); err != nil { + r.t.Fatal(err) + } + stamp := at.UTC().Format(time.RFC3339) + log := stamp + " admitted boot.ipxe bytes=1\n" + for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + log += stamp + " write-complete " + name + " bytes=1\n" + } + if err := os.WriteFile(filepath.Join(dir, "boot-delivery.log"), []byte(log), 0o600); err != nil { + r.t.Fatal(err) + } + } +} + func commissioningSpec(mutate func(*ops.CommissioningPlanContent)) ops.DeviceCommissioningSpec { name, digest, _ := strings.Cut(image, "@") content := ops.CommissioningPlanContent{ @@ -91,7 +163,7 @@ func (r *rig) commission(uid string, spec ops.DeviceCommissioningSpec) (custody. // TestCommissioningBurnsInOnceAndLeavesNoDisk inspects the enrolled guest, // boots the site image once in burn-in mode, and passes on its receipt. func TestCommissioningBurnsInOnceAndLeavesNoDisk(t *testing.T) { - r := commissioningRig(t, true) + r := commissioningRig(t, time.Minute, 2*time.Minute) result, evidence := r.commission("00000000-0000-4000-8000-000000000301", commissioningSpec(nil)) if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningPassed || evidence.BurnIn == nil || evidence.BurnIn.Result != ops.BurnInPassed { t.Fatalf("result = %+v, evidence %+v", result, evidence) @@ -100,36 +172,139 @@ func TestCommissioningBurnsInOnceAndLeavesNoDisk(t *testing.T) { t.Fatalf("boots = %d, want one burn-in boot", r.vm.creates) } xml, err := os.ReadFile(filepath.Join(r.config.directory(device, r.assignment("DeviceCommissioning", "00000000-0000-4000-8000-000000000301", 2, nil).Key()), burnInStage+".xml")) - if err != nil || !strings.Contains(string(xml), "fleet.mode=burnin fleet.duration=60") { - t.Fatalf("the burn-in boot does not pass the mode and duration: %v", err) + if err != nil || !strings.Contains(string(xml), "") { + t.Fatalf("the burn-in does not boot from the network: %v", err) + } + var boot Boot + if found, err := r.store.GetRecord(device, bootRecords, Key(r.assignment("DeviceCommissioning", "00000000-0000-4000-8000-000000000301", 2, nil).Key()), &boot); err != nil || !found || + boot.Mode != burnInStage || boot.DurationSeconds != 60 || boot.Open || !boot.Closed { + t.Fatalf("the burn-in admission = %+v, %v, %v", boot, found, err) } if disks, _ := filepath.Glob(filepath.Join(r.config.Disks, "*", "*", "disk.raw")); len(disks) != 0 { t.Fatalf("the commissioning left disks %v", disks) } } +// burnInFailed checks a proven burn-in failure with the given mismatch. +func burnInFailed(t *testing.T, result custody.SiteResult, evidence ops.CommissioningEvidence, mismatch string) { + t.Helper() + if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn || + len(evidence.Mismatches) != 1 || evidence.Mismatches[0] != mismatch { + t.Fatalf("result = %+v, evidence %+v; want the burn-in to fail with %q", result, evidence, mismatch) + } +} + // TestABurnInFailureOrAShortBurnInFails records a failed burn-in, and one // that reported before the plan's duration, as proven failures. func TestABurnInFailureOrAShortBurnInFails(t *testing.T) { - failing := commissioningRig(t, true) + failing := commissioningRig(t, 0, 2*time.Minute) failing.vm.burnInFails = true if result, evidence := failing.commission("00000000-0000-4000-8000-000000000302", commissioningSpec(nil)); result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn || evidence.BurnIn.Result != ops.BurnInFailed { t.Fatalf("a failed burn-in = %+v, %+v", result, evidence) } - // With the real clock the fake guest reports at once, well short of the - // plan's minute. - short := commissioningRig(t, false) - if result, evidence := short.commission("00000000-0000-4000-8000-000000000303", commissioningSpec(nil)); result.Phase != ops.PhaseSucceeded || - evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseBurnIn { - t.Fatalf("a short burn-in = %+v, %+v", result, evidence) + short := commissioningRig(t, 0, 30*time.Second) + result, evidence := short.commission("00000000-0000-4000-8000-000000000303", commissioningSpec(nil)) + burnInFailed(t, result, evidence, burnin.TooShort) +} + +// TestASlowBootDoesNotLengthenTheBurnIn times the burn-in from the boot +// server's delivery: five minutes of firmware and network boot do not make +// an image that ran thirty seconds long enough. +func TestASlowBootDoesNotLengthenTheBurnIn(t *testing.T) { + r := commissioningRig(t, 5*time.Minute, 30*time.Second) + result, evidence := r.commission("00000000-0000-4000-8000-000000000306", commissioningSpec(nil)) + burnInFailed(t, result, evidence, burnin.TooShort) + if got := evidence.BurnIn.CompletedAt.Sub(evidence.BurnIn.StartedAt.Time); got >= time.Minute { + t.Fatalf("burn-in recorded as %s", got) + } +} + +// TestBurnInStartsTheSecondAfterTheLastDelivery: the boot log records whole +// seconds, so a burn-in that ran exactly the plan's minute from the logged +// second may have run a little less, and fails. +func TestBurnInStartsTheSecondAfterTheLastDelivery(t *testing.T) { + r := commissioningRig(t, 0, time.Minute) + result, evidence := r.commission("00000000-0000-4000-8000-000000000307", commissioningSpec(nil)) + burnInFailed(t, result, evidence, burnin.TooShort) + if got := evidence.BurnIn.CompletedAt.Sub(evidence.BurnIn.StartedAt.Time); got != 59*time.Second { + t.Fatalf("burn-in recorded as %s, want 59s", got) + } +} + +// TestARestartAfterAnEarlyReceiptStillFails stops the worker after the +// image reported early and resumes it ten minutes later. The journal would +// show a burn-in far longer than the plan's, but burn-in ends at the last +// sighting without the receipt, so it still fails. A worker that watched the +// receipt appear proves the burn-in too short; one that did not can only +// say a restart left it unproven. +func TestARestartAfterAnEarlyReceiptStillFails(t *testing.T) { + for name, c := range map[string]struct { + watched bool + mismatch string + }{ + "receipt seen before the restart": {watched: true, mismatch: burnin.TooShort}, + "receipt printed during the restart": {watched: false, mismatch: burnin.Restarted}, + } { + t.Run(name, func(t *testing.T) { + r := commissioningRig(t, 0, 0) + uid := "00000000-0000-4000-8000-000000000308" + spec := commissioningSpec(nil) + work := r.assignment("DeviceCommissioning", uid, 2, spec) + work.Snapshot.Extra = map[string]string{custody.SnapshotSerialNumber: "serial-001"} + ctx, cancel := context.WithCancel(context.Background()) + guest := r.burnInGuest(0, 10*time.Second) + r.vm.burnIn = func(lists int) (bool, bool) { + if lists < 3 { + return guest(lists) + } + // The worker stops while the guest still runs, after it + // read the receipt or before the guest printed it. + cancel() + return c.watched, false + } + if _, err := r.runner.Run(ctx, work); !errors.Is(err, context.Canceled) { + t.Fatalf("interrupted: %v", err) + } + if r.journaled(work, burnInStage+"-verified") { + t.Fatal("the first worker journaled the burn-in before it was stopped") + } + r.vm.finish() + r.clock.advance(10 * time.Minute) + result, evidence := r.commission(uid, spec) + burnInFailed(t, result, evidence, c.mismatch) + if got := evidence.BurnIn.CompletedAt.Sub(evidence.BurnIn.StartedAt.Time); got >= time.Minute { + t.Fatalf("burn-in recorded as %s", got) + } + if r.vm.creates != 1 { + t.Fatalf("boots = %d, want one", r.vm.creates) + } + }) + } +} + +// TestNoSightingIsAZeroLengthBurnIn: a guest that reported before any +// worker read its console leaves no sighting, so nothing shows the burn-in +// ran, and it fails as a restart left it unproven. +func TestNoSightingIsAZeroLengthBurnIn(t *testing.T) { + r := commissioningRig(t, 0, 0) + r.vm.burnIn = func(int) (bool, bool) { + r.deliver(r.clock.read()) + r.clock.advance(10 * time.Minute) + return true, true + } + result, evidence := r.commission("00000000-0000-4000-8000-000000000309", commissioningSpec(nil)) + burnInFailed(t, result, evidence, burnin.Restarted) + if !evidence.BurnIn.CompletedAt.Equal(&evidence.BurnIn.StartedAt) { + t.Fatalf("burn-in recorded as %+v, want zero length", evidence.BurnIn) } } // TestCommissioningChecksBeforeAnyBoot fails a guest that does not meet the -// plan, and refuses a burn-in image the site does not serve, without booting. +// plan, and refuses a burn-in image the site does not serve, or a site that +// cannot time a burn-in from a network boot, without booting. func TestCommissioningChecksBeforeAnyBoot(t *testing.T) { - r := commissioningRig(t, true) + r := commissioningRig(t, 0, 2*time.Minute) result, evidence := r.commission("00000000-0000-4000-8000-000000000304", commissioningSpec(func(c *ops.CommissioningPlanContent) { c.Inspection.CPU.Cores = 4 })) if result.Phase != ops.PhaseSucceeded || evidence.Result != ops.CommissioningFailed || evidence.FailedPhase != ops.PhaseInspect || r.vm.creates != 0 { t.Fatalf("a mismatched guest = %+v, %+v, boots %d", result, evidence, r.vm.creates) @@ -140,4 +315,26 @@ func TestCommissioningChecksBeforeAnyBoot(t *testing.T) { if refused.Phase != ops.PhaseFailed || refused.Reason != custody.ReasonTargetUnsupported || r.vm.creates != 0 { t.Fatalf("another burn-in image = %+v, boots %d", refused, r.vm.creates) } + direct := r.config + direct.PXE = false + r.runner.Kinds["DeviceCommissioning"] = Commissioning{direct} + refused, _ = r.commission("00000000-0000-4000-8000-000000000310", commissioningSpec(nil)) + if refused.Phase != ops.PhaseFailed || refused.Reason != custody.ReasonTargetUnsupported || r.vm.creates != 0 { + t.Fatalf("a direct kernel boot = %+v, boots %d", refused, r.vm.creates) + } +} + +// journaled reports whether a step of the operation is journaled done. +func (r *rig) journaled(work site.Assignment, step string) bool { + r.t.Helper() + journal, err := r.store.Journal(device) + if err != nil { + r.t.Fatal(err) + } + for _, entry := range journal { + if entry.Operation == work.Key() && entry.Step == step && entry.State == site.StepDone { + return true + } + } + return false } diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 938a0b49..a8d3c6c0 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -59,6 +59,16 @@ type Config struct { // Command runs libvirt's virsh. Tests replace it. Command func(ctx context.Context, name string, args ...string) (string, error) Now func() time.Time + // Poll is how often a worker reads a running burn-in guest. Zero means + // a second. + Poll time.Duration +} + +func (c Config) poll() time.Duration { + if c.Poll > 0 { + return c.Poll + } + return time.Second } func (c Config) now() time.Time { diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index 17ebd0f1..7b716135 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -42,6 +42,39 @@ type hypervisor struct { exited bool // burnInFails makes a burn-in guest report a failure. burnInFails bool + // burnIn, when set, scripts a burn-in guest instead of letting it + // report at once. It is called on each domain list while the guest + // runs, with the number of lists so far, and says whether the guest now + // prints its receipt and whether it stops. + burnIn func(lists int) (receipt, stop bool) + burnInLists int + // pending is a scripted burn-in guest's receipt line, by domain. + pending map[string]string + // admission returns the open boot admission a network-booted guest's + // boot script carries, as the boot server would serve it. + admission func() (Boot, bool) +} + +// finish prints every scripted guest's receipt and stops it, as a guest +// that reported while no worker watched. +func (h *hypervisor) finish() { + h.mu.Lock() + defer h.mu.Unlock() + for name := range h.running { + h.print(name) + delete(h.running, name) + } +} + +func (h *hypervisor) print(name string) { + if line, ok := h.pending[name]; ok { + file, err := os.OpenFile(h.running[name], os.O_APPEND|os.O_WRONLY, 0o600) + if err == nil { + _, _ = file.WriteString(line + "\n") + file.Close() + } + delete(h.pending, name) + } } var receiptArg = regexp.MustCompile(`fleet.receipt=([0-9a-f]{64})`) @@ -61,6 +94,13 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e log := regexp.MustCompile(``).FindStringSubmatch(xml)[1] marker := "FLEET-DISK-BOOT:" receipt := "" + if strings.Contains(xml, "") && h.admission != nil { + // The firmware fetches the boot script, which carries the + // admission's receipt and mode. + if boot, ok := h.admission(); ok { + xml += " fleet.receipt=" + boot.Receipt + modeArgs(boot) + } + } if match := receiptArg.FindStringSubmatch(xml); match != nil && strings.Contains(xml, "fleet.mode=burnin") { result := "passed" if h.burnInFails { @@ -80,11 +120,19 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e if h.noReceipt { console = "booting\n" } + scripted := marker == "FLEET-BURNIN:" && h.burnIn != nil + if scripted { + console = "booting\n" + if h.pending == nil { + h.pending = map[string]string{} + } + h.pending[name], h.burnInLists = marker+receipt, 0 + } if err := os.WriteFile(log, []byte(console), 0o600); err != nil { return "", err } h.running[name] = log - if !h.hold { + if !h.hold && !scripted { delete(h.running, name) } case "destroy": @@ -96,11 +144,27 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e delete(h.running, args[1]) } case "list": + for name := range h.running { + if _, ok := h.pending[name]; !ok { + continue + } + h.burnInLists++ + receipt, stop := h.burnIn(h.burnInLists) + if receipt { + h.print(name) + } + if stop { + h.print(name) + delete(h.running, name) + } + } var names []string for name := range h.running { names = append(names, name) } return strings.Join(names, "\n"), nil + case "net-dhcp-leases": + return guestMAC + " 192.168.77.2/24", nil } return "", nil } @@ -111,6 +175,7 @@ type rig struct { runner *site.Runner config Config vm *hypervisor + clock *clock } func newRig(t *testing.T) *rig {