From a25dc2197bd19aedffa5c1a146b6a082e7395fbf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 20:47:57 -0600 Subject: [PATCH 1/8] refactor(redfish): Separate identity from install capabilities Identify walks the Systems collection and verifies the enrolled System with reads only, and records what it offers without requiring it. Discover is Identify followed by the install and cleanup capability checks, so the existing executor behaves as before. A kind that needs no network boot, such as power, can then verify identity alone. Co-Authored-By: Claude Opus 5.5 --- internal/redfish/client.go | 56 +++++++++++++++++++++++++------------- 1 file changed, 37 insertions(+), 19 deletions(-) diff --git a/internal/redfish/client.go b/internal/redfish/client.go index d3e6576a..f1c085ce 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -227,8 +227,13 @@ type System struct { ResetTarget string `json:"resetTarget"` ResetTypes []string `json:"resetTypes"` BootTargets []string `json:"bootTargets"` + // noOnce records that the System does not offer a one-time override. + noOnce bool } +// OffersOnce reports whether the System offers a one-time boot override. +func (s System) OffersOnce() bool { return !s.noOnce } + // Power is one observation of a System's power and boot override state. type Power struct { State string `json:"state"` @@ -251,13 +256,38 @@ type resetAction struct { } } -// Discover walks the service root to the enrolled System. Every member of the -// Systems collection, across all pages, must be read: exactly one must carry -// the enrolled UUID, and it must have the enrolled Id; a member with the -// enrolled Id but another UUID is a renumbered or swapped target. The reset -// target and ActionInfo must belong to that System, and On, ForceOff, Pxe and -// Hdd must be advertised. Discovery issues GETs only. +// Discover is Identify followed by the install and cleanup capability +// checks: On, ForceOff, Pxe and Hdd must be advertised, and a one-time boot +// override offered. func (c *Client) Discover(ctx context.Context, t Target) (System, error) { + sys, err := c.Identify(ctx, t) + if err != nil { + return System{}, err + } + for _, need := range []string{"On", "ForceOff"} { + if !contains(sys.ResetTypes, need) { + return System{}, fmt.Errorf("%w: ResetType %s", ErrUnsupported, need) + } + } + for _, need := range []string{"Pxe", "Hdd"} { + if !contains(sys.BootTargets, need) { + return System{}, fmt.Errorf("%w: boot override target %s", ErrUnsupported, need) + } + } + if sys.noOnce { + return System{}, fmt.Errorf("%w: one-time boot override", ErrUnsupported) + } + return sys, nil +} + +// Identify walks the service root to the enrolled System and reads what it +// offers. Every member of the Systems collection, across all pages, must be +// read: exactly one must carry the enrolled UUID, and it must have the +// enrolled Id; a member with the enrolled Id but another UUID is a renumbered +// or swapped target. The reset target and ActionInfo must belong to that +// System. It requires no capability, so each caller checks what it uses. It +// issues GETs only. +func (c *Client) Identify(ctx context.Context, t Target) (System, error) { api, err := c.connect(ctx) if err != nil { return System{}, err @@ -349,19 +379,7 @@ func (c *Client) Discover(ctx context.Context, t Target) (System, error) { for _, b := range s.Boot.AllowableBootSourceOverrideTargetValues { sys.BootTargets = append(sys.BootTargets, string(b)) } - for _, need := range []string{"On", "ForceOff"} { - if !contains(sys.ResetTypes, need) { - return System{}, fmt.Errorf("%w: ResetType %s", ErrUnsupported, need) - } - } - for _, need := range []string{"Pxe", "Hdd"} { - if !contains(sys.BootTargets, need) { - return System{}, fmt.Errorf("%w: boot override target %s", ErrUnsupported, need) - } - } - if raw.Boot.Enabled != nil && !contains(*raw.Boot.Enabled, "Once") { - return System{}, fmt.Errorf("%w: one-time boot override", ErrUnsupported) - } + sys.noOnce = raw.Boot.Enabled != nil && !contains(*raw.Boot.Enabled, "Once") return sys, nil } From 1c0b28d3708ceaec1acdba6fab054afb35c216e1 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 20:47:57 -0600 Subject: [PATCH 2/8] feat(site): Fence and journal each Device at the site Add the site framework for Device operations. Each Device has a durable fence store and journal on the site's retained volume. A newer fence stops the older worker before the newer one starts, and the site records that confirmation for the coordinator. The journal records each step and its payload before sending it, refuses steps below the stored fence, and replays a step after a crash by observing it. Before anything is sent, the framework checks the inputs' digest, the site's enrollment against the admitted snapshot, the per-Device credential, the approved TLS pin, and the server's identity. Workers stop at their deadline, and results carry the fence and typed evidence. The coordinator records an undeclared worker reason as UndeclaredReason. It is inert: nothing delivers an assignment to it until the cutover. Co-Authored-By: Claude Opus 5.5 --- internal/bmcdiscovery/credentials.go | 13 + internal/custody/coordinator.go | 4 +- internal/custody/extension_test.go | 16 + internal/custody/registry.go | 17 +- internal/custody/results.go | 7 + internal/site/access.go | 107 +++++ internal/site/config.go | 67 ++++ internal/site/config_test.go | 82 ++++ internal/site/results.go | 87 ++++ internal/site/runner.go | 400 +++++++++++++++++++ internal/site/runner_test.go | 577 +++++++++++++++++++++++++++ internal/site/store.go | 401 +++++++++++++++++++ internal/site/store_test.go | 195 +++++++++ 13 files changed, 1970 insertions(+), 3 deletions(-) create mode 100644 internal/site/access.go create mode 100644 internal/site/config.go create mode 100644 internal/site/config_test.go create mode 100644 internal/site/results.go create mode 100644 internal/site/runner.go create mode 100644 internal/site/runner_test.go create mode 100644 internal/site/store.go create mode 100644 internal/site/store_test.go diff --git a/internal/bmcdiscovery/credentials.go b/internal/bmcdiscovery/credentials.go index 7ef7e77f..a6b2746e 100644 --- a/internal/bmcdiscovery/credentials.go +++ b/internal/bmcdiscovery/credentials.go @@ -84,3 +84,16 @@ func selectCredential(secrets []corev1.Secret) (cred Credential, found bool, err } return cred, true, nil } + +// CredentialFor returns the credential for one Device, named +// "/" in project, from the credential Secrets of its site. +// The site worker uses it, with the same contract as discovery. +func CredentialFor(secrets []corev1.Secret, project, device string) (Credential, bool, error) { + var matched []corev1.Secret + for index := range secrets { + if deviceKey(&secrets[index], project) == device { + matched = append(matched, secrets[index]) + } + } + return selectCredential(matched) +} diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 8542ea6a..6be3aed9 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -20,8 +20,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -// Sites reports what each site serving a Device has stored. Delivery and -// results are added in Increment B; until then tests supply a fake. +// Sites reports what each site serving a Device has stored. The site +// framework's Report implements it for one site; tests supply a fake. type Sites interface { // Serving returns the sites explicitly configured to serve the Device. // The coordinator never infers a site from placement. diff --git a/internal/custody/extension_test.go b/internal/custody/extension_test.go index 65d70b52..526cb12b 100644 --- a/internal/custody/extension_test.go +++ b/internal/custody/extension_test.go @@ -203,6 +203,22 @@ func TestExtensionSeams(t *testing.T) { e.requirePhase(refused, ops.PhaseFailed, ReasonNotRetryable) }) + t.Run("a worker result with a reason its kind never declared is recorded as UndeclaredReason", func(t *testing.T) { + e := e.sub(t) + device := fresh() + operation := e.staffOp(device, "ok") + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + if err := e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseFailed, Reason: "InventedAtTheSite"}); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + status := e.requirePhase(operation, ops.PhaseFailed, ReasonUndeclared) + if !strings.Contains(status.Message, "InventedAtTheSite") { + t.Fatalf("message = %s", status.Message) + } + }) + t.Run("a worker refusal with nothing sent ends Failed and returns a Service holder to None", func(t *testing.T) { e := e.sub(t) device := fresh() diff --git a/internal/custody/registry.go b/internal/custody/registry.go index 13cc2d8c..f45a9f96 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -227,8 +227,23 @@ const ( ReasonSnapshotInvalid = "SnapshotInvalid" ) +// Reasons the site framework raises for any kind. +const ( + ReasonUnsupportedKind = "UnsupportedKind" + ReasonInputMismatch = "InputMismatch" + ReasonCredentialMissing = "CredentialMissing" + ReasonPinNotApproved = "PinNotApproved" + ReasonPublicKeyMismatch = "PublicKeyMismatch" + ReasonNotEnrolled = "NotEnrolled" + ReasonBMCUnavailable = "BMCUnavailable" + ReasonWorkerRunning = "OlderWorkerRunning" + ReasonStale = "Stale" + ReasonStepUnknown = "StepOutcomeUnknown" +) + // sharedReasons are the reasons every kind may raise. -var sharedReasons = []string{ReasonCustodyUnverified, ReasonCreatorNotPermitted, ReasonHolderMismatch, ReasonOperationInProgress, ReasonDeviceIdentityMismatch, +var sharedReasons = []string{ReasonUnsupportedKind, ReasonInputMismatch, ReasonCredentialMissing, ReasonPinNotApproved, ReasonPublicKeyMismatch, + ReasonNotEnrolled, ReasonBMCUnavailable, ReasonWorkerRunning, ReasonStale, ReasonStepUnknown, ReasonCustodyUnverified, ReasonCreatorNotPermitted, ReasonHolderMismatch, ReasonOperationInProgress, ReasonDeviceIdentityMismatch, ReasonSharedPublicKey, ReasonRecoveryHold, ReasonNameMismatch, ReasonExpired, ReasonSuperseded, ReasonWithdrawn, ReasonDeadlineExceeded, ReasonSiteNotConfirmed, ReasonSiteUnknown, ReasonInvalidEvidence, ReasonUndeclared, ReasonSnapshotInvalid} diff --git a/internal/custody/results.go b/internal/custody/results.go index 75ad3cb2..8a69b9ff 100644 --- a/internal/custody/results.go +++ b/internal/custody/results.go @@ -123,6 +123,13 @@ func (c *Coordinator) AcceptResult(ctx context.Context, result SiteResult) error default: return fmt.Errorf("a site cannot report phase %q", result.Phase) } + // A worker reports only reasons that are shared or that its kind + // declares. + reason, message := result.Reason, result.Message + if reason != "" && !c.Registry.Declared(kind.GVK.Kind, reason, RaisedByWorker) { + reason, message = ReasonUndeclared, fmt.Sprintf("the site reported %s, which %s does not declare", reason, kind.GVK.Kind) + } + result.Reason, result.Message = reason, message var evidence []byte if result.Phase == ops.PhaseSucceeded && kind.EvidenceRequired && len(result.Evidence) == 0 { c.holdUnknown(custody, *active, ReasonInvalidEvidence, "the kind requires evidence, and the site sent none", nil) diff --git a/internal/site/access.go b/internal/site/access.go new file mode 100644 index 00000000..c3c44793 --- /dev/null +++ b/internal/site/access.go @@ -0,0 +1,107 @@ +package site + +import ( + "context" + "errors" + "strings" + "time" + + "go.datum.net/fleet/internal/bmcdiscovery" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" +) + +// Access is the framework's check that it is safe to reach a Device's +// server, and the connection a kind then uses. It reads the credential, the +// enrollment and the server's identity, and changes nothing. Adding an access +// type, such as the local VM's, does not change the Kind contract. +type Access interface { + Prepare(ctx context.Context, assignment Assignment) (any, *custody.Refusal) +} + +// Credentials looks up a Device's BMC credential at the site. +type Credentials interface { + Lookup(ctx context.Context, device string) (bmcdiscovery.Credential, bool, error) +} + +// Targets is the site's enrollment: the Redfish System and boot NIC of each +// Device it serves. It is a site-local fact, checked against the snapshot. +type Targets interface { + Target(device string) (redfish.Target, bool) +} + +// RedfishConnection is what RedfishAccess prepares: the enrolled target, the +// System whose identity it verified, and a client pinned to the approved +// key. The framework checks identity only; each kind checks the capabilities +// it uses, such as boot targets or reset types, on System. +type RedfishConnection struct { + Target redfish.Target + System redfish.System + BMC *redfish.Client +} + +// Observe reads the verified System's power and boot override. +func (c *RedfishConnection) Observe(ctx context.Context) (redfish.Power, error) { + return c.BMC.Observe(ctx, c.System) +} + +// Reset posts one ComputerSystem.Reset to the verified System. +func (c *RedfishConnection) Reset(ctx context.Context, kind string) error { + return c.BMC.Reset(ctx, c.System, kind) +} + +// SetBootOnce arms one boot override on the verified System. +func (c *RedfishConnection) SetBootOnce(ctx context.Context, target string) error { + return c.BMC.SetBootOnce(ctx, c.System, target) +} + +// RedfishAccess reaches a server through its BMC. It checks the site's +// enrollment against the admitted snapshot, reads the per-Device credential, +// requires the operator-approved pin to equal the key discovery recorded at +// admission, and reads the BMC only over a connection pinned to that key. +type RedfishAccess struct { + Credentials Credentials + Targets Targets + // Dial opens a client pinned to the approved key. Tests replace it. + Dial func(endpoint, username, password, pin string) (*redfish.Client, error) +} + +func (a RedfishAccess) Prepare(ctx context.Context, assignment Assignment) (any, *custody.Refusal) { + target, ok := a.Targets.Target(assignment.Device) + if !ok { + return nil, &custody.Refusal{Reason: ReasonNotEnrolled, Message: "this site does not serve the Device"} + } + snapshot := assignment.Snapshot + if !strings.EqualFold(target.SystemUUID, snapshot.SystemUUID) || target.Endpoint != snapshot.BMCEndpoint || (snapshot.BootMACAddress != "" && !strings.EqualFold(target.MAC, snapshot.BootMACAddress)) { + return nil, &custody.Refusal{Reason: custody.ReasonDeviceIdentityMismatch, Message: "the site's enrollment does not match the admitted snapshot"} + } + credential, found, err := a.Credentials.Lookup(ctx, assignment.Device) + switch { + case err != nil || !found: + return nil, &custody.Refusal{Reason: ReasonCredentialMissing, Message: "no usable BMC credential is on record for the Device"} + case credential.Pin == "": + return nil, &custody.Refusal{Reason: ReasonPinNotApproved, Message: "no operator has approved the BMC's key"} + case credential.Pin != snapshot.BMCPublicKeySHA256: + return nil, &custody.Refusal{Reason: ReasonPublicKeyMismatch, Message: "the approved key differs from the key discovery recorded at admission"} + } + dial := a.Dial + if dial == nil { + dial = func(endpoint, username, password, pin string) (*redfish.Client, error) { + return redfish.NewPinnedClient(endpoint, username, password, pin, 30*time.Second) + } + } + client, err := dial(target.Endpoint, credential.Username, credential.Password, credential.Pin) + if err != nil { + return nil, &custody.Refusal{Reason: ReasonBMCUnavailable, Message: "a pinned BMC client could not be built"} + } + system, err := client.Identify(ctx, target) + switch { + case errors.Is(err, redfish.ErrPinMismatch): + return nil, &custody.Refusal{Reason: ReasonPublicKeyMismatch, Message: "the BMC presented a key other than the approved one"} + case errors.Is(err, redfish.ErrIdentity): + return nil, &custody.Refusal{Reason: custody.ReasonDeviceIdentityMismatch, Message: "the BMC reports another system"} + case err != nil: + return nil, &custody.Refusal{Reason: ReasonBMCUnavailable, Message: "the BMC could not be read"} + } + return &RedfishConnection{Target: target, System: system, BMC: client}, nil +} diff --git a/internal/site/config.go b/internal/site/config.go new file mode 100644 index 00000000..0e831754 --- /dev/null +++ b/internal/site/config.go @@ -0,0 +1,67 @@ +package site + +import ( + "context" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/bmcdiscovery" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" + corev1 "k8s.io/api/core/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// SecretCredentials reads per-Device BMC credential Secrets in the site +// cluster, using the contract BMC discovery uses. The approved pin comes from +// the same Secret. +type SecretCredentials struct { + Reader client.Reader + Namespace string + // Project is the provider project the Devices belong to. + Project string +} + +func (s SecretCredentials) Lookup(ctx context.Context, device string) (bmcdiscovery.Credential, bool, error) { + var secrets corev1.SecretList + if err := s.Reader.List(ctx, &secrets, client.InNamespace(s.Namespace), client.MatchingLabels{bmcdiscovery.CredentialLabel: "true"}); err != nil { + return bmcdiscovery.Credential{}, false, err + } + return bmcdiscovery.CredentialFor(secrets.Items, s.Project, device) +} + +// StaticTargets is a site's explicit enrollment, keyed by +// "/". The site never infers which Devices it serves. +type StaticTargets map[string]redfish.Target + +func (t StaticTargets) Target(device string) (redfish.Target, bool) { + target, ok := t[device] + return target, ok +} + +// Report is the site's fence report for the coordinator. Targets is the +// explicit list of Devices this site serves. +type Report struct { + Site string + Store *Store + Targets StaticTargets +} + +var _ custody.Sites = Report{} + +func (r Report) Serving(device *inventory.Device) []string { + if _, ok := r.Targets[device.Namespace+"/"+device.Name]; ok { + return []string{r.Site} + } + return nil +} + +func (r Report) Fence(_ context.Context, site string, device *inventory.Device) (custody.SiteFence, bool, error) { + if site != r.Site { + return custody.SiteFence{}, false, nil + } + fence, stopped, err := r.Store.Current(device.Namespace + "/" + device.Name) + if err != nil { + return custody.SiteFence{}, false, err + } + return custody.SiteFence{Seen: fence, Stopped: stopped}, true, nil +} diff --git a/internal/site/config_test.go b/internal/site/config_test.go new file mode 100644 index 00000000..e15305f1 --- /dev/null +++ b/internal/site/config_test.go @@ -0,0 +1,82 @@ +package site + +import ( + "context" + "strings" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/bmcdiscovery" + "go.datum.net/fleet/internal/custody" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func credentialSecret(name, project, device string, data map[string]string) *corev1.Secret { + secret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "fleet-site", UID: types.UID("uid-" + name), ResourceVersion: "1", + Labels: map[string]string{bmcdiscovery.CredentialLabel: "true"}, + Annotations: map[string]string{bmcdiscovery.ProjectAnnotation: project, bmcdiscovery.NamespaceAnnotation: "default", bmcdiscovery.NameAnnotation: device}}} + secret.Data = map[string][]byte{} + for key, value := range data { + secret.Data[key] = []byte(value) + } + return secret +} + +func TestSecretCredentialsUseThePerDeviceContract(t *testing.T) { + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + pin := strings.Repeat("ab", 32) + reader := fake.NewClientBuilder().WithScheme(scheme).WithObjects( + credentialSecret("server-a", "provider-example", "server-example-001", map[string]string{"username": "operator", "password": "synthetic-secret", "tlsPublicKeySHA256": pin}), + credentialSecret("server-b", "provider-example", "server-example-002", map[string]string{"username": "operator", "password": "synthetic-secret"}), + credentialSecret("server-b-2", "provider-example", "server-example-002", map[string]string{"username": "other", "password": "synthetic-secret"}), + credentialSecret("elsewhere", "provider-other", "server-example-003", map[string]string{"username": "operator", "password": "synthetic-secret"}), + ).Build() + credentials := SecretCredentials{Reader: reader, Namespace: "fleet-site", Project: "provider-example"} + ctx := context.Background() + credential, found, err := credentials.Lookup(ctx, "default/server-example-001") + if err != nil || !found || credential.Username != "operator" || credential.Pin != pin { + t.Fatalf("credential = %+v %v %v", credential, found, err) + } + // Two Secrets naming one Device are a conflict, never a choice. + if _, _, err := credentials.Lookup(ctx, "default/server-example-002"); err == nil { + t.Fatal("two credential Secrets for one Device were accepted") + } + // A Secret for another project's Device is not this Device's. + if _, found, _ := credentials.Lookup(ctx, "default/server-example-003"); found { + t.Fatal("another project's credential was used") + } +} + +func TestReportGivesTheCoordinatorSeenAndStoppedFences(t *testing.T) { + store := newStore(t) + report := Report{Site: "site-example-a", Store: store, Targets: StaticTargets{"default/server-example-001": {}}} + var _ custody.Sites = report + served := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "server-example-001"}} + other := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "server-example-002"}} + if sites := report.Serving(served); len(sites) != 1 || sites[0] != "site-example-a" { + t.Fatalf("serving = %v", sites) + } + if sites := report.Serving(other); len(sites) != 0 { + t.Fatal("the site claims a Device it does not enroll") + } + if err := store.Raise("default/server-example-001", 4); err != nil { + t.Fatal(err) + } + fence, reported, err := report.Fence(context.Background(), "site-example-a", served) + if err != nil || !reported || fence.Seen != 4 || fence.Stopped != 0 { + t.Fatalf("fence = %+v %v %v", fence, reported, err) + } + if err := store.ConfirmStopped("default/server-example-001", 4); err != nil { + t.Fatal(err) + } + if fence, _, _ := report.Fence(context.Background(), "site-example-a", served); fence.Stopped != 4 { + t.Fatalf("fence = %+v", fence) + } +} diff --git a/internal/site/results.go b/internal/site/results.go new file mode 100644 index 00000000..ce63ba61 --- /dev/null +++ b/internal/site/results.go @@ -0,0 +1,87 @@ +package site + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "sort" + + "go.datum.net/fleet/internal/custody" +) + +// Results is the site's copy of each result until the coordinator accepts or +// rejects it. Results live beside the Device's journal. +type Results struct{ store *Store } + +func NewResults(store *Store) *Results { return &Results{store: store} } + +type storedResult struct { + Device string `json:"device"` + Result custody.SiteResult `json:"result"` +} + +func (r *Results) dir(device string) string { + return filepath.Join(r.store.deviceDir(device), "results") +} + +// Put stores a result, named by its operation UID and fence. +func (r *Results) Put(device string, result custody.SiteResult) error { + dir := r.dir(device) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + return writeAtomic(dir, resultName(result), storedResult{Device: device, Result: result}) +} + +func resultName(result custody.SiteResult) string { + return result.Operation.UID + "-" + jsonInt(result.Fence) + ".json" +} + +func jsonInt(value int64) string { data, _ := json.Marshal(value); return string(data) } + +// Pending returns every stored result, oldest file name first. +func (r *Results) Pending() ([]storedResult, error) { + paths, err := filepath.Glob(filepath.Join(r.store.root, "devices", "*", "results", "*.json")) + if err != nil { + return nil, err + } + sort.Strings(paths) + var out []storedResult + for _, path := range paths { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var stored storedResult + if err := json.Unmarshal(data, &stored); err != nil { + return nil, errors.New("site: a stored result is unreadable") + } + out = append(out, stored) + } + return out, nil +} + +// Deliver offers every stored result to accept, which reports it to the +// coordinator. The site deletes its copy once the coordinator accepts it or +// rejects it for a stale fence. Any other error keeps the copy for the next +// delivery. +func (r *Results) Deliver(ctx context.Context, accept func(context.Context, custody.SiteResult) error) error { + pending, err := r.Pending() + if err != nil { + return err + } + var failed error + for _, stored := range pending { + err := accept(ctx, stored.Result) + if err != nil && !errors.Is(err, custody.ErrStaleFence) { + failed = errors.Join(failed, err) + continue + } + if err := os.Remove(filepath.Join(r.dir(stored.Device), resultName(stored.Result))); err != nil && !os.IsNotExist(err) { + return err + } + } + return failed +} diff --git a/internal/site/runner.go b/internal/site/runner.go new file mode 100644 index 00000000..eb016315 --- /dev/null +++ b/internal/site/runner.go @@ -0,0 +1,400 @@ +package site + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" +) + +// Assignment is the handoff payload: one admitted operation, its fence and +// deadline, the Device snapshot the coordinator captured at admission, and +// the exact inputs. Bootstrap, when it is supported, arrives as a sealed +// reference and digest, never as a payload. It replaces the request JSON of +// the old handoff in Increment C. +type Assignment struct { + // Device is "/" in the provider project. + Device string `json:"device"` + Operation ops.OperationReference `json:"operation"` + Fence int64 `json:"fence"` + AdmittedAt time.Time `json:"admittedAt"` + Deadline time.Time `json:"deadline"` + Snapshot ops.DeviceSnapshot `json:"snapshot"` + InputDigest string `json:"inputDigest"` + // Inputs is the operation's spec exactly as admitted. Its SHA-256 is + // InputDigest. + Inputs json.RawMessage `json:"inputs"` + Sealed *ops.SealedInput `json:"sealed,omitempty"` +} + +const maxInputs = 16 << 10 + +// Validate checks the payload's shape. It does not check the inputs +// against their digest; the worker does, before anything is sent. +func (a Assignment) Validate() error { + namespace, name, ok := strings.Cut(a.Device, "/") + switch { + case !ok || namespace == "" || name == "" || strings.Contains(name, "/"): + return errors.New("site: an assignment names one Device as namespace/name") + case a.Operation.Kind == "" || a.Operation.Name == "" || a.Operation.UID == "": + return errors.New("site: an assignment names one operation incarnation") + case a.Fence < 1 || a.AdmittedAt.IsZero() || a.Deadline.IsZero() || !a.AdmittedAt.Before(a.Deadline) || a.InputDigest == "": + return errors.New("site: an assignment carries a fence, its admission time, a later deadline and an input digest") + case len(a.Inputs) == 0 || len(a.Inputs) > maxInputs: + return errors.New("site: an assignment carries bounded inputs") + case a.Snapshot.BMCEndpoint == "" || a.Snapshot.SystemUUID == "" || a.Snapshot.BMCPublicKeySHA256 == "": + return errors.New("site: an assignment carries the Device snapshot") + } + return nil +} + +// Reasons the site framework reports. They are shared reasons in custody, +// so every kind may report them. A refusal ends the operation Failed when +// nothing was sent for it, and OutcomeUnknown otherwise. +const ( + ReasonUnsupportedKind = custody.ReasonUnsupportedKind + ReasonInputMismatch = custody.ReasonInputMismatch + ReasonCredentialMissing = custody.ReasonCredentialMissing + ReasonPinNotApproved = custody.ReasonPinNotApproved + ReasonPublicKeyMismatch = custody.ReasonPublicKeyMismatch + ReasonNotEnrolled = custody.ReasonNotEnrolled + ReasonBMCUnavailable = custody.ReasonBMCUnavailable + ReasonWorkerRunning = custody.ReasonWorkerRunning + ReasonStale = custody.ReasonStale + ReasonSuperseded = custody.ReasonSuperseded + ReasonDeadline = custody.ReasonDeadlineExceeded + ReasonStep = custody.ReasonStepUnknown +) + +// Work is what a kind sees while it runs. +type Work struct { + Assignment + // Connection is what the site's Access prepared, such as a + // *RedfishConnection. A kind asserts the type it supports. + Connection any + store *Store + sent bool +} + +// Kind is the site worker contract for one operation kind. +type Kind interface { + // Check runs after the site's Access has checked the credential, the + // pin and the identity, and before anything is sent. It may read the + // server but must not change it. + Check(ctx context.Context, work *Work) *custody.Refusal + // Run performs the kind's effects, each through Work.Step, and returns + // its typed evidence. + Run(ctx context.Context, work *Work) (any, error) +} + +// Step is one effect a kind sends to the server. +type Step struct { + // Name is unique within the operation. + Name string + // Payload is the kind's bounded record of the step, journaled before it + // is sent, such as the send time or the power state before it. + Payload any + Send func(context.Context) error + // Observe decides, from the server and the journaled payload, whether a + // step found journaled but not done took effect. + Observe func(ctx context.Context, payload json.RawMessage) (bool, error) + // Idempotent marks a step that is safe to send again after a crash, + // such as powering off before a boot of this phase was requested. + Idempotent bool +} + +// StartBy is implemented by a kind whose work must begin soon after +// admission. A worker that has sent nothing and starts later than the +// window after the admission time refuses as Stale. +type StartBy interface { + StartBy() time.Duration +} + +// Store is the site's store, for a kind's per-operation records. +func (w *Work) Store() *Store { return w.store } + +// Step journals a step, then sends it, then records it done. A step found +// journaled but not done, after a crash or a lost response, is observed +// instead of sent again, unless it is Idempotent; if the observation cannot +// show it took effect, the outcome is unknown. A step below the stored fence +// is refused. +func (w *Work) Step(ctx context.Context, step Step) error { + if err := ctx.Err(); err != nil { + return context.Cause(ctx) + } + var payload json.RawMessage + if step.Payload != nil { + data, err := json.Marshal(step.Payload) + if err != nil { + return err + } + payload = data + } + name := step.Name + prior, recorded, err := w.store.IntendWithPayload(w.Device, w.Fence, w.Operation.UID, name, payload) + switch { + case errors.Is(err, ErrStaleFence): + return errSuperseded + case errors.Is(err, ErrStepReplayed) && step.Idempotent: + w.sent = true + if err := step.Send(ctx); err != nil { + return err + } + case errors.Is(err, ErrStepReplayed): + w.sent = true + if step.Observe == nil { + return fmt.Errorf("%w: %s", errStepUnknown, name) + } + done, err := step.Observe(ctx, recorded) + if err != nil { + return err + } + if !done { + return fmt.Errorf("%w: %s", errStepUnknown, name) + } + case err != nil: + return err + case prior == StepDone: + return nil + default: + w.sent = true + if err := step.Send(ctx); err != nil { + return err + } + } + if err := w.store.Done(w.Device, w.Fence, w.Operation.UID, name); errors.Is(err, ErrStaleFence) { + return errSuperseded + } else if err != nil { + return err + } + return nil +} + +var ( + errSuperseded = errors.New("a newer operation was admitted for the Device") + errStepUnknown = errors.New("a journaled step's outcome could not be observed") +) + +// Runner runs assignments at one site. +type Runner struct { + Site string + Store *Store + Results *Results + // Access checks that it is safe to reach the Device's server and opens + // the connection kinds use. Redfish sites use RedfishAccess; the local + // VM and simulator executors add their own in Increment C. + Access Access + Kinds map[string]Kind + // Poll is how often a worker checks for a newer fence and for the run + // lock. It defaults to one second. + Poll time.Duration + Now func() time.Time +} + +func (r *Runner) now() time.Time { + if r.Now != nil { + return r.Now() + } + return time.Now() +} + +func (r *Runner) poll() time.Duration { + if r.Poll > 0 { + return r.Poll + } + return time.Second +} + +// Fence raises the Device's fence for an assignment, waits until no older +// worker runs, and records the stop confirmation the coordinator reads. A +// DeviceRecovery is delivered this way and runs nothing else. +func (r *Runner) Fence(ctx context.Context, assignment Assignment) error { + if err := assignment.Validate(); err != nil { + return err + } + lock, err := r.acquire(ctx, assignment) + if err != nil { + return err + } + lock.release() + return nil +} + +// acquire raises the fence, waits for the run lock until the deadline, and +// confirms that older workers stopped. +func (r *Runner) acquire(ctx context.Context, assignment Assignment) (*runLock, error) { + if err := r.Store.Raise(assignment.Device, assignment.Fence); err != nil { + return nil, err + } + ctx, cancel := context.WithDeadline(ctx, assignment.Deadline) + defer cancel() + for { + lock, err := r.Store.tryRunLock(assignment.Device) + if err != nil { + return nil, err + } + if lock != nil { + if err := r.Store.ConfirmStopped(assignment.Device, assignment.Fence); err != nil { + lock.release() + return nil, err + } + return lock, nil + } + select { + case <-ctx.Done(): + return nil, errWorkerRunning + case <-time.After(r.poll()): + } + } +} + +var errWorkerRunning = errors.New("an older worker did not stop before the deadline") + +// Run executes one assignment and stores its result. It returns +// ErrStaleFence, and stores nothing, for an assignment below the Device's +// stored fence. +func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteResult, error) { + if err := assignment.Validate(); err != nil { + return custody.SiteResult{}, err + } + result := custody.SiteResult{Site: r.Site, Device: deviceName(assignment.Device), Operation: assignment.Operation, Fence: assignment.Fence} + finish := func(phase ops.Phase, reason, message string, evidence []byte) (custody.SiteResult, error) { + result.Phase, result.Reason, result.Message, result.Evidence = phase, reason, message, evidence + if err := r.Results.Put(assignment.Device, result); err != nil { + return result, err + } + return result, nil + } + lock, err := r.acquire(ctx, assignment) + switch { + case errors.Is(err, ErrStaleFence): + return custody.SiteResult{}, err + case errors.Is(err, errWorkerRunning): + return finish(ops.PhaseFailed, ReasonWorkerRunning, err.Error(), nil) + case err != nil: + return custody.SiteResult{}, err + } + defer lock.release() + // The worker stops at its deadline exactly, and as soon as a newer fence + // is stored for the Device. + ctx, cancel := context.WithDeadlineCause(ctx, assignment.Deadline, errDeadline) + defer cancel() + ctx, stop := context.WithCancelCause(ctx) + defer stop(nil) + go r.watch(ctx, assignment, stop) + + work := &Work{Assignment: assignment, store: r.Store} + // Whether anything may have been sent comes from the journal, not from + // this process: an earlier worker for the same operation may have sent + // steps before it was interrupted. + journal, err := r.Store.Journal(assignment.Device) + if err != nil { + return custody.SiteResult{}, err + } + work.sent = slices.ContainsFunc(journal, func(entry Entry) bool { return entry.Operation == assignment.Operation.UID }) + end := func(reason, message string) (custody.SiteResult, error) { + if work.sent { + return finish(ops.PhaseOutcomeUnknown, reason, message, nil) + } + return finish(ops.PhaseFailed, reason, message, nil) + } + if !r.now().Before(assignment.Deadline) { + return end(ReasonDeadline, errDeadline.Error()) + } + // A kind that must start soon after admission refuses a late start, but + // a resumed worker finishes what an earlier one began. + if kind, ok := r.Kinds[assignment.Operation.Kind].(StartBy); ok && !work.sent && r.now().After(assignment.AdmittedAt.Add(kind.StartBy())) { + return end(ReasonStale, "the worker started too long after admission") + } + if refusal := r.prepare(ctx, work); refusal != nil { + return end(refusal.Reason, refusal.Message) + } + evidence, err := r.Kinds[assignment.Operation.Kind].Run(ctx, work) + if err != nil { + var refusal *custody.Refusal + if errors.As(err, &refusal) { + return end(refusal.Reason, refusal.Message) + } + // With nothing journaled for the operation, nothing was sent. + return end(outcomeReason(ctx, err), sanitize(err)) + } + data, err := json.Marshal(evidence) + if err != nil { + return finish(ops.PhaseOutcomeUnknown, ReasonStep, "the evidence could not be encoded", nil) + } + return finish(ops.PhaseSucceeded, "", "", data) +} + +var errDeadline = errors.New("the operation's deadline passed") + +func outcomeReason(ctx context.Context, err error) string { + switch cause := context.Cause(ctx); { + case errors.Is(err, errSuperseded) || errors.Is(cause, errSuperseded): + return ReasonSuperseded + case errors.Is(cause, errDeadline): + return ReasonDeadline + } + return ReasonStep +} + +// sanitize keeps a result's message free of BMC responses and endpoints. +func sanitize(err error) string { + switch { + case errors.Is(err, errSuperseded): + return errSuperseded.Error() + case errors.Is(err, errStepUnknown): + return errStepUnknown.Error() + case errors.Is(err, context.DeadlineExceeded), errors.Is(err, errDeadline): + return errDeadline.Error() + } + return "the worker stopped before it could prove the outcome" +} + +// watch cancels the worker when a newer fence is stored for the Device. +func (r *Runner) watch(ctx context.Context, assignment Assignment, stop context.CancelCauseFunc) { + ticker := time.NewTicker(r.poll()) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + if fence, _, err := r.Store.Current(assignment.Device); err == nil && fence > assignment.Fence { + stop(errSuperseded) + return + } + } + } +} + +// prepare runs every check the framework owns before a kind runs. Each +// refuses with a named reason and sends nothing. +func (r *Runner) prepare(ctx context.Context, work *Work) *custody.Refusal { + assignment := work.Assignment + kind, ok := r.Kinds[assignment.Operation.Kind] + if !ok { + return &custody.Refusal{Reason: ReasonUnsupportedKind, Message: "this site runs no worker for the kind"} + } + if sum := sha256.Sum256(assignment.Inputs); "sha256:"+hex.EncodeToString(sum[:]) != assignment.InputDigest { + return &custody.Refusal{Reason: ReasonInputMismatch, Message: "the inputs do not match the admitted digest"} + } + connection, refusal := r.Access.Prepare(ctx, assignment) + if refusal != nil { + return refusal + } + work.Connection = connection + return kind.Check(ctx, work) +} + +func deviceName(device string) string { + _, name, _ := strings.Cut(device, "/") + return name +} diff --git a/internal/site/runner_test.go b/internal/site/runner_test.go new file mode 100644 index 00000000..2283e9da --- /dev/null +++ b/internal/site/runner_test.go @@ -0,0 +1,577 @@ +package site + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/json" + "errors" + "math/big" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/bmcdiscovery" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" +) + +const ( + testUUID = "00000000-0000-4000-8000-000000000001" + otherUUID = "00000000-0000-4000-8000-000000000002" + testDevice = "default/server-example-001" + testMAC = "02:00:00:00:00:01" +) + +// bmc is a TLS Redfish stub that records every request it receives. +type bmc struct { + mu sync.Mutex + uuid string + // bootTargets defaults to Pxe and Hdd. + bootTargets []string + requests []string + server *httptest.Server +} + +// newBMC serves a Redfish stub over TLS with its own freshly generated key. +// httptest's default certificate is shared by every test server, so each BMC +// gets its own. +func newBMC(t *testing.T, uuid string) *bmc { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}} + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + b := &bmc{uuid: uuid} + b.server = httptest.NewUnstartedServer(b) + b.server.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}} + b.server.StartTLS() + t.Cleanup(b.server.Close) + return b +} + +func (b *bmc) pin() string { + certificate, _ := x509.ParseCertificate(b.server.TLS.Certificates[0].Certificate[0]) + sum := sha256.Sum256(certificate.RawSubjectPublicKeyInfo) + return hex.EncodeToString(sum[:]) +} + +func (b *bmc) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b.mu.Lock() + b.requests = append(b.requests, r.Method+" "+r.URL.Path) + uuid := b.uuid + targets := b.bootTargets + if targets == nil { + targets = []string{"Pxe", "Hdd"} + } + b.mu.Unlock() + path := "/redfish/v1/Systems/A" + docs := map[string]any{ + "/redfish/v1/": map[string]any{"@odata.id": "/redfish/v1", "Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}, + "/redfish/v1/Systems": map[string]any{"Members": []any{map[string]string{"@odata.id": path}}}, + path: map[string]any{"@odata.id": path, "Id": "A", "UUID": uuid, "PowerState": "Off", + "Boot": map[string]any{"BootSourceOverrideEnabled": "Disabled", "BootSourceOverrideTarget": "None", "BootSourceOverrideTarget@Redfish.AllowableValues": targets}, + "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": path + "/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff"}}}}, + } + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusNoContent) + return + } + doc, ok := docs[strings.TrimSuffix(r.URL.Path, "/")] + if r.URL.Path == "/redfish/v1/" { + doc, ok = docs["/redfish/v1/"] + } + if !ok { + w.WriteHeader(http.StatusNotFound) + return + } + json.NewEncoder(w).Encode(doc) +} + +func (b *bmc) count(filter func(string) bool) int { + b.mu.Lock() + defer b.mu.Unlock() + n := 0 + for _, request := range b.requests { + if filter(request) { + n++ + } + } + return n +} + +func notGet(request string) bool { return !strings.HasPrefix(request, "GET ") } +func any_(string) bool { return true } + +type fixedCredentials struct { + credential bmcdiscovery.Credential + found bool +} + +func (f fixedCredentials) Lookup(context.Context, string) (bmcdiscovery.Credential, bool, error) { + return f.credential, f.found, nil +} + +// fakeKind journals one step per entry of steps and records each send. +type fakeKind struct { + steps []string + sends atomic.Int32 + block chan struct{} + observe func(context.Context, json.RawMessage) (bool, error) + check func(*Work) +} + +func (k *fakeKind) Check(_ context.Context, work *Work) *custody.Refusal { + if k.check != nil { + k.check(work) + } + return nil +} + +func (k *fakeKind) Run(ctx context.Context, work *Work) (any, error) { + for _, step := range k.steps { + err := work.Step(ctx, Step{Name: step, Payload: map[string]string{"step": step}, Send: func(ctx context.Context) error { + k.sends.Add(1) + if k.block != nil { + select { + case <-k.block: + case <-ctx.Done(): + return context.Cause(ctx) + } + } + return nil + }, Observe: k.observe}) + if err != nil { + return nil, err + } + } + return ops.InstallationEvidence{Steps: []ops.StepEvidence{{Name: "done"}}}, nil +} + +type fixture struct { + runner *Runner + bmc *bmc + kind *fakeKind +} + +func newFixture(t *testing.T, uuid string) *fixture { + t.Helper() + store := newStore(t) + b := newBMC(t, uuid) + kind := &fakeKind{steps: []string{"power-off", "boot"}} + runner := &Runner{ + Site: "site-example-a", Store: store, Results: NewResults(store), + Access: &RedfishAccess{ + Credentials: fixedCredentials{credential: bmcdiscovery.Credential{Username: "operator", Password: "synthetic-secret", Pin: b.pin()}, found: true}, + Targets: StaticTargets{testDevice: {AssetID: "server-example-001", Endpoint: b.server.URL, SystemID: "A", SystemUUID: testUUID, MAC: testMAC}}, + }, + Kinds: map[string]Kind{"DeviceInstallation": kind}, + Poll: 10 * time.Millisecond, + } + return &fixture{runner: runner, bmc: b, kind: kind} +} + +func (f *fixture) access() *RedfishAccess { return f.runner.Access.(*RedfishAccess) } + +func (f *fixture) assignment(fence int64, uid string) Assignment { + inputs := json.RawMessage(`{"image":"debian-12"}`) + sum := sha256.Sum256(inputs) + return Assignment{ + Device: testDevice, + Operation: ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-install-" + uid, UID: uid}, + Fence: fence, + AdmittedAt: time.Now(), + Deadline: time.Now().Add(time.Minute), + Snapshot: ops.DeviceSnapshot{BMCEndpoint: f.bmc.server.URL, SystemUUID: testUUID, BootMACAddress: testMAC, BMCPublicKeySHA256: f.bmc.pin()}, + InputDigest: "sha256:" + hex.EncodeToString(sum[:]), + Inputs: inputs, + } +} + +func TestRunSucceedsWithFencedTypedEvidence(t *testing.T) { + f := newFixture(t, testUUID) + result, err := f.runner.Run(context.Background(), f.assignment(3, "op-1")) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseSucceeded || result.Fence != 3 || result.Site != "site-example-a" || result.Device != "server-example-001" || f.kind.sends.Load() != 2 { + t.Fatalf("result = %+v, sends %d", result, f.kind.sends.Load()) + } + var evidence ops.InstallationEvidence + if err := json.Unmarshal(result.Evidence, &evidence); err != nil || len(evidence.Steps) != 1 { + t.Fatalf("evidence = %s", result.Evidence) + } + if _, stopped, _ := f.runner.Store.Current(testDevice); stopped != 3 { + t.Fatalf("stop confirmation = %d", stopped) + } + journal, _ := f.runner.Store.Journal(testDevice) + if len(journal) != 2 || journal[0].State != StepDone || journal[1].State != StepDone { + t.Fatalf("journal = %+v", journal) + } +} + +// TestPinMismatchSendsNothing proves that a BMC presenting another key gets +// no request at all: the handshake is aborted before any request is written, +// so no credential reaches it. +func TestPinMismatchSendsNothing(t *testing.T) { + f := newFixture(t, testUUID) + impostor := newBMC(t, testUUID) + // Enrollment and the snapshot name the impostor's endpoint, while the + // approved pin and the snapshot's key are the real BMC's. + f.access().Targets = StaticTargets{testDevice: {Endpoint: impostor.server.URL, SystemID: "A", SystemUUID: testUUID, MAC: testMAC}} + assignment := f.assignment(1, "op-pin") + assignment.Snapshot.BMCEndpoint = impostor.server.URL + result, err := f.runner.Run(context.Background(), assignment) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseFailed || result.Reason != ReasonPublicKeyMismatch { + t.Fatalf("result = %+v", result) + } + if n := impostor.count(any_); n != 0 { + t.Fatalf("the impostor BMC received %d requests", n) + } + if f.kind.sends.Load() != 0 { + t.Fatal("the kind sent a step") + } + // An approved pin that differs from the key discovery recorded is + // refused before any connection. + g := newFixture(t, testUUID) + stale := g.assignment(1, "op-stale-key") + stale.Snapshot.BMCPublicKeySHA256 = strings.Repeat("0", 64) + result, _ = g.runner.Run(context.Background(), stale) + if result.Phase != ops.PhaseFailed || result.Reason != ReasonPublicKeyMismatch || g.bmc.count(any_) != 0 { + t.Fatalf("result = %+v, requests %d", result, g.bmc.count(any_)) + } +} + +// TestIdentityMismatchSendsNothing proves a BMC reporting another system is +// read but never changed. +func TestIdentityMismatchSendsNothing(t *testing.T) { + f := newFixture(t, otherUUID) + result, err := f.runner.Run(context.Background(), f.assignment(1, "op-identity")) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonDeviceIdentityMismatch { + t.Fatalf("result = %+v", result) + } + if n := f.bmc.count(notGet); n != 0 || f.kind.sends.Load() != 0 { + t.Fatalf("%d changing requests and %d steps reached the BMC", n, f.kind.sends.Load()) + } + // Enrollment that disagrees with the snapshot is refused before the BMC + // is contacted. + g := newFixture(t, testUUID) + moved := g.assignment(1, "op-moved") + moved.Snapshot.BootMACAddress = "02:00:00:00:00:99" + result, _ = g.runner.Run(context.Background(), moved) + if result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonDeviceIdentityMismatch || g.bmc.count(any_) != 0 { + t.Fatalf("result = %+v, requests %d", result, g.bmc.count(any_)) + } +} + +func TestPreEffectRefusalsSendNothing(t *testing.T) { + cases := map[string]func(*fixture, *Assignment){ + ReasonCredentialMissing: func(f *fixture, _ *Assignment) { f.access().Credentials = fixedCredentials{} }, + ReasonPinNotApproved: func(f *fixture, _ *Assignment) { + f.access().Credentials = fixedCredentials{credential: bmcdiscovery.Credential{Username: "operator", Password: "synthetic-secret"}, found: true} + }, + ReasonInputMismatch: func(_ *fixture, a *Assignment) { a.Inputs = json.RawMessage(`{"image":"other"}`) }, + ReasonNotEnrolled: func(f *fixture, _ *Assignment) { f.access().Targets = StaticTargets{} }, + ReasonUnsupportedKind: func(_ *fixture, a *Assignment) { a.Operation.Kind = "DeviceTestUnknown" }, + } + for reason, mutate := range cases { + t.Run(reason, func(t *testing.T) { + f := newFixture(t, testUUID) + assignment := f.assignment(1, "op-"+reason) + mutate(f, &assignment) + result, err := f.runner.Run(context.Background(), assignment) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseFailed || result.Reason != reason || f.bmc.count(notGet) != 0 || f.kind.sends.Load() != 0 { + t.Fatalf("result = %+v", result) + } + }) + } +} + +func TestAStaleAssignmentIsRefusedAndStoresNothing(t *testing.T) { + f := newFixture(t, testUUID) + if err := f.runner.Store.Raise(testDevice, 9); err != nil { + t.Fatal(err) + } + if _, err := f.runner.Run(context.Background(), f.assignment(8, "op-old")); !errors.Is(err, ErrStaleFence) { + t.Fatalf("stale assignment: %v", err) + } + if pending, _ := f.runner.Results.Pending(); len(pending) != 0 || f.bmc.count(any_) != 0 { + t.Fatal("a stale assignment stored a result or reached the BMC") + } +} + +// TestANewerFenceStopsTheOlderWorker runs an older worker that blocks inside +// a step, then delivers a newer assignment. The newer worker raises the fence, +// waits for the older one to stop, and confirms the stop. +func TestANewerFenceStopsTheOlderWorker(t *testing.T) { + f := newFixture(t, testUUID) + f.kind.block = make(chan struct{}) + older := make(chan custody.SiteResult, 1) + go func() { + result, err := f.runner.Run(context.Background(), f.assignment(1, "op-older")) + if err != nil { + t.Error(err) + } + older <- result + }() + waitFor(t, func() bool { return f.kind.sends.Load() == 1 }) + // The newer admission is a DeviceRecovery: it only fences. + newer := f.assignment(2, "op-recovery") + newer.Operation.Kind = "DeviceRecovery" + if err := f.runner.Fence(context.Background(), newer); err != nil { + t.Fatal(err) + } + result := <-older + if result.Phase != ops.PhaseOutcomeUnknown || result.Reason != ReasonSuperseded || result.Fence != 1 { + t.Fatalf("older result = %+v", result) + } + if fence, stopped, _ := f.runner.Store.Current(testDevice); fence != 2 || stopped != 2 { + t.Fatalf("fence %d stopped %d", fence, stopped) + } + // The older worker journaled nothing after the newer fence. + journal, _ := f.runner.Store.Journal(testDevice) + if len(journal) != 1 || journal[0].Step != "power-off" || journal[0].State != StepIntended { + t.Fatalf("journal = %+v", journal) + } + if f.kind.sends.Load() != 1 { + t.Fatalf("%d sends", f.kind.sends.Load()) + } +} + +func TestAWorkerStopsAtItsDeadline(t *testing.T) { + f := newFixture(t, testUUID) + f.kind.block = make(chan struct{}) + assignment := f.assignment(1, "op-deadline") + assignment.Deadline = time.Now().Add(300 * time.Millisecond) + result, err := f.runner.Run(context.Background(), assignment) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseOutcomeUnknown || result.Reason != ReasonDeadline { + t.Fatalf("result = %+v", result) + } + if time.Now().After(assignment.Deadline.Add(time.Second)) { + t.Fatal("the worker ran past its deadline") + } +} + +func TestAReplayedStepIsObservedNotSentAgain(t *testing.T) { + f := newFixture(t, testUUID) + assignment := f.assignment(1, "op-replay") + // A previous worker journaled the first step and crashed. + if err := f.runner.Store.Raise(testDevice, 1); err != nil { + t.Fatal(err) + } + if _, err := f.runner.Store.Intend(testDevice, 1, "op-replay", "power-off"); err != nil { + t.Fatal(err) + } + var observed atomic.Int32 + f.kind.observe = func(_ context.Context, payload json.RawMessage) (bool, error) { + observed.Add(1) + // A step journaled by an earlier worker carries no payload here. + return payload == nil, nil + } + result, err := f.runner.Run(context.Background(), assignment) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseSucceeded || observed.Load() != 1 || f.kind.sends.Load() != 1 { + t.Fatalf("result %+v, observed %d, sent %d", result, observed.Load(), f.kind.sends.Load()) + } + // An observation that cannot prove the step leaves the outcome unknown. + g := newFixture(t, testUUID) + if err := g.runner.Store.Raise(testDevice, 1); err != nil { + t.Fatal(err) + } + if _, err := g.runner.Store.Intend(testDevice, 1, "op-replay", "power-off"); err != nil { + t.Fatal(err) + } + g.kind.observe = func(context.Context, json.RawMessage) (bool, error) { return false, nil } + result, _ = g.runner.Run(context.Background(), g.assignment(1, "op-replay")) + if result.Phase != ops.PhaseOutcomeUnknown || result.Reason != ReasonStep || g.kind.sends.Load() != 0 { + t.Fatalf("result %+v, sent %d", result, g.kind.sends.Load()) + } +} + +func TestResultsAreDeletedOnceTheCoordinatorAnswers(t *testing.T) { + f := newFixture(t, testUUID) + for index, uid := range []string{"op-a", "op-b", "op-c"} { + if _, err := f.runner.Run(context.Background(), f.assignment(int64(index+1), uid)); err != nil { + t.Fatal(err) + } + } + answers := map[string]error{"op-a": nil, "op-b": custody.ErrStaleFence, "op-c": errors.New("coordinator unreachable")} + err := f.runner.Results.Deliver(context.Background(), func(_ context.Context, result custody.SiteResult) error { + return answers[result.Operation.UID] + }) + if err == nil { + t.Fatal("the failed delivery was not reported") + } + pending, _ := f.runner.Results.Pending() + if len(pending) != 1 || pending[0].Result.Operation.UID != "op-c" { + t.Fatalf("pending = %+v", pending) + } +} + +func TestAssignmentValidation(t *testing.T) { + f := newFixture(t, testUUID) + valid := f.assignment(1, "op") + if err := valid.Validate(); err != nil { + t.Fatal(err) + } + for name, mutate := range map[string]func(*Assignment){ + "device": func(a *Assignment) { a.Device = "server-example-001" }, + "nested": func(a *Assignment) { a.Device = "default/a/b" }, + "uid": func(a *Assignment) { a.Operation.UID = "" }, + "fence": func(a *Assignment) { a.Fence = 0 }, + "deadline": func(a *Assignment) { a.Deadline = time.Time{} }, + "inputs": func(a *Assignment) { a.Inputs = make(json.RawMessage, maxInputs+1) }, + "snapshot": func(a *Assignment) { a.Snapshot.BMCPublicKeySHA256 = "" }, + } { + assignment := valid + mutate(&assignment) + if assignment.Validate() == nil { + t.Fatalf("%s: accepted", name) + } + } +} + +func waitFor(t *testing.T, condition func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !condition() { + if time.Now().After(deadline) { + t.Fatal("condition not met") + } + time.Sleep(5 * time.Millisecond) + } +} + +// TestAResumedWorkerThatCannotReachTheBMCReportsUnknown proves that a +// refusal after an earlier worker journaled steps is not reported as "nothing +// sent". +func TestAResumedWorkerThatCannotReachTheBMCReportsUnknown(t *testing.T) { + f := newFixture(t, testUUID) + if err := f.runner.Store.Raise(testDevice, 1); err != nil { + t.Fatal(err) + } + if _, err := f.runner.Store.Intend(testDevice, 1, "op-resumed", "power-off"); err != nil { + t.Fatal(err) + } + f.access().Credentials = fixedCredentials{} + result, err := f.runner.Run(context.Background(), f.assignment(1, "op-resumed")) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseOutcomeUnknown || result.Reason != ReasonCredentialMissing { + t.Fatalf("result = %+v", result) + } + // A worker started after its deadline sends nothing. + g := newFixture(t, testUUID) + late := g.assignment(1, "op-late") + late.AdmittedAt, late.Deadline = time.Now().Add(-time.Minute), time.Now().Add(-time.Second) + result, _ = g.runner.Run(context.Background(), late) + if result.Phase != ops.PhaseFailed || result.Reason != ReasonDeadline || g.bmc.count(any_) != 0 { + t.Fatalf("result = %+v", result) + } +} + +// startingKind must start within one second of admission. +type startingKind struct{ *fakeKind } + +func (startingKind) StartBy() time.Duration { return time.Second } + +func TestALateStartIsStaleAndSendsNothing(t *testing.T) { + f := newFixture(t, testUUID) + f.runner.Kinds["DeviceInstallation"] = startingKind{f.kind} + late := f.assignment(1, "op-stale") + late.AdmittedAt = time.Now().Add(-time.Minute) + result, err := f.runner.Run(context.Background(), late) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseFailed || result.Reason != ReasonStale || f.bmc.count(any_) != 0 || f.kind.sends.Load() != 0 { + t.Fatalf("result = %+v", result) + } + // A worker resuming steps an earlier worker sent is not stale. + g := newFixture(t, testUUID) + g.runner.Kinds["DeviceInstallation"] = startingKind{g.kind} + if err := g.runner.Store.Raise(testDevice, 1); err != nil { + t.Fatal(err) + } + if _, err := g.runner.Store.Intend(testDevice, 1, "op-resume-late", "power-off"); err != nil { + t.Fatal(err) + } + g.kind.observe = func(context.Context, json.RawMessage) (bool, error) { return true, nil } + resumed := g.assignment(1, "op-resume-late") + resumed.AdmittedAt = time.Now().Add(-time.Minute) + if result, _ := g.runner.Run(context.Background(), resumed); result.Phase != ops.PhaseSucceeded { + t.Fatalf("resumed result = %+v", result) + } +} + +func TestAStepPayloadIsJournaledAndReadBack(t *testing.T) { + store := newStore(t) + if err := store.Raise(testDevice, 1); err != nil { + t.Fatal(err) + } + payload := json.RawMessage(`{"powerBefore":"Off"}`) + if _, _, err := store.IntendWithPayload(testDevice, 1, "op", "reset", payload); err != nil { + t.Fatal(err) + } + _, recorded, err := store.IntendWithPayload(testDevice, 1, "op", "reset", json.RawMessage(`{"powerBefore":"changed"}`)) + if !errors.Is(err, ErrStepReplayed) || string(recorded) != string(payload) { + t.Fatalf("replay = %s %v", recorded, err) + } + if _, _, err := store.IntendWithPayload(testDevice, 1, "op", "too-big", make(json.RawMessage, maxPayload+1)); err == nil { + t.Fatal("an oversized payload was journaled") + } +} + +// TestIdentityIsSeparateFromInstallCapabilities proves the framework checks +// only the pin and the System, so a kind that needs no network boot, such as +// power, runs on a System that offers no boot override. +func TestIdentityIsSeparateFromInstallCapabilities(t *testing.T) { + f := newFixture(t, testUUID) + f.bmc.mu.Lock() + f.bmc.bootTargets = []string{} + f.bmc.mu.Unlock() + var system redfish.System + f.kind.check = func(work *Work) { + if connection, ok := work.Connection.(*RedfishConnection); ok { + system = connection.System + } + } + result, err := f.runner.Run(context.Background(), f.assignment(1, "op-power-like")) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseSucceeded || system.UUID != testUUID || len(system.BootTargets) != 0 { + t.Fatalf("result = %+v, system = %+v", result, system) + } +} diff --git a/internal/site/store.go b/internal/site/store.go new file mode 100644 index 00000000..4ae948ff --- /dev/null +++ b/internal/site/store.go @@ -0,0 +1,401 @@ +// Package site runs admitted Device operations at the site that can reach the +// server, as proposed in datum-cloud/fleet#174 at d4d17f9. +// +// The framework owns everything a kind must not implement itself: the +// per-Device fence, the per-Device journal, stopping older workers, the +// credential lookup, the TLS pin and identity checks, the deadline, and the +// result that carries the fence. A kind supplies only its pre-effect checks, +// its journaled steps, how it observes after a lost response, and its typed +// evidence. +// +// Increment B is inert: nothing delivers assignments to it until the cutover +// in Increment C. +package site + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +var ( + // ErrStaleFence means a fence is below the Device's stored fence. The + // site refuses the assignment, the step or the result. + ErrStaleFence = errors.New("site: fence is below the Device's stored fence") + // ErrStepReplayed means a step was journaled before and its outcome + // must be observed, not sent again. + ErrStepReplayed = errors.New("site: step was journaled before; observe it instead of sending again") +) + +// StepState is how far a journaled step got. +type StepState string + +const ( + // StepIntended is journaled before the step is sent. Finding it after + // a crash means the step may or may not have reached the server. + StepIntended StepState = "Intended" + StepDone StepState = "Done" +) + +// Entry is one journaled step. +type Entry struct { + Operation string `json:"operation"` + Fence int64 `json:"fence"` + Step string `json:"step"` + State StepState `json:"state"` + At time.Time `json:"at"` + // Payload is the kind's bounded record of the step, such as the send + // time or the power state before it. It is journaled before the step is + // sent and read back when the step is observed after a crash. + Payload json.RawMessage `json:"payload,omitempty"` +} + +// maxPayload bounds a journaled step's payload. +const maxPayload = 1024 + +// deviceState is the durable state of one Device at this site. +type deviceState struct { + Device string `json:"device"` + // Fence is the highest fence the site has seen for the Device. + Fence int64 `json:"fence"` + // Stopped is the highest fence for which every older worker is known to + // have stopped. The coordinator reads it as the site's fence report. + Stopped int64 `json:"stopped"` + Journal []Entry `json:"journal,omitempty"` +} + +// Store is the site's per-Device fence store and journal. It must live on +// durable storage, the site's retained volume, so the site still refuses old +// fences after a restart. Each Device has its own directory, lock and state +// file, so work on one Device never waits for another. +type Store struct { + root string + now func() time.Time +} + +// OpenStore opens a store rooted at an existing, owner-only directory. +func OpenStore(root string, now func() time.Time) (*Store, error) { + info, err := os.Stat(root) + if err != nil { + return nil, err + } + if !info.IsDir() || info.Mode().Perm()&0o077 != 0 { + return nil, errors.New("site: the store root must be an owner-only directory") + } + if now == nil { + now = time.Now + } + return &Store{root: root, now: now}, nil +} + +// deviceDir is the Device's directory. Device names a Device as +// "/"; the directory is a digest so no name can escape root. +func (s *Store) deviceDir(device string) string { + sum := sha256.Sum256([]byte(device)) + return filepath.Join(s.root, "devices", hex.EncodeToString(sum[:16])) +} + +// locked runs change on the Device's state under its exclusive lock and +// saves the result atomically when change returns save=true. +func (s *Store) locked(device string, change func(*deviceState) (bool, error)) error { + if device == "" { + return errors.New("site: a Device is required") + } + dir := s.deviceDir(device) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + lock, err := os.OpenFile(filepath.Join(dir, "state.lock"), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return err + } + defer lock.Close() + if err := unix.Flock(int(lock.Fd()), unix.LOCK_EX); err != nil { + return err + } + state := &deviceState{Device: device} + data, err := os.ReadFile(filepath.Join(dir, "state.json")) + switch { + case os.IsNotExist(err): + case err != nil: + return err + default: + if err := json.Unmarshal(data, state); err != nil || state.Device != device { + return errors.New("site: the Device's state file is unreadable; refusing to guess its fence") + } + } + save, err := change(state) + if err != nil || !save { + return err + } + return writeAtomic(dir, "state.json", state) +} + +func writeAtomic(dir, name string, value any) error { + data, err := json.Marshal(value) + if err != nil { + return err + } + file, err := os.CreateTemp(dir, name+".tmp-*") + if err != nil { + return err + } + defer os.Remove(file.Name()) + if _, err := file.Write(data); err != nil { + file.Close() + return err + } + if err := file.Sync(); err != nil { + file.Close() + return err + } + if err := file.Close(); err != nil { + return err + } + if err := os.Rename(file.Name(), filepath.Join(dir, name)); err != nil { + return err + } + parent, err := os.Open(dir) + if err != nil { + return err + } + defer parent.Close() + return parent.Sync() +} + +// Raise stores fence as the Device's highest fence. A fence below the stored +// one is refused. An equal fence is accepted again: delivery is replayed from +// custody after a crash. +func (s *Store) Raise(device string, fence int64) error { + if fence < 1 { + return errors.New("site: a fence is at least 1") + } + return s.locked(device, func(state *deviceState) (bool, error) { + if fence < state.Fence { + return false, ErrStaleFence + } + if fence == state.Fence { + return false, nil + } + state.Fence = fence + return true, nil + }) +} + +// Current returns the Device's stored fence and the fence for which older +// workers are confirmed stopped. +func (s *Store) Current(device string) (fence, stopped int64, err error) { + err = s.locked(device, func(state *deviceState) (bool, error) { + fence, stopped = state.Fence, state.Stopped + return false, nil + }) + return fence, stopped, err +} + +// ConfirmStopped records that no worker below fence still runs for the +// Device. It is refused if fence is no longer the stored fence. +func (s *Store) ConfirmStopped(device string, fence int64) error { + return s.locked(device, func(state *deviceState) (bool, error) { + if fence != state.Fence { + return false, ErrStaleFence + } + if state.Stopped >= fence { + return false, nil + } + state.Stopped = fence + return true, nil + }) +} + +// Intend journals a step before it is sent. It refuses a fence below the +// stored fence. A step already journaled for the operation returns +// ErrStepReplayed if it was only intended, so the caller observes it, and +// its state if it was done. +func (s *Store) Intend(device string, fence int64, operation, step string) (StepState, error) { + prior, _, err := s.IntendWithPayload(device, fence, operation, step, nil) + return prior, err +} + +// IntendWithPayload is Intend with a payload. For a step journaled before, it +// returns the payload recorded then. +func (s *Store) IntendWithPayload(device string, fence int64, operation, step string, payload json.RawMessage) (StepState, json.RawMessage, error) { + if len(payload) > maxPayload { + return "", nil, fmt.Errorf("site: a step payload is at most %d bytes", maxPayload) + } + var prior StepState + var recorded json.RawMessage + err := s.locked(device, func(state *deviceState) (bool, error) { + if fence < state.Fence { + return false, ErrStaleFence + } + if fence > state.Fence { + return false, fmt.Errorf("site: fence %d was never raised", fence) + } + for _, entry := range state.Journal { + if entry.Operation == operation && entry.Step == step { + prior, recorded = entry.State, entry.Payload + if entry.State == StepIntended { + return false, ErrStepReplayed + } + return false, nil + } + } + state.Journal = append(state.Journal, Entry{Operation: operation, Fence: fence, Step: step, State: StepIntended, At: s.now().UTC(), Payload: payload}) + recorded = payload + return true, nil + }) + return prior, recorded, err +} + +// Done marks a journaled step done. It refuses a fence below the stored +// fence, so an older worker cannot record progress after a newer admission. +func (s *Store) Done(device string, fence int64, operation, step string) error { + return s.locked(device, func(state *deviceState) (bool, error) { + if fence < state.Fence { + return false, ErrStaleFence + } + index := slices.IndexFunc(state.Journal, func(entry Entry) bool { return entry.Operation == operation && entry.Step == step }) + if index < 0 { + return false, errors.New("site: a step must be journaled before it is done") + } + if state.Journal[index].State == StepDone { + return false, nil + } + state.Journal[index].State = StepDone + state.Journal[index].At = s.now().UTC() + return true, nil + }) +} + +// Journal returns the Device's journal. +func (s *Store) Journal(device string) ([]Entry, error) { + var out []Entry + err := s.locked(device, func(state *deviceState) (bool, error) { + out = slices.Clone(state.Journal) + return false, nil + }) + return out, err +} + +// runLock is held by the one worker running for a Device. A worker that +// raises the fence waits for it, so an older worker has stopped before the +// newer one starts. A worker that dies releases it with its process. +type runLock struct{ file *os.File } + +func (s *Store) tryRunLock(device string) (*runLock, error) { + dir := s.deviceDir(device) + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + file, err := os.OpenFile(filepath.Join(dir, "run.lock"), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, err + } + if err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + file.Close() + if errors.Is(err, unix.EWOULDBLOCK) { + return nil, nil + } + return nil, err + } + return &runLock{file: file}, nil +} + +func (l *runLock) release() { l.file.Close() } + +// PutRecord stores a kind's per-operation record for a Device, such as its +// boot admission, beside the journal. A record below the stored fence is +// refused. +func (s *Store) PutRecord(device string, fence int64, collection, name string, value any) error { + if !validRecordName(collection) || !validRecordName(name) { + return errors.New("site: invalid record name") + } + return s.locked(device, func(state *deviceState) (bool, error) { + if fence < state.Fence { + return false, ErrStaleFence + } + dir := filepath.Join(s.deviceDir(device), collection) + if err := os.MkdirAll(dir, 0o700); err != nil { + return false, err + } + return false, writeAtomic(dir, name+".json", value) + }) +} + +// GetRecord reads a kind's record. It returns false if there is none. +func (s *Store) GetRecord(device, collection, name string, into any) (bool, error) { + if !validRecordName(collection) || !validRecordName(name) { + return false, errors.New("site: invalid record name") + } + data, err := os.ReadFile(filepath.Join(s.deviceDir(device), collection, name+".json")) + if os.IsNotExist(err) { + return false, nil + } + if err != nil { + return false, err + } + return true, json.Unmarshal(data, into) +} + +func validRecordName(name string) bool { + if name == "" || len(name) > 128 { + return false + } + for _, r := range name { + if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-' || r == '.') || name == "." || name == ".." { + return false + } + } + return true +} + +// Record is one stored per-operation record. +type Record struct { + Device string + Name string + Data []byte +} + +// Records returns every Device's records in a collection. +func (s *Store) Records(collection string) ([]Record, error) { + if !validRecordName(collection) { + return nil, errors.New("site: invalid record name") + } + dirs, err := filepath.Glob(filepath.Join(s.root, "devices", "*")) + if err != nil { + return nil, err + } + var out []Record + for _, dir := range dirs { + data, err := os.ReadFile(filepath.Join(dir, "state.json")) + if err != nil { + continue + } + var state deviceState + if json.Unmarshal(data, &state) != nil { + continue + } + paths, err := filepath.Glob(filepath.Join(dir, collection, "*.json")) + if err != nil { + return nil, err + } + slices.Sort(paths) + for _, path := range paths { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + out = append(out, Record{Device: state.Device, Name: strings.TrimSuffix(filepath.Base(path), ".json"), Data: data}) + } + } + return out, nil +} diff --git a/internal/site/store_test.go b/internal/site/store_test.go new file mode 100644 index 00000000..ce7ff5d4 --- /dev/null +++ b/internal/site/store_test.go @@ -0,0 +1,195 @@ +package site + +import ( + "errors" + "fmt" + "os" + "sync" + "sync/atomic" + "testing" + "time" +) + +func newStore(t *testing.T) *Store { + t.Helper() + dir := t.TempDir() + if err := os.Chmod(dir, 0o700); err != nil { + t.Fatal(err) + } + store, err := OpenStore(dir, nil) + if err != nil { + t.Fatal(err) + } + return store +} + +func TestStoreRefusesOlderFencesAndSurvivesARestart(t *testing.T) { + store := newStore(t) + device := "default/server-example-001" + if err := store.Raise(device, 5); err != nil { + t.Fatal(err) + } + if err := store.Raise(device, 5); err != nil { + t.Fatalf("a replayed delivery at the stored fence: %v", err) + } + if err := store.Raise(device, 4); !errors.Is(err, ErrStaleFence) { + t.Fatalf("an older fence: %v", err) + } + if _, err := store.Intend(device, 5, "op-a", "power-off"); err != nil { + t.Fatal(err) + } + if err := store.Raise(device, 6); err != nil { + t.Fatal(err) + } + // The older worker can neither journal nor finish a step. + if _, err := store.Intend(device, 5, "op-a", "boot"); !errors.Is(err, ErrStaleFence) { + t.Fatalf("a stale step: %v", err) + } + if err := store.Done(device, 5, "op-a", "power-off"); !errors.Is(err, ErrStaleFence) { + t.Fatalf("a stale completion: %v", err) + } + before, err := os.ReadFile(store.deviceDir(device) + "/state.json") + if err != nil { + t.Fatal(err) + } + // A restarted site reads the same fence from disk. + reopened, err := OpenStore(store.root, nil) + if err != nil { + t.Fatal(err) + } + if _, err := reopened.Intend(device, 5, "op-a", "boot"); !errors.Is(err, ErrStaleFence) { + t.Fatalf("a stale step after restart: %v", err) + } + after, _ := os.ReadFile(store.deviceDir(device) + "/state.json") + if string(before) != string(after) { + t.Fatal("a refused step changed the journal") + } + if fence, _, _ := reopened.Current(device); fence != 6 { + t.Fatalf("fence after restart = %d", fence) + } +} + +func TestStoreReplaysAJournaledStepAsAnObservation(t *testing.T) { + store := newStore(t) + device := "default/server-example-002" + if err := store.Raise(device, 1); err != nil { + t.Fatal(err) + } + if _, err := store.Intend(device, 1, "op", "reset"); err != nil { + t.Fatal(err) + } + // The worker crashed after journaling and before recording the step. + if _, err := store.Intend(device, 1, "op", "reset"); !errors.Is(err, ErrStepReplayed) { + t.Fatalf("a replayed step: %v", err) + } + if err := store.Done(device, 1, "op", "reset"); err != nil { + t.Fatal(err) + } + if state, err := store.Intend(device, 1, "op", "reset"); err != nil || state != StepDone { + t.Fatalf("a done step = %s %v", state, err) + } + if err := store.Done(device, 1, "op", "never-journaled"); err == nil { + t.Fatal("a step was done without being journaled") + } +} + +// TestTwoWorkersOnOneDevice races a stream of steps from an older worker +// against a newer admission. Once the newer fence is stored, no older step is +// journaled. +func TestTwoWorkersOnOneDevice(t *testing.T) { + store := newStore(t) + device := "default/server-example-003" + if err := store.Raise(device, 1); err != nil { + t.Fatal(err) + } + var raised atomic.Bool + var lateSteps atomic.Int32 + var group sync.WaitGroup + group.Add(2) + go func() { + defer group.Done() + for index := range 200 { + wasRaised := raised.Load() + _, err := store.Intend(device, 1, "op-old", fmt.Sprintf("step-%d", index)) + if err == nil && wasRaised { + lateSteps.Add(1) + } + if errors.Is(err, ErrStaleFence) { + return + } + } + }() + go func() { + defer group.Done() + time.Sleep(2 * time.Millisecond) + if err := store.Raise(device, 2); err != nil { + t.Error(err) + } + raised.Store(true) + }() + group.Wait() + if lateSteps.Load() != 0 { + t.Fatalf("%d older steps journaled after the newer fence", lateSteps.Load()) + } + journal, err := store.Journal(device) + if err != nil { + t.Fatal(err) + } + for _, entry := range journal { + if entry.Fence != 1 || entry.Operation != "op-old" { + t.Fatalf("entry = %+v", entry) + } + } +} + +func TestTwoDevicesInParallel(t *testing.T) { + store := newStore(t) + first, second := "default/server-example-004", "default/server-example-005" + for _, device := range []string{first, second} { + if err := store.Raise(device, 1); err != nil { + t.Fatal(err) + } + } + // A worker holding one Device's run lock does not block the other. + held, err := store.tryRunLock(first) + if err != nil || held == nil { + t.Fatalf("first run lock: %v", err) + } + defer held.release() + other, err := store.tryRunLock(second) + if err != nil || other == nil { + t.Fatalf("second Device blocked: %v", err) + } + other.release() + if again, err := store.tryRunLock(first); err != nil || again != nil { + t.Fatal("two workers held one Device's run lock") + } + var group sync.WaitGroup + for _, device := range []string{first, second} { + group.Add(1) + go func() { + defer group.Done() + for index := range 50 { + if _, err := store.Intend(device, 1, "op", fmt.Sprintf("step-%d", index)); err != nil { + t.Error(err) + } + } + }() + } + group.Wait() + for _, device := range []string{first, second} { + if journal, _ := store.Journal(device); len(journal) != 50 { + t.Fatalf("%s journaled %d steps", device, len(journal)) + } + } +} + +func TestStoreRootMustBeOwnerOnly(t *testing.T) { + dir := t.TempDir() + if err := os.Chmod(dir, 0o755); err != nil { + t.Fatal(err) + } + if _, err := OpenStore(dir, nil); err == nil { + t.Fatal("a shared store root was accepted") + } +} From 8b4da2d9bbc61129440927c4b2e7458c24720416 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 20:47:58 -0600 Subject: [PATCH 3/8] feat(site): Run Redfish installs and wipes behind the worker contract Port the Redfish executor's install and wipe phases to the site framework. Power-on is journaled and sent once, and observed after a crash. Boot admissions are served only at the Device's stored fence, so a superseded operation can never boot the server. Co-Authored-By: Claude Opus 5.5 --- internal/custody/kinds.go | 11 +- internal/site/redfishwork/kinds.go | 473 ++++++++++++++++++++++++ internal/site/redfishwork/kinds_test.go | 316 ++++++++++++++++ 3 files changed, 799 insertions(+), 1 deletion(-) create mode 100644 internal/site/redfishwork/kinds.go create mode 100644 internal/site/redfishwork/kinds_test.go diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index af1af83f..2f179eed 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -36,8 +36,16 @@ const ( ReasonRetryAuthorized = "RetryAlreadyAuthorized" ReasonDisposalRequired = "DisposalRequired" ReasonInvalidResolve = "InvalidResolve" + // Reasons the Redfish install and wipe workers raise. + ReasonTargetUnsupported = "TargetUnsupported" + ReasonTargetDisks = "TargetDisksUnknown" + ReasonInputsUnreadable = "InputsUnreadable" ) +// redfishWorkerReasons are the reasons the site's install and wipe workers +// raise before sending anything. +var redfishWorkerReasons = []Reason{{Name: ReasonTargetUnsupported, RaisedBy: RaisedByWorker}, {Name: ReasonTargetDisks, RaisedBy: RaisedByWorker}, {Name: ReasonInputsUnreadable, RaisedBy: RaisedByWorker}} + const evidenceLimit = 4096 var gv = ops.GroupVersion @@ -106,7 +114,7 @@ func DeviceInstallationKind() Kind { return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", installation.Spec.BootInterface) }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, - Reasons: []Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}}, + Reasons: append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}}, redfishWorkerReasons...), Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.InstallationEvidence) error { return validateSteps(evidence.Steps) }), @@ -135,6 +143,7 @@ func DeviceWipeKind() Kind { // settled by a later wipe only after a DeviceRecovery with Retry. Settles: []SettleRule{{Held: "DeviceInstallation"}, {Held: "DeviceWipe", RequiresRetry: true}}, Retryable: true, + Reasons: redfishWorkerReasons, Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.WipeEvidence) error { if len(evidence.WipedDisks) > 16 { return errors.New("evidence records at most 16 disks") diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go new file mode 100644 index 00000000..30cf7376 --- /dev/null +++ b/internal/site/redfishwork/kinds.go @@ -0,0 +1,473 @@ +// Package redfishwork runs DeviceInstallation and DeviceWipe over Redfish +// behind the site worker contract. It ports the phases of the Redfish +// executor: power off, arm a one-time boot, power on once, then observe the +// console receipt and, for a network boot, the boot server's delivery +// evidence. Each effect is a journaled step; the framework owns the fence, +// journal, credential, pin, identity and deadline. +// +// Increment B is inert: the old executor in internal/redfish keeps running +// the existing lifecycle until the cutover in Increment C deletes it. +package redfishwork + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// Kind-specific refusal reasons. Each ends the operation Failed with nothing +// sent. +// They are declared on the DeviceInstallation and DeviceWipe kinds as raised +// by the worker. +const ( + ReasonUnsupportedTarget = custody.ReasonTargetUnsupported + ReasonTargetDisks = custody.ReasonTargetDisks + ReasonInputs = custody.ReasonInputsUnreadable +) + +// phase is one boot of the server. +type phase struct{ name, boot, marker, mode string } + +var ( + installPhases = []phase{{"installer", "Pxe", "FLEET-INSTALLED:", "install"}, {"disk", "Hdd", "FLEET-DISK-BOOT:", ""}} + wipePhases = []phase{{"wipe", "Pxe", "FLEET-WIPED:", "wipe"}} +) + +// Config is what both kinds read at the site. +type Config struct { + // ConsoleRoot holds each target's serial console capture. + ConsoleRoot string + // BootRoot holds the boot server's per-operation delivery evidence. + BootRoot string + // Poll is how often the kinds observe the server. It defaults to two + // seconds. + Poll time.Duration + // OffGrace bounds how long the server may stay off without its receipt, + // and Outage how long the BMC may be unreadable while a phase runs. + OffGrace, Outage time.Duration + // BootWindow bounds how long a network boot admission stays open. + BootWindow time.Duration + Now func() time.Time +} + +func (c Config) now() time.Time { + if c.Now != nil { + return c.Now() + } + return time.Now() +} + +func (c Config) durations() (poll, offGrace, outage, window time.Duration) { + poll, offGrace, outage, window = c.Poll, c.OffGrace, c.Outage, c.BootWindow + if poll <= 0 { + poll = 2 * time.Second + } + if offGrace <= 0 { + offGrace = time.Minute + } + if outage <= 0 { + outage = 5 * time.Minute + } + if window <= 0 { + window = 20 * time.Minute + } + return +} + +// Installation is the DeviceInstallation worker. +type Installation struct{ Config } + +// Wipe is the DeviceWipe worker. +type Wipe struct{ Config } + +var ( + _ site.Kind = Installation{} + _ site.Kind = Wipe{} +) + +// conn is the Redfish connection the site prepared. Check refuses any other. +func conn(work *site.Work) *site.RedfishConnection { + connection, _ := work.Connection.(*site.RedfishConnection) + return connection +} + +func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal { + if conn(work) == nil { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "this site does not reach the server over Redfish"} + } + var spec ops.DeviceInstallationSpec + if err := json.Unmarshal(work.Inputs, &spec); err != nil { + return &custody.Refusal{Reason: ReasonInputs, Message: "the admitted inputs are not a DeviceInstallation spec"} + } + if spec.Bootstrap != nil { + return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} + } + return checkTarget(work, spec.TargetDisks, installPhases) +} + +func (k Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { + if conn(work) == nil { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "this site does not reach the server over Redfish"} + } + var spec ops.DeviceWipeSpec + if err := json.Unmarshal(work.Inputs, &spec); err != nil { + return &custody.Refusal{Reason: ReasonInputs, Message: "the admitted inputs are not a DeviceWipe spec"} + } + if conn(work).Target.DiskBytes <= 0 { + return &custody.Refusal{Reason: ReasonTargetDisks, Message: "the site's enrollment records no disk size to verify the wipe against"} + } + return checkTarget(work, spec.TargetDisks, wipePhases) +} + +// checkTarget requires the one enrolled disk and every capability the phases +// use. Target disks stay a site-local enrollment fact: the site enrolls one +// disk per server, named disk-0. +func checkTarget(work *site.Work, disks []string, phases []phase) *custody.Refusal { + if len(disks) != 1 || disks[0] != "disk-0" { + return &custody.Refusal{Reason: ReasonTargetDisks, Message: "the site enrolls exactly one disk, disk-0"} + } + if conn(work).Target.Console == "" { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the site's enrollment names no console for receipts"} + } + for _, ph := range phases { + if !contains(conn(work).System.BootTargets, ph.boot) { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the system does not offer boot override " + ph.boot} + } + } + if !conn(work).System.OffersOnce() { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the system does not offer a one-time boot override"} + } + for _, need := range []string{"On", "ForceOff"} { + if !contains(conn(work).System.ResetTypes, need) { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the system does not offer reset " + need} + } + } + return nil +} + +func contains(list []string, value string) bool { + for _, item := range list { + if item == value { + return true + } + } + return false +} + +func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { + steps, err := k.run(ctx, work, installPhases) + if err != nil { + return nil, err + } + return ops.InstallationEvidence{Steps: steps}, nil +} + +func (k Wipe) Run(ctx context.Context, work *site.Work) (any, error) { + steps, err := k.run(ctx, work, wipePhases) + if err != nil { + return nil, err + } + return ops.WipeEvidence{Steps: steps, WipedDisks: []string{"disk-0"}}, nil +} + +// powerOn is the journaled payload of a power-on step. +type powerOn struct { + RequestedAt time.Time `json:"requestedAt"` +} + +// Boot is one operation's boot admission. The boot server serves a network +// boot only while an admission is open and its fence is still the Device's +// stored fence. +type Boot struct { + Operation string `json:"operation"` + Fence int64 `json:"fence"` + Mode string `json:"mode"` + MAC string `json:"mac"` + Receipt string `json:"receipt"` + Token string `json:"token"` + Expires time.Time `json:"expires"` + // Phase is the network-booting phase, set while it may boot. + Phase string `json:"phase,omitempty"` + Closed bool `json:"closed,omitempty"` +} + +const bootRecords = "boot" + +// boot reads the operation's boot admission, creating it once. The receipt is +// fixed before any boot, so a replay waits for the same receipt. +func (c Config) boot(ctx context.Context, work *site.Work, mode string) (Boot, error) { + store := work.Store() + var boot Boot + found, err := store.GetRecord(work.Device, bootRecords, work.Operation.UID, &boot) + if err != nil || found { + return boot, err + } + receipt, token := make([]byte, 32), make([]byte, 32) + if _, err := rand.Read(receipt); err != nil { + return boot, err + } + if _, err := rand.Read(token); err != nil { + return boot, err + } + _, _, _, window := c.durations() + boot = Boot{Operation: work.Operation.UID, Fence: work.Fence, Mode: mode, MAC: strings.ToLower(conn(work).Target.MAC), Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Expires: c.now().Add(window).UTC()} + return boot, store.PutRecord(work.Device, work.Fence, bootRecords, work.Operation.UID, boot) +} + +func (c Config) saveBoot(work *site.Work, boot Boot) error { + return work.Store().PutRecord(work.Device, work.Fence, bootRecords, work.Operation.UID, boot) +} + +func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops.StepEvidence, error) { + mode := phases[0].mode + boot, err := c.boot(ctx, work, mode) + if err != nil { + return nil, err + } + var evidence []ops.StepEvidence + for _, ph := range phases { + // Power off and arm the one-time override. Both are safe to send + // again: no boot of this phase has been requested yet. + if err := work.Step(ctx, site.Step{Name: ph.name + "-power-off", Send: func(ctx context.Context) error { return c.powerOff(ctx, work) }, Idempotent: true}); err != nil { + return nil, err + } + if ph.mode != "" { + if boot.Closed || !c.now().Before(boot.Expires) { + return nil, errors.New("boot admission expired or closed before the network boot") + } + } + if err := work.Step(ctx, site.Step{Name: ph.name + "-arm", Send: func(ctx context.Context) error { return conn(work).SetBootOnce(ctx, ph.boot) }, Idempotent: true}); err != nil { + return nil, err + } + if ph.mode != "" { + boot.Phase = ph.name + if err := c.saveBoot(work, boot); err != nil { + return nil, err + } + } + // Power on is sent once. After a crash or lost response it is + // observed: any sign that the boot began counts, and no sign leaves + // the outcome unknown rather than sending it again. + if err := work.Step(ctx, site.Step{ + Name: ph.name + "-power-on", + Payload: powerOn{RequestedAt: c.now().UTC()}, + Send: func(ctx context.Context) error { return conn(work).Reset(ctx, "On") }, + Observe: func(ctx context.Context, _ json.RawMessage) (bool, error) { return c.started(ctx, work, boot, ph) }, + }); err != nil { + return nil, err + } + if err := c.complete(ctx, work, boot, ph); err != nil { + return nil, err + } + if ph.mode != "" { + boot.Phase, boot.Closed = "", true + if err := c.saveBoot(work, boot); err != nil { + return nil, err + } + } + evidence = append(evidence, ops.StepEvidence{Name: ph.name, CompletedAt: metaNow(c.now())}) + } + return evidence, nil +} + +func (c Config) powerOff(ctx context.Context, work *site.Work) error { + poll, _, _, _ := c.durations() + requested := false + for { + power, err := conn(work).Observe(ctx) + if err != nil { + return err + } + if power.State == "Off" { + return nil + } + if !requested { + // A slow or lost ForceOff is observed, not trusted. + if err := conn(work).Reset(ctx, "ForceOff"); errors.Is(err, redfish.ErrUnauthorized) || errors.Is(err, redfish.ErrUnsupported) { + return err + } + requested = true + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// started reports whether a requested boot may have begun: power not off, +// the override consumed, a receipt, or a boot delivery. +func (c Config) started(ctx context.Context, work *site.Work, boot Boot, ph phase) (bool, error) { + power, err := conn(work).Observe(ctx) + if err != nil { + return false, err + } + seen, err := c.receipts(work, boot, ph) + if err != nil { + return false, err + } + delivered := ph.mode != "" && c.deliveries(work)["admitted boot.ipxe"] + return power.State != "Off" || power.OverrideEnabled != "Once" || power.OverrideTarget != ph.boot || seen > 0 || delivered, nil +} + +// complete waits for exactly one receipt for this operation and the server +// off again. The BMC may be unreadable for a bounded time. +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 + for { + power, err := conn(work).Observe(ctx) + switch { + case errors.Is(err, redfish.ErrIdentity): + return err + case err != nil: + if failingSince.IsZero() { + failingSince = c.now() + } + if c.now().Sub(failingSince) > outage { + return fmt.Errorf("the BMC was unreadable while %s ran: %w", ph.name, err) + } + default: + failingSince = time.Time{} + seen, err := c.receipts(work, boot, ph) + if err != nil { + return err + } + if power.State == "Off" { + if seen == 1 { + if ph.mode != "" { + return c.verifyDelivery(work) + } + return nil + } + if offSince.IsZero() { + offSince = c.now() + } + if c.now().Sub(offSince) > offGrace { + return fmt.Errorf("the server powered off without the %s receipt", ph.name) + } + } else { + offSince = time.Time{} + } + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// receipts counts exact receipt lines for this operation on the console. +// More than one means the phase ran twice, which never succeeds. +func (c Config) receipts(work *site.Work, boot Boot, ph phase) (int, error) { + data, err := os.ReadFile(filepath.Join(c.ConsoleRoot, filepath.Base(conn(work).Target.Console))) + if os.IsNotExist(err) { + return 0, nil + } + if err != nil { + return 0, err + } + want := ph.marker + boot.Receipt + if ph.name == "wipe" { + want += ":" + strconv.FormatInt(conn(work).Target.DiskBytes, 10) + } + n := 0 + for _, line := range strings.Split(string(data), "\n") { + if strings.TrimSpace(line) == want { + n++ + } + } + if ph.name == "disk" { + installed, err := c.receipts(work, boot, installPhases[0]) + if err != nil { + return 0, err + } + if installed != 1 { + return 0, errors.New("a disk receipt needs exactly one installer receipt") + } + } + if n > 1 { + return 0, fmt.Errorf("duplicate %s receipt: the phase ran more than once", ph.name) + } + return n, nil +} + +// BootDirectory is where the boot server writes an operation's delivery +// evidence. +func BootDirectory(root, operationUID string) string { + sum := sha256.Sum256([]byte(operationUID)) + return filepath.Join(root, hex.EncodeToString(sum[:])[:16]) +} + +func (c Config) deliveries(work *site.Work) map[string]bool { + data, _ := os.ReadFile(filepath.Join(BootDirectory(c.BootRoot, work.Operation.UID), "boot-delivery.log")) + done := map[string]bool{} + for _, line := range strings.Split(string(data), "\n") { + fields := strings.Fields(line) + if len(fields) == 4 && (fields[1] == "write-complete" || fields[1] == "admitted") && strings.HasPrefix(fields[3], "bytes=") { + done[fields[1]+" "+fields[2]] = true + } + } + return done +} + +func (c Config) verifyDelivery(work *site.Work) error { + done := c.deliveries(work) + for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + if !done["write-complete "+name] { + return fmt.Errorf("missing network delivery: %s", name) + } + } + return nil +} + +func sleep(ctx context.Context, d time.Duration) error { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-ctx.Done(): + return context.Cause(ctx) + case <-timer.C: + return nil + } +} + +func metaNow(at time.Time) metav1.Time { return metav1.NewTime(at.UTC()) } + +// OpenAdmission returns the open network boot admission for a boot NIC, as +// the boot server must check it: open for a network-booting phase, not +// expired, and at the Device's stored fence, so a superseded operation can +// never boot the server. +func OpenAdmission(store *site.Store, mac string, now time.Time) (Boot, bool, error) { + records, err := store.Records(bootRecords) + if err != nil { + return Boot{}, false, err + } + for _, record := range records { + var boot Boot + if json.Unmarshal(record.Data, &boot) != nil || boot.MAC != strings.ToLower(mac) || boot.Phase == "" || boot.Closed || !now.Before(boot.Expires) { + continue + } + fence, _, err := store.Current(record.Device) + if err != nil { + return Boot{}, false, err + } + if fence == boot.Fence { + return boot, true, nil + } + } + return Boot{}, false, nil +} diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go new file mode 100644 index 00000000..5a0d0c0c --- /dev/null +++ b/internal/site/redfishwork/kinds_test.go @@ -0,0 +1,316 @@ +package redfishwork + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/json" + "fmt" + "math/big" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/bmcdiscovery" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" +) + +const ( + uuid = "00000000-0000-4000-8000-000000000001" + device = "default/server-example-001" + mac = "02:00:00:00:00:01" + diskBytes = int64(64 << 30) +) + +// lab simulates one server behind a TLS Redfish BMC. Powering it on with a +// one-time override runs that boot: a network boot is delivered and prints +// its receipt; a disk boot prints the disk receipt. Then it powers off. +type lab struct { + mu sync.Mutex + t *testing.T + power string + enabled string + target string + ons int + onHook func() + server *httptest.Server + console string + bootRoot string + store *site.Store + operation string +} + +func newLab(t *testing.T) *lab { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}} + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + l := &lab{t: t, power: "Off", enabled: "Disabled", target: "None", console: filepath.Join(t.TempDir(), "console.log"), bootRoot: t.TempDir()} + l.server = httptest.NewUnstartedServer(l) + l.server.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}} + l.server.StartTLS() + t.Cleanup(l.server.Close) + return l +} + +func (l *lab) pin() string { + certificate, _ := x509.ParseCertificate(l.server.TLS.Certificates[0].Certificate[0]) + sum := sha256.Sum256(certificate.RawSubjectPublicKeyInfo) + return hex.EncodeToString(sum[:]) +} + +func (l *lab) ServeHTTP(w http.ResponseWriter, r *http.Request) { + path := "/redfish/v1/Systems/A" + l.mu.Lock() + defer l.mu.Unlock() + switch { + case r.Method == http.MethodPatch && r.URL.Path == path: + var body struct{ Boot map[string]string } + json.NewDecoder(r.Body).Decode(&body) + l.enabled, l.target = body.Boot["BootSourceOverrideEnabled"], body.Boot["BootSourceOverrideTarget"] + w.WriteHeader(http.StatusNoContent) + return + case r.Method == http.MethodPost && r.URL.Path == path+"/Actions/ComputerSystem.Reset": + var body struct{ ResetType string } + json.NewDecoder(r.Body).Decode(&body) + switch body.ResetType { + case "ForceOff": + l.power = "Off" + case "On": + l.ons++ + l.power = "On" + target := l.target + l.enabled, l.target = "Disabled", "None" + go l.boot(target) + if l.onHook != nil { + go l.onHook() + } + } + w.WriteHeader(http.StatusNoContent) + return + } + docs := map[string]any{ + "/redfish/v1": map[string]any{"@odata.id": "/redfish/v1", "Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}, + "/redfish/v1/Systems": map[string]any{"Members": []any{map[string]string{"@odata.id": path}}}, + path: map[string]any{"@odata.id": path, "Id": "A", "UUID": uuid, "PowerState": l.power, + "Boot": map[string]any{"BootSourceOverrideEnabled": l.enabled, "BootSourceOverrideTarget": l.target, "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"Pxe", "Hdd"}}, + "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": path + "/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff"}}}}, + } + doc, ok := docs[strings.TrimSuffix(r.URL.Path, "/")] + if !ok { + w.WriteHeader(http.StatusNotFound) + return + } + json.NewEncoder(w).Encode(doc) +} + +// boot runs the armed boot, as the server and the boot server would. +func (l *lab) boot(target string) { + time.Sleep(30 * time.Millisecond) + var boot Boot + if _, err := l.store.GetRecord(device, "boot", l.operation, &boot); err != nil { + l.t.Error(err) + return + } + var line string + switch { + case target == "Pxe" && boot.Mode == "wipe": + l.deliver() + line = fmt.Sprintf("FLEET-WIPED:%s:%d", boot.Receipt, diskBytes) + case target == "Pxe": + l.deliver() + line = "FLEET-INSTALLED:" + boot.Receipt + case target == "Hdd": + line = "FLEET-DISK-BOOT:" + boot.Receipt + } + file, err := os.OpenFile(l.console, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + if err == nil { + fmt.Fprintln(file, line) + file.Close() + } + l.mu.Lock() + l.power = "Off" + l.mu.Unlock() +} + +func (l *lab) deliver() { + dir := BootDirectory(l.bootRoot, l.operation) + os.MkdirAll(dir, 0o700) + log := "t admitted boot.ipxe bytes=1\n" + for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + log += "t write-complete " + name + " bytes=1\n" + } + os.WriteFile(filepath.Join(dir, "boot-delivery.log"), []byte(log), 0o600) +} + +func (l *lab) onCount() int { + l.mu.Lock() + defer l.mu.Unlock() + return l.ons +} + +type credentials struct{ pin string } + +func (c credentials) Lookup(context.Context, string) (bmcdiscovery.Credential, bool, error) { + return bmcdiscovery.Credential{Username: "operator", Password: "synthetic-secret", Pin: c.pin}, true, nil +} + +func runner(t *testing.T, l *lab) *site.Runner { + t.Helper() + root := t.TempDir() + if err := os.Chmod(root, 0o700); err != nil { + t.Fatal(err) + } + store, err := site.OpenStore(root, nil) + if err != nil { + t.Fatal(err) + } + l.store = store + config := Config{ConsoleRoot: filepath.Dir(l.console), BootRoot: l.bootRoot, Poll: 10 * time.Millisecond, OffGrace: 2 * time.Second} + return &site.Runner{ + Site: "site-example-a", Store: store, Results: site.NewResults(store), + Access: site.RedfishAccess{Credentials: credentials{pin: l.pin()}, + Targets: site.StaticTargets{device: {AssetID: "server-example-001", Endpoint: l.server.URL, SystemID: "A", SystemUUID: uuid, MAC: mac, DiskBytes: diskBytes, Console: filepath.Base(l.console)}}}, + Kinds: map[string]site.Kind{"DeviceInstallation": Installation{config}, "DeviceWipe": Wipe{config}}, + Poll: 10 * time.Millisecond, + } +} + +func assignment(l *lab, kind, uid string, fence int64, spec any) site.Assignment { + inputs, _ := json.Marshal(spec) + sum := sha256.Sum256(inputs) + l.operation = uid + return site.Assignment{ + Device: device, Operation: ops.OperationReference{Kind: kind, Name: "alloc-example-" + uid, UID: uid}, Fence: fence, AdmittedAt: time.Now(), Deadline: time.Now().Add(time.Minute), + Snapshot: ops.DeviceSnapshot{BMCEndpoint: l.server.URL, SystemUUID: uuid, BootMACAddress: mac, BMCPublicKeySHA256: l.pin()}, + InputDigest: "sha256:" + hex.EncodeToString(sum[:]), Inputs: inputs, + } +} + +func installSpec() ops.DeviceInstallationSpec { + return ops.DeviceInstallationSpec{Image: ops.ImageInput{Name: "debian-12", Digest: "sha256:" + strings.Repeat("a", 64)}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, RequestUID: "request-1"} +} + +func TestInstallationRunsBothPhasesWithOneOnEach(t *testing.T) { + l := newLab(t) + r := runner(t, l) + result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-install", 1, installSpec())) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseSucceeded || l.onCount() != 2 { + t.Fatalf("result = %+v, %d power-ons", result, l.onCount()) + } + var evidence ops.InstallationEvidence + if err := json.Unmarshal(result.Evidence, &evidence); err != nil || len(evidence.Steps) != 2 || evidence.Steps[0].Name != "installer" || evidence.Steps[1].Name != "disk" { + t.Fatalf("evidence = %s", result.Evidence) + } + if _, open, _ := OpenAdmission(r.Store, mac, time.Now()); open { + t.Fatal("the boot admission stayed open after the install") + } +} + +func TestWipeChecksTheEnrolledDisk(t *testing.T) { + l := newLab(t) + r := runner(t, l) + spec := ops.DeviceWipeSpec{Step: 1, CleaningPolicyDigest: "sha256:" + strings.Repeat("b", 64), TargetDisks: []string{"disk-0"}} + result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-wipe", 1, spec)) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseSucceeded || l.onCount() != 1 { + t.Fatalf("result = %+v, %d power-ons", result, l.onCount()) + } + // A disk the site does not enroll is refused before anything is sent. + m := newLab(t) + s := runner(t, m) + spec.TargetDisks = []string{"disk-1"} + result, _ = s.Run(context.Background(), assignment(m, "DeviceWipe", "op-wipe-other", 1, spec)) + if result.Phase != ops.PhaseFailed || result.Reason != ReasonTargetDisks || m.onCount() != 0 { + t.Fatalf("result = %+v", result) + } +} + +func TestBootstrapIsRefusedAtTheSiteToo(t *testing.T) { + l := newLab(t) + r := runner(t, l) + spec := installSpec() + spec.Bootstrap = &ops.SealedInput{Ref: "sealed-example", Digest: "sha256:" + strings.Repeat("c", 64)} + result, _ := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-bootstrap", 1, spec)) + if result.Phase != ops.PhaseFailed || l.onCount() != 0 { + t.Fatalf("result = %+v", result) + } +} + +// TestAnInterruptedWorkerResumesWithoutASecondOn kills the worker right +// after its first power-on. A new worker for the same assignment observes +// that the boot began instead of powering on again. +func TestAnInterruptedWorkerResumesWithoutASecondOn(t *testing.T) { + l := newLab(t) + r := runner(t, l) + work := assignment(l, "DeviceInstallation", "op-resume", 1, installSpec()) + ctx, cancel := context.WithCancel(context.Background()) + var once sync.Once + l.onHook = func() { once.Do(cancel) } + first, err := r.Run(ctx, work) + if err != nil { + t.Fatal(err) + } + if first.Phase != ops.PhaseOutcomeUnknown { + t.Fatalf("interrupted result = %+v", first) + } + l.onHook = nil + second, err := r.Run(context.Background(), work) + if err != nil { + t.Fatal(err) + } + if second.Phase != ops.PhaseSucceeded || l.onCount() != 2 { + t.Fatalf("resumed result = %+v, %d power-ons, want one per phase", second, l.onCount()) + } +} + +func TestOnlyTheCurrentFenceHasAnOpenBootAdmission(t *testing.T) { + l := newLab(t) + r := runner(t, l) + store := r.Store + if err := store.Raise(device, 3); err != nil { + t.Fatal(err) + } + boot := Boot{Operation: "op", Fence: 3, Mode: "install", MAC: mac, Receipt: "r", Token: strings.Repeat("0", 64), Expires: time.Now().Add(time.Minute), Phase: "installer"} + if err := store.PutRecord(device, 3, "boot", "op", boot); err != nil { + t.Fatal(err) + } + if _, open, err := OpenAdmission(store, strings.ToUpper(mac), time.Now()); err != nil || !open { + t.Fatalf("open admission not found: %v", err) + } + if err := store.Raise(device, 4); err != nil { + t.Fatal(err) + } + if _, open, _ := OpenAdmission(store, mac, time.Now()); open { + t.Fatal("a superseded operation can still boot the server") + } + if _, open, _ := OpenAdmission(store, mac, time.Now().Add(2*time.Minute)); open { + t.Fatal("an expired admission is open") + } +} + +var _ = redfish.ErrPinMismatch From 423b600ae20eb21a0aa459c8742d8df080851572 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 20:47:58 -0600 Subject: [PATCH 4/8] docs: Record the site execution framework Mark Increment B implemented and inert, record where a site stores fences and its journal, and describe the worker contract. Co-Authored-By: Claude Opus 5.5 --- docs/development/README.md | 6 +- docs/development/device-custody.md | 120 +++++++++++++++++++++++++---- docs/development/roadmap.md | 4 +- docs/operations/redfish-lab.md | 6 ++ docs/operations/site-execution.md | 1 + test/acceptance/coverage.md | 7 +- 6 files changed, 124 insertions(+), 20 deletions(-) diff --git a/docs/development/README.md b/docs/development/README.md index 200d034a..f459ea45 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -55,8 +55,10 @@ and inert: the `DeviceCustody` and Device operation kinds, the creator webhook, the kind registry and admission rule table, and the coordinator that admits, fences, holds, recovers and rebuilds custody. Tests against a real API server verify it. No deployment root, manager or staging overlay includes it, and the -Secret-backed lifecycle is unchanged. Site execution, the cutover and the -end-to-end failure scenarios are proposed. +Secret-backed lifecycle is unchanged. Increment B, the site framework with +per-Device fencing, journal, credentials and pinned TLS and the Redfish +install and wipe workers, is implemented and inert until the cutover. The +cutover and the end-to-end failure scenarios are proposed. ## API group naming diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 1d6f68c9..7fc797a5 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -13,8 +13,8 @@ marked **implemented and verified**, **implemented and inert**, or | Increment | What it covers | Status | | --- | --- | --- | | A: control-plane foundation | API types and CRDs for `DeviceCustody`, `DeviceInstallation`, `DeviceWipe` and `DeviceRecovery`; CEL rules; IAM resources and roles; the creator webhook; the kind registry and admission rule table; the coordinator's custody reconciler, admission, results, recovery, rebuild and retention; the capacity projector | **Implemented and inert.** Verified with unit tests and with tests against a real API server. No deployment root, manager, or staging overlay includes it. The existing Secret-backed lifecycle is unchanged. | -| B: site execution | Per-Device fence store and journal, older-worker stop, deadlines, fenced results, per-Device credentials, pinned TLS, the new handoff payload | **Proposed** | -| C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the projector as the only condition writer, removal of the private Secret records | **Proposed.** Starts after B. | +| B: site execution | Per-Device fence store and journal, older-worker stop with a confirmation, deadlines, fenced typed results, per-Device credentials, pinned TLS, identity checks, the handoff payload, the site fence report, and the Redfish install and wipe phases behind the worker contract | **Implemented and inert.** Unit tested, including against TLS BMC stubs. Nothing delivers to it until C; the old executors keep their own journals until C deletes them. | +| C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the projector as the only condition writer, the site access layer for the local VM and simulator executors, removal of the private Secret records and the old executor journals | **Proposed.** Starts after B. | | D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests | **Proposed** | ## What Increment A adds @@ -46,6 +46,79 @@ marked **implemented and verified**, **implemented and inert**, or Creating or importing a Device creates `Unverified` custody. That sends nothing to a BMC and makes no capacity `Available`. +## Site execution (Increment B) + +Increment B adds the site framework (`internal/site`) and the Redfish +install and wipe workers (`internal/site/redfishwork`). It is implemented and +inert. Until Increment C, the old coordinator still drives the old executors +with their own site-wide journals, and nothing delivers an assignment to the +new framework. There is no bridge between the two paths, and C deletes the old +one. + +### Where a site stores fences and its journal + +Each site keeps one directory per Device on its retained volume, under an +owner-only root. A Device's directory holds one state file and its lock. The +state file records the highest fence the site has seen, the highest fence for +which older workers are confirmed stopped, and the journal. The directory +also holds per-operation records, such as boot admissions, and the site's +copy of results. Every write replaces the file atomically and syncs it, so the +site still refuses older fences after a restart. Each Device has its own lock, +so work on one Device never waits for another. + +### What the framework owns + +- **Fences.** An assignment below the stored fence is refused and stores no + result. An equal fence is accepted again, because delivery is replayed from + custody after a crash. +- **Older-worker stop.** One worker runs per Device. A newer assignment raises + the fence, then waits for the run lock. The older worker sees the higher + fence within a second, stops, and releases the lock, and a worker that dies + releases it with its process. The newer worker then records the stop + confirmation, and the coordinator reads it as the site's `Stopped` fence. A + `DeviceRecovery` is delivered the same way and runs nothing else. +- **The journal.** Each step is journaled before it is sent and marked done + after. The journal refuses any step below the stored fence. A step found + journaled but not done is observed instead of sent again. If the observation + cannot show it took effect, the outcome is unknown. Only a step that is safe + to repeat, such as powering off before a boot was requested, is sent again. +- **Deadlines.** A worker stops at its deadline exactly. If nothing was sent, + it reports `Failed`. Otherwise it reports `OutcomeUnknown`. +- **Checks before any effect.** The inputs must match the admitted digest. The + site's enrollment must match the snapshot's BMC endpoint, system UUID and boot + MAC. The per-Device credential Secret must exist, its operator-approved pin + must equal the key discovery recorded at admission (O9), and the BMC is read + only over a connection pinned to that key. A different key aborts the TLS + handshake before any request, so no credential is sent. Each failure is a + named refusal that ends the operation `Failed` with nothing sent. +- **Results.** Each result carries the operation's fence and typed evidence, + and messages never carry a BMC response or an endpoint. The site keeps its + copy until the coordinator accepts it or rejects it for a stale fence. +- **The fence report.** Each site reports, for each Device it is configured to + serve, the fence it has seen and the fence for which it confirmed the stop. +- **Boot admissions.** A network boot is served only while the operation's + admission is open, unexpired, and at the Device's stored fence, so a + superseded operation can never boot the server. The boot server reads + admissions this way from Increment C. + +### The Redfish workers + +The install and wipe workers port the executor's phases: power off, arm a +one-time boot, power on once, then wait for exactly one console receipt and, +for a network boot, the boot server's delivery evidence. Power-on is the only +step that is not repeated after a crash; it is observed instead. Each site +enrolls one disk per server, named `disk-0`, with its size (O12). An +installation or wipe that names other disks is refused before anything is +sent. Synchronized DHCP reservations are not yet supported by the new workers. +They arrive with the cutover. + +### Access to the server + +How the framework reaches a server is behind an `Access` interface. +`RedfishAccess` performs the credential, pin and identity checks above. In C, +the local VM and simulator executors get their own access types and workers. +That adds no change to the worker contract. + ## Implementation decisions Each decision lists the open point from the implementation brief it settles. @@ -323,13 +396,13 @@ these seams. Each is decided here. | 2 | Pending replacement is scoped to the kind and the authority | A newer pending operation replaces only an older one of the same kind under the same authority. A power request never cancels a pending installation. | Implemented and inert | | 3 | Kinds add bounded snapshot fields | `SnapshotExtra` adds up to 16 camelCase fields of at most 256 bytes each. The snapshot goes to the operation, the active operation, the hold, and the site. | Implemented and inert | | 4 | The settle hook sees the hold's end time, its deadline and current Device status | The hold records when it ended (`Since`), the operation's deadline and its snapshot. The hook gets the Device as read when the recovery is admitted and again when it is applied. A hold that rebuild created has `Since` set to the rebuild time, and copies the deadline and snapshot from the operation's status, so both are absent for an operation whose status never recorded them. A hook checks for that. | Implemented and inert | -| 5 | Kinds register their refusal reasons | Each reason is declared with where it is raised. The registry refuses a malformed name, a shared name, a duplicate, or a missing source. A coordinator refusal with an undeclared reason ends `UndeclaredReason`. A recovery's refusal may carry the held kind's declared reason only when it comes from that kind's settle hook. | Implemented and inert. Worker reasons are checked when results arrive, in B. | +| 5 | Kinds register their refusal reasons | Each reason is declared with where it is raised. The registry refuses a malformed name, a shared name, a duplicate, or a missing source. A coordinator refusal, or a site result, with an undeclared reason is recorded as `UndeclaredReason`. A recovery's refusal may carry the held kind's declared reason only when it comes from that kind's settle hook. The site framework's own reasons are shared, and the Redfish workers' reasons are declared on their kinds. | Implemented and inert | | 6 | A kind may settle no hold, and declares whether `Retry` applies | `Settles` may be empty. `Retryable` marks a kind whose holds a `Retry` may unblock: a wipe, and power, whose hold settles with `Settle` and fresh discovery evidence or with `Retry` and a later power operation. A hold counts the `Retry` decisions applied to it, and the operation created after a `Retry` is named from the held operation and that count, as [Retries](#admission) describes. | Implemented and inert | | 7 | End-to-end proof that Milo enforces the CRD rules | The `custody-crd-rules` phase of both local end-to-end runs installs only these CRDs into the provider project, requires the project API to refuse eight forbidden writes, and removes them. | Implemented and verified in the local end-to-end runs | -| 8 | Journal steps carry a kind's payload | A step records a bounded payload, such as the send time or the power state before. Observation after a crash reads it. | Proposed for B | -| 9 | Delivery carries the admission time, and kinds declare a start-by window | A worker that starts after the window refuses as `Stale`, with nothing sent. | Proposed for B | -| 10 | The TLS and identity check is separate from install capabilities | The framework verifies the pin and the System only. Each kind checks the capabilities it uses, such as the Pxe and Hdd boot targets, against a pinned client bound to the verified System. | Proposed for B | -| 11 | A worker refusal with nothing sent ends `Failed` | It ends `Failed` under the operation's fence and returns a `Service` holder to `None`. It never ends `OutcomeUnknown`. | Implemented in the coordinator; the worker side arrives in B | +| 8 | Journal steps carry a kind's payload | A step records a payload of at most 1 KiB, such as the send time or the power state before, journaled before it is sent. Observation after a crash reads it back. | Implemented and inert | +| 9 | Delivery carries the admission time, and kinds declare a start-by window | A kind that implements `StartBy` refuses as `Stale` when its worker starts later than the window after admission, with nothing sent. A worker resuming steps an earlier worker sent is not stale. | Implemented and inert | +| 10 | The TLS and identity check is separate from install capabilities | The framework verifies the pin and the System only, through the Redfish client's identity walk. Each kind checks the capabilities it uses, such as the Pxe and Hdd boot targets, and drives the System through a connection bound to it. | Implemented and inert | +| 11 | A worker refusal with nothing sent ends `Failed` | It ends `Failed` under the operation's fence and returns a `Service` holder to `None`. It never ends `OutcomeUnknown`. Whether anything was sent comes from the journal. | Implemented and inert | | 12 | The single writer of `Machine.status.power` | The manager's Machine status projector stays the only writer. It reads the custody of the Machine's allocation: while a recovery hold exists it reports power `Unknown`, and otherwise it reports the power state of the last succeeded power operation's evidence or of discovery, whichever is newer. | Proposed for C | None of these conflicts with #174. @@ -394,12 +467,21 @@ four seams. It needs no change to the coordinator. The test-only kinds in with `HoldSettlesRequired`. Staff rows never queue. To admit a new service principal, add its class to the coordinator's principal configuration. Never hard-code an identity. -3. **Implement its site worker** (Increment B). The site framework owns the - fence, the journal, credential lookup, the TLS pin and identity checks, the - deadline and result delivery. A kind supplies only its pre-effect checks, - which refuse with a named reason and send nothing, its journaled steps, how - it recovers by observation after a lost response, and its typed result - evidence. The worker contract is proposed and lands in Increment B. +3. **Implement its site worker.** Implement `site.Kind`: `Check` runs after the + framework's checks and must not change the server, and checks the + capabilities the kind uses. `Run` performs every effect through + `Work.Step` with a `site.Step`. Give each step a bounded `Payload` for what + its observation needs, and an `Observe` that reads the server and that + payload to show whether the step took effect, for replay after a crash or + a lost response. Mark a step `Idempotent` only if sending it twice is + harmless. Implement `site.StartBy` if the work must begin soon after + admission. Return the + typed evidence. The framework owns the fence, the journal, the credential + lookup, the TLS pin and identity checks, the deadline, and result delivery, + and a kind never implements them. A Redfish kind reads its connection from + `Work.Connection` as a `*site.RedfishConnection`. Register the worker in + the site's `Runner.Kinds` under the kind's name. See + `internal/site/redfishwork` and its tests. 4. **Define its evidence.** Set `Evidence` to `custody.StrictEvidence` over a typed, bounded Go struct. Its validator receives the operation, so it can require what that operation must prove, such as reset proof for a @@ -448,3 +530,15 @@ Both local end-to-end runs include the `custody-crd-rules` phase. It proves that a Milo project API refuses every write the CRD rules forbid, which envtest alone cannot show, because Milo ignores admission policies stored in a project. + +Increment B's site tests run with `go test -race ./internal/site/...`: + +| Area | Tests | +| --- | --- | +| Stale fences and steps refused, also after a restart; replay observed | `TestStoreRefusesOlderFencesAndSurvivesARestart`, `TestStoreReplaysAJournaledStepAsAnObservation` | +| Two workers on one Device, two Devices in parallel | `TestTwoWorkersOnOneDevice`, `TestTwoDevicesInParallel`, `TestANewerFenceStopsTheOlderWorker` | +| A TLS pin mismatch and an identity mismatch send nothing, against TLS servers | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing` | +| Every pre-effect refusal, stale assignments, deadlines, result deletion, payload validation | `TestPreEffectRefusalsSendNothing`, `TestAStaleAssignmentIsRefusedAndStoresNothing`, `TestAWorkerStopsAtItsDeadline`, `TestResultsAreDeletedOnceTheCoordinatorAnswers`, `TestAssignmentValidation` | +| Per-Device credentials, the fence report | `TestSecretCredentialsUseThePerDeviceContract`, `TestReportGivesTheCoordinatorSeenAndStoppedFences` | +| Step payloads, the start-by window, identity separate from capabilities, a resumed worker reporting unknown | `TestAStepPayloadIsJournaledAndReadBack`, `TestALateStartIsStaleAndSendsNothing`, `TestIdentityIsSeparateFromInstallCapabilities`, `TestAResumedWorkerThatCannotReachTheBMCReportsUnknown` | +| Install and wipe against a simulated BMC, one power-on per phase after an interruption, fenced boot admission, bootstrap refused | `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestBootstrapIsRefusedAtTheSiteToo` | diff --git a/docs/development/roadmap.md b/docs/development/roadmap.md index 10629347..767f0644 100644 --- a/docs/development/roadmap.md +++ b/docs/development/roadmap.md @@ -48,8 +48,8 @@ and incomplete cleaning cannot cause duplicate effects or premature reuse. The [device custody and operations work](device-custody.md) replaces per-allocation fencing with one custody record per Device, ahead of real hardware qualification. Increment A, the inert control-plane foundation, is -implemented. Increments B (site execution), C (cutover) and D (end-to-end -failure scenarios) are proposed. An allocation's private facts will live on +implemented, and so is Increment B, the inert site execution framework. +Increments C (cutover) and D (end-to-end failure scenarios) are proposed. An allocation's private facts will live on its MachineAllocation, which C implements after B. Acceptance: the #174 acceptance tests pass, in envtest and in fresh local diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index a96498ff..92edf39b 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -129,6 +129,12 @@ later. ## Redfish executor contract +The [site framework for Device custody](../development/device-custody.md#site-execution-increment-b) +ports the install and wipe phases below to per-Device fencing, a per-Device +journal and per-Device credentials with the approved TLS pin. It is +implemented and inert. This lab still runs the executor described here until +the cutover. + `internal/redfish` implements `executor.Client` behind the unchanged `LocalAssetMapping`, coordination and lifecycle code. It has no process execution, libvirt client or lab dependency. A Go test parses its imports to diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index fec814ef..311c7d80 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -362,6 +362,7 @@ container and is unchanged. | Redfish execution Jobs with no libvirt path, against the DMTF Redfish Interface Emulator and lab VMs | Implemented as a separate mode; see [Redfish-mode acceptance](redfish-lab.md) for its run record | | Synchronized DHCP boot reservations with served and withdrawn evidence | Implemented and unit tested; not exercised at a site ([Boot network](boot-network.md)) | | Physical Redfish/BMC execution Jobs | Not qualified (lab emulator only; see the [hardware readiness checklist](redfish-lab.md#limitations-and-physical-hardware-readiness)) | +| Per-Device fence store and journal, older-worker stop with a confirmation, worker deadlines, fenced typed results, per-Device credentials with the approved TLS pin, and the operation handoff payload ([device custody](../development/device-custody.md#site-execution-increment-b)) | Implemented and inert: unit tested, and nothing at the site runs it until the cutover. The site-wide journal above still drives this acceptance. | ## Independent review of the recorded run diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 3e4dd6f4..17e913fd 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -32,8 +32,8 @@ result reports every required phase `Passed`. ## Device custody and operations These are the acceptance tests of [#174 at `d4d17f9`](https://github.com/datum-cloud/fleet/pull/174). -Increment A covers them against a real API server. End-to-end coverage arrives -in Increments C and D. See [device custody](../../docs/development/device-custody.md#tests). +Increment A covers them against a real API server, and Increment B covers the +site side in unit tests. End-to-end coverage arrives in Increments C and D. See [device custody](../../docs/development/device-custody.md#tests). | #174 acceptance test | Executable evidence | Current state | | --- | --- | --- | @@ -43,7 +43,8 @@ in Increments C and D. See [device custody](../../docs/development/device-custod | A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope; the mechanism is envtest verified | | A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery` | Envtest verified; end to end proposed | | A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery` | Envtest verified with a fake site; end to end proposed | -| A delayed worker's step after a newer admission is refused by the journal | None yet | Proposed in B | +| A delayed worker's step after a newer admission is refused by the journal | `TestTwoWorkersOnOneDevice`, `TestANewerFenceStopsTheOlderWorker`, `TestStoreRefusesOlderFencesAndSurvivesARestart` | Unit verified; end to end proposed | +| A TLS pin mismatch or an identity mismatch sends nothing | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`, against TLS servers | Unit verified; the emulator lab has no TLS | | Custody deleted and restored stays unallocatable until rebuilt with a higher fence | `TestRebuild` | Envtest verified with a fake site; end to end proposed | | A Machine deleted during installation; release waits; a wipe settles the install hold | `TestLifecycle`, `TestRecovery` | Envtest verified; end to end proposed | | No staff role can read a bootstrap payload | `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets` | Role definitions verified; bootstrap stays refused | From caf164c5be096aa6dfea07c4416aced04d2d03bb Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 21:39:09 -0600 Subject: [PATCH 5/8] fix(site): Keep one result per assignment and resume interrupted work A worker that finds the same assignment already holding the run lock now stores nothing and leaves the result to that worker. Any other refusal is Failed only when the journal holds nothing for the operation. A stored result is final, and a redelivery returns it. A worker stopped from outside stores no result, so its replacement resumes from the journal. The fence is checked again just before each send. The Redfish workers journal each verified phase and skip it on resume, so a worker interrupted in the disk phase continues. Power-off is bounded at five minutes again, and the receipt wait after power-off is 30 seconds, as in the old executor. Co-Authored-By: Claude Opus 5.5 --- internal/site/redfishwork/kinds.go | 33 ++++++++- internal/site/redfishwork/kinds_test.go | 59 ++++++++++++++-- internal/site/results.go | 66 ++++++++++++++++-- internal/site/runner.go | 68 +++++++++++++++--- internal/site/runner_test.go | 93 +++++++++++++++++++++++++ 5 files changed, 296 insertions(+), 23 deletions(-) diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 30cf7376..b59a7c52 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -62,7 +62,10 @@ type Config struct { OffGrace, Outage time.Duration // BootWindow bounds how long a network boot admission stays open. BootWindow time.Duration - Now func() time.Time + // PowerOffBound bounds how long the server may take to power off. It + // defaults to five minutes. + PowerOffBound time.Duration + Now func() time.Time } func (c Config) now() time.Time { @@ -78,7 +81,7 @@ func (c Config) durations() (poll, offGrace, outage, window time.Duration) { poll = 2 * time.Second } if offGrace <= 0 { - offGrace = time.Minute + offGrace = 30 * time.Second } if outage <= 0 { outage = 5 * time.Minute @@ -241,12 +244,20 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops } var evidence []ops.StepEvidence for _, ph := range phases { + // A phase verified by an earlier worker is done; resume after it. + if work.Journaled(ph.name + "-verified") { + evidence = append(evidence, ops.StepEvidence{Name: ph.name, CompletedAt: metaNow(c.now())}) + continue + } + // The boot admission is checked only before this phase's boot is + // requested; a resumed worker whose boot already began observes it. + requested := work.Journaled(ph.name + "-power-on") // Power off and arm the one-time override. Both are safe to send // again: no boot of this phase has been requested yet. if err := work.Step(ctx, site.Step{Name: ph.name + "-power-off", Send: func(ctx context.Context) error { return c.powerOff(ctx, work) }, Idempotent: true}); err != nil { return nil, err } - if ph.mode != "" { + if ph.mode != "" && !requested { if boot.Closed || !c.now().Before(boot.Expires) { return nil, errors.New("boot admission expired or closed before the network boot") } @@ -280,14 +291,27 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops return nil, err } } + // Journal the verified phase, so a resumed worker skips it. + if err := work.Step(ctx, site.Step{Name: ph.name + "-verified", Send: func(context.Context) error { return nil }, Idempotent: true}); err != nil { + return nil, err + } evidence = append(evidence, ops.StepEvidence{Name: ph.name, CompletedAt: metaNow(c.now())}) } return evidence, nil } +// defaultPowerOffBound is how long the server may take to power off, as the +// old executor allowed. +const defaultPowerOffBound = 5 * time.Minute + func (c Config) powerOff(ctx context.Context, work *site.Work) error { poll, _, _, _ := c.durations() requested := false + bound := c.PowerOffBound + if bound <= 0 { + bound = defaultPowerOffBound + } + deadline := c.now().Add(bound) for { power, err := conn(work).Observe(ctx) if err != nil { @@ -303,6 +327,9 @@ func (c Config) powerOff(ctx context.Context, work *site.Work) error { } requested = true } + if c.now().After(deadline) { + return errors.New("the server did not power off") + } if err := sleep(ctx, poll); err != nil { return err } diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 5a0d0c0c..29919c7d 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -10,6 +10,7 @@ import ( "crypto/x509" "encoding/hex" "encoding/json" + "errors" "fmt" "math/big" "net" @@ -46,6 +47,7 @@ type lab struct { target string ons int onHook func() + ignoreOff bool server *httptest.Server console string bootRoot string @@ -94,7 +96,9 @@ func (l *lab) ServeHTTP(w http.ResponseWriter, r *http.Request) { json.NewDecoder(r.Body).Decode(&body) switch body.ResetType { case "ForceOff": - l.power = "Off" + if !l.ignoreOff { + l.power = "Off" + } case "On": l.ons++ l.power = "On" @@ -271,12 +275,10 @@ func TestAnInterruptedWorkerResumesWithoutASecondOn(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) var once sync.Once l.onHook = func() { once.Do(cancel) } - first, err := r.Run(ctx, work) - if err != nil { - t.Fatal(err) - } - if first.Phase != ops.PhaseOutcomeUnknown { - t.Fatalf("interrupted result = %+v", first) + // The worker is stopped from outside, as a Pod would be, and stores + // no result. + if _, err := r.Run(ctx, work); !errors.Is(err, context.Canceled) { + t.Fatalf("interrupted: %v", err) } l.onHook = nil second, err := r.Run(context.Background(), work) @@ -314,3 +316,46 @@ func TestOnlyTheCurrentFenceHasAnOpenBootAdmission(t *testing.T) { } var _ = redfish.ErrPinMismatch + +// TestAWorkerInterruptedInTheDiskPhaseResumes kills the worker after the +// disk phase's power-on. The new worker skips the verified installer phase +// and observes the disk boot, with no further power-on. +func TestAWorkerInterruptedInTheDiskPhaseResumes(t *testing.T) { + l := newLab(t) + r := runner(t, l) + work := assignment(l, "DeviceInstallation", "op-disk-resume", 1, installSpec()) + ctx, cancel := context.WithCancel(context.Background()) + l.onHook = func() { + if l.onCount() == 2 { + cancel() + } + } + if _, err := r.Run(ctx, work); !errors.Is(err, context.Canceled) { + t.Fatalf("interrupted: %v", err) + } + l.onHook = nil + second, err := r.Run(context.Background(), work) + if err != nil { + t.Fatal(err) + } + if second.Phase != ops.PhaseSucceeded || l.onCount() != 2 { + t.Fatalf("resumed result = %+v, %d power-ons", second, l.onCount()) + } +} + +func TestAServerThatNeverPowersOffEndsTheStep(t *testing.T) { + l := newLab(t) + l.power = "On" + l.ignoreOff = true + r := runner(t, l) + installation := r.Kinds["DeviceInstallation"].(Installation) + installation.PowerOffBound = 100 * time.Millisecond + r.Kinds["DeviceInstallation"] = installation + result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-stuck-on", 1, installSpec())) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseOutcomeUnknown || l.onCount() != 0 { + t.Fatalf("result = %+v, %d power-ons", result, l.onCount()) + } +} diff --git a/internal/site/results.go b/internal/site/results.go index ce63ba61..36a2571f 100644 --- a/internal/site/results.go +++ b/internal/site/results.go @@ -8,6 +8,7 @@ import ( "path/filepath" "sort" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/custody" ) @@ -26,13 +27,70 @@ func (r *Results) dir(device string) string { return filepath.Join(r.store.deviceDir(device), "results") } -// Put stores a result, named by its operation UID and fence. -func (r *Results) Put(device string, result custody.SiteResult) error { +// Put stores a result, named by its operation UID and fence, unless one is +// already stored for them. A stored result is final: a redelivered +// assignment never replaces it, so a success still waiting for delivery +// cannot be lost, and Deliver never deletes a result it did not offer. Put +// returns the result that is stored. +func (r *Results) Put(device string, result custody.SiteResult) (custody.SiteResult, error) { dir := r.dir(device) if err := os.MkdirAll(dir, 0o700); err != nil { - return err + return result, err + } + data, err := json.Marshal(storedResult{Device: device, Result: result}) + if err != nil { + return result, err + } + file, err := os.CreateTemp(dir, "result.tmp-*") + if err != nil { + return result, err + } + defer os.Remove(file.Name()) + if _, err := file.Write(data); err != nil { + file.Close() + return result, err + } + if err := file.Sync(); err != nil { + file.Close() + return result, err + } + if err := file.Close(); err != nil { + return result, err + } + // A hard link creates the name only if it is absent, with its whole + // content, so a reader never sees a partial result. + if err := os.Link(file.Name(), filepath.Join(dir, resultName(result))); err != nil { + if os.IsExist(err) { + stored, found, readErr := r.Get(device, result.Operation.UID, result.Fence) + if readErr != nil || !found { + return result, errors.New("site: a stored result is unreadable") + } + return stored, nil + } + return result, err + } + parent, err := os.Open(dir) + if err != nil { + return result, err + } + defer parent.Close() + return result, parent.Sync() +} + +// Get returns the stored result for an operation and fence. +func (r *Results) Get(device, operation string, fence int64) (custody.SiteResult, bool, error) { + data, err := os.ReadFile(filepath.Join(r.dir(device), resultName(custody.SiteResult{Operation: ops.OperationReference{UID: operation}, Fence: fence}))) + if os.IsNotExist(err) { + return custody.SiteResult{}, false, nil + } + if err != nil { + return custody.SiteResult{}, false, err + } + var stored storedResult + if err := json.Unmarshal(data, &stored); err != nil { + return custody.SiteResult{}, false, errors.New("site: a stored result is unreadable") } - return writeAtomic(dir, resultName(result), storedResult{Device: device, Result: result}) + return stored.Result, true, nil } func resultName(result custody.SiteResult) string { diff --git a/internal/site/runner.go b/internal/site/runner.go index eb016315..fb35ff26 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -121,6 +121,17 @@ type StartBy interface { // Store is the site's store, for a kind's per-operation records. func (w *Work) Store() *Store { return w.store } +// Journaled reports whether a step of this operation is journaled done. +func (w *Work) Journaled(step string) bool { + journal, err := w.store.Journal(w.Device) + if err != nil { + return false + } + return slices.ContainsFunc(journal, func(entry Entry) bool { + return entry.Operation == w.Operation.UID && entry.Step == step && entry.State == StepDone + }) +} + // Step journals a step, then sends it, then records it done. A step found // journaled but not done, after a crash or a lost response, is observed // instead of sent again, unless it is Idempotent; if the observation cannot @@ -166,6 +177,13 @@ func (w *Work) Step(ctx context.Context, step Step) error { return nil default: w.sent = true + // The fence is checked again just before the send, so a newer + // admission stored after the step was journaled stops it. + if fence, _, err := w.store.Current(w.Device); err != nil { + return err + } else if fence > w.Fence { + return errSuperseded + } if err := step.Send(ctx); err != nil { return err } @@ -258,6 +276,10 @@ func (r *Runner) acquire(ctx context.Context, assignment Assignment) (*runLock, var errWorkerRunning = errors.New("an older worker did not stop before the deadline") +// ErrAlreadyRunning means another worker already runs this same assignment. +// No result is stored; that worker reports it. +var ErrAlreadyRunning = errors.New("site: another worker runs this assignment") + // Run executes one assignment and stores its result. It returns // ErrStaleFence, and stores nothing, for an assignment below the Device's // stored fence. @@ -265,24 +287,49 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe if err := assignment.Validate(); err != nil { return custody.SiteResult{}, err } + // A redelivered assignment that already has a result returns it. + if stored, found, err := r.Results.Get(assignment.Device, assignment.Operation.UID, assignment.Fence); err != nil || found { + return stored, err + } result := custody.SiteResult{Site: r.Site, Device: deviceName(assignment.Device), Operation: assignment.Operation, Fence: assignment.Fence} finish := func(phase ops.Phase, reason, message string, evidence []byte) (custody.SiteResult, error) { result.Phase, result.Reason, result.Message, result.Evidence = phase, reason, message, evidence - if err := r.Results.Put(assignment.Device, result); err != nil { - return result, err + return r.Results.Put(assignment.Device, result) + } + // Whether anything may have been sent comes from the journal, not from + // this process: an earlier worker for the same operation may have sent + // steps before it was interrupted, or may still be running. + sent := func() (bool, error) { + journal, err := r.Store.Journal(assignment.Device) + if err != nil { + return false, err } - return result, nil + return slices.ContainsFunc(journal, func(entry Entry) bool { return entry.Operation == assignment.Operation.UID }), nil } lock, err := r.acquire(ctx, assignment) switch { case errors.Is(err, ErrStaleFence): return custody.SiteResult{}, err case errors.Is(err, errWorkerRunning): + // A worker at this assignment's own fence took the run lock: it is + // running this same operation and will report it. An older worker + // can never take the lock once this fence is stored. + if _, stopped, serr := r.Store.Current(assignment.Device); serr == nil && stopped == assignment.Fence { + return custody.SiteResult{}, ErrAlreadyRunning + } + journaled, jerr := sent() + if jerr != nil { + return custody.SiteResult{}, jerr + } + if journaled { + return finish(ops.PhaseOutcomeUnknown, ReasonWorkerRunning, err.Error(), nil) + } return finish(ops.PhaseFailed, ReasonWorkerRunning, err.Error(), nil) case err != nil: return custody.SiteResult{}, err } defer lock.release() + parent := ctx // The worker stops at its deadline exactly, and as soon as a newer fence // is stored for the Device. ctx, cancel := context.WithDeadlineCause(ctx, assignment.Deadline, errDeadline) @@ -292,14 +339,9 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe go r.watch(ctx, assignment, stop) work := &Work{Assignment: assignment, store: r.Store} - // Whether anything may have been sent comes from the journal, not from - // this process: an earlier worker for the same operation may have sent - // steps before it was interrupted. - journal, err := r.Store.Journal(assignment.Device) - if err != nil { + if work.sent, err = sent(); err != nil { return custody.SiteResult{}, err } - work.sent = slices.ContainsFunc(journal, func(entry Entry) bool { return entry.Operation == assignment.Operation.UID }) end := func(reason, message string) (custody.SiteResult, error) { if work.sent { return finish(ops.PhaseOutcomeUnknown, reason, message, nil) @@ -315,9 +357,17 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe return end(ReasonStale, "the worker started too long after admission") } if refusal := r.prepare(ctx, work); refusal != nil { + if parent.Err() != nil { + return custody.SiteResult{}, context.Cause(parent) + } return end(refusal.Reason, refusal.Message) } evidence, err := r.Kinds[assignment.Operation.Kind].Run(ctx, work) + // A worker stopped from outside, such as a Pod being shut down, stores + // no result: its replacement resumes from the journal. + if err != nil && parent.Err() != nil { + return custody.SiteResult{}, context.Cause(parent) + } if err != nil { var refusal *custody.Refusal if errors.As(err, &refusal) { diff --git a/internal/site/runner_test.go b/internal/site/runner_test.go index 2283e9da..6914baba 100644 --- a/internal/site/runner_test.go +++ b/internal/site/runner_test.go @@ -135,6 +135,9 @@ type fakeKind struct { block chan struct{} observe func(context.Context, json.RawMessage) (bool, error) check func(*Work) + // stuck makes a blocked step ignore cancellation, as a worker that does + // not stop would. + stuck bool } func (k *fakeKind) Check(_ context.Context, work *Work) *custody.Refusal { @@ -149,6 +152,10 @@ func (k *fakeKind) Run(ctx context.Context, work *Work) (any, error) { err := work.Step(ctx, Step{Name: step, Payload: map[string]string{"step": step}, Send: func(ctx context.Context) error { k.sends.Add(1) if k.block != nil { + if k.stuck { + <-k.block + return nil + } select { case <-k.block: case <-ctx.Done(): @@ -575,3 +582,89 @@ func TestIdentityIsSeparateFromInstallCapabilities(t *testing.T) { t.Fatalf("result = %+v, system = %+v", result, system) } } + +// TestARedeliveryWhileTheSameOperationRunsStoresNothing reproduces a rolling +// restart that overlaps two workers for one assignment. The second cannot get +// the run lock and leaves the result to the first, which has sent a step. +func TestARedeliveryWhileTheSameOperationRunsStoresNothing(t *testing.T) { + f := newFixture(t, testUUID) + f.kind.block = make(chan struct{}) + first := make(chan custody.SiteResult, 1) + go func() { + result, err := f.runner.Run(context.Background(), f.assignment(1, "op-same")) + if err != nil { + t.Error(err) + } + first <- result + }() + waitFor(t, func() bool { return f.kind.sends.Load() == 1 }) + again := f.assignment(1, "op-same") + again.Deadline = time.Now().Add(200 * time.Millisecond) + if _, err := f.runner.Run(context.Background(), again); !errors.Is(err, ErrAlreadyRunning) { + t.Fatalf("redelivery: %v", err) + } + if _, found, _ := f.runner.Results.Get(testDevice, "op-same", 1); found { + t.Fatal("the redelivery stored a result while the first worker ran") + } + close(f.kind.block) + if result := <-first; result.Phase != ops.PhaseSucceeded { + t.Fatalf("first worker = %+v", result) + } +} + +// TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing covers an +// older worker that does not stop: the newer assignment sent nothing, so it +// ends Failed. +func TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing(t *testing.T) { + f := newFixture(t, testUUID) + f.kind.block, f.kind.stuck = make(chan struct{}), true + done := make(chan struct{}) + defer func() { close(f.kind.block); <-done }() + go func() { defer close(done); _, _ = f.runner.Run(context.Background(), f.assignment(1, "op-stuck")) }() + waitFor(t, func() bool { return f.kind.sends.Load() == 1 }) + newer := f.assignment(2, "op-newer") + newer.Deadline = time.Now().Add(300 * time.Millisecond) + result, err := f.runner.Run(context.Background(), newer) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseFailed || result.Reason != ReasonWorkerRunning || f.kind.sends.Load() != 1 { + t.Fatalf("result = %+v", result) + } +} + +// TestAStoredResultSurvivesARedelivery proves a success still waiting for +// delivery is never replaced by a redelivered assignment's refusal. +func TestAStoredResultSurvivesARedelivery(t *testing.T) { + f := newFixture(t, testUUID) + first, err := f.runner.Run(context.Background(), f.assignment(1, "op-kept")) + if err != nil || first.Phase != ops.PhaseSucceeded { + t.Fatalf("first = %+v %v", first, err) + } + f.access().Credentials = fixedCredentials{} + again, err := f.runner.Run(context.Background(), f.assignment(1, "op-kept")) + if err != nil || again.Phase != ops.PhaseSucceeded || f.kind.sends.Load() != 2 { + t.Fatalf("redelivered = %+v %v, sends %d", again, err, f.kind.sends.Load()) + } + // Put keeps the first result even when called again directly. + stored, err := f.runner.Results.Put(testDevice, custody.SiteResult{Operation: first.Operation, Fence: 1, Phase: ops.PhaseOutcomeUnknown}) + if err != nil || stored.Phase != ops.PhaseSucceeded { + t.Fatalf("stored = %+v %v", stored, err) + } +} + +func TestAWorkerStoppedFromOutsideStoresNoResult(t *testing.T) { + f := newFixture(t, testUUID) + f.kind.block = make(chan struct{}) + ctx, cancel := context.WithCancel(context.Background()) + go func() { + waitFor(t, func() bool { return f.kind.sends.Load() == 1 }) + cancel() + }() + if _, err := f.runner.Run(ctx, f.assignment(1, "op-shutdown")); !errors.Is(err, context.Canceled) { + t.Fatalf("shutdown: %v", err) + } + if _, found, _ := f.runner.Results.Get(testDevice, "op-shutdown", 1); found { + t.Fatal("a worker shut down from outside stored a result") + } +} From 9becc67c0a6e7424720c61e402154c0795c51ce7 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 21:39:09 -0600 Subject: [PATCH 6/8] docs: Record how the site keeps one result per assignment Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 42 +++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 7fc797a5..39746088 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -70,7 +70,8 @@ so work on one Device never waits for another. - **Fences.** An assignment below the stored fence is refused and stores no result. An equal fence is accepted again, because delivery is replayed from - custody after a crash. + custody after a crash. The fence is checked when a step is journaled and + again just before it is sent. - **Older-worker stop.** One worker runs per Device. A newer assignment raises the fence, then waits for the run lock. The older worker sees the higher fence within a second, stops, and releases the lock, and a worker that dies @@ -82,18 +83,29 @@ so work on one Device never waits for another. journaled but not done is observed instead of sent again. If the observation cannot show it took effect, the outcome is unknown. Only a step that is safe to repeat, such as powering off before a boot was requested, is sent again. -- **Deadlines.** A worker stops at its deadline exactly. If nothing was sent, - it reports `Failed`. Otherwise it reports `OutcomeUnknown`. +- **Deadlines and shutdown.** A worker stops at its deadline exactly. If the + journal holds nothing for the operation, it reports `Failed`. Otherwise it + reports `OutcomeUnknown`. A worker stopped from outside, such as a Pod + being shut down, stores no result, so its replacement resumes from the + journal. +- **One worker per assignment.** A redelivered assignment that already has a + result returns it. One that finds a worker for the same assignment holding + the run lock stores nothing and leaves the result to that worker. A newer + assignment that cannot stop an older worker before its deadline ends + `Failed`, or `OutcomeUnknown` if the journal holds steps for it. - **Checks before any effect.** The inputs must match the admitted digest. The site's enrollment must match the snapshot's BMC endpoint, system UUID and boot MAC. The per-Device credential Secret must exist, its operator-approved pin must equal the key discovery recorded at admission (O9), and the BMC is read only over a connection pinned to that key. A different key aborts the TLS handshake before any request, so no credential is sent. Each failure is a - named refusal that ends the operation `Failed` with nothing sent. + named refusal. It ends the operation `Failed` when the journal holds + nothing for it, and `OutcomeUnknown` when an earlier worker for the same + operation journaled steps. - **Results.** Each result carries the operation's fence and typed evidence, - and messages never carry a BMC response or an endpoint. The site keeps its - copy until the coordinator accepts it or rejects it for a stale fence. + and messages never carry a BMC response or an endpoint. A stored result is + final: nothing replaces it. The site keeps its copy until the coordinator + accepts it or rejects it for a stale fence. - **The fence report.** Each site reports, for each Device it is configured to serve, the fence it has seen and the fence for which it confirmed the stop. - **Boot admissions.** A network boot is served only while the operation's @@ -109,8 +121,19 @@ for a network boot, the boot server's delivery evidence. Power-on is the only step that is not repeated after a crash; it is observed instead. Each site enrolls one disk per server, named `disk-0`, with its size (O12). An installation or wipe that names other disks is refused before anything is -sent. Synchronized DHCP reservations are not yet supported by the new workers. -They arrive with the cutover. +sent. Each verified phase is journaled, so a resumed worker continues from +the next phase. + +The port differs from the old executor in three ways: + +- After a crash or a lost response, a power-on is observed and never sent + again. The old executor sent `On` again, up to a small budget, when the + server was still off and armed after a settle window. +- Synchronized DHCP reservations are not yet supported by the new workers. + They arrive with the cutover. +- Its timing values match the old executor's, including the five-minute + power-off bound and the 30-second wait for a receipt after power-off, and + each is configurable. ### Access to the server @@ -539,6 +562,7 @@ Increment B's site tests run with `go test -race ./internal/site/...`: | Two workers on one Device, two Devices in parallel | `TestTwoWorkersOnOneDevice`, `TestTwoDevicesInParallel`, `TestANewerFenceStopsTheOlderWorker` | | A TLS pin mismatch and an identity mismatch send nothing, against TLS servers | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing` | | Every pre-effect refusal, stale assignments, deadlines, result deletion, payload validation | `TestPreEffectRefusalsSendNothing`, `TestAStaleAssignmentIsRefusedAndStoresNothing`, `TestAWorkerStopsAtItsDeadline`, `TestResultsAreDeletedOnceTheCoordinatorAnswers`, `TestAssignmentValidation` | +| One worker per assignment, final results, shutdown, an older worker that does not stop | `TestARedeliveryWhileTheSameOperationRunsStoresNothing`, `TestAStoredResultSurvivesARedelivery`, `TestAWorkerStoppedFromOutsideStoresNoResult`, `TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing` | | Per-Device credentials, the fence report | `TestSecretCredentialsUseThePerDeviceContract`, `TestReportGivesTheCoordinatorSeenAndStoppedFences` | | Step payloads, the start-by window, identity separate from capabilities, a resumed worker reporting unknown | `TestAStepPayloadIsJournaledAndReadBack`, `TestALateStartIsStaleAndSendsNothing`, `TestIdentityIsSeparateFromInstallCapabilities`, `TestAResumedWorkerThatCannotReachTheBMCReportsUnknown` | -| Install and wipe against a simulated BMC, one power-on per phase after an interruption, fenced boot admission, bootstrap refused | `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestBootstrapIsRefusedAtTheSiteToo` | +| Install and wipe against a simulated BMC, one power-on per phase after an interruption in either phase, the power-off bound, fenced boot admission, bootstrap refused | `TestAWorkerInterruptedInTheDiskPhaseResumes`, `TestAServerThatNeverPowersOffEndsTheStep`, `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestBootstrapIsRefusedAtTheSiteToo` | From e4ec436c094621cb79a345a85fa9f70ccf5d6e86 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 21:47:36 -0600 Subject: [PATCH 7/8] fix(site): Store nothing when shut down while waiting for the lock A worker stopped from outside while it waits for the run lock now stores no result, like one stopped during its checks or its steps. A resumed phase keeps the time it was first verified. Add tests for each shutdown stage, a lost lock with journaled steps, a fence raised between journal and send, and the power-off bound's reason and timing. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 2 +- internal/site/redfishwork/kinds.go | 4 +- internal/site/redfishwork/kinds_test.go | 6 +- internal/site/runner.go | 27 ++++++-- internal/site/runner_test.go | 90 ++++++++++++++++++++++++- 5 files changed, 119 insertions(+), 10 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 39746088..27c8c212 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -562,7 +562,7 @@ Increment B's site tests run with `go test -race ./internal/site/...`: | Two workers on one Device, two Devices in parallel | `TestTwoWorkersOnOneDevice`, `TestTwoDevicesInParallel`, `TestANewerFenceStopsTheOlderWorker` | | A TLS pin mismatch and an identity mismatch send nothing, against TLS servers | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing` | | Every pre-effect refusal, stale assignments, deadlines, result deletion, payload validation | `TestPreEffectRefusalsSendNothing`, `TestAStaleAssignmentIsRefusedAndStoresNothing`, `TestAWorkerStopsAtItsDeadline`, `TestResultsAreDeletedOnceTheCoordinatorAnswers`, `TestAssignmentValidation` | -| One worker per assignment, final results, shutdown, an older worker that does not stop | `TestARedeliveryWhileTheSameOperationRunsStoresNothing`, `TestAStoredResultSurvivesARedelivery`, `TestAWorkerStoppedFromOutsideStoresNoResult`, `TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing` | +| One worker per assignment, final results, shutdown at each stage, an older worker that does not stop, a fence raised between journal and send | `TestARedeliveryWhileTheSameOperationRunsStoresNothing`, `TestAStoredResultSurvivesARedelivery`, `TestAWorkerStoppedFromOutsideStoresNoResult`, `TestAShutdownWhileWaitingForTheRunLockStoresNothing`, `TestAShutdownDuringTheChecksStoresNothing`, `TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing`, `TestALostLockWithJournaledStepsIsUnknown`, `TestAFenceRaisedBetweenJournalAndSendStopsTheStep` | | Per-Device credentials, the fence report | `TestSecretCredentialsUseThePerDeviceContract`, `TestReportGivesTheCoordinatorSeenAndStoppedFences` | | Step payloads, the start-by window, identity separate from capabilities, a resumed worker reporting unknown | `TestAStepPayloadIsJournaledAndReadBack`, `TestALateStartIsStaleAndSendsNothing`, `TestIdentityIsSeparateFromInstallCapabilities`, `TestAResumedWorkerThatCannotReachTheBMCReportsUnknown` | | Install and wipe against a simulated BMC, one power-on per phase after an interruption in either phase, the power-off bound, fenced boot admission, bootstrap refused | `TestAWorkerInterruptedInTheDiskPhaseResumes`, `TestAServerThatNeverPowersOffEndsTheStep`, `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestBootstrapIsRefusedAtTheSiteToo` | diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index b59a7c52..cb616ec6 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -245,8 +245,8 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops var evidence []ops.StepEvidence for _, ph := range phases { // A phase verified by an earlier worker is done; resume after it. - if work.Journaled(ph.name + "-verified") { - evidence = append(evidence, ops.StepEvidence{Name: ph.name, CompletedAt: metaNow(c.now())}) + if at, done := work.JournaledAt(ph.name + "-verified"); done { + evidence = append(evidence, ops.StepEvidence{Name: ph.name, CompletedAt: metaNow(at)}) continue } // The boot admission is checked only before this phase's boot is diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 29919c7d..79fa21c2 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -351,11 +351,13 @@ func TestAServerThatNeverPowersOffEndsTheStep(t *testing.T) { installation := r.Kinds["DeviceInstallation"].(Installation) installation.PowerOffBound = 100 * time.Millisecond r.Kinds["DeviceInstallation"] = installation + started := time.Now() result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-stuck-on", 1, installSpec())) if err != nil { t.Fatal(err) } - if result.Phase != ops.PhaseOutcomeUnknown || l.onCount() != 0 { - t.Fatalf("result = %+v, %d power-ons", result, l.onCount()) + // The bound ends the step, long before the one-minute deadline. + if result.Phase != ops.PhaseOutcomeUnknown || result.Reason != site.ReasonStep || l.onCount() != 0 || time.Since(started) > 10*time.Second { + t.Fatalf("result = %+v, %d power-ons after %s", result, l.onCount(), time.Since(started)) } } diff --git a/internal/site/runner.go b/internal/site/runner.go index fb35ff26..28b7612b 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -123,13 +123,22 @@ func (w *Work) Store() *Store { return w.store } // Journaled reports whether a step of this operation is journaled done. func (w *Work) Journaled(step string) bool { + _, done := w.JournaledAt(step) + return done +} + +// JournaledAt returns when a step of this operation was journaled done. +func (w *Work) JournaledAt(step string) (time.Time, bool) { journal, err := w.store.Journal(w.Device) if err != nil { - return false + return time.Time{}, false + } + for _, entry := range journal { + if entry.Operation == w.Operation.UID && entry.Step == step && entry.State == StepDone { + return entry.At, true + } } - return slices.ContainsFunc(journal, func(entry Entry) bool { - return entry.Operation == w.Operation.UID && entry.Step == step && entry.State == StepDone - }) + return time.Time{}, false } // Step journals a step, then sends it, then records it done. A step found @@ -179,6 +188,9 @@ func (w *Work) Step(ctx context.Context, step Step) error { w.sent = true // The fence is checked again just before the send, so a newer // admission stored after the step was journaled stops it. + if beforeSend != nil { + beforeSend() + } if fence, _, err := w.store.Current(w.Device); err != nil { return err } else if fence > w.Fence { @@ -196,6 +208,10 @@ func (w *Work) Step(ctx context.Context, step Step) error { return nil } +// beforeSend runs between journaling a step and re-checking the fence. Only +// tests set it. +var beforeSend func() + var ( errSuperseded = errors.New("a newer operation was admitted for the Device") errStepUnknown = errors.New("a journaled step's outcome could not be observed") @@ -308,6 +324,9 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe } lock, err := r.acquire(ctx, assignment) switch { + case err != nil && ctx.Err() != nil: + // Stopped from outside while waiting: store nothing. + return custody.SiteResult{}, context.Cause(ctx) case errors.Is(err, ErrStaleFence): return custody.SiteResult{}, err case errors.Is(err, errWorkerRunning): diff --git a/internal/site/runner_test.go b/internal/site/runner_test.go index 6914baba..87b2a7a0 100644 --- a/internal/site/runner_test.go +++ b/internal/site/runner_test.go @@ -641,11 +641,16 @@ func TestAStoredResultSurvivesARedelivery(t *testing.T) { if err != nil || first.Phase != ops.PhaseSucceeded { t.Fatalf("first = %+v %v", first, err) } - f.access().Credentials = fixedCredentials{} + // A redelivery returns the stored result without running again. again, err := f.runner.Run(context.Background(), f.assignment(1, "op-kept")) if err != nil || again.Phase != ops.PhaseSucceeded || f.kind.sends.Load() != 2 { t.Fatalf("redelivered = %+v %v, sends %d", again, err, f.kind.sends.Load()) } + f.access().Credentials = fixedCredentials{} + again, err = f.runner.Run(context.Background(), f.assignment(1, "op-kept")) + if err != nil || again.Phase != ops.PhaseSucceeded || f.kind.sends.Load() != 2 { + t.Fatalf("redelivered = %+v %v, sends %d", again, err, f.kind.sends.Load()) + } // Put keeps the first result even when called again directly. stored, err := f.runner.Results.Put(testDevice, custody.SiteResult{Operation: first.Operation, Fence: 1, Phase: ops.PhaseOutcomeUnknown}) if err != nil || stored.Phase != ops.PhaseSucceeded { @@ -668,3 +673,86 @@ func TestAWorkerStoppedFromOutsideStoresNoResult(t *testing.T) { t.Fatal("a worker shut down from outside stored a result") } } + +func TestAShutdownWhileWaitingForTheRunLockStoresNothing(t *testing.T) { + f := newFixture(t, testUUID) + f.kind.block, f.kind.stuck = make(chan struct{}), true + done := make(chan struct{}) + defer func() { close(f.kind.block); <-done }() + go func() { defer close(done); _, _ = f.runner.Run(context.Background(), f.assignment(1, "op-holder")) }() + waitFor(t, func() bool { return f.kind.sends.Load() == 1 }) + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + if _, err := f.runner.Run(ctx, f.assignment(2, "op-waiting")); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("shutdown while waiting: %v", err) + } + if _, found, _ := f.runner.Results.Get(testDevice, "op-waiting", 2); found { + t.Fatal("a worker shut down while waiting stored a result") + } +} + +// TestALostLockWithJournaledStepsIsUnknown covers a newer assignment whose +// operation already has journaled steps but which cannot stop an older +// worker before its deadline. +func TestALostLockWithJournaledStepsIsUnknown(t *testing.T) { + f := newFixture(t, testUUID) + f.kind.block, f.kind.stuck = make(chan struct{}), true + done := make(chan struct{}) + defer func() { close(f.kind.block); <-done }() + go func() { defer close(done); _, _ = f.runner.Run(context.Background(), f.assignment(1, "op-old")) }() + waitFor(t, func() bool { return f.kind.sends.Load() == 1 }) + if err := f.runner.Store.Raise(testDevice, 2); err != nil { + t.Fatal(err) + } + if _, err := f.runner.Store.Intend(testDevice, 2, "op-journaled", "power-off"); err != nil { + t.Fatal(err) + } + newer := f.assignment(2, "op-journaled") + newer.Deadline = time.Now().Add(300 * time.Millisecond) + result, err := f.runner.Run(context.Background(), newer) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseOutcomeUnknown || result.Reason != ReasonWorkerRunning { + t.Fatalf("result = %+v", result) + } +} + +func TestAFenceRaisedBetweenJournalAndSendStopsTheStep(t *testing.T) { + f := newFixture(t, testUUID) + beforeSend = func() { + _ = f.runner.Store.Raise(testDevice, 2) + } + defer func() { beforeSend = nil }() + result, err := f.runner.Run(context.Background(), f.assignment(1, "op-raced")) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseOutcomeUnknown || result.Reason != ReasonSuperseded || f.kind.sends.Load() != 0 { + t.Fatalf("result = %+v, sends %d", result, f.kind.sends.Load()) + } +} + +func TestAShutdownDuringTheChecksStoresNothing(t *testing.T) { + f := newFixture(t, testUUID) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + // The shutdown arrives while the framework looks up the credential, so + // the lookup's refusal must not be stored. + f.access().Credentials = cancellingCredentials{cancel: cancel} + if _, err := f.runner.Run(ctx, f.assignment(1, "op-checks")); !errors.Is(err, context.Canceled) { + t.Fatalf("shutdown during checks: %v", err) + } + if _, found, _ := f.runner.Results.Get(testDevice, "op-checks", 1); found { + t.Fatal("a worker shut down during its checks stored a result") + } +} + +// cancellingCredentials cancels the worker's context, as a shutdown would, +// and then reports no credential. +type cancellingCredentials struct{ cancel context.CancelFunc } + +func (c cancellingCredentials) Lookup(context.Context, string) (bmcdiscovery.Credential, bool, error) { + c.cancel() + return bmcdiscovery.Credential{}, false, nil +} From 98859279433805eaf84c2c1367fbd86dbe6a2955 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 08:51:50 -0600 Subject: [PATCH 8/8] fix(site): Return the stored result to a copy that waited for the lock A same-fence redelivery checked for a stored result only before it waited for the run lock. If the first worker stored its outcome while the copy waited, the copy took the lock, resumed from the journal and could send to the server again, as a step marked safe to repeat did. The copy now checks again once it holds the lock and returns the stored result without running the kind. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 7 +++- internal/site/runner.go | 12 ++++++ internal/site/runner_test.go | 66 +++++++++++++++++++++++++++--- 3 files changed, 77 insertions(+), 8 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 27c8c212..dff962f2 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -90,7 +90,10 @@ so work on one Device never waits for another. journal. - **One worker per assignment.** A redelivered assignment that already has a result returns it. One that finds a worker for the same assignment holding - the run lock stores nothing and leaves the result to that worker. A newer + the run lock stores nothing and leaves the result to that worker. A copy + that waits for the lock checks for a stored result again once it holds the + lock, and returns that result without running, so it never sends after the + first worker recorded the outcome. A newer assignment that cannot stop an older worker before its deadline ends `Failed`, or `OutcomeUnknown` if the journal holds steps for it. - **Checks before any effect.** The inputs must match the admitted digest. The @@ -562,7 +565,7 @@ Increment B's site tests run with `go test -race ./internal/site/...`: | Two workers on one Device, two Devices in parallel | `TestTwoWorkersOnOneDevice`, `TestTwoDevicesInParallel`, `TestANewerFenceStopsTheOlderWorker` | | A TLS pin mismatch and an identity mismatch send nothing, against TLS servers | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing` | | Every pre-effect refusal, stale assignments, deadlines, result deletion, payload validation | `TestPreEffectRefusalsSendNothing`, `TestAStaleAssignmentIsRefusedAndStoresNothing`, `TestAWorkerStopsAtItsDeadline`, `TestResultsAreDeletedOnceTheCoordinatorAnswers`, `TestAssignmentValidation` | -| One worker per assignment, final results, shutdown at each stage, an older worker that does not stop, a fence raised between journal and send | `TestARedeliveryWhileTheSameOperationRunsStoresNothing`, `TestAStoredResultSurvivesARedelivery`, `TestAWorkerStoppedFromOutsideStoresNoResult`, `TestAShutdownWhileWaitingForTheRunLockStoresNothing`, `TestAShutdownDuringTheChecksStoresNothing`, `TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing`, `TestALostLockWithJournaledStepsIsUnknown`, `TestAFenceRaisedBetweenJournalAndSendStopsTheStep` | +| One worker per assignment, final results, shutdown at each stage, an older worker that does not stop, a fence raised between journal and send | `TestARedeliveryWhileTheSameOperationRunsStoresNothing`, `TestACopyWaitingForTheLockReturnsTheStoredResult`, `TestAStoredResultSurvivesARedelivery`, `TestAWorkerStoppedFromOutsideStoresNoResult`, `TestAShutdownWhileWaitingForTheRunLockStoresNothing`, `TestAShutdownDuringTheChecksStoresNothing`, `TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing`, `TestALostLockWithJournaledStepsIsUnknown`, `TestAFenceRaisedBetweenJournalAndSendStopsTheStep` | | Per-Device credentials, the fence report | `TestSecretCredentialsUseThePerDeviceContract`, `TestReportGivesTheCoordinatorSeenAndStoppedFences` | | Step payloads, the start-by window, identity separate from capabilities, a resumed worker reporting unknown | `TestAStepPayloadIsJournaledAndReadBack`, `TestALateStartIsStaleAndSendsNothing`, `TestIdentityIsSeparateFromInstallCapabilities`, `TestAResumedWorkerThatCannotReachTheBMCReportsUnknown` | | Install and wipe against a simulated BMC, one power-on per phase after an interruption in either phase, the power-off bound, fenced boot admission, bootstrap refused | `TestAWorkerInterruptedInTheDiskPhaseResumes`, `TestAServerThatNeverPowersOffEndsTheStep`, `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestBootstrapIsRefusedAtTheSiteToo` | diff --git a/internal/site/runner.go b/internal/site/runner.go index 28b7612b..c82f831c 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -231,6 +231,9 @@ type Runner struct { // lock. It defaults to one second. Poll time.Duration Now func() time.Time + // waiting, when set, is called each time a worker waits for the run + // lock. Tests use it to know a copy is waiting. + waiting func() } func (r *Runner) now() time.Time { @@ -282,6 +285,9 @@ func (r *Runner) acquire(ctx context.Context, assignment Assignment) (*runLock, } return lock, nil } + if r.waiting != nil { + r.waiting() + } select { case <-ctx.Done(): return nil, errWorkerRunning @@ -348,6 +354,12 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe return custody.SiteResult{}, err } defer lock.release() + // A worker for this same assignment may have stored its result while + // this one waited for the lock. Return that result; running the kind + // again could send to the server after the outcome was recorded. + if stored, found, err := r.Results.Get(assignment.Device, assignment.Operation.UID, assignment.Fence); err != nil || found { + return stored, err + } parent := ctx // The worker stops at its deadline exactly, and as soon as a newer fence // is stored for the Device. diff --git a/internal/site/runner_test.go b/internal/site/runner_test.go index 87b2a7a0..10abee89 100644 --- a/internal/site/runner_test.go +++ b/internal/site/runner_test.go @@ -130,11 +130,16 @@ func (f fixedCredentials) Lookup(context.Context, string) (bmcdiscovery.Credenti // fakeKind journals one step per entry of steps and records each send. type fakeKind struct { - steps []string - sends atomic.Int32 - block chan struct{} - observe func(context.Context, json.RawMessage) (bool, error) - check func(*Work) + steps []string + runs atomic.Int32 + sends atomic.Int32 + // fail is what a blocked send returns once unblocked. + fail error + // idempotent marks every step safe to send again. + idempotent bool + block chan struct{} + observe func(context.Context, json.RawMessage) (bool, error) + check func(*Work) // stuck makes a blocked step ignore cancellation, as a worker that does // not stop would. stuck bool @@ -148,6 +153,7 @@ func (k *fakeKind) Check(_ context.Context, work *Work) *custody.Refusal { } func (k *fakeKind) Run(ctx context.Context, work *Work) (any, error) { + k.runs.Add(1) for _, step := range k.steps { err := work.Step(ctx, Step{Name: step, Payload: map[string]string{"step": step}, Send: func(ctx context.Context) error { k.sends.Add(1) @@ -158,12 +164,13 @@ func (k *fakeKind) Run(ctx context.Context, work *Work) (any, error) { } select { case <-k.block: + return k.fail case <-ctx.Done(): return context.Cause(ctx) } } return nil - }, Observe: k.observe}) + }, Observe: k.observe, Idempotent: k.idempotent}) if err != nil { return nil, err } @@ -612,6 +619,53 @@ func TestARedeliveryWhileTheSameOperationRunsStoresNothing(t *testing.T) { } } +// TestACopyWaitingForTheLockReturnsTheStoredResult covers a same-fence +// redelivery that waits for the run lock while the first worker runs. The +// first worker's send fails and it stores OutcomeUnknown. The copy then takes +// the lock and must return that result, not resume from the journal: its +// step is safe to send again, so running would send to the server a second +// time after the outcome was recorded. +func TestACopyWaitingForTheLockReturnsTheStoredResult(t *testing.T) { + f := newFixture(t, testUUID) + f.kind.block, f.kind.fail, f.kind.idempotent = make(chan struct{}), errors.New("the BMC dropped the request"), true + first := make(chan custody.SiteResult, 1) + go func() { + result, err := f.runner.Run(context.Background(), f.assignment(1, "op-same")) + if err != nil { + t.Error(err) + } + first <- result + }() + waitFor(t, func() bool { return f.kind.sends.Load() == 1 }) + waiting := make(chan struct{}, 1) + f.runner.waiting = func() { + select { + case waiting <- struct{}{}: + default: + } + } + copied := make(chan custody.SiteResult, 1) + go func() { + result, err := f.runner.Run(context.Background(), f.assignment(1, "op-same")) + if err != nil { + t.Error(err) + } + copied <- result + }() + <-waiting + close(f.kind.block) + stored := <-first + if stored.Phase != ops.PhaseOutcomeUnknown { + t.Fatalf("first worker = %+v", stored) + } + if result := <-copied; result.Phase != stored.Phase || result.Reason != stored.Reason || result.Message != stored.Message { + t.Fatalf("copy = %+v, want the stored %+v", result, stored) + } + if runs, sends := f.kind.runs.Load(), f.kind.sends.Load(); runs != 1 || sends != 1 { + t.Fatalf("runs = %d, sends = %d, want one run and one send", runs, sends) + } +} + // TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing covers an // older worker that does not stop: the newer assignment sent nothing, so it // ends Failed.