From b8d5e4b1690696a08fae111b73c79076ce119a4e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 12:32:43 -0600 Subject: [PATCH 1/5] feat(simulator): Run power on simulated servers Customer power needs a site that can run it without a BMC. The simulator site now registers a power worker for its simulated servers. Like the Redfish worker, it reads the server's power before it sends anything, sends at most one reset through the journal, and reports Succeeded only for the state it then reads. A restart is proven only by the server's reset time moving to the command. A test-only fault makes a server ignore resets, so the operation ends unknown. The reset step journals the read before the command and the send time, so a run resumed after a crash, finished or not, reports both, sends nothing again, and proves a restart against the journaled send time. The simulator's fixture discovery reports each server's power and offers every power action. Fixture discovery without an observer, as synthetic staging runs it, still reports power off and no reset types. A server the observer cannot read keeps its last discovery, so a running server is never reported off. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-simulator/main.go | 3 +- internal/site/fixture/discovery.go | 27 +++- internal/site/fixture/discovery_test.go | 58 ++++++++ internal/site/simwork/kinds.go | 18 +++ internal/site/simwork/power.go | 165 +++++++++++++++++++++ internal/site/simwork/power_test.go | 184 ++++++++++++++++++++++++ 6 files changed, 452 insertions(+), 3 deletions(-) create mode 100644 internal/site/fixture/discovery_test.go create mode 100644 internal/site/simwork/power.go create mode 100644 internal/site/simwork/power_test.go diff --git a/cmd/fleet-simulator/main.go b/cmd/fleet-simulator/main.go index d4903a4c..517dc89f 100644 --- a/cmd/fleet-simulator/main.go +++ b/cmd/fleet-simulator/main.go @@ -74,6 +74,7 @@ func main() { results := site.NewResults(store) runner := &site.Runner{Site: siteName, Store: store, Results: results, Access: fixture.Access{Enrollment: enrollment}, Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}} + runner.Kinds["DevicePowerOperation"] = simwork.Power{} dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx, Logger: logger} server := newServer(address, siteapi.Handler(dispatcher, store, results, func() (string, error) { return readToken(tokenPath) }), logger) if discover { @@ -83,7 +84,7 @@ func main() { } go func() { for { - if err := fixture.Discover(ctx, api, enrollment, time.Now()); err != nil && ctx.Err() == nil { + if err := fixture.DiscoverPower(ctx, api, enrollment, time.Now(), simwork.Observe(store)); err != nil && ctx.Err() == nil { logger.Info("fixture discovery incomplete", "error", err.Error()) } select { diff --git a/internal/site/fixture/discovery.go b/internal/site/fixture/discovery.go index 1585c85e..44ae2ac3 100644 --- a/internal/site/fixture/discovery.go +++ b/internal/site/fixture/discovery.go @@ -17,9 +17,21 @@ import ( // discovery runs at the site and writes only the status of the Devices that // site serves; a synthetic Device has no BMC, so this writes what discovery // would observe: the enrolled key at the recorded endpoint, the enrolled -// system identity, and power off. A Device whose recorded identity differs -// from the enrollment gets IdentityMatched False. +// system identity, and power off with no reset types offered. A Device +// whose recorded identity differs from the enrollment gets IdentityMatched +// False. func Discover(ctx context.Context, api client.Client, enrollment Enrollment, now time.Time) error { + return DiscoverPower(ctx, api, enrollment, now, nil) +} + +// PowerObserver reports a synthetic Device's power state and the reset +// types its site's power worker offers, as BMC discovery would read them. +type PowerObserver func(device string) (state string, resetTypes []string, err error) + +// DiscoverPower is Discover with the power each Device reports. Without an +// observer, every Device reports power off and records no reset types. A +// Device whose power the observer cannot read keeps its last discovery. +func DiscoverPower(ctx context.Context, api client.Client, enrollment Enrollment, now time.Time, observe PowerObserver) error { var failed error for key, target := range enrollment { namespace, name, _ := strings.Cut(key, "/") @@ -42,6 +54,17 @@ func Discover(ctx context.Context, api client.Client, enrollment Enrollment, now ID: "simulated", UUID: target.SystemUUID, PowerState: "Off", }}}, } + if observe != nil { + // A server the observer cannot read keeps its last discovery: + // writing power off would report a running server as off. + state, offered, err := observe(key) + if err != nil { + failed = errors.Join(failed, err) + continue + } + system := &device.Status.Discovery.Inventory.Systems[0] + system.PowerState, system.ResetTypes = state, offered + } status, reason := metav1.ConditionTrue, "FixtureEnrollment" if !matched { status, reason = metav1.ConditionFalse, "FixtureEnrollmentDiffers" diff --git a/internal/site/fixture/discovery_test.go b/internal/site/fixture/discovery_test.go new file mode 100644 index 00000000..529eeebc --- /dev/null +++ b/internal/site/fixture/discovery_test.go @@ -0,0 +1,58 @@ +package fixture + +import ( + "context" + "errors" + "slices" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" +) + +// TestDiscoverPowerKeepsTheLastReadWhenPowerCannotBeRead requires a Device +// whose power the observer cannot read to keep its last discovery, rather +// than report a running server as off, and a readable one to report what the +// observer read. +func TestDiscoverPowerKeepsTheLastReadWhenPowerCannotBeRead(t *testing.T) { + scheme := runtime.NewScheme() + if err := inventory.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + const uuid = "00000000-0000-4000-8000-0000000000a1" + earlier := metav1.NewTime(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)) + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Namespace: "fleet-provider", Name: "server-example-001"}, Spec: inventory.DeviceSpec{ + Identity: inventory.DeviceIdentity{SystemUUID: uuid}, BMC: &inventory.BMC{Endpoint: "https://[2001:db8::1]"}}, + Status: inventory.DeviceStatus{Discovery: &inventory.DeviceDiscovery{Inventory: &inventory.ObservedInventory{ObservedAt: earlier, Endpoint: "https://[2001:db8::1]", + Systems: []inventory.ObservedSystem{{ID: "simulated", UUID: uuid, PowerState: "On", ResetTypes: []string{"On", "ForceOff"}}}}}}} + api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(device).WithStatusSubresource(&inventory.Device{}).Build() + enrollment := Enrollment{"fleet-provider/server-example-001": {BMCEndpoint: "https://[2001:db8::1]", SystemUUID: uuid, BMCPublicKeySHA256: "aa"}} + read := func() inventory.ObservedSystem { + current := &inventory.Device{} + if err := api.Get(context.Background(), client.ObjectKeyFromObject(device), current); err != nil { + t.Fatal(err) + } + return current.Status.Discovery.Inventory.Systems[0] + } + + unreadable := errors.New("the simulated server could not be read") + err := DiscoverPower(context.Background(), api, enrollment, earlier.Add(time.Minute), func(string) (string, []string, error) { return "", nil, unreadable }) + if !errors.Is(err, unreadable) { + t.Fatalf("err = %v", err) + } + if system := read(); system.PowerState != "On" || !slices.Equal(system.ResetTypes, []string{"On", "ForceOff"}) { + t.Fatalf("after an unreadable server: %+v", system) + } + + if err := DiscoverPower(context.Background(), api, enrollment, earlier.Add(time.Minute), func(string) (string, []string, error) { return "Off", []string{"On"}, nil }); err != nil { + t.Fatal(err) + } + if system := read(); system.PowerState != "Off" || !slices.Equal(system.ResetTypes, []string{"On"}) { + t.Fatalf("after a read: %+v", system) + } +} diff --git a/internal/site/simwork/kinds.go b/internal/site/simwork/kinds.go index 545f12be..cd3fb6a9 100644 --- a/internal/site/simwork/kinds.go +++ b/internal/site/simwork/kinds.go @@ -25,6 +25,13 @@ type Server struct { Image string `json:"image,omitempty"` // Booted is the digest the server last booted from disk. Booted string `json:"booted,omitempty"` + // Power is On or Off; empty is Off. + Power string `json:"power,omitempty"` + // LastReset is when the server last came out of a reset. + LastReset *metav1.Time `json:"lastReset,omitempty"` + // Unresponsive is a test fault: the server ignores power resets, so a + // power operation cannot prove its outcome. + Unresponsive bool `json:"unresponsive,omitempty"` } const serverRecords = "simulator" @@ -42,6 +49,17 @@ func write(work *site.Work, server Server) error { return work.Store().PutRecord(work.Device, work.Fence, serverRecords, serverName, server) } +// WriteServer replaces a Device's simulated server at its stored fence. Tests +// use it to set the server's power or a fault, only while no worker runs for +// the Device: it reads the fence and writes under separate locks. +func WriteServer(store *site.Store, device string, server Server) error { + fence, _, err := store.Current(device) + if err != nil { + return err + } + return store.PutRecord(device, fence, serverRecords, serverName, server) +} + // ReadServer returns a Device's simulated server, for evidence checks. func ReadServer(store *site.Store, device string) (Server, error) { var server Server diff --git a/internal/site/simwork/power.go b/internal/site/simwork/power.go new file mode 100644 index 00000000..cfc2177a --- /dev/null +++ b/internal/site/simwork/power.go @@ -0,0 +1,165 @@ +package simwork + +import ( + "context" + "encoding/json" + "errors" + "slices" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" +) + +// ResetTypes are the power actions the simulated server offers. +var ResetTypes = []string{string(ops.PowerOn), string(ops.PowerForceOff), string(ops.PowerForceRestart), string(ops.PowerCycle)} + +// Power is the simulator's DevicePowerOperation worker. Like the Redfish +// worker, it reads the server's power before it sends anything, sends at +// most one reset through the journal, and reports Succeeded only for the +// state it then reads. +type Power struct{} + +var _ site.Kind = Power{} + +// State is a simulated server's power: Off until something powers it on. +func State(server Server) ops.ObservedPowerState { + if server.Power == string(ops.PowerStateOn) { + return ops.PowerStateOn + } + return ops.PowerStateOff +} + +func powerSpec(work *site.Work) (ops.DevicePowerOperationSpec, *custody.Refusal) { + var spec ops.DevicePowerOperationSpec + if err := json.Unmarshal(work.Inputs, &spec); err != nil || !slices.Contains(ops.PowerActions, spec.Action) { + return spec, &custody.Refusal{Reason: site.ReasonInputMismatch, Message: "the admitted inputs are not a power operation"} + } + return spec, nil +} + +func (Power) Check(_ context.Context, work *site.Work) *custody.Refusal { + if connection(work) == nil { + return &custody.Refusal{Reason: site.ReasonUnsupportedKind, Message: "this site does not run the simulator"} + } + _, refusal := powerSpec(work) + return refusal +} + +func (Power) Run(ctx context.Context, work *site.Work) (any, error) { + spec, refusal := powerSpec(work) + if refusal != nil { + return nil, refusal + } + server, err := read(work) + if err != nil { + return nil, err + } + want := ops.PowerStateOn + if spec.Action == ops.PowerForceOff { + want = ops.PowerStateOff + } + // A resumed run, whose reset step an earlier run journaled whether or + // not it finished, reports that run's read and send time: the server + // may have changed since, so it is neither read again nor skipped as + // already in the requested state. + reset, resumed, err := journaledReset(work) + if err != nil { + return nil, err + } + if !resumed { + before := ops.PowerObservation{State: State(server), ObservedAt: metav1.NewTime(time.Now().UTC())} + switch { + case spec.Action == ops.PowerOn && before.State == ops.PowerStateOn, spec.Action == ops.PowerForceOff && before.State == ops.PowerStateOff: + // Already in the requested state: nothing is sent. + return ops.PowerEvidence{Power: &ops.PowerObservations{Before: &before, After: &before}}, nil + case spec.Action.Resets() && before.State == ops.PowerStateOff: + return nil, &custody.Refusal{Reason: custody.ReasonNotPoweredOn, Message: "a restart needs a server that is on"} + } + // The server record keeps times to the second, so the send time + // does too. + reset = resetPayload{Before: before, SentAt: metav1.NewTime(time.Now().UTC().Truncate(time.Second))} + } + before, sent := reset.Before, reset.SentAt + // A restart or power cycle leaves a server on, so only its reset time + // moving to the command proves it. + proven := func(server Server) bool { + if State(server) != want { + return false + } + return !spec.Action.Resets() || (server.LastReset != nil && !server.LastReset.Before(&sent)) + } + if err := work.Step(ctx, site.Step{ + Name: "reset", + Payload: reset, + Send: func(context.Context) error { + server, err := read(work) + if err != nil || server.Unresponsive { + return err + } + server.Power = string(want) + if spec.Action != ops.PowerForceOff { + server.LastReset = &sent + } + return write(work, server) + }, + Observe: func(context.Context, json.RawMessage) (bool, error) { + server, err := read(work) + return proven(server), err + }, + }); err != nil { + return nil, err + } + server, err = read(work) + if err != nil { + return nil, err + } + if !proven(server) { + return nil, &custody.Refusal{Reason: site.ReasonStep, Message: "the simulated server did not reach the requested power state"} + } + after := ops.PowerObservation{State: want, ObservedAt: metav1.NewTime(time.Now().UTC())} + evidence := ops.PowerEvidence{RequestSentAt: &sent, Power: &ops.PowerObservations{Before: &before, After: &after}} + if spec.Action.Resets() { + evidence.ResetEvidence = ops.ResetLastResetTime + } + return evidence, nil +} + +// resetPayload is what the reset step journals before its command: the +// power read before it and when it is sent. +type resetPayload struct { + Before ops.PowerObservation `json:"before"` + SentAt metav1.Time `json:"sentAt"` +} + +// journaledReset returns the reset step an earlier run of this operation +// journaled, if any. +func journaledReset(work *site.Work) (resetPayload, bool, error) { + journal, err := work.Store().Journal(work.Device) + if err != nil { + return resetPayload{}, false, err + } + for _, entry := range journal { + if entry.Operation != work.Key() || entry.Step != "reset" { + continue + } + var reset resetPayload + if err := json.Unmarshal(entry.Payload, &reset); err != nil || reset.Before.ObservedAt.IsZero() || reset.SentAt.IsZero() { + return resetPayload{}, false, errors.New("the journaled reset is unreadable") + } + return reset, true, nil + } + return resetPayload{}, false, nil +} + +// Observe is the simulator site's fixture discovery of power: each Device +// reports its simulated server's power and offers every power action. +func Observe(store *site.Store) func(device string) (string, []string, error) { + return func(device string) (string, []string, error) { + server, err := ReadServer(store, device) + return string(State(server)), slices.Clone(ResetTypes), err + } +} diff --git a/internal/site/simwork/power_test.go b/internal/site/simwork/power_test.go new file mode 100644 index 00000000..b8e02bda --- /dev/null +++ b/internal/site/simwork/power_test.go @@ -0,0 +1,184 @@ +package simwork + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "os" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" +) + +const ( + device = "fleet-provider/server-example-001" + endpoint = "https://[2001:db8::1]" + uuid = "00000000-0000-4000-8000-0000000000a1" + key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +) + +func powerRunner(t *testing.T) *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) + } + return &site.Runner{Site: "site-example-a", Store: store, Results: site.NewResults(store), Poll: 10 * time.Millisecond, + Access: fixture.Access{Enrollment: fixture.Enrollment{device: {BMCEndpoint: endpoint, SystemUUID: uuid, BMCPublicKeySHA256: key, Disks: []string{"disk-0"}}}}, + Kinds: map[string]site.Kind{"DevicePowerOperation": Power{}}} +} + +func powerAssignment(uid string, fence int64, action ops.PowerAction) site.Assignment { + inputs, _ := json.Marshal(ops.DevicePowerOperationSpec{Action: action, MachineGeneration: 2, + OperationEnvelope: ops.OperationEnvelope{Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: "alloc-example"}}}}) + sum := sha256.Sum256(inputs) + return site.Assignment{Device: device, Operation: ops.OperationReference{Kind: "DevicePowerOperation", Name: "alloc-example-power-" + uid}, Fence: fence, + AdmittedAt: time.Now(), Deadline: time.Now().Add(time.Minute), InputDigest: "sha256:" + hex.EncodeToString(sum[:]), Inputs: inputs, + Snapshot: ops.DeviceSnapshot{BMCEndpoint: endpoint, SystemUUID: uuid, BMCPublicKeySHA256: key}} +} + +// TestARestartIsProvenOnlyByItsResetTime requires a simulated restart to move +// the server's reset time: a server that ignores the reset stays on, which +// proves nothing. +func TestARestartIsProvenOnlyByItsResetTime(t *testing.T) { + for name, unresponsive := range map[string]bool{"the server restarts": false, "the server ignores the reset": true} { + t.Run(name, func(t *testing.T) { + r := powerRunner(t) + if err := WriteServer(r.Store, device, Server{Power: "On", Unresponsive: unresponsive}); err != nil { + t.Fatal(err) + } + result, err := r.Run(context.Background(), powerAssignment("op-restart", 1, ops.PowerForceRestart)) + if err != nil { + t.Fatal(err) + } + want := ops.PhaseSucceeded + if unresponsive { + want = ops.PhaseOutcomeUnknown + } + if result.Phase != want { + t.Fatalf("result = %+v, want %s", result, want) + } + if result.Phase == ops.PhaseSucceeded { + spec := ops.DevicePowerOperationSpec{Action: ops.PowerForceRestart} + kind, operation := custody.DevicePowerOperationKind(), &ops.DevicePowerOperation{Spec: spec} + canonical, err := kind.Evidence(operation, result.Evidence) + if err != nil { + t.Fatalf("the coordinator would refuse the evidence %s: %v", result.Evidence, err) + } + if err := kind.ProvesSuccess(operation, canonical); err != nil { + t.Fatalf("the coordinator would not count the success %s: %v", result.Evidence, err) + } + } + }) + } +} + +// TestAResumedRunReportsTheReadBeforeItsCommand stops a run after its reset +// step is done but before its result is kept. The run that replaces it sends +// nothing and reports the power read made before the command, so custody +// counts the success. +func TestAResumedRunReportsTheReadBeforeItsCommand(t *testing.T) { + r := powerRunner(t) + if err := WriteServer(r.Store, device, Server{Power: "Off"}); err != nil { + t.Fatal(err) + } + work := powerAssignment("op-resume", 1, ops.PowerOn) + first, err := r.Run(context.Background(), work) + if err != nil || first.Phase != ops.PhaseSucceeded { + t.Fatalf("first = %+v, %v", first, err) + } + if err := r.Results.Forget(device, first); err != nil { + t.Fatal(err) + } + // The replacement reads the server a second later, already on. + time.Sleep(1100 * time.Millisecond) + resumed, err := r.Run(context.Background(), work) + if err != nil || resumed.Phase != ops.PhaseSucceeded { + t.Fatalf("resumed = %+v, %v", resumed, err) + } + spec := ops.DevicePowerOperationSpec{Action: ops.PowerOn} + kind, operation := custody.DevicePowerOperationKind(), &ops.DevicePowerOperation{Spec: spec} + canonical, err := kind.Evidence(operation, resumed.Evidence) + if err != nil { + t.Fatalf("the coordinator would refuse the evidence %s: %v", resumed.Evidence, err) + } + if err := kind.ProvesSuccess(operation, canonical); err != nil { + t.Fatalf("the coordinator would not count the success %s: %v", resumed.Evidence, err) + } + var evidence ops.PowerEvidence + if err := json.Unmarshal(resumed.Evidence, &evidence); err != nil || evidence.Power.Before.State != ops.PowerStateOff || evidence.RequestSentAt == nil { + t.Fatalf("evidence = %s", resumed.Evidence) + } +} + +// TestAResumedRunReportsTheJournaledCommand resumes a run whose reset an +// earlier run journaled and sent, left unfinished or finished seconds +// later. The server already shows the effect. The resumed run sends +// nothing, never mistakes the effect for a server that needed no command, +// and proves a restart against the journaled send time. +func TestAResumedRunReportsTheJournaledCommand(t *testing.T) { + for _, tc := range []struct { + name string + action ops.PowerAction + done bool + }{ + {"a power on left unfinished", ops.PowerOn, false}, + {"a restart left unfinished", ops.PowerForceRestart, false}, + {"a restart finished seconds after its send", ops.PowerForceRestart, true}, + } { + t.Run(tc.name, func(t *testing.T) { + r := powerRunner(t) + work := powerAssignment("op-journaled", 1, tc.action) + sent := metav1.NewTime(time.Now().UTC().Add(-3 * time.Second).Truncate(time.Second)) + before := "On" + if tc.action == ops.PowerOn { + before = "Off" + } + payload, _ := json.Marshal(resetPayload{Before: ops.PowerObservation{State: ops.ObservedPowerState(before), ObservedAt: sent}, SentAt: sent}) + key := custody.OperationKey(work.Operation, work.Fence) + if err := r.Store.Raise(device, work.Fence); err != nil { + t.Fatal(err) + } + if _, _, err := r.Store.IntendWithPayload(device, work.Fence, key, "reset", payload); err != nil { + t.Fatal(err) + } + if tc.done { + if err := r.Store.Done(device, work.Fence, key, "reset"); err != nil { + t.Fatal(err) + } + } + // The earlier run's command took effect. + if err := WriteServer(r.Store, device, Server{Power: "On", LastReset: &sent}); err != nil { + t.Fatal(err) + } + result, err := r.Run(context.Background(), work) + if err != nil || result.Phase != ops.PhaseSucceeded { + t.Fatalf("result = %+v, %v", result, err) + } + spec := ops.DevicePowerOperationSpec{Action: tc.action} + kind, operation := custody.DevicePowerOperationKind(), &ops.DevicePowerOperation{Spec: spec} + canonical, err := kind.Evidence(operation, result.Evidence) + if err != nil { + t.Fatalf("the coordinator would refuse the evidence %s: %v", result.Evidence, err) + } + if err := kind.ProvesSuccess(operation, canonical); err != nil { + t.Fatalf("the coordinator would not count the success %s: %v", result.Evidence, err) + } + var evidence ops.PowerEvidence + if err := json.Unmarshal(result.Evidence, &evidence); err != nil || evidence.RequestSentAt == nil || !evidence.RequestSentAt.Equal(&sent) || string(evidence.Power.Before.State) != before { + t.Fatalf("evidence = %s", result.Evidence) + } + }) + } +} From f16f7296eab18aa45805c2d3f14f54bc4fda9307 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 12:32:43 -0600 Subject: [PATCH 2/5] feat(allocation): Request power from powerState The Metal provider asks the allocator to apply a Machine's power intent. On is the action On and Off is ForceOff, named from the allocation and the Machine generation, so a refused request is not created again until the generation changes. A request is due when powerState differs from the Machine's observed power, or when this allocation's request for another action has not run yet, so the newer request replaces it. Observed power must be On or Off: every Machine defaults to Off, so power not yet observed, or Unknown, asks for nothing. During a power hold, nothing is created until staff apply a Retry; then the provider repeats the held operation under the foundation's retry name, and only while powerState still maps to the held action. Co-Authored-By: Claude Opus 5.5 --- internal/allocation/power.go | 129 +++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 internal/allocation/power.go diff --git a/internal/allocation/power.go b/internal/allocation/power.go new file mode 100644 index 00000000..daf27c55 --- /dev/null +++ b/internal/allocation/power.go @@ -0,0 +1,129 @@ +package allocation + +import ( + "context" + "fmt" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" +) + +// PowerAction maps a Machine's powerState to the power action that applies +// it, as #173 defines: On is On, and Off is ForceOff. +func PowerAction(state string) (ops.PowerAction, error) { + switch state { + case "On": + return ops.PowerOn, nil + case "Off": + return ops.PowerForceOff, nil + } + return "", fmt.Errorf("%w: powerState %q is neither On nor Off", ErrUnsupported, state) +} + +// Power creates the DevicePowerOperation that applies a Machine's power +// intent, or returns nil when none is due. Owner is the Machine's identity, +// whose allocation is the one given. It is create-only: a retry finds +// the same operation by name. +// +// An operation is named from the allocation and the Machine generation, so +// a refused one is not created again until the generation changes. It is +// due only when powerState differs from the Machine's observed power, which +// the power projector alone writes, or when a request for another action has +// not run yet. Power not yet observed, or Unknown, differs from nothing: +// every Machine defaults to Off, and a server is not forced off before its +// power is known. A generation runs at most one power operation, so power +// that drifts after it succeeded, as after a crash, is not corrected until the +// generation changes. +// +// While a power hold on this allocation exists, observed power is Unknown. +// Power then creates nothing until staff apply a DeviceRecovery Retry, and +// creates the retry only while powerState still maps to the held action. +// Otherwise staff settle the hold, and the newer operation runs after it. +func (a *Allocator) Power(ctx context.Context, allocation *fleetv1.MachineAllocation, owner Machine, machine *fleetv1.Machine) (*ops.DevicePowerOperation, error) { + if allocation.Status.Phase != fleetv1.AllocationActive { + return nil, ErrReleased + } + // The allocation belongs to this Machine only if its name is the one the + // Machine's incarnation derives, and it records the same Machine and + // consumer. A same-name Machine never inherits it. + if owner.UID != machine.UID || owner.Namespace != machine.Namespace || owner.Name != machine.Name || allocation.Name != Name(owner) || + allocation.Spec.ConsumerRef != owner.Consumer || allocation.Spec.MachineRef != owner.reference() || + allocation.Labels[fleetv1.LabelMachineUID] != string(owner.UID) || allocation.Labels[fleetv1.LabelConsumerUID] != string(owner.ConsumerUID) { + return nil, ErrConflict + } + if machine.Spec.PowerState == "" { + return nil, nil + } + action, err := PowerAction(machine.Spec.PowerState) + if err != nil { + return nil, err + } + state := &ops.DeviceCustody{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: allocation.Spec.DeviceRef.Name}, state); err != nil { + return nil, err + } + operation := &ops.DevicePowerOperation{ + ObjectMeta: metav1.ObjectMeta{Name: custody.PowerName(allocation.Name, machine.Generation), Namespace: a.Namespace, Labels: operationLabels(allocation)}, + Spec: ops.DevicePowerOperationSpec{ + OperationEnvelope: a.envelope(allocation, a.ProviderCreator), + Action: action, + MachineGeneration: machine.Generation, + }, + } + if hold := state.Spec.RecoveryHold; hold != nil && hold.Kind == "DevicePowerOperation" { + held := &ops.DevicePowerOperation{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: hold.Name}, held); apierrors.IsNotFound(err) { + return nil, nil + } else if err != nil { + return nil, err + } + reference := held.Spec.Authority.AllocationRef + if reference == nil || reference.Name != allocation.Name || hold.RetryAuthorizedBy == nil || held.Spec.Action != action { + return nil, nil + } + // The retry repeats the held operation's inputs under the + // foundation's retry name. + operation.Name = custody.RetryName(*hold, hold.Retries) + operation.Spec = held.Spec + return operation, a.createOnce(ctx, a.Provider, operation, &ops.DevicePowerOperation{}) + } + observed := machine.Status.Power + if observed == nil || (observed.State != "On" && observed.State != "Off") { + return nil, nil + } + if observed.State == machine.Spec.PowerState { + // A request for another action that has not run yet would undo the + // intent the Machine now states, so a newer one replaces it. + pending, err := a.pendingPower(ctx, allocation) + if err != nil || pending == nil || pending.Spec.Action == action { + return nil, err + } + } + return operation, a.createOnce(ctx, a.Provider, operation, &ops.DevicePowerOperation{}) +} + +// pendingPower returns this allocation's newest power request that custody +// has not ended, or nil. +func (a *Allocator) pendingPower(ctx context.Context, allocation *fleetv1.MachineAllocation) (*ops.DevicePowerOperation, error) { + var list ops.DevicePowerOperationList + if err := a.Provider.List(ctx, &list, client.InNamespace(a.Namespace)); err != nil { + return nil, err + } + var newest *ops.DevicePowerOperation + for index := range list.Items { + operation := &list.Items[index] + reference := operation.Spec.Authority.AllocationRef + if reference == nil || reference.Name != allocation.Name || operation.Status.Phase.Ended() { + continue + } + if newest == nil || newest.Spec.MachineGeneration < operation.Spec.MachineGeneration { + newest = operation + } + } + return newest, nil +} From 98152fc954e510d089f8012b241bad3d4c97508e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 12:32:43 -0600 Subject: [PATCH 3/5] feat(manager): Report proven power on the Machine Discovery reads each server about hourly, so after a power change it reports the old state for a while. The power projector, still the only writer of Machine power, now reports the newer of discovery's state and the state custody's last succeeded power operation proved, a tie going to the operation. When any other operation except a recovery finished at or after discovery's read, power is Unknown until discovery reads it again, because that operation may have changed it. Power stays Unknown during any hold. The standalone smoke commissions the server just before it allocates, so it now waits for discovery to read the server after commissioning before it checks the Machine's power. Co-Authored-By: Claude Opus 5.5 --- hack/standalone-smoke.sh | 17 ++++++++++++ internal/manager/power.go | 54 +++++++++++++++++++++++++++++++-------- 2 files changed, 61 insertions(+), 10 deletions(-) diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index 7507c90d..e33bb658 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -113,6 +113,23 @@ test "$(kubectl --context "$context" -n fleet-provider get devicecommissionings test "$(kubectl --context "$context" -n fleet-provider get machinecapacity central1-baremetal-01 -o jsonpath='{.status.conditions[?(@.type=="Available")].status}')" = "True" test "$(kubectl --context "$context" auth can-i update machinecapacities/status --as=system:serviceaccount:fleet-system:fleet-standalone-smoke -n fleet-provider)" = "no" test "$(kubectl --context "$context" auth can-i create devicecommissioningplanapprovals --as=system:serviceaccount:fleet-system:fleet-plan-author -n fleet-provider)" = "no" +# Power is Unknown after an operation that may have changed it, until +# discovery reads the server again. The simulator rediscovers each minute, so +# wait for a read after the commissioning finished before allocating. +finished=$(kubectl --context "$context" -n fleet-provider get devicecustody synthetic-device-central-01 -o jsonpath='{.spec.lastResult.finishedAt}') +test -n "$finished" +observed= +for _ in $(seq 1 75); do + observed=$(kubectl --context "$context" -n fleet-provider get device synthetic-device-central-01 -o jsonpath='{.status.discovery.inventory.observedAt}') + if [ "$observed" != "$finished" ] && [ "$(printf '%s\n%s\n' "$finished" "$observed" | sort | tail -n 1)" = "$observed" ]; then + break + fi + sleep 2 +done +if [ "$observed" = "$finished" ] || [ "$(printf '%s\n%s\n' "$finished" "$observed" | sort | tail -n 1)" != "$observed" ]; then + echo "discovery did not read the server after commissioning finished" >&2 + exit 1 +fi run_phase allocate fleet-smoke-allocate-run kubectl --context "$context" get machines -A test "$(kubectl --context "$context" -n fleet-project-a get machine -o name)" = "machine.metal.datumapis.com/allocation" diff --git a/internal/manager/power.go b/internal/manager/power.go index 586f4bbb..1bf8953c 100644 --- a/internal/manager/power.go +++ b/internal/manager/power.go @@ -2,10 +2,12 @@ package manager import ( "context" + "encoding/json" "errors" "strings" apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" @@ -19,9 +21,12 @@ import ( // PowerProjector is the only writer of Machine status.power. It reads the // custody of the Machine's allocation in the provider project: while a // recovery hold exists, or custody is unverified, power is Unknown, because -// nothing proves what the server did. Otherwise it is the power state the -// Device's last discovery observed. A Machine without an active allocation -// reports no power. +// nothing proves what the server did. Otherwise it is the newer of the power +// state the Device's last discovery observed and the state custody's last +// succeeded power operation proved. When an operation that may have changed +// power, other than a recovery, finished after discovery's read and proved no +// power state, power is Unknown until discovery reads it again. A Machine +// without an active allocation reports no power. type PowerProjector struct { Client client.Client Project controller.ProjectIdentity @@ -101,18 +106,47 @@ func power(ctx context.Context, provider client.Reader, namespace string, machin } else if err != nil { return nil, err } - if device.UID != types.UID(current.Labels[fleetv1.LabelDeviceUID]) || device.Status.Discovery == nil || device.Status.Discovery.Inventory == nil { + if device.UID != types.UID(current.Labels[fleetv1.LabelDeviceUID]) { return unknown, nil } - for _, system := range device.Status.Discovery.Inventory.Systems { - if strings.EqualFold(system.UUID, device.Spec.Identity.SystemUUID) { - switch system.PowerState { - case "On", "Off": - return &fleetv1.PowerStatus{State: system.PowerState}, nil + var observed metav1.Time + result := unknown + if discovery := device.Status.Discovery; discovery != nil && discovery.Inventory != nil { + for _, system := range discovery.Inventory.Systems { + if strings.EqualFold(system.UUID, device.Spec.Identity.SystemUUID) { + switch system.PowerState { + case "On", "Off": + observed, result = discovery.Inventory.ObservedAt, &fleetv1.PowerStatus{State: system.PowerState} + } } } } - return unknown, nil + // A tie favors the operation's proven state: a discovery read stamped in + // the same second cannot be shown to be later. + if after := provenPower(state); after != nil && (result == unknown || !after.ObservedAt.Before(&observed)) { + return &fleetv1.PowerStatus{State: string(after.State)}, nil + } + // An operation that finished after discovery's read, and proved no power + // state, may have changed power since: discovery no longer shows it. A + // tie in the one-second timestamps cannot be ordered, so it counts too. + if last := state.Spec.LastResult; last != nil && last.Kind != "DeviceRecovery" && !last.FinishedAt.Before(&observed) { + return unknown, nil + } + return result, nil +} + +// provenPower returns the power state custody's last result proved, when +// that result is a succeeded power operation with a settled state. +func provenPower(state *ops.DeviceCustody) *ops.PowerObservation { + last := state.Spec.LastResult + if last == nil || last.Kind != "DevicePowerOperation" || last.Phase != ops.PhaseSucceeded || last.Evidence == nil { + return nil + } + var evidence ops.PowerEvidence + if json.Unmarshal(last.Evidence.Raw, &evidence) != nil || evidence.Power == nil || evidence.Power.After == nil || !evidence.Power.After.State.Settled() { + return nil + } + return evidence.Power.After } // Chain runs projectors in order and stops at the first that must retry. From 27ebe66a3941110a7196e26dd9d519f6cf49a99e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 12:32:43 -0600 Subject: [PATCH 4/5] test(manager): Run customer power through custody The customer power flow runs against a real API server with the coordinator, delivery and the simulator site behind its site API: - power under an allocation, and unknown after a later installation; - a change waiting behind an installation; - a newer request replacing a pending one, including an intent that returns to the observed state; - a hold reporting Unknown through release and settling with fresh discovery; - a retry that repeats only the held action; - a request waiting through a discovery lapse, sending nothing, and running once discovery returns. The allocator gets a capacity evaluator that offers every fixture server, since these tests cover power, not commissioning. The custody guide records customer power and two remaining gaps. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 21 +- .../manager/customer_power_envtest_test.go | 728 ++++++++++++++++++ 2 files changed, 748 insertions(+), 1 deletion(-) create mode 100644 internal/manager/customer_power_envtest_test.go diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 6b9bbb14..f1c5743f 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -18,7 +18,9 @@ marked **implemented and verified**, **implemented and inert**, or | D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests, and the two site fixes they found. See [Failure scenarios](#failure-scenarios-increment-d). | **Implemented and verified** by unit tests and both multi-plane runs, local VM and Redfish. | | Commissioning, step 1 | `DeviceCommissioning`, `DeviceCommissioningPlan` and `DeviceCommissioningPlanApproval`: CRDs, ProtectedResources, roles, the creator webhook route, the kind and its rows, plan qualification and the current plan. See [Commissioning](#commissioning). | **Implemented and inert.** Verified by tests against a real API server. No site runs a commissioning worker yet, and no mode creates one. | | Power P1: control plane | `DevicePowerOperation`, its registry entry, rows, checks, evidence and settle hook, its roles, and the Device field for offered reset types. See [Device power operations](#device-power-operations). | **Implemented.** The kind ships with the component in every root C wires, and the creator webhook, standalone's creator policy and each coordinator's access cover it. Nothing creates power operations yet. Discovery records the reset types each server offers. | -| Power P2 to P4 | The site worker (on B), customer power from `Machine.spec.powerState` (on C), and the UI | **Proposed** | +| Power P2: site worker | The power worker behind the site worker contract, registered at Redfish sites | **Implemented.** No end-to-end run creates power operations yet; see [Worker gaps that remain](#worker-gaps-that-remain). | +| Power P3: customer power | The Metal provider's power request from `Machine.spec.powerState`, the projector's proven power, and the simulator's power worker | **Implemented and verified** against a real API server with the simulator site. No running provider calls it yet. | +| Power P4 | The UI | **Proposed** | ## What Increment A adds @@ -1254,6 +1256,17 @@ The lab BMC records `LastResetTime` and adds faults for a withheld request, a hidden reset time and an identity swap, as [the Redfish lab](../operations/redfish-lab.md) describes. +### Customer power + +| Piece | Decision | +| --- | --- | +| Request | The Metal provider asks the allocator for the Machine's power. `powerState` `On` is the action `On`, and `Off` is `ForceOff`. The operation is named from the allocation and the Machine generation, so a refused one is not created again until the generation changes. A request whose discovery lapsed waits in `Pending` instead, as [the admission checks](#device-power-operations) describe, and runs once discovery reads the server again. If discovery stays away past that bound, the request ends `Failed` and, like any refused one, is not created again until the generation changes. | +| When it is due | When `powerState` differs from the Machine's observed power, or when this allocation's request for another action has not run yet, so a newer request replaces it. A Machine generation runs at most one power operation, so power that drifts after it succeeded is not corrected until the generation changes. Observed power must be `On` or `Off`. Every Machine defaults to `Off`, so power not yet observed, or `Unknown`, asks for nothing, and no server is forced off before its power is known. | +| During a power hold | Observed power is `Unknown`, so nothing is created. After staff apply a `Retry`, the provider creates the retry under the foundation's retry name, repeating the held operation's inputs, and only while `powerState` still maps to the held action. Otherwise staff settle the hold, and the newer request runs after it. | +| Observed power | The manager's power projector stays the only writer of `Machine.status.power`. It reports `Unknown` during any hold or unverified custody, and otherwise the newer of discovery's power state and the state custody's last succeeded power operation proved, a tie going to the operation. When any other operation except a recovery finished at or after discovery's read, power is `Unknown` until discovery reads it again, because that operation may have changed it. | +| Simulator | The simulator site registers a power worker for its simulated servers, and its fixture discovery reports each server's power and offers every action. A restart is proven only by the server's reset time moving to the command. The reset step journals the power read before the command and the send time. A resumed run, whether the step finished or not, reports both, and never treats the command's effect as a server that needed none. A test-only fault makes a server ignore resets, so a power operation ends unknown. | +| Not yet wired | No running provider calls the power request. The synthetic staging provider accepts only Machines that ask for power `Off`, and the harness runners do not change power. | + ### Foundation seams power added Power needed two general seams in the foundation, and adds them rather than @@ -1282,6 +1295,11 @@ around here. operation, and a `Settle` has no real power state to cite. The power phases need real BMC discovery in the Redfish run, or fixture discovery that reports the server's power. +- **The two-minute start window against delivery latency.** A power worker + that starts more than two minutes after admission refuses as `Stale`, with + nothing sent. The multi-plane harness allows up to about eight minutes for + Karmada delivery, kro and the worker Pod, so a slow delivery would fail a + power operation safely once a run creates one. - **A swap before the command is reported as `DeviceIdentityMismatch`.** The framework verifies the System's identity before a kind runs, with the shared reason. #173 names this refusal `SystemUUIDMismatch` at the worker. @@ -1318,6 +1336,7 @@ a real API server: | Power: each refusal with custody unchanged, both rows and every other pair, staff racing an allocation, replacement only by the provider row and waiting under a hold, expiry, an early staff retry settling after `Retry`, `Settle` evidence, required evidence, a provider request waiting for discovery (its bound, its replacement, and two coordinators admitting it once), and proof of a success, including a retry's | `TestPowerOperations` | | A check refusal that waits only on a queue row, within its bound from when the Device was last free, and only with a declared reason; proof of success needs required evidence | `TestExtensionSeams`, `TestRegistryRequiresEvidenceForProofOfSuccess` | | Power: CEL inputs and evidence pruning, checks, input digest, evidence bounds, registration | `TestPowerCRDRules`, `TestPowerChecks`, `TestPowerInputDigestIsStable`, `TestPowerEvidenceIsTypedAndBounded`, `TestPowerRegistration` | +| Customer power: power under an allocation, waiting behind an installation, a newer request replacing a pending one, a hold reporting `Unknown` through release and settling with fresh discovery, a retry repeating only the held action, a request waiting through a discovery lapse | `TestCustomerPower` | | Power worker: one reset per action and its proof, sending nothing when already in the requested state, each refusal with nothing sent, a lost response, a request never applied, an unprovable restart, a swap after the command, a resumed worker, two workers for one assignment | `go test ./internal/site/powerwork` | | The BMC's reset time and the lab's power faults | `TestObserveReadsTheLastResetTime`; the lab adapter self-test | diff --git a/internal/manager/customer_power_envtest_test.go b/internal/manager/customer_power_envtest_test.go new file mode 100644 index 00000000..13d81458 --- /dev/null +++ b/internal/manager/customer_power_envtest_test.go @@ -0,0 +1,728 @@ +package manager + +import ( + "context" + "errors" + "fmt" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/go-logr/logr" + 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" + "sigs.k8s.io/controller-runtime/pkg/envtest" + ctrllog "sigs.k8s.io/controller-runtime/pkg/log" + + "go.datum.net/fleet/internal/allocation" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/delivery" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/site/simwork" + "go.datum.net/fleet/internal/site/siteapi" + "go.datum.net/fleet/internal/tenancy" +) + +// The customer power flow: the Metal provider's power requests, custody, +// the simulator site and the power projector, against a real API server. + +const ( + namespace = "fleet-provider" + providerUser = "system:serviceaccount:fleet-system:metal-provider" + releaseUser = "system:serviceaccount:fleet-system:release-controller" + siteName = "site-example-a" + siteToken = "synthetic-site-token" + keyDigest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + imageRef = "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" + policyDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" +) + +func uid(n int) string { return fmt.Sprintf("00000000-0000-4000-8000-%012d", n) } + +// env is a real API server with the metal, inventory and custody CRDs, one +// simulator site behind its HTTP API, and the coordinator loop. +type env struct { + t *testing.T + ctx context.Context + admin client.Client + allocator *allocation.Allocator + loop *delivery.Loop + store *site.Store + enrollment fixture.Enrollment + class *fleetv1.MachineClass + profile *fleetv1.MachineProfile +} + +func scheme(t *testing.T) *runtime.Scheme { + s := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, fleetv1.AddToScheme, ops.AddToScheme} { + if err := add(s); err != nil { + t.Fatal(err) + } + } + return s +} + +func startEnv(t *testing.T) *env { + t.Helper() + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctrllog.SetLogger(logr.Discard()) + root := filepath.Join("..", "..") + environment := &envtest.Environment{CRDDirectoryPaths: []string{ + filepath.Join(root, "config", "base", "crd"), + filepath.Join(root, "config", "components", "inventory", "crds"), + filepath.Join(root, "config", "components", "device-operations", "crds"), + }, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = environment.Stop() }) + admin, err := client.New(config, client.Options{Scheme: scheme(t)}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + e := &env{t: t, ctx: ctx, admin: admin, enrollment: fixture.Enrollment{}} + e.create(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}) + + dir := t.TempDir() + if err := os.Chmod(dir, 0o700); err != nil { + t.Fatal(err) + } + e.store, err = site.OpenStore(dir, nil) + if err != nil { + t.Fatal(err) + } + runner := &site.Runner{Site: siteName, Store: e.store, Results: site.NewResults(e.store), Access: fixture.Access{Enrollment: e.enrollment}, + Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DevicePowerOperation": simwork.Power{}}, Poll: 20 * time.Millisecond} + dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx} + server := httptest.NewServer(siteapi.Handler(dispatcher, e.store, runner.Results, func() (string, error) { return siteToken, nil })) + t.Cleanup(func() { cancel(); server.Close(); dispatcher.Wait() }) + remote, err := siteapi.NewClient(server.URL, func() (string, error) { return siteToken, nil }, server.Client()) + if err != nil { + t.Fatal(err) + } + registry, err := custody.DefaultRegistry() + if err != nil { + t.Fatal(err) + } + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} + coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: custody.Principals{ + custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, + }}} + e.loop = &delivery.Loop{Client: admin, Coordinator: coordinator, Namespace: namespace, + Courier: &delivery.Courier{Client: admin, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}} + e.allocator = &allocation.Allocator{ + Provider: admin, ProviderCreator: ops.Creator{Username: providerUser, UID: uid(801)}, + Releaser: admin, ReleaseCreator: ops.Creator{Username: releaseUser, UID: uid(802)}, + Custody: coordinator, Namespace: namespace, + Cleaning: func(string) (string, error) { return policyDigest, nil }, + BootInterface: "primary", TargetDisks: []string{"disk-0"}, + Capacity: fixtureOffers{}, + } + e.class = &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "class-example"}, Spec: fleetv1.MachineClassSpec{ProfilePolicy: &fleetv1.ProfilePolicy{AllowedProfiles: []fleetv1.LocalReference{{Name: "profile-example"}}}, Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: namespace, Selector: metav1.LabelSelector{MatchLabels: map[string]string{"pool": "example"}}}}}} + e.create(e.class) + e.profile = &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "profile-example"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: fleetv1.MemoryRequirement{Capacity: "2Gi"}}} + e.create(e.profile) + return e +} + +// fixtureOffers offers every capacity with the hardware its fixture status +// records. These tests cover power, not commissioning, so no server needs +// commissioning evidence to be offered. +type fixtureOffers struct{} + +func (fixtureOffers) Offer(_ context.Context, capacity *fleetv1.MachineCapacity) (bool, fleetv1.Hardware, error) { + return true, capacity.Status.Hardware, nil +} + +func (e *env) create(object client.Object) { + e.t.Helper() + if err := e.admin.Create(e.ctx, object); err != nil { + e.t.Fatal(err) + } +} + +// server adds a synthetic Device, its enrollment at the site, its capacity +// and fixture discovery. +func (e *env) server(n int) *inventory.Device { + e.t.Helper() + name := fmt.Sprintf("server-example-%03d", n) + mac := fmt.Sprintf("02:00:00:00:00:%02x", n) + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, Spec: inventory.DeviceSpec{ + ClaimRef: inventory.LocalReference{Name: "claim-" + name}, + Identity: inventory.DeviceIdentity{Model: "example", Serial: "serial-" + name, SystemUUID: uid(100 + n)}, + BMC: &inventory.BMC{Endpoint: fmt.Sprintf("https://[2001:db8::%x]", n)}, + Interfaces: []inventory.Interface{{Name: "primary", MACAddress: mac}}, + }} + e.create(device) + key := fmt.Sprintf("%064x", n) + e.enrollment[namespace+"/"+name] = fixture.Target{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: uid(100 + n), BootMACAddress: mac, BMCPublicKeySHA256: key, Disks: []string{"disk-0"}} + e.loop.Courier.Sites.Devices[name] = []string{siteName} + capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "capacity-" + name, Namespace: namespace, Labels: map[string]string{"pool": "example"}}, + Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: name}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "example-cleaning"}, ReclaimPolicy: "Retain"}} + e.create(capacity) + capacity.Status.Hardware = fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleetv1.HardwareMemory{Capacity: "2Gi"}} + for _, kind := range []string{"Prepared", "Healthy", "Available"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, metav1.Condition{Type: kind, Status: metav1.ConditionTrue, Reason: "Fixture", ObservedGeneration: capacity.Generation, LastTransitionTime: metav1.Now()}) + } + if err := e.admin.Status().Update(e.ctx, capacity); err != nil { + e.t.Fatal(err) + } + e.discover(name) + e.until("custody is Verified", func() bool { + state := e.custody(name) + return state != nil && state.Spec.State == ops.CustodyVerified + }) + return device +} + +// discover writes fixture discovery for one Device, with its simulated +// server's power, as the simulator site does. +func (e *env) discover(name string) { + e.t.Helper() + if err := fixture.DiscoverPower(e.ctx, e.admin, fixture.Enrollment{namespace + "/" + name: e.enrollment[namespace+"/"+name]}, time.Now(), simwork.Observe(e.store)); err != nil { + e.t.Fatal(err) + } +} + +// until runs coordinator passes until done holds. +func (e *env) until(what string, done func() bool) { + e.t.Helper() + deadline := time.Now().Add(30 * time.Second) + for !done() { + if time.Now().After(deadline) { + e.t.Fatalf("timed out waiting until %s", what) + } + if err := e.loop.Pass(e.ctx); err != nil { + e.t.Logf("pass: %v", err) + } + time.Sleep(20 * time.Millisecond) + } +} + +func (e *env) custody(name string) *ops.DeviceCustody { + state := &ops.DeviceCustody{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: name}, state); err != nil { + return nil + } + return state +} + +func machine(n int) allocation.Machine { + return allocation.Machine{Consumer: tenancy.Project(fmt.Sprintf("consumer-%d", n)), ConsumerUID: types.UID(uid(500 + n)), Namespace: "default", Name: "allocation", UID: types.UID(uid(600 + n))} +} + +func (e *env) request(n int) allocation.Request { + return allocation.Request{Machine: machine(n), Class: e.class, Profile: e.profile, Authority: fleetv1.AllocationAuthority{Principal: "fixture", Decision: fmt.Sprintf("fixture-%d", n)}} +} + +func (e *env) installation(n int, name, predecessor string) *fleetv1.Installation { + installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", UID: types.UID(uid(700 + n))}, + Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: "allocation"}, ImageRef: fleetv1.LocalReference{Name: imageRef}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}}} + if predecessor != "" { + installation.Spec.ExpectedPredecessor = fleetv1.InstallationPredecessor{Type: "Installation", Name: predecessor} + } + return installation +} + +// release repeats Release while the coordinator runs, until it is Released. +func (e *env) release(bound *fleetv1.MachineAllocation, owner allocation.Machine) { + e.t.Helper() + e.until("the allocation is Released", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(bound), bound); err != nil { + e.t.Fatal(err) + } + released, err := e.allocator.Release(e.ctx, bound, owner) + if err != nil { + e.t.Logf("release: %v", err) + } + return released + }) +} + +const staffUser = "staff-example@example.com" + +// powered is one allocated Machine on a simulated server. +type powered struct { + e *env + n int + device string + deviceUID string + allocation *fleetv1.MachineAllocation + machine *fleetv1.Machine + owner allocation.Machine +} + +// allocatePowered creates a Machine that asks for power Off, allocates it a +// Device, and projects its observed power. +func (e *env) allocatePowered(n int) *powered { + e.t.Helper() + e.server(n) + object := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("machine-%d", n), Namespace: "default"}, Spec: fleetv1.MachineSpec{ + MachineClassRef: fleetv1.LocalReference{Name: e.class.Name}, MachineProfileRef: fleetv1.LocalReference{Name: e.profile.Name}, + LocationRef: fleetv1.LocalReference{Name: "location-example"}, PowerState: "Off", + }} + e.create(object) + owner := machine(n) + owner.Name, owner.UID = object.Name, object.UID + request := e.request(n) + request.Machine = owner + allocation, err := e.allocator.Allocate(e.ctx, request) + if err != nil { + e.t.Fatal(err) + } + // The allocator may choose any free Device in the pool, such as one an + // earlier subtest released, so the Device is the one the allocation + // names. + p := &powered{e: e, n: n, device: allocation.Spec.DeviceRef.Name, deviceUID: allocation.Labels[fleetv1.LabelDeviceUID], allocation: allocation, machine: object, owner: owner} + // A reused Device's last operation, such as its wipe, finished after its + // last discovery read, so its power is unknown until discovery reads it + // again, as the simulator site does every minute. + time.Sleep(1100 * time.Millisecond) + e.discover(p.device) + p.project() + return p +} + +// project runs the power projector, the only writer of Machine power, and +// reads the Machine back. +func (p *powered) project() string { + p.e.t.Helper() + if err := ProjectPower(p.e.ctx, p.e.admin, p.e.admin, namespace, p.owner); err != nil { + p.e.t.Fatal(err) + } + if err := p.e.admin.Get(p.e.ctx, client.ObjectKeyFromObject(p.machine), p.machine); err != nil { + p.e.t.Fatal(err) + } + if p.machine.Status.Power == nil { + return "" + } + return p.machine.Status.Power.State +} + +// want sets the Machine's powerState, which raises its generation. +func (p *powered) want(state string) { + p.e.t.Helper() + if err := p.e.admin.Get(p.e.ctx, client.ObjectKeyFromObject(p.machine), p.machine); err != nil { + p.e.t.Fatal(err) + } + p.machine.Spec.PowerState = state + if err := p.e.admin.Update(p.e.ctx, p.machine); err != nil { + p.e.t.Fatal(err) + } +} + +func (p *powered) power() *ops.DevicePowerOperation { + p.e.t.Helper() + if err := p.e.admin.Get(p.e.ctx, client.ObjectKeyFromObject(p.machine), p.machine); err != nil { + p.e.t.Fatal(err) + } + operation, err := p.e.allocator.Power(p.e.ctx, p.allocation, p.owner, p.machine) + if err != nil { + p.e.t.Fatal(err) + } + return operation +} + +func (p *powered) server() simwork.Server { + server, err := simwork.ReadServer(p.e.store, namespace+"/"+p.device) + if err != nil { + p.e.t.Fatal(err) + } + return server +} + +func (p *powered) setServer(change func(*simwork.Server)) { + p.e.t.Helper() + server := p.server() + change(&server) + if err := simwork.WriteServer(p.e.store, namespace+"/"+p.device, server); err != nil { + p.e.t.Fatal(err) + } +} + +func (e *env) ended(operation ops.Operation) ops.Phase { + e.t.Helper() + e.until(operation.GetName()+" ends", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + e.t.Fatal(err) + } + return operation.OperationStatus().Phase.Ended() + }) + return operation.OperationStatus().Phase +} + +// recover creates a staff DeviceRecovery for the Device's current hold. +func (p *powered) recover(decision ops.RecoveryDecision, evidence ops.RecoveryEvidence) *ops.DeviceRecovery { + p.e.t.Helper() + hold := p.e.custody(p.device).Spec.RecoveryHold + if hold == nil { + p.e.t.Fatal("no hold to recover") + } + if evidence.Summary == "" { + evidence = ops.RecoveryEvidence{ObservedAt: metav1.NewTime(time.Now().UTC()), Summary: "staff decided"} + } + recovery := &ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: p.device + "-recovery-", Namespace: namespace, Labels: map[string]string{ops.LabelDeviceUID: p.deviceUID}}, Spec: ops.DeviceRecoverySpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: ops.Creator{Username: staffUser, UID: uid(900)}, DeviceRef: ops.DeviceReference{Name: p.device}, + Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "settle the customer's power"}}}, + Decision: decision, Hold: &ops.HeldOperationReference{Kind: hold.Kind, Name: hold.Name, Fence: hold.Fence}, Evidence: evidence, + }} + p.e.create(recovery) + return recovery +} + +// holdPower runs a power change the server ignores, which ends unknown and +// holds the Device. +func (p *powered) holdPower(state string) *ops.DevicePowerOperation { + p.e.t.Helper() + p.setServer(func(s *simwork.Server) { s.Unresponsive = true }) + p.want(state) + held := p.power() + if held == nil { + p.e.t.Fatal("no power operation was created") + } + if phase := p.e.ended(held); phase != ops.PhaseOutcomeUnknown { + p.e.t.Fatalf("held operation ended %s, want OutcomeUnknown", phase) + } + return held +} + +func TestCustomerPower(t *testing.T) { + e := startEnv(t) + + t.Run("power under an allocation follows the Machine's powerState", func(t *testing.T) { + p := e.allocatePowered(11) + // The server starts off and the Machine asks for off: nothing is due. + if observed := p.project(); observed != "Off" { + t.Fatalf("observed power = %q", observed) + } + if operation := p.power(); operation != nil { + t.Fatalf("an operation was created with nothing to change: %s", operation.Name) + } + p.want("On") + // Before the projector reports power, nothing is due: every Machine + // defaults to Off, and a server is not forced to a state before its + // power is known. + unobserved := p.machine.DeepCopyObject().(*fleetv1.Machine) + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(p.machine), unobserved); err != nil { + t.Fatal(err) + } + for _, state := range []*fleetv1.PowerStatus{nil, {State: "Unknown"}} { + unobserved.Status.Power = state + if operation, err := e.allocator.Power(e.ctx, p.allocation, p.owner, unobserved); err != nil || operation != nil { + t.Fatalf("power %v: operation %v, %v", state, operation, err) + } + } + operation := p.power() + if operation == nil || operation.Name != custody.PowerName(p.allocation.Name, p.machine.Generation) || operation.Spec.Action != ops.PowerOn { + t.Fatalf("operation = %+v", operation) + } + if phase := e.ended(operation); phase != ops.PhaseSucceeded { + t.Fatalf("power ended %s: %s", phase, operation.Status.Message) + } + if simwork.State(p.server()) != ops.PowerStateOn { + t.Fatalf("server = %+v", p.server()) + } + // The projector reports the proven state before discovery reads it + // again, and with it nothing more is due. + if observed := p.project(); observed != "On" { + t.Fatalf("observed power after the operation = %q", observed) + } + if again := p.power(); again != nil { + t.Fatalf("a second operation was created: %s", again.Name) + } + // An installation that finishes after discovery's read proves no + // power, so power is unknown until discovery reads it again. + install, err := e.allocator.Install(e.ctx, p.allocation, allocation.Installation{Installation: e.installation(11, "debian-12", "")}) + if err != nil { + t.Fatal(err) + } + if phase := e.ended(install); phase != ops.PhaseSucceeded { + t.Fatalf("installation ended %s", phase) + } + if observed := p.project(); observed != "Unknown" { + t.Fatalf("observed power after a later installation = %q", observed) + } + time.Sleep(1100 * time.Millisecond) + e.discover(p.device) + if observed := p.project(); observed != "On" { + t.Fatalf("observed power after discovery read it again = %q", observed) + } + }) + + t.Run("only the Machine that owns the allocation can request its power", func(t *testing.T) { + p := e.allocatePowered(17) + p.want("On") + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(p.machine), p.machine); err != nil { + t.Fatal(err) + } + // Each case differs from the owner in one place, so each ownership + // check has a case that only it refuses. + otherMachine := func(change func(*fleetv1.Machine)) *fleetv1.Machine { + copied := p.machine.DeepCopyObject().(*fleetv1.Machine) + change(copied) + return copied + } + otherAllocation := func(change func(*fleetv1.MachineAllocation)) *fleetv1.MachineAllocation { + copied := p.allocation.DeepCopyObject().(*fleetv1.MachineAllocation) + change(copied) + return copied + } + for name, c := range map[string]struct { + allocation *fleetv1.MachineAllocation + machine *fleetv1.Machine + }{ + "a same-name Machine created again": {p.allocation, otherMachine(func(m *fleetv1.Machine) { m.UID = types.UID(uid(699)) })}, + "a Machine in another namespace": {p.allocation, otherMachine(func(m *fleetv1.Machine) { m.Namespace = "other" })}, + "a Machine with another name": {p.allocation, otherMachine(func(m *fleetv1.Machine) { m.Name = "machine-other" })}, + "an allocation named for another Machine": {otherAllocation(func(a *fleetv1.MachineAllocation) { a.Name = "alloc-0000000000000000" }), p.machine}, + "an allocation for another consumer": {otherAllocation(func(a *fleetv1.MachineAllocation) { a.Spec.ConsumerRef = tenancy.Project("consumer-other") }), p.machine}, + "an allocation recording another Machine": {otherAllocation(func(a *fleetv1.MachineAllocation) { a.Spec.MachineRef.Name = "machine-other" }), p.machine}, + "an allocation labeled with another Machine UID": {otherAllocation(func(a *fleetv1.MachineAllocation) { a.Labels[fleetv1.LabelMachineUID] = uid(698) }), p.machine}, + "an allocation labeled with another consumer UID": {otherAllocation(func(a *fleetv1.MachineAllocation) { a.Labels[fleetv1.LabelConsumerUID] = uid(598) }), p.machine}, + } { + if operation, err := e.allocator.Power(e.ctx, c.allocation, p.owner, c.machine); !errors.Is(err, allocation.ErrConflict) || operation != nil { + t.Errorf("%s: operation %v, %v", name, operation, err) + } + } + var list ops.DevicePowerOperationList + if err := e.admin.List(e.ctx, &list, client.InNamespace(namespace)); err != nil { + t.Fatal(err) + } + for _, operation := range list.Items { + if reference := operation.Spec.Authority.AllocationRef; reference != nil && reference.Name == p.allocation.Name { + t.Fatalf("a refused request created %s", operation.Name) + } + } + if operation := p.power(); operation == nil { + t.Fatal("the owning Machine's request created no operation") + } + }) + + t.Run("a power change waits behind a running installation", func(t *testing.T) { + p := e.allocatePowered(12) + install, err := e.allocator.Install(e.ctx, p.allocation, allocation.Installation{Installation: e.installation(12, "debian-12", "")}) + if err != nil { + t.Fatal(err) + } + p.want("On") + operation := p.power() + if phase := e.ended(operation); phase != ops.PhaseSucceeded { + t.Fatalf("power ended %s: %s", phase, operation.Status.Message) + } + if phase := e.ended(install); phase != ops.PhaseSucceeded { + t.Fatalf("installation ended %s", phase) + } + // Custody admitted the installation first, and power only after it + // finished. + if operation.Status.Fence <= install.Status.Fence || operation.Status.AdmittedAt.Before(install.Status.FinishedAt) { + t.Fatalf("power admitted at fence %d %v, installation fence %d finished %v", operation.Status.Fence, operation.Status.AdmittedAt, install.Status.Fence, install.Status.FinishedAt) + } + }) + + t.Run("a newer power request replaces a pending one", func(t *testing.T) { + p := e.allocatePowered(13) + install, err := e.allocator.Install(e.ctx, p.allocation, allocation.Installation{Installation: e.installation(13, "debian-12", "")}) + if err != nil { + t.Fatal(err) + } + p.want("On") + older := p.power() + // Newer by at least the API server's one-second timestamp. + time.Sleep(1100 * time.Millisecond) + p.setServer(func(s *simwork.Server) { s.Power = "On" }) + e.discover(p.device) + p.project() + p.want("Off") + newer := p.power() + if newer == nil || newer.Name == older.Name || newer.Spec.Action != ops.PowerForceOff { + t.Fatalf("newer = %+v", newer) + } + if phase := e.ended(older); phase != ops.PhaseCancelled || older.Status.Reason != custody.ReasonSuperseded { + t.Fatalf("older ended %s %s", phase, older.Status.Reason) + } + if phase := e.ended(newer); phase != ops.PhaseSucceeded { + t.Fatalf("newer ended %s: %s", phase, newer.Status.Message) + } + if phase := e.ended(install); phase != ops.PhaseSucceeded { + t.Fatalf("installation ended %s", phase) + } + }) + + t.Run("an intent that returns to the observed state replaces the request that has not run", func(t *testing.T) { + p := e.allocatePowered(16) + install, err := e.allocator.Install(e.ctx, p.allocation, allocation.Installation{Installation: e.installation(16, "debian-12", "")}) + if err != nil { + t.Fatal(err) + } + p.want("On") + queued := p.power() + time.Sleep(1100 * time.Millisecond) + // The customer changes their mind before the queued On runs. The + // server is still observed off, and the queued On would undo the + // intent, so a ForceOff replaces it. + p.want("Off") + reverted := p.power() + if reverted == nil || reverted.Spec.Action != ops.PowerForceOff { + t.Fatalf("reverted = %+v", reverted) + } + if phase := e.ended(queued); phase != ops.PhaseCancelled || queued.Status.Reason != custody.ReasonSuperseded { + t.Fatalf("queued ended %s %s", phase, queued.Status.Reason) + } + if phase := e.ended(reverted); phase != ops.PhaseSucceeded { + t.Fatalf("reverted ended %s: %s", phase, reverted.Status.Message) + } + if phase := e.ended(install); phase != ops.PhaseSucceeded { + t.Fatalf("installation ended %s", phase) + } + if simwork.State(p.server()) != ops.PowerStateOff { + t.Fatalf("server = %+v", p.server()) + } + // With the intent met and nothing pending, nothing more is due. + if again := p.power(); again != nil && !again.Status.Phase.Ended() { + t.Fatalf("another operation is due: %s", again.Name) + } + }) + + t.Run("a power hold reports Unknown, moves into release, and settles with fresh discovery", func(t *testing.T) { + p := e.allocatePowered(14) + held := p.holdPower("On") + hold := e.custody(p.device).Spec.RecoveryHold + if hold == nil || hold.Name != held.Name || e.custody(p.device).Spec.Holder.Type != ops.HolderAllocation { + t.Fatalf("custody = %+v", e.custody(p.device).Spec) + } + if observed := p.project(); observed != "Unknown" { + t.Fatalf("observed power while held = %q", observed) + } + // The customer's power is unknown, so nothing more is created. + p.want("Off") + if operation := p.power(); operation != nil { + t.Fatalf("an operation was created during the hold: %s", operation.Name) + } + // Release starts, the hold moves with it, and the wipe waits. + for range 5 { + released, err := e.allocator.Release(e.ctx, p.allocation, p.owner) + if err != nil && !errors.Is(err, allocation.ErrReleased) { + t.Logf("release: %v", err) + } + if released { + t.Fatal("the allocation released while its Device was held") + } + if err := e.loop.Pass(e.ctx); err != nil { + t.Logf("pass: %v", err) + } + } + state := e.custody(p.device) + if state.Spec.Holder.Type != ops.HolderRelease || state.Spec.RecoveryHold == nil || state.Spec.RecoveryHold.Name != held.Name { + t.Fatalf("custody during release = %+v", state.Spec) + } + // Staff settle the hold with discovery read after it began. + time.Sleep(1100 * time.Millisecond) + e.discover(p.device) + // Staff cite the discovery read: its time and the state it read. + read := &inventory.Device{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: p.device}, read); err != nil { + t.Fatal(err) + } + settle := p.recover(ops.DecisionSettle, ops.RecoveryEvidence{ObservedAt: read.Status.Discovery.Inventory.ObservedAt, Summary: "discovery reads the server off", + Data: map[string]string{custody.SettlePowerState: "Off"}}) + if phase := e.ended(settle); phase != ops.PhaseSucceeded { + t.Fatalf("settle ended %s %s: %s", phase, settle.Status.Reason, settle.Status.Message) + } + p.setServer(func(s *simwork.Server) { s.Unresponsive = false }) + e.release(p.allocation, p.owner) + }) + + t.Run("after a Retry the provider repeats the held action, and only that action", func(t *testing.T) { + p := e.allocatePowered(15) + held := p.holdPower("On") + // Until staff apply a Retry, nothing is created, even though + // powerState still asks for the held action. + if operation := p.power(); operation != nil { + t.Fatalf("a retry was created before staff applied a Retry: %s", operation.Name) + } + time.Sleep(1100 * time.Millisecond) + e.discover(p.device) + retry := p.recover(ops.DecisionRetry, ops.RecoveryEvidence{}) + if phase := e.ended(retry); phase != ops.PhaseSucceeded { + t.Fatalf("retry ended %s %s: %s", phase, retry.Status.Reason, retry.Status.Message) + } + // A changed powerState no longer maps to the held action: no retry. + p.want("Off") + if operation := p.power(); operation != nil { + t.Fatalf("a retry was created for another action: %s", operation.Name) + } + p.want("On") + p.setServer(func(s *simwork.Server) { s.Unresponsive = false }) + repeated := p.power() + hold := e.custody(p.device).Spec.RecoveryHold + if repeated == nil || repeated.Name != custody.RetryName(*hold, hold.Retries) || !reflect.DeepEqual(repeated.Spec, held.Spec) { + t.Fatalf("retry operation = %+v", repeated) + } + if phase := e.ended(repeated); phase != ops.PhaseSucceeded { + t.Fatalf("retried power ended %s: %s", phase, repeated.Status.Message) + } + if state := e.custody(p.device); state.Spec.RecoveryHold != nil { + t.Fatalf("hold after the retry succeeded = %+v", state.Spec.RecoveryHold) + } + if observed := p.project(); observed != "On" { + t.Fatalf("observed power after the retry = %q", observed) + } + }) + + t.Run("a power request waits through a discovery lapse and runs when discovery returns", func(t *testing.T) { + p := e.allocatePowered(18) + // Discovery last read the server three hours ago, past the two + // hours power accepts with the default one-hour interval. + lapsed := fixture.Enrollment{namespace + "/" + p.device: e.enrollment[namespace+"/"+p.device]} + if err := fixture.DiscoverPower(e.ctx, e.admin, lapsed, time.Now().Add(-3*time.Hour), simwork.Observe(e.store)); err != nil { + t.Fatal(err) + } + fence := e.custody(p.device).Spec.Fence + p.want("On") + operation := p.power() + e.until(operation.Name+" waits for discovery", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + t.Fatal(err) + } + return operation.Status.Phase == ops.PhasePending && operation.Status.Reason == custody.ReasonDiscoveryNotCurrent + }) + // More passes change nothing: the request neither fails nor runs. + for range 5 { + if err := e.loop.Pass(e.ctx); err != nil { + t.Logf("pass: %v", err) + } + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + t.Fatal(err) + } + if operation.Status.Phase != ops.PhasePending || e.custody(p.device).Spec.Fence != fence || p.server().Power == "On" { + t.Fatalf("while discovery lapsed: %+v, fence %d from %d, server %+v", operation.Status, e.custody(p.device).Spec.Fence, fence, p.server()) + } + if observed := p.project(); observed == "On" { + t.Fatalf("observed power while waiting = %q", observed) + } + e.discover(p.device) + if phase := e.ended(operation); phase != ops.PhaseSucceeded { + t.Fatalf("power ended %s %s: %s", phase, operation.Status.Reason, operation.Status.Message) + } + if observed := p.project(); observed != "On" { + t.Fatalf("observed power after discovery returned = %q", observed) + } + }) +} From 02059066cb1de961502f2791218d4b45bcebea94 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 18:13:04 -0600 Subject: [PATCH 5/5] fix(metal): Leave power unmanaged when unset Machine.spec.powerState defaulted to Off, and an install leaves the server on. Once a provider asked for power, the first discovery read after an install would have forced every freshly installed server off. powerState now has no default. Unset means Fleet does not manage the Machine's power: no power operation is created, whatever the server's state. A Machine that asks for Off or On still gets ForceOff or On when its observed power differs. A request created before powerState was cleared still runs, and Machines already stored with Off keep it. The synthetic provider and the standalone runner accept a claim whose power is unset or Off, and still refuse On. Fixtures that are not about power leave it unset, so they take that path. The consumer UI no longer creates Machines with power Off, and shows no requested power for an unmanaged Machine. Tests cover an unmanaged Machine after an install with its server on, which creates nothing until it asks for Off and then gets ForceOff; unset, Off and On claims through the synthetic provider; the standalone runner's fixture check; and the UI's create payload and power intent. Co-Authored-By: Claude Opus 5.5 --- config/README.md | 16 ++--- config/base/crd/metal.datumapis.com.yaml | 2 +- config/standalone/fixtures.yaml | 2 - docs/development/README.md | 18 +++--- docs/development/device-custody.md | 6 +- docs/enhancements/machine-lifecycle/README.md | 4 +- .../machine-lifecycle/api-examples.md | 2 +- docs/enhancements/metal-cli/README.md | 2 +- docs/troubleshooting/README.md | 2 +- hack/multiplane/steps.sh | 4 +- internal/allocation/power.go | 9 ++- .../manager/customer_power_envtest_test.go | 60 +++++++++++++++++-- internal/manager/multicluster_harness_test.go | 2 +- internal/manager/requested_hardware_test.go | 2 +- .../multiplane/location_adversarial_test.go | 2 +- internal/multiplane/seed.go | 2 +- internal/staging/handler.go | 12 ++-- internal/staging/handler_test.go | 38 +++++++++++- internal/staging/harness_test.go | 2 +- internal/staging/multicluster_test.go | 2 +- internal/standalone/runner.go | 11 +++- internal/standalone/runner_test.go | 39 ++++++++++++ ui/consumer/src/components/machine-status.tsx | 4 +- ui/consumer/src/lib/api.test.ts | 9 +++ ui/consumer/src/lib/api.ts | 6 +- ui/consumer/src/lib/fixtures.ts | 1 - ui/consumer/src/types.test.ts | 6 +- ui/consumer/src/types.ts | 5 +- 28 files changed, 208 insertions(+), 62 deletions(-) create mode 100644 internal/standalone/runner_test.go create mode 100644 ui/consumer/src/lib/api.test.ts diff --git a/config/README.md b/config/README.md index a456ebc9..e8603b08 100644 --- a/config/README.md +++ b/config/README.md @@ -93,14 +93,14 @@ production roots, and neither production root may reference them. `config/overlays/synthetic-staging` is the temporary Milo-routed acceptance environment. It uses the real Device custody, exclusivity, release, and reuse implementation, but substitutes synthetic admission and provider evidence. It -accepts only powered-off, networkless claims in `us-central-1`; its status -conditions identify that boundary. The manager still engages every consuming -project, but the synthetic handler and publisher act only for the one -configured consumer project (`consumerProjectName`); every other engaged -project gets blocked lifecycle handlers and requested-hardware resolution. With -the publication keys documented below it uses one distinct provider project, -publishes a locked class reference and exact profile copy into the consumer, -and records both project lifetimes on each allocation. Provider Machine events wake +accepts only networkless claims in `us-central-1` whose power is unset or `Off`; +its status conditions identify that boundary. The manager still engages every +consuming project, but the synthetic handler and publisher act only for the one +configured consumer project (`consumerProjectName`); every other engaged project +gets blocked lifecycle handlers and requested-hardware resolution. With the +publication keys documented below it uses one distinct provider project, +publishes a locked class reference and exact profile copy into the consumer, and +records both project lifetimes on each allocation. Provider Machine events wake consumer claims directly; no polling resync is enabled. The simulator is a site. It runs in a separate `fleet-synthetic-provider` diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index 481cb14b..f4386862 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -259,7 +259,7 @@ spec: required: [name] properties: {name: {type: string, minLength: 1}} reclaimPolicy: {type: string, enum: [Delete, Retain], default: Delete} - powerState: {type: string, enum: ["On", "Off"], default: "Off"} + powerState: {type: string, enum: ["On", "Off"]} status: type: object x-kubernetes-validations: diff --git a/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index 38ee08d5..5489f150 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -51,7 +51,6 @@ spec: machineClassRef: {name: standard-metal} machineProfileRef: {name: general-purpose-24c-128g} locationRef: {name: us-central-1} - powerState: "Off" --- apiVersion: metal.datumapis.com/v1alpha1 kind: Machine @@ -60,7 +59,6 @@ spec: machineClassRef: {name: standard-metal} machineProfileRef: {name: general-purpose-24c-128g} locationRef: {name: us-central-1} - powerState: "Off" --- apiVersion: metal.datumapis.com/v1alpha1 kind: Installation diff --git a/docs/development/README.md b/docs/development/README.md index d29ccc22..77018a02 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -464,16 +464,16 @@ it after object creation, so this increment does not fabricate that authority with annotations or controller credentials. The opt-in `--synthetic-staging` mode is a temporary acceptance boundary. It -accepts only powered-off, networkless claims in `us-central-1`, synthesizes -clearly labelled admission and provider evidence, and uses the same allocation -library on Device custody as the standalone smoke. The manager also runs the -custody coordinator loop and fixture discovery under its leader lease. It is -event-driven: claim, class, profile, Machine, namespace, and deletion events -route exact work; it adds no periodic re-sync. One synthetic Machine is +accepts only networkless claims in `us-central-1` whose power is unset or `Off`, +synthesizes clearly labelled admission and provider evidence, and uses the same +allocation library on Device custody as the standalone smoke. The manager also +runs the custody coordinator loop and fixture discovery under its leader lease. +It is event-driven: claim, class, profile, Machine, namespace, and deletion +events route exact work; it adds no periodic re-sync. One synthetic Machine is exclusively bound, competing claims remain pending, release must complete before -finalizer removal, and release wakes waiting claims for reuse. -Public conditions say `SyntheticStagingAdmission`, so this result cannot be -mistaken for Milo caller-preserving authorization. +finalizer removal, and release wakes waiting claims for reuse. Public conditions +say `SyntheticStagingAdmission`, so this result cannot be mistaken for Milo +caller-preserving authorization. `config/overlays/synthetic-staging` is the only packaged activation path. It packages the simulator site as a separate single-replica Deployment and diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index f1c5743f..07f27a64 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -1260,8 +1260,8 @@ lab](../operations/redfish-lab.md) describes. | Piece | Decision | | --- | --- | -| Request | The Metal provider asks the allocator for the Machine's power. `powerState` `On` is the action `On`, and `Off` is `ForceOff`. The operation is named from the allocation and the Machine generation, so a refused one is not created again until the generation changes. A request whose discovery lapsed waits in `Pending` instead, as [the admission checks](#device-power-operations) describe, and runs once discovery reads the server again. If discovery stays away past that bound, the request ends `Failed` and, like any refused one, is not created again until the generation changes. | -| When it is due | When `powerState` differs from the Machine's observed power, or when this allocation's request for another action has not run yet, so a newer request replaces it. A Machine generation runs at most one power operation, so power that drifts after it succeeded is not corrected until the generation changes. Observed power must be `On` or `Off`. Every Machine defaults to `Off`, so power not yet observed, or `Unknown`, asks for nothing, and no server is forced off before its power is known. | +| Request | The Metal provider asks the allocator for the Machine's power. `powerState` `On` is the action `On`, and `Off` is `ForceOff`. `powerState` has no default: unset means Fleet does not manage the Machine's power, and no operation is created whatever the server's state, so a freshly installed server that boots on is never forced off. A request created before `powerState` was cleared still runs. Machines stored with `Off` before the default was removed keep it, and stay managed. The operation is named from the allocation and the Machine generation, so a refused one is not created again until the generation changes. A request whose discovery lapsed waits in `Pending` instead, as [the admission checks](#device-power-operations) describe, and runs once discovery reads the server again. If discovery stays away past that bound, the request ends `Failed` and, like any refused one, is not created again until the generation changes. | +| When it is due | When `powerState` differs from the Machine's observed power, or when this allocation's request for another action has not run yet, so a newer request replaces it. A Machine generation runs at most one power operation, so power that drifts after it succeeded is not corrected until the generation changes. Observed power must be `On` or `Off`, so power not yet observed, or `Unknown`, asks for nothing, and no server is forced to a state before its power is known. | | During a power hold | Observed power is `Unknown`, so nothing is created. After staff apply a `Retry`, the provider creates the retry under the foundation's retry name, repeating the held operation's inputs, and only while `powerState` still maps to the held action. Otherwise staff settle the hold, and the newer request runs after it. | | Observed power | The manager's power projector stays the only writer of `Machine.status.power`. It reports `Unknown` during any hold or unverified custody, and otherwise the newer of discovery's power state and the state custody's last succeeded power operation proved, a tie going to the operation. When any other operation except a recovery finished at or after discovery's read, power is `Unknown` until discovery reads it again, because that operation may have changed it. | | Simulator | The simulator site registers a power worker for its simulated servers, and its fixture discovery reports each server's power and offers every action. A restart is proven only by the server's reset time moving to the command. The reset step journals the power read before the command and the send time. A resumed run, whether the step finished or not, reports both, and never treats the command's effect as a server that needed none. A test-only fault makes a server ignore resets, so a power operation ends unknown. | @@ -1336,7 +1336,7 @@ a real API server: | Power: each refusal with custody unchanged, both rows and every other pair, staff racing an allocation, replacement only by the provider row and waiting under a hold, expiry, an early staff retry settling after `Retry`, `Settle` evidence, required evidence, a provider request waiting for discovery (its bound, its replacement, and two coordinators admitting it once), and proof of a success, including a retry's | `TestPowerOperations` | | A check refusal that waits only on a queue row, within its bound from when the Device was last free, and only with a declared reason; proof of success needs required evidence | `TestExtensionSeams`, `TestRegistryRequiresEvidenceForProofOfSuccess` | | Power: CEL inputs and evidence pruning, checks, input digest, evidence bounds, registration | `TestPowerCRDRules`, `TestPowerChecks`, `TestPowerInputDigestIsStable`, `TestPowerEvidenceIsTypedAndBounded`, `TestPowerRegistration` | -| Customer power: power under an allocation, waiting behind an installation, a newer request replacing a pending one, a hold reporting `Unknown` through release and settling with fresh discovery, a retry repeating only the held action, a request waiting through a discovery lapse | `TestCustomerPower` | +| Customer power: an unset `powerState` leaving power unmanaged after an install until the Machine asks for `Off`, power under an allocation, waiting behind an installation, a newer request replacing a pending one, a hold reporting `Unknown` through release and settling with fresh discovery, a retry repeating only the held action, a request waiting through a discovery lapse | `TestCustomerPower` | | Power worker: one reset per action and its proof, sending nothing when already in the requested state, each refusal with nothing sent, a lost response, a request never applied, an unprovable restart, a swap after the command, a resumed worker, two workers for one assignment | `go test ./internal/site/powerwork` | | The BMC's reset time and the lab's power faults | `TestObserveReadsTheLastResetTime`; the lab adapter self-test | diff --git a/docs/enhancements/machine-lifecycle/README.md b/docs/enhancements/machine-lifecycle/README.md index b3d6dcf1..a47f3ddf 100644 --- a/docs/enhancements/machine-lifecycle/README.md +++ b/docs/enhancements/machine-lifecycle/README.md @@ -536,7 +536,7 @@ spec: # Omission requests none. Delete is the default and requires verified release. addresses: [] reclaimPolicy: Delete - # Off is the default so creating a Machine does not request runtime power-on. + # Unset leaves power unmanaged, so creating a Machine requests no power change. # On expresses intent; authorization and activation gates still control effects. powerState: "On" @@ -1324,7 +1324,7 @@ release without Milo downtime or machine reprovisioning. #### Does enabling the feature change any default behavior? -No. MachineCapacity resources default to `Disabled` and Machines to power `Off`. +No. MachineCapacity resources default to `Disabled`, and a Machine without `powerState` leaves its power unmanaged. Creating or importing records cannot trigger provisioning. #### Can operators disable the feature after enabling it? diff --git a/docs/enhancements/machine-lifecycle/api-examples.md b/docs/enhancements/machine-lifecycle/api-examples.md index d9b9ce5c..7882b278 100644 --- a/docs/enhancements/machine-lifecycle/api-examples.md +++ b/docs/enhancements/machine-lifecycle/api-examples.md @@ -286,7 +286,7 @@ spec: # Omission requests none. Delete is the default and requires verified release. addresses: [] reclaimPolicy: Delete - # Off is the default so creating a Machine does not request runtime power-on. + # Unset leaves power unmanaged, so creating a Machine requests no power change. # On expresses intent; authorization and activation gates still control effects. powerState: "On" diff --git a/docs/enhancements/metal-cli/README.md b/docs/enhancements/metal-cli/README.md index cbe20df6..63974acd 100644 --- a/docs/enhancements/metal-cli/README.md +++ b/docs/enhancements/metal-cli/README.md @@ -158,7 +158,7 @@ datumctl metal machines wait worker-01 \ ``` Require exactly one of `--allocate-only` or `--image` so the handoff is deliberate. -Allocation-only defaults to power off and no network attachments. Its ready +Allocation-only sets power Off and no network attachments. Its ready message explicitly says: “Allocation handoff complete; no OS installation was requested; desired power is Off.” It does not claim a bootable machine, guest connectivity, or application health. diff --git a/docs/troubleshooting/README.md b/docs/troubleshooting/README.md index 51db5c1a..0eac3c52 100644 --- a/docs/troubleshooting/README.md +++ b/docs/troubleshooting/README.md @@ -17,7 +17,7 @@ integration as a bug. | Standalone smoke script refuses a cluster | Check for existing Fleet APIs, fixture namespaces, controllers, and context/cluster mismatch; use the required fresh dedicated cluster | [Smoke prerequisites](../operations/standalone-smoke.md#run-with-kind-and-colima) | | One standalone claim remains pending | The fixture intentionally offers one machine to two consumers; the second binds only after the first releases and cleanup is verified | [Smoke scenario and expected output](../operations/standalone-smoke.md) | | Smoke output has blank network and address columns | The fixture requests no network interface and does not exercise NSO/IPAM or routing | [Smoke scope](../operations/standalone-smoke.md) | -| Synthetic staging does not publish or allocate as expected | Check the exact publication contract, distinct projects, allowed profile, and powered-off, networkless claim restriction | [Staging configuration and limits](../../config/README.md) | +| Synthetic staging does not publish or allocate as expected | Check the exact publication contract, distinct projects, allowed profile, and networkless claim restriction with power unset or `Off` | [Staging configuration and limits](../../config/README.md) | | Milo live acceptance returns nonzero or reports `Blocked` | The current harness does not run the live scenario; valid preflight cannot establish `Passed`. Invalid configuration yields `NotRun` evidence when possible | [Acceptance commands](../../test/acceptance/milo/README.md#commands) | | Acceptance evidence cannot be written or verified | Check the absent-or-empty destination, file permissions, symlink restrictions, and exact three-file evidence contract | [Acceptance evidence](../../test/acceptance/milo/README.md#evidence) | diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index 4d33a439..2f69ee4c 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -198,7 +198,7 @@ case "$step" in customer="$state/consumer-a/customer-project.json" k "$customer" -n default delete machine allocation --wait --timeout=60s >/dev/null k "$customer" -n default create -f - >/dev/null <<'JSON' -{"apiVersion":"metal.datumapis.com/v1alpha1","kind":"Machine","metadata":{"name":"allocation","namespace":"default"},"spec":{"machineClassRef":{"name":"local-class"},"machineProfileRef":{"name":"local-profile"},"locationRef":{"name":"local"},"powerState":"Off"}} +{"apiVersion":"metal.datumapis.com/v1alpha1","kind":"Machine","metadata":{"name":"allocation","namespace":"default"},"spec":{"machineClassRef":{"name":"local-class"},"machineProfileRef":{"name":"local-profile"},"locationRef":{"name":"local"}}} JSON "$host" probe-unallocatable --config "$state/acceptance.json" --once trap - ERR @@ -503,7 +503,7 @@ PY customer="$state/consumer-a/customer-project.json" k "$customer" -n default delete machine allocation --wait --timeout=60s >/dev/null k "$customer" -n default create -f - >/dev/null <<'JSON' -{"apiVersion":"metal.datumapis.com/v1alpha1","kind":"Machine","metadata":{"name":"allocation","namespace":"default"},"spec":{"machineClassRef":{"name":"local-class"},"machineProfileRef":{"name":"local-profile"},"locationRef":{"name":"remote-elsewhere"},"powerState":"Off"}} +{"apiVersion":"metal.datumapis.com/v1alpha1","kind":"Machine","metadata":{"name":"allocation","namespace":"default"},"spec":{"machineClassRef":{"name":"local-class"},"machineProfileRef":{"name":"local-profile"},"locationRef":{"name":"remote-elsewhere"}}} JSON set +e "$host" allocate --config "$state/acceptance.json" > "$state/wrong-location.out" 2> "$state/wrong-location.err" diff --git a/internal/allocation/power.go b/internal/allocation/power.go index daf27c55..ffc91e8e 100644 --- a/internal/allocation/power.go +++ b/internal/allocation/power.go @@ -34,9 +34,12 @@ func PowerAction(state string) (ops.PowerAction, error) { // a refused one is not created again until the generation changes. It is // due only when powerState differs from the Machine's observed power, which // the power projector alone writes, or when a request for another action has -// not run yet. Power not yet observed, or Unknown, differs from nothing: -// every Machine defaults to Off, and a server is not forced off before its -// power is known. A generation runs at most one power operation, so power +// not run yet. An unset powerState leaves the Machine's power unmanaged, so +// nothing is created whatever the server's state. A request created before +// powerState was cleared still runs: clearing it creates nothing to replace +// that request. Power not yet observed, or +// Unknown, differs from nothing, so a server is not forced to a state before +// its power is known. A generation runs at most one power operation, so power // that drifts after it succeeded, as after a crash, is not corrected until the // generation changes. // diff --git a/internal/manager/customer_power_envtest_test.go b/internal/manager/customer_power_envtest_test.go index 13d81458..937d22fe 100644 --- a/internal/manager/customer_power_envtest_test.go +++ b/internal/manager/customer_power_envtest_test.go @@ -271,11 +271,18 @@ type powered struct { // allocatePowered creates a Machine that asks for power Off, allocates it a // Device, and projects its observed power. func (e *env) allocatePowered(n int) *powered { + e.t.Helper() + return e.allocateWithPower(n, "Off") +} + +// allocateWithPower is allocatePowered with the Machine's powerState, which +// may be unset. +func (e *env) allocateWithPower(n int, state string) *powered { e.t.Helper() e.server(n) object := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("machine-%d", n), Namespace: "default"}, Spec: fleetv1.MachineSpec{ MachineClassRef: fleetv1.LocalReference{Name: e.class.Name}, MachineProfileRef: fleetv1.LocalReference{Name: e.profile.Name}, - LocationRef: fleetv1.LocalReference{Name: "location-example"}, PowerState: "Off", + LocationRef: fleetv1.LocalReference{Name: "location-example"}, PowerState: state, }} e.create(object) owner := machine(n) @@ -415,9 +422,8 @@ func TestCustomerPower(t *testing.T) { t.Fatalf("an operation was created with nothing to change: %s", operation.Name) } p.want("On") - // Before the projector reports power, nothing is due: every Machine - // defaults to Off, and a server is not forced to a state before its - // power is known. + // Before the projector reports power, nothing is due: a server is not + // forced to a state before its power is known. unobserved := p.machine.DeepCopyObject().(*fleetv1.Machine) if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(p.machine), unobserved); err != nil { t.Fatal(err) @@ -465,6 +471,52 @@ func TestCustomerPower(t *testing.T) { } }) + t.Run("a Machine with no powerState leaves its power unmanaged until it asks", func(t *testing.T) { + p := e.allocateWithPower(19, "") + // The API server applies no default: unset stays unset. + if p.machine.Spec.PowerState != "" { + t.Fatalf("powerState = %q", p.machine.Spec.PowerState) + } + install, err := e.allocator.Install(e.ctx, p.allocation, allocation.Installation{Installation: e.installation(19, "debian-12", "")}) + if err != nil { + t.Fatal(err) + } + if phase := e.ended(install); phase != ops.PhaseSucceeded { + t.Fatalf("installation ended %s", phase) + } + // The installed server boots, so it is on, and discovery reads it. + p.setServer(func(s *simwork.Server) { s.Power = "On" }) + time.Sleep(1100 * time.Millisecond) + e.discover(p.device) + if observed := p.project(); observed != "On" { + t.Fatalf("observed power = %q", observed) + } + if operation := p.power(); operation != nil { + t.Fatalf("an unmanaged Machine created %s", operation.Name) + } + var operations ops.DevicePowerOperationList + if err := e.admin.List(e.ctx, &operations, client.InNamespace(namespace)); err != nil { + t.Fatal(err) + } + for _, operation := range operations.Items { + if reference := operation.Spec.Authority.AllocationRef; reference != nil && reference.Name == p.allocation.Name { + t.Fatalf("power operation %s exists for an unmanaged Machine", operation.Name) + } + } + // Once it asks for Off, the server that is on is forced off. + p.want("Off") + operation := p.power() + if operation == nil || operation.Spec.Action != ops.PowerForceOff { + t.Fatalf("operation = %+v", operation) + } + if phase := e.ended(operation); phase != ops.PhaseSucceeded { + t.Fatalf("power ended %s: %s", phase, operation.Status.Message) + } + if simwork.State(p.server()) != ops.PowerStateOff { + t.Fatalf("server = %+v", p.server()) + } + }) + t.Run("only the Machine that owns the allocation can request its power", func(t *testing.T) { p := e.allocatePowered(17) p.want("On") diff --git a/internal/manager/multicluster_harness_test.go b/internal/manager/multicluster_harness_test.go index 2299fc16..b139c109 100644 --- a/internal/manager/multicluster_harness_test.go +++ b/internal/manager/multicluster_harness_test.go @@ -200,7 +200,7 @@ func (r *recordingHandlers) all(name multicluster.ClusterName) []ProjectRequest func mcMachine(name, uid, profile string) *fleetv1.Machine { return &fleetv1.Machine{ ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name, UID: types.UID(uid), Generation: 1}, - Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: "standard"}, MachineProfileRef: fleetv1.LocalReference{Name: profile}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}, + Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: "standard"}, MachineProfileRef: fleetv1.LocalReference{Name: profile}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}}, } } diff --git a/internal/manager/requested_hardware_test.go b/internal/manager/requested_hardware_test.go index e5840033..97c4ae91 100644 --- a/internal/manager/requested_hardware_test.go +++ b/internal/manager/requested_hardware_test.go @@ -32,7 +32,7 @@ func newRequestedFixture(t *testing.T, funcs interceptor.Funcs, objects ...clien } machine := &fleetv1.Machine{ ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "example", UID: "machine-uid", Generation: 1}, - Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: "standard"}, MachineProfileRef: fleetv1.LocalReference{Name: "general-8c-32g"}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}, + Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: "standard"}, MachineProfileRef: fleetv1.LocalReference{Name: "general-8c-32g"}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}}, } writes := 0 statusUpdate := funcs.SubResourceUpdate diff --git a/internal/multiplane/location_adversarial_test.go b/internal/multiplane/location_adversarial_test.go index c1af29c0..ce40b02e 100644 --- a/internal/multiplane/location_adversarial_test.go +++ b/internal/multiplane/location_adversarial_test.go @@ -38,7 +38,7 @@ func TestAdversarialRejectNonlocalMachineBeforeAllocation(t *testing.T) { profile.Spec.CPU.Cores = 2 profile.Spec.Memory.Capacity = "2Gi" class := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "source-class"}, Spec: fleet.MachineClassSpec{Capacity: &fleet.CapacityPolicy{MachineCapacities: fleet.MachineSelector{Namespace: DeviceNamespace}}}, Status: fleet.MachineClassStatus{EvaluatedRevision: "v1"}} - machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "machine"}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: "local-class"}, MachineProfileRef: fleet.LocalReference{Name: "local-profile"}, LocationRef: fleet.LocalReference{Name: "not-the-local-location"}, PowerState: "Off"}} + machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "machine"}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: "local-class"}, MachineProfileRef: fleet.LocalReference{Name: "local-profile"}, LocationRef: fleet.LocalReference{Name: "not-the-local-location"}}} localClass := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "consumer-class"}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{PublisherRef: tenancy.Project("provider"), Name: "local-class"}}} localProfile := profile.DeepCopyObject().(*fleet.MachineProfile) localProfile.UID = "consumer-profile" diff --git a/internal/multiplane/seed.go b/internal/multiplane/seed.go index b2bfafed..142a314a 100644 --- a/internal/multiplane/seed.go +++ b/internal/multiplane/seed.go @@ -90,7 +90,7 @@ func Seed(ctx context.Context, c Config) error { w.Stop() return err } - machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: class.Name}, MachineProfileRef: fleet.LocalReference{Name: profile.Name}, LocationRef: fleet.LocalReference{Name: Location}, PowerState: "Off"}} + machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: class.Name}, MachineProfileRef: fleet.LocalReference{Name: profile.Name}, LocationRef: fleet.LocalReference{Name: Location}}} if err := ensure(ctx, user, machine); err != nil { w.Stop() return err diff --git a/internal/staging/handler.go b/internal/staging/handler.go index 83cdfe36..61d0e125 100644 --- a/internal/staging/handler.go +++ b/internal/staging/handler.go @@ -28,8 +28,8 @@ import ( // Handler is an event-driven synthetic provider and claim coordinator. It uses // the real durable allocator but substitutes an explicit synthetic admission -// decision and provider observation. It accepts only powered-off, networkless -// claims in one configured location. +// decision and provider observation. It accepts only networkless claims in +// one configured location whose power is unset, so unmanaged, or Off. type Handler struct { Public client.Client Provider client.Client @@ -64,8 +64,8 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ if claim.DeletionTimestamp != nil { return h.release(ctx, claim.Namespace, claim.UID, &claim) } - if claim.Spec.LocationRef.Name != h.Location || claim.Spec.PowerState != "Off" || len(claim.Spec.NetworkInterfaces) != 0 || claim.Spec.InitialInstallationRef != nil { - return h.rejected(ctx, &claim, "UnsupportedSyntheticRequest", "Synthetic staging accepts powered-off, networkless claims without an initial installation.") + if claim.Spec.LocationRef.Name != h.Location || !poweredOff(claim.Spec.PowerState) || len(claim.Spec.NetworkInterfaces) != 0 || claim.Spec.InitialInstallationRef != nil { + return h.rejected(ctx, &claim, "UnsupportedSyntheticRequest", "Synthetic staging accepts networkless claims without an initial installation whose power is unmanaged or Off.") } var namespace corev1.Namespace @@ -380,3 +380,7 @@ func ConsumerHandlers(base manager.HandlerFactory, consumer controller.ProjectId return handlers, nil } } + +// poweredOff reports whether a claim's power intent fits a synthetic server, +// which is always off: unset, so Fleet does not manage its power, or Off. +func poweredOff(state string) bool { return state == "" || state == "Off" } diff --git a/internal/staging/handler_test.go b/internal/staging/handler_test.go index 1635fcda..00fb863e 100644 --- a/internal/staging/handler_test.go +++ b/internal/staging/handler_test.go @@ -182,6 +182,40 @@ func TestHandlerStatusWritesPreserveStatusPower(t *testing.T) { } } +// TestHandlerAcceptsUnmanagedOrOffPower requires the synthetic provider to +// hand off a claim that leaves power unset, so Fleet does not manage it, or +// asks for Off, and to refuse one that asks for On. +func TestHandlerAcceptsUnmanagedOrOffPower(t *testing.T) { + s := startStack(t) + s.server(1) + s.server(2) + handler := s.handler() + for _, tt := range []struct { + name, state, phase, condition, reason string + status metav1.ConditionStatus + }{ + {"power-unset", "", "Ready", "Ready", "PoweredOffHandoff", metav1.ConditionTrue}, + {"power-off", "Off", "Ready", "Ready", "PoweredOffHandoff", metav1.ConditionTrue}, + {"power-on", "On", "Pending", "Accepted", "UnsupportedSyntheticRequest", metav1.ConditionFalse}, + } { + claim := s.claim(tt.name) + if tt.state != "" { + current := s.get(claim) + current.Spec.PowerState = tt.state + if err := s.admin.Update(s.ctx, current); err != nil { + t.Fatal(err) + } + } + if got := s.get(claim).Spec.PowerState; got != tt.state { + t.Fatalf("%s: powerState = %q, want %q", tt.name, got, tt.state) + } + drive(t, s.ctx, handler, consumerProject, claim, 2) + got := s.get(claim) + assertPhase(t, got, tt.phase) + assertCondition(t, got, tt.condition, tt.status, tt.reason) + } +} + func TestPublishedConsumerClaimAllocatesProviderMachine(t *testing.T) { s := startStack(t) device := s.server(1) @@ -201,7 +235,7 @@ func TestPublishedConsumerClaimAllocatesProviderMachine(t *testing.T) { localClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: sourceClass.Name, UID: "local-class-uid", Generation: 1, Annotations: provenance(sourceClass)}, Spec: fleetv1.MachineClassSpec{Source: &fleetv1.SourceReference{PublisherRef: tenancy.Project(provider.RouteName), Name: sourceClass.Name}}, Status: fleetv1.MachineClassStatus{EvaluatedRevision: revision, ResolvedClass: &fleetv1.ResolvedClass{ProfilePolicy: *sourceClass.Spec.ProfilePolicy}, Conditions: []metav1.Condition{publicationCondition("SourceResolved", metav1.ConditionTrue, 1, "AuthorizedSource", "resolved")}}} localProfile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: sourceProfile.Name, UID: "local-profile-uid", Generation: 1, Annotations: provenance(sourceProfile)}, Spec: sourceProfile.Spec} localProfile.Status.Conditions = []metav1.Condition{publicationCondition("Published", metav1.ConditionTrue, 1, "SourceCopied", "copied")} - claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "cross-project", UID: types.UID(uid(901))}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: localClass.Name}, MachineProfileRef: fleetv1.LocalReference{Name: localProfile.Name}, LocationRef: fleetv1.LocalReference{Name: locationName}, PowerState: "Off"}} + claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "cross-project", UID: types.UID(uid(901))}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: localClass.Name}, MachineProfileRef: fleetv1.LocalReference{Name: localProfile.Name}, LocationRef: fleetv1.LocalReference{Name: locationName}}} consumerKube := fake.NewClientBuilder().WithScheme(stackScheme(t)).WithStatusSubresource(&fleetv1.Machine{}).WithObjects(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-uid"}}, localClass, localProfile, claim).Build() handler := Handler{Public: consumerKube, Provider: s.admin, Allocator: s.allocator, Project: consumer, ProviderProject: provider, Location: locationName, Now: time.Now} @@ -313,7 +347,7 @@ func TestAClassFromAnotherPublisherIsRejected(t *testing.T) { localClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: sourceClass.Name, UID: "local-class-uid", Generation: 1, Annotations: provenance(sourceClass)}, Spec: fleetv1.MachineClassSpec{Source: &fleetv1.SourceReference{PublisherRef: publisher, Name: sourceClass.Name}}, Status: fleetv1.MachineClassStatus{EvaluatedRevision: revision, ResolvedClass: &fleetv1.ResolvedClass{ProfilePolicy: *sourceClass.Spec.ProfilePolicy}, Conditions: []metav1.Condition{publicationCondition("SourceResolved", metav1.ConditionTrue, 1, "AuthorizedSource", "resolved")}}} localProfile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: sourceProfile.Name, UID: "local-profile-uid", Generation: 1, Annotations: provenance(sourceProfile)}, Spec: sourceProfile.Spec} localProfile.Status.Conditions = []metav1.Condition{publicationCondition("Published", metav1.ConditionTrue, 1, "SourceCopied", "copied")} - claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "cross-project", UID: types.UID(uid(910 + i))}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: localClass.Name}, MachineProfileRef: fleetv1.LocalReference{Name: localProfile.Name}, LocationRef: fleetv1.LocalReference{Name: locationName}, PowerState: "Off"}} + claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "cross-project", UID: types.UID(uid(910 + i))}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: localClass.Name}, MachineProfileRef: fleetv1.LocalReference{Name: localProfile.Name}, LocationRef: fleetv1.LocalReference{Name: locationName}}} consumerKube := fake.NewClientBuilder().WithScheme(stackScheme(t)).WithStatusSubresource(&fleetv1.Machine{}).WithObjects(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-uid"}}, localClass, localProfile, claim).Build() handler := Handler{Public: consumerKube, Provider: s.admin, Allocator: s.allocator, Project: consumer, ProviderProject: provider, Location: locationName, Now: time.Now} handler.ReconcileEvent(s.ctx, projectRequest(consumer, claim)) diff --git a/internal/staging/harness_test.go b/internal/staging/harness_test.go index 106be793..20ae74ef 100644 --- a/internal/staging/harness_test.go +++ b/internal/staging/harness_test.go @@ -251,7 +251,7 @@ func (s *stack) handler() Handler { // claim creates a powered-off Machine in the default namespace. func (s *stack) claim(name string) *fleetv1.Machine { s.t.Helper() - claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: className}, MachineProfileRef: fleetv1.LocalReference{Name: profileName}, LocationRef: fleetv1.LocalReference{Name: locationName}, PowerState: "Off"}} + claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: className}, MachineProfileRef: fleetv1.LocalReference{Name: profileName}, LocationRef: fleetv1.LocalReference{Name: locationName}}} s.create(claim) return claim } diff --git a/internal/staging/multicluster_test.go b/internal/staging/multicluster_test.go index 2251c667..f96b08a8 100644 --- a/internal/staging/multicluster_test.go +++ b/internal/staging/multicluster_test.go @@ -84,7 +84,7 @@ func TestStagingAllocatesOnlyForThePublicationConsumer(t *testing.T) { sourceClass := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: className, UID: "source-class-uid", Generation: 1}, Spec: fleetv1.MachineClassSpec{ProfilePolicy: &fleetv1.ProfilePolicy{AllowedProfiles: []fleetv1.LocalReference{{Name: profileName}}}, Access: &fleetv1.AccessPolicy{}, Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: providerNamespace, Selector: metav1.LabelSelector{MatchLabels: map[string]string{"pool": "example"}}}}}} capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: providerNamespace, Name: "capacity-" + device.Name, UID: "capacity-uid", Labels: map[string]string{"pool": "example"}}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: device.Name}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "example-cleaning"}, ReclaimPolicy: "Retain"}} claim := func() *fleetv1.Machine { - return &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "m", UID: types.UID(uid(901)), Generation: 1}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: className}, MachineProfileRef: fleetv1.LocalReference{Name: profileName}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}} + return &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "m", UID: types.UID(uid(901)), Generation: 1}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: className}, MachineProfileRef: fleetv1.LocalReference{Name: profileName}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}}} } // The provider project is also an Active metal consumer with its own // Machine of the same name; it must engage with requested hardware only. diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index 3ec3d0ad..894ea5bc 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -51,6 +51,14 @@ type Options struct { Wait time.Duration } +// matchesFixture reports whether a claim asks for the configured synthetic +// fixture. Its server is off, so power may be unset, leaving it unmanaged, +// or Off, but not On. +func (o Options) matchesFixture(spec fleetv1.MachineSpec) bool { + return spec.LocationRef.Name == o.LocationName && spec.MachineClassRef.Name == o.ClassName && spec.MachineProfileRef.Name == o.ProfileName && + len(spec.NetworkInterfaces) == 0 && (spec.PowerState == "" || spec.PowerState == "Off") +} + func DefaultOptions() Options { return Options{ ProviderNamespace: "fleet-provider", @@ -334,8 +342,7 @@ func (r Runner) prepareClaim(ctx context.Context, namespaceName string) (claim, if err != nil { return claim{}, err } - spec := current.claim.Spec - if spec.LocationRef.Name != r.Options.LocationName || spec.MachineClassRef.Name != r.Options.ClassName || spec.MachineProfileRef.Name != r.Options.ProfileName || len(spec.NetworkInterfaces) != 0 || spec.PowerState != "Off" { + if !r.Options.matchesFixture(current.claim.Spec) { return claim{}, errors.New("the claim does not match the configured synthetic fixture") } if !contains(current.claim.Finalizers, allocation.MachineFinalizer) { diff --git a/internal/standalone/runner_test.go b/internal/standalone/runner_test.go new file mode 100644 index 00000000..87e077e6 --- /dev/null +++ b/internal/standalone/runner_test.go @@ -0,0 +1,39 @@ +package standalone + +import ( + "testing" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" +) + +// TestTheFixtureLeavesPowerUnmanagedOrOff requires the standalone runner to +// accept the synthetic fixture's claim with power unset or Off, and to refuse +// one that asks for On or differs from the fixture. +func TestTheFixtureLeavesPowerUnmanagedOrOff(t *testing.T) { + options := DefaultOptions() + fixture := func(mutate func(*fleetv1.MachineSpec)) fleetv1.MachineSpec { + spec := fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: options.ClassName}, MachineProfileRef: fleetv1.LocalReference{Name: options.ProfileName}, + LocationRef: fleetv1.LocalReference{Name: options.LocationName}} + if mutate != nil { + mutate(&spec) + } + return spec + } + for _, tc := range []struct { + name string + spec fleetv1.MachineSpec + want bool + }{ + {"power unset", fixture(nil), true}, + {"power Off", fixture(func(s *fleetv1.MachineSpec) { s.PowerState = "Off" }), true}, + {"power On", fixture(func(s *fleetv1.MachineSpec) { s.PowerState = "On" }), false}, + {"another location", fixture(func(s *fleetv1.MachineSpec) { s.LocationRef.Name = "elsewhere" }), false}, + {"a network interface", fixture(func(s *fleetv1.MachineSpec) { + s.NetworkInterfaces = []fleetv1.NetworkInterfaceRequest{{Name: "eth0"}} + }), false}, + } { + if got := options.matchesFixture(tc.spec); got != tc.want { + t.Errorf("%s: matchesFixture = %v, want %v", tc.name, got, tc.want) + } + } +} diff --git a/ui/consumer/src/components/machine-status.tsx b/ui/consumer/src/components/machine-status.tsx index 595ad11f..d89df83e 100644 --- a/ui/consumer/src/components/machine-status.tsx +++ b/ui/consumer/src/components/machine-status.tsx @@ -44,13 +44,13 @@ export function MachineStatus({ machine }: { machine: StatusInput }) { /** * Observed power, then the requested state in amber when it differs. Intent - * alone never says the machine is on. + * alone never says the machine is on, and an unmanaged machine has none. */ export function Power({ machine, lower }: { machine: PowerInput; lower?: boolean }) { const { powerObserved, powerIntent } = machine; if (!powerObserved) return <>—; const say = (s: string) => (lower ? s.toLowerCase() : s); - const differs = powerIntent !== powerObserved; + const differs = powerIntent !== undefined && powerIntent !== powerObserved; return ( { + it('leaves power unmanaged, so Fleet never forces a freshly installed server off', () => { + const raw = toRawMachine({ name: 'web-2', machineClass: 'standard-metal', machineProfile: 'general-purpose-24c-128g' }); + expect(raw.spec).not.toHaveProperty('powerState'); + }); +}); diff --git a/ui/consumer/src/lib/api.ts b/ui/consumer/src/lib/api.ts index 5576c129..e6090ac2 100644 --- a/ui/consumer/src/lib/api.ts +++ b/ui/consumer/src/lib/api.ts @@ -153,8 +153,9 @@ export interface CreateMachineInput { machineProfile: string; } -// Deploying allocates a machine and hands it over powered off; installing an -// OS is a separate Installation, which this plugin does not offer yet. +// Deploying allocates a machine and leaves its power unmanaged, so Fleet never +// forces a freshly installed server off; installing an OS is a separate +// Installation, which this plugin does not offer yet. export function toRawMachine(input: CreateMachineInput): RawMachine { return { metadata: { name: input.name, namespace: MACHINE_NAMESPACE }, @@ -162,7 +163,6 @@ export function toRawMachine(input: CreateMachineInput): RawMachine { machineClassRef: { name: input.machineClass }, machineProfileRef: { name: input.machineProfile }, locationRef: { name: DEFAULT_LOCATION }, - powerState: 'Off', }, }; } diff --git a/ui/consumer/src/lib/fixtures.ts b/ui/consumer/src/lib/fixtures.ts index f7db1730..a1c462c9 100644 --- a/ui/consumer/src/lib/fixtures.ts +++ b/ui/consumer/src/lib/fixtures.ts @@ -15,7 +15,6 @@ const SPEC = { machineClassRef: { name: 'standard-metal' }, machineProfileRef: { name: 'general-purpose-24c-128g' }, locationRef: { name: 'us-central-1' }, - powerState: 'Off', } as const; const PLACEMENT = { locationRef: { name: 'us-central-1' } }; diff --git a/ui/consumer/src/types.test.ts b/ui/consumer/src/types.test.ts index 3853463b..e02ea46e 100644 --- a/ui/consumer/src/types.test.ts +++ b/ui/consumer/src/types.test.ts @@ -65,11 +65,11 @@ describe('toMachine', () => { expect(toMachine(FIXTURE_MACHINES[0]).addresses).toEqual([]); }); - it('defaults power intent to Off and leaves an unresolved request absent', () => { - const { powerState: _, ...spec } = FIXTURE_MACHINES[1].spec; + it('leaves power intent and an unresolved request absent', () => { + const spec = FIXTURE_MACHINES[1].spec; const { requestedHardware: __, ...status } = FIXTURE_MACHINES[1].status ?? {}; const machine = toMachine({ ...FIXTURE_MACHINES[1], spec, status }); - expect(machine.powerIntent).toBe('Off'); + expect(machine.powerIntent).toBeUndefined(); expect(machine.powerObserved).toBeUndefined(); expect(machine.cpu).toBeUndefined(); expect(machine.memory).toBeUndefined(); diff --git a/ui/consumer/src/types.ts b/ui/consumer/src/types.ts index 52aa24b9..ab6fc73f 100644 --- a/ui/consumer/src/types.ts +++ b/ui/consumer/src/types.ts @@ -23,7 +23,8 @@ export interface Machine { machineProfile: string; location: string; /** Requested power state (spec). */ - powerIntent: 'On' | 'Off'; + // powerIntent is absent when the Machine leaves its power unmanaged. + powerIntent?: 'On' | 'Off'; /** Observed power state (status); absent until reported. */ powerObserved?: 'On' | 'Off' | 'Unknown'; /** Requested CPU pinned in status.requestedHardware; absent until resolved. */ @@ -137,7 +138,7 @@ export function toMachine(raw: RawMachine): Machine { machineClass: raw.spec.machineClassRef.name, machineProfile: raw.spec.machineProfileRef.name, location: raw.spec.locationRef.name, - powerIntent: raw.spec.powerState ?? 'Off', + powerIntent: raw.spec.powerState, powerObserved: raw.status?.power?.state, cpu: requested ? `${requested.cpu.cores} cores · ${requested.cpu.architecture}` : undefined, memory: requested?.memory.capacity,