diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index 3c4c1f6c..854296fa 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -17,6 +17,7 @@ import ( "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" "go.datum.net/fleet/internal/site/fixture" + "go.datum.net/fleet/internal/site/powerwork" "go.datum.net/fleet/internal/site/redfishwork" "go.datum.net/fleet/internal/site/vmwork" ) @@ -212,11 +213,19 @@ func siteRunner(_ context.Context, config *rest.Config, cell string, store *site return nil, err } _, burnIn, _ := strings.Cut(image, "@") - runner.Kinds = map[string]site.Kind{"DeviceInstallation": redfishwork.Installation{Config: work}, "DeviceWipe": redfishwork.Wipe{Config: work}, - "DeviceCommissioning": redfishwork.Commissioning{Config: work, BurnInDigest: burnIn}} + runner.Kinds = redfishKinds(work, burnIn) return runner, nil } +// redfishKinds are the workers a Redfish site runs. Power runs only over +// Redfish: the local VM site has no BMC, so it refuses a power operation as +// an unsupported kind with nothing sent. +func redfishKinds(work redfishwork.Config, burnIn string) map[string]site.Kind { + return map[string]site.Kind{"DeviceInstallation": redfishwork.Installation{Config: work}, "DeviceWipe": redfishwork.Wipe{Config: work}, + "DeviceCommissioning": redfishwork.Commissioning{Config: work, BurnInDigest: burnIn}, + "DevicePowerOperation": powerwork.Power{}} +} + // boot serves network boots, the DHCP reservation feed, or probes that // every closed admission is denied. func boot(command, origin, extraMAC, syncToken string) error { diff --git a/cmd/fleet-multiplane/site_test.go b/cmd/fleet-multiplane/site_test.go index 59daaf6a..4a6e6c32 100644 --- a/cmd/fleet-multiplane/site_test.go +++ b/cmd/fleet-multiplane/site_test.go @@ -3,7 +3,11 @@ package main import ( "os" "path/filepath" + "strings" "testing" + + "go.datum.net/fleet/internal/site/powerwork" + "go.datum.net/fleet/internal/site/redfishwork" ) // TestAWorkerRunsOnlyAgainstARuntimeWithItsAccelerator refuses a runtime @@ -23,3 +27,19 @@ func TestAWorkerRunsOnlyAgainstARuntimeWithItsAccelerator(t *testing.T) { t.Fatalf("a TCG worker refused a TCG runtime: %v", err) } } + +// TestARedfishSiteRunsPowerOperations requires the Redfish site's worker kinds, +// which siteRunner installs, to include power beside the install, wipe and +// commissioning workers. siteRunner itself reads the site image's artifacts, +// so the multi-plane Redfish run covers that it uses them. +func TestARedfishSiteRunsPowerOperations(t *testing.T) { + kinds := redfishKinds(redfishwork.Config{}, "sha256:"+strings.Repeat("0", 64)) + if _, ok := kinds["DevicePowerOperation"].(powerwork.Power); !ok { + t.Fatalf("kinds = %v", kinds) + } + for _, kind := range []string{"DeviceInstallation", "DeviceWipe", "DeviceCommissioning"} { + if kinds[kind] == nil { + t.Fatalf("%s is not registered", kind) + } + } +} diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 3e8f7b08..6b9bbb14 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -1211,12 +1211,15 @@ against a real API server. This section records how Fleet implements the power kind of the [device power operations proposal](https://github.com/datum-cloud/fleet/pull/173) (#173, -pinned at `d6744ab`) on this foundation. Step P1 is **implemented**: the -coordinator admits, holds and settles power operations in every mode the -cutover wires, but no site worker runs them and nothing creates them. It -follows [Adding an operation kind](#adding-an-operation-kind), and adds no -change to the coordinator. The kind joins the creator webhook's governed -kinds, standalone's creator policy and each coordinator's access, and +pinned at `d6744ab`) on this foundation. Step P1, the control plane, is +**implemented**: the coordinator admits, holds and settles power operations in +every mode the cutover wires. Step P2, the site worker, is **implemented** +behind the site worker contract. Nothing creates power operations yet. It +follows [Adding an operation kind](#adding-an-operation-kind), and adds the +two [foundation seams](#foundation-seams-power-added) below. The worker +changes no coordinator behavior and no site framework code, and adds only +reasons to the kind's reason table. The kind joins the creator webhook's +governed kinds, standalone's creator policy and each coordinator's access, and `TestEveryOperationKindIsGoverned` requires every operation kind to be governed. @@ -1234,9 +1237,22 @@ governed. | Roles | The **device power operator** inherits the viewer and creates only `DevicePowerOperation`. It does not read MachineAllocations. The **device power requester** is the Fleet provider for Metal's role. The viewer and coordinator cover the new kind. | | Discovery | Power reads the `ComputerSystem.Reset` types the Device's observed System offers, which BMC discovery records with GETs only. | -The worker reasons `Stale`, `NotPoweredOn` and `PowerStateNotSettled` before -a command, the start-by window and the journal payload arrive with the worker -in B. +### The power worker + +| Piece | Decision | +| --- | --- | +| Before the command | The framework checks the credential, the pin and the System's identity. The worker then checks the expected system UUID against that System (`SystemUUIDMismatch`) and that the BMC still offers the action (`ResetTypeNotOffered`). It reads the power state once: a transition state refuses with `PowerStateNotSettled`, and a restart or power cycle of a server that is off refuses with `NotPoweredOn`. Each refusal sends nothing and ends `Failed`. | +| Start-by window | Two minutes after admission. A later start with nothing sent ends `Failed` with the shared reason `Stale`. | +| Already in the requested state | `On` of a server that is on and `ForceOff` of one that is off send nothing and succeed, with no `requestSentAt`. | +| The one reset | One journaled step. Its payload records when the command was sent, the power state read before it, and the BMC's `LastResetTime` as the baseline. A response the BMC returns refusing the command is an error. A lost response is not: the worker watches for the effect. | +| Success | `On` and `ForceOff`: the requested state appears within three minutes of the command. A restart or power cycle: the BMC's `LastResetTime` moves past the baseline, or the worker sees the server off, and then the server is on again. `resetEvidence` records which. When the BMC reported no reset time before the command, only seeing the server off proves a restart. A restart the server made by itself between the baseline read and the command would also move the reset time; the window is one request long, and the BMC's clock is not trusted enough to compare against the send time. | +| Crash or lost response | A resumed worker reads the journaled payload instead of reading the server again, and watches for the effect. It never sends a second reset. | +| Not proven | A reset whose effect does not appear in time, a BMC that refused the command, and a BMC that starts reporting another system after the command all end `OutcomeUnknown`, which places a recovery hold. | +| Registration | A Redfish site registers the worker as `DevicePowerOperation`. The local VM and simulator sites have no BMC and no power worker, so they refuse a power operation as an unsupported kind, with nothing sent. | + +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. ### Foundation seams power added @@ -1254,6 +1270,29 @@ working around their absence: a `Succeeded` restart with no reset proof, or with the empty object `{}`, was accepted. `ProvesSuccess` runs on a `Succeeded` result's evidence only. +### Worker gaps that remain + +Each needs a change in the site framework or the harness, and none is worked +around here. + +- **No end-to-end run creates a power operation yet.** Both multi-plane runs + and the synthetic staging write fixture discovery, which reports every + server off and records no reset types. Admission then leaves the reset-type + check to the worker's live read, but no run's phases create a power + 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. +- **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. + Power raises `SystemUUIDMismatch` only for a swap after the framework's + check. +- **A command the BMC refused ends `OutcomeUnknown`, not `Failed`.** Once a + step is journaled, the framework ends any refusal as `OutcomeUnknown`. + #173 asks for `Failed` when the BMC refused and the power state did not + change. The result is safe, but it places a hold that a recovery must + settle. + ## Tests Run `task test:envtest`. It runs these tests with the race detector against @@ -1279,6 +1318,8 @@ 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` | +| 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 | Increment A has no site, so "nothing was sent" means custody admitted nothing and the fence did not rise. Increment D's phases prove it end to end, with the diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index a52cf661..37a1da70 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -91,13 +91,14 @@ does not fork or patch upstream files. | `ComputerSystem.Reset` with `On`, `ForceOff` and `ForceRestart` applied to one exact persistent libvirt domain per System | Adapter (replaces upstream's in-memory handler for the two lab Systems) | | `PowerState` read from libvirt on every System read | Adapter | | `Boot` source override (`Pxe` or `Hdd`, `Once`), persisted in NVRAM state on the site volume and consumed at power-on | Adapter | +| `LastResetTime`, set for each System when the adapter first starts, persisted on the site volume, and moved forward each time a reset starts the domain | Adapter | | `ResetType` and boot `AllowableValues` narrowed to what the adapter implements; System `UUID` and `SerialNumber` set from the lab target | Adapter | | No `Storage` link on the lab Systems: upstream's sample `Storage` drives are not the target's disk, so commissioning reads the populated `SimpleStorage` device | Adapter | | A read-only `UpdateService` and `FirmwareInventory` from `firmware.json`, synthetic versions upstream does not serve, so a commissioning plan's firmware baseline can be checked | Adapter | | Definition of the lab domains and the provisioning network, re-created with the same identity if the runtime loses them | Adapter | | Append-only request audit: method, path, status, principal class, client User-Agent, ResetType, boot override, effect and fault. It never records bodies or credentials. | Adapter | | `DELETE /redfish/v1/reset` and non-Redfish paths | Refused by the adapter | -| Bounded, one-shot lab faults (`reject-auth`, `hide-reset`, `drop-response`) from a fault file | Adapter, lab only | +| Bounded lab faults from a fault file: one-shot `reject-auth`, `drop-response` (any applied reset, response withheld) and `drop-request` (response withheld, reset never applied); and, until cleared, `hide-reset` (a reset type), `hide-reset-time` and `swap-identity` (the System reports another UUID) | Adapter, lab only | `hack/redfish-lab/test_adapter.py` runs inside the built image, with the real upstream emulator and a fake `virsh`, in the `bmc-self-test` phase. diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index 42497719..91dbae8c 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -15,6 +15,8 @@ * a firmware inventory (UpdateService and FirmwareInventory) from firmware.json, which upstream does not serve, so a commissioning plan's firmware baseline can be checked against the lab; + * LastResetTime, persisted per System and moved forward each time a reset + starts the domain; * an append-only request audit log (no bodies, no credentials), each entry naming the client's User-Agent so a check can tell readers apart; * bounded, one-shot lab fault injection driven by a state file. @@ -161,6 +163,13 @@ def __init__(self, targets, state, boot_ip): for sid in targets: self.nvram.setdefault(sid, {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'}) atomic_write(self.nvram_path, self.nvram) + self.reset_path = os.path.join(state, 'last-reset.json') + self.last_reset = read_json(self.reset_path, {}) + # A real BMC reports a reset time from its first read, so a restart + # always has a baseline to move past. + for sid in targets: + self.last_reset.setdefault(sid, now()) + atomic_write(self.reset_path, self.last_reset) def ensure(self, sid): """Define lost libvirt objects (the runtime Pod's libvirt config is not durable).""" @@ -203,6 +212,9 @@ def power_on(self, sid): require_accelerator() virsh('define', '/dev/stdin', input=domain_xml(t, boot)) virsh('start', t['domain']) + # The System came out of a reset now, as a BMC reports it. + self.last_reset[sid] = now() + atomic_write(self.reset_path, self.last_reset) return boot @@ -238,7 +250,9 @@ def create_app(targets, state, credentials, boot_ip): def publish(sid, power=None): m = cs.members[sid] - m['UUID'] = targets[sid]['uuid'] + current = faults.read() + # Lab fault: the BMC reports another server, as after a board swap. + m['UUID'] = current.get('swapIdentity', {}).get(sid, targets[sid]['uuid']) # The serial the target's synthetic Device records, so commissioning # can match the chassis to the Device. m['SerialNumber'] = targets[sid]['serial'] @@ -254,7 +268,11 @@ def publish(sid, power=None): 'BootSourceOverrideEnabled@Redfish.AllowableValues': list(BOOT_ENABLED)}) if power: m['PowerState'] = power - hidden = set(faults.read().get('hideResetTypes', [])) + if sid in lab.last_reset and sid not in current.get('hideResetTime', []): + m['LastResetTime'] = lab.last_reset[sid] + else: + m.pop('LastResetTime', None) + hidden = set(current.get('hideResetTypes', [])) rai.members[sid]['Parameters'][0]['AllowableValues'] = [v for v in RESET_TYPES if v not in hidden] for sid in targets: @@ -366,6 +384,13 @@ def reset(sid): if kind not in allowed: return error(400, 'unsupported ResetType') domain = targets[sid]['domain'] + withheld = take('dropRequest', lambda f: f.get('system') == sid and f.get('resetType') == kind) + if withheld: + # Lab fault: the request is withheld past the client timeout and + # never applied. + request_context.detail = {'resetType': kind, 'effect': 'none', 'fault': 'drop-request'} + time.sleep(min(int(withheld.get('seconds', 45)), 120)) + return error(503, 'lab BMC dropped the request') try: with LOCK: power = lab.power(sid) @@ -379,7 +404,7 @@ def reset(sid): except LibvirtError as e: return error(503, 'lab hardware unavailable: %s' % e) request_context.detail = {'resetType': kind, 'effect': effect} - drop = take('dropResponse', lambda f: f.get('system') == sid and f.get('resetType') == kind) if effect.startswith('started') else None + drop = take('dropResponse', lambda f: f.get('system') == sid and f.get('resetType') == kind) if effect != 'none' else None if drop: # Lab fault: the effect is applied, the response is withheld past the client timeout. request_context.detail['fault'] = 'drop-response-after-effect' @@ -429,12 +454,20 @@ def fault_cli(args): faults.update(lambda v: v.__setitem__('rejectAuth', int(args[1]))) elif args[:1] == ['hide-reset'] and len(args) == 2: faults.update(lambda v: v.setdefault('hideResetTypes', []).append(args[1])) + elif args[:1] == ['drop-request'] and len(args) in (4, 5): + skip = int(args[4]) if len(args) == 5 else 0 + faults.update(lambda v: v.setdefault('dropRequest', []).append({'system': args[1], 'resetType': args[2], 'seconds': int(args[3]), 'skip': skip})) + elif args[:1] == ['swap-identity'] and len(args) == 3: + faults.update(lambda v: v.setdefault('swapIdentity', {}).__setitem__(args[1], args[2])) + elif args[:1] == ['hide-reset-time'] and len(args) == 2: + faults.update(lambda v: v.setdefault('hideResetTime', []).append(args[1])) elif args == ['clear']: faults.update(lambda v: v.clear()) elif args == ['show']: pass else: - raise SystemExit('usage: fault drop-response SYSTEM RESETTYPE SECONDS [SKIP] | reject-auth COUNT | hide-reset TYPE | clear | show') + raise SystemExit('usage: fault drop-response SYSTEM RESETTYPE SECONDS [SKIP] | drop-request SYSTEM RESETTYPE SECONDS [SKIP]' + ' | swap-identity SYSTEM UUID | hide-reset-time SYSTEM | reject-auth COUNT | hide-reset TYPE | clear | show') print(json.dumps(faults.read(), sort_keys=True)) diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index 9d85c5eb..fb899a22 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -125,6 +125,47 @@ def test_5_faults_are_bounded_and_audited(self): self.assertNotIn('synthetic-test-password', text) self.assertNotIn('Authorization', text) + def test_5a_reset_time_from_the_first_read(self): + # A fresh lab reports every System's reset time before any reset, so a + # first restart has a baseline to prove itself against. + fresh = pathlib.Path(tempfile.mkdtemp()) + lab = adapter.Lab(adapter.load_targets(), str(fresh), '10.96.0.80') + self.assertEqual(sorted(lab.last_reset), sorted(adapter.load_targets())) + self.assertEqual(json.loads((fresh / 'last-reset.json').read_text()), lab.last_reset) + + def test_5b_power_faults_and_reset_time(self): + reset = '/redfish/v1/Systems/System-2/Actions/ComputerSystem.Reset' + system = lambda: self.app.get('/redfish/v1/Systems/System-2', headers=AUTH).json + self.app.post(reset, headers=AUTH, json={'ResetType': 'ForceOff'}) + self.app.post(reset, headers=AUTH, json={'ResetType': 'On'}) + first = system()['LastResetTime'] + # A restart moves the reset time forward; a ForceOff does not. + self.app.post(reset, headers=AUTH, json={'ResetType': 'ForceRestart'}) + second = system()['LastResetTime'] + self.assertGreater(second, first) + self.app.post(reset, headers=AUTH, json={'ResetType': 'ForceOff'}) + self.assertEqual(system()['LastResetTime'], second) + adapter.fault_cli(['hide-reset-time', 'System-2']) + self.assertNotIn('LastResetTime', system()) + adapter.fault_cli(['swap-identity', 'System-2', '00000000-0000-4000-8000-0000000000b2']) + self.assertEqual(system()['UUID'], '00000000-0000-4000-8000-0000000000b2') + adapter.fault_cli(['clear']) + self.assertEqual(system()['UUID'], '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b') + self.assertEqual(system()['LastResetTime'], second) + # A withheld request is never applied, and is audited as received. + adapter.fault_cli(['drop-request', 'System-2', 'On', '0']) + self.assertEqual(self.app.post(reset, headers=AUTH, json={'ResetType': 'On'}).status_code, 503) + self.assertEqual(system()['PowerState'], 'Off') + entries = self.audit() + posts = [e for e in entries if e['method'] == 'POST' and e['path'] == reset] + self.assertEqual((posts[-1]['fault'], posts[-1]['effect']), ('drop-request', 'none')) + # A withheld response follows any applied reset, such as a ForceOff. + self.app.post(reset, headers=AUTH, json={'ResetType': 'On'}) + adapter.fault_cli(['drop-response', 'System-2', 'ForceOff', '0']) + self.app.post(reset, headers=AUTH, json={'ResetType': 'ForceOff'}) + self.assertEqual(self.audit()[-1]['fault'], 'drop-response-after-effect') + self.assertEqual(system()['PowerState'], 'Off') + def test_6_lost_libvirt_definitions_are_redefined_with_the_same_identity(self): s = virsh_state() s['domains'].pop('fleet-lab-target-a') diff --git a/internal/custody/power.go b/internal/custody/power.go index 29dc0ca4..c42849f3 100644 --- a/internal/custody/power.go +++ b/internal/custody/power.go @@ -19,15 +19,16 @@ import ( // three-minute observation of the outcome, and a minute of margin. const PowerDeadline = 8 * time.Minute -// Power refusal reasons the coordinator raises. The worker's own reasons -// (Stale, NotPoweredOn, and PowerStateNotSettled before a command) arrive -// with the site worker; SystemUUIDMismatch and ResetTypeNotOffered are -// raised by both. +// Power refusal reasons. SystemUUIDMismatch and ResetTypeNotOffered are +// raised by the coordinator and the site worker, NotPoweredOn by the worker +// only, and PowerStateNotSettled by the worker before a command and by the +// settle hook. Stale is the site framework's shared reason. const ( ReasonSystemUUIDNotRecorded = "SystemUUIDNotRecorded" ReasonSystemUUIDMismatch = "SystemUUIDMismatch" ReasonDiscoveryNotCurrent = "DiscoveryNotCurrent" ReasonResetTypeNotOffered = "ResetTypeNotOffered" + ReasonNotPoweredOn = "NotPoweredOn" // The reasons a DeviceRecovery Settle of a power hold is refused with. ReasonPowerEvidenceNotCurrent = "PowerEvidenceNotCurrent" ReasonPowerEvidenceWrongEndpoint = "PowerEvidenceWrongEndpoint" @@ -90,7 +91,8 @@ func DevicePowerOperationKind() Kind { {Name: ReasonResetTypeNotOffered, RaisedBy: RaisedByBoth}, {Name: ReasonPowerEvidenceNotCurrent, RaisedBy: RaisedByCoordinator}, {Name: ReasonPowerEvidenceWrongEndpoint, RaisedBy: RaisedByCoordinator}, - {Name: ReasonPowerStateNotSettled, RaisedBy: RaisedByCoordinator}, + {Name: ReasonPowerStateNotSettled, RaisedBy: RaisedByBoth}, + {Name: ReasonNotPoweredOn, RaisedBy: RaisedByWorker}, {Name: ReasonPowerEvidenceMismatch, RaisedBy: RaisedByCoordinator}, }, SnapshotExtra: powerSnapshot, diff --git a/internal/redfish/client.go b/internal/redfish/client.go index 487029e7..86d3706c 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -263,7 +263,10 @@ type Power struct { State string `json:"state"` OverrideEnabled string `json:"overrideEnabled"` OverrideTarget string `json:"overrideTarget"` - etag string + // LastResetTime is when the BMC reports the System last came out of a + // reset. It is zero when the BMC reports none or an unreadable time. + LastResetTime time.Time `json:"lastResetTime,omitzero"` + etag string } // resetAction holds the annotations gofish decodes into unexported fields. @@ -383,8 +386,9 @@ func observe(api *gofish.APIClient, sys System) (Power, error) { if s.ID != sys.ID || !strings.EqualFold(s.UUID, sys.UUID) { return Power{}, fmt.Errorf("%w: retained System path changed identity", ErrIdentity) } + lastReset, _ := time.Parse(time.RFC3339, s.LastResetTime) return Power{State: string(s.PowerState), OverrideEnabled: string(s.Boot.BootSourceOverrideEnabled), - OverrideTarget: string(s.Boot.BootSourceOverrideTarget), etag: s.ODataEtag}, nil + OverrideTarget: string(s.Boot.BootSourceOverrideTarget), LastResetTime: lastReset.UTC(), etag: s.ODataEtag}, nil } // Observe reads the retained System again and re-checks its identity. diff --git a/internal/redfish/client_test.go b/internal/redfish/client_test.go index 1c54b957..ae354c1f 100644 --- a/internal/redfish/client_test.go +++ b/internal/redfish/client_test.go @@ -286,3 +286,31 @@ func TestClientRejectsUntrustedTLSAndEnvironmentProxy(t *testing.T) { t.Fatal("BMC requests may be sent through an environment proxy") } } + +// Observe reads the BMC's LastResetTime, in the lab's microsecond form, and +// leaves it zero when the BMC reports none or an unreadable time. +func TestObserveReadsTheLastResetTime(t *testing.T) { + b := newStub() + c := stubClient(t, b, time.Second) + sys, err := c.Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}) + if err != nil { + t.Fatal(err) + } + for value, want := range map[any]time.Time{ + "2026-01-02T03:04:05.123456+00:00": time.Date(2026, 1, 2, 3, 4, 5, 123456000, time.UTC), + "2026-01-02T03:04:05Z": time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), + "not a time": {}, + nil: {}, + } { + doc := b.docs["/redfish/v1/Systems/A"].(map[string]any) + if value == nil { + delete(doc, "LastResetTime") + } else { + doc["LastResetTime"] = value + } + power, err := c.Observe(context.Background(), sys) + if err != nil || !power.LastResetTime.Equal(want) { + t.Fatalf("LastResetTime %v: got %v, %v", value, power.LastResetTime, err) + } + } +} diff --git a/internal/site/powerwork/power.go b/internal/site/powerwork/power.go new file mode 100644 index 00000000..dfdbcbc5 --- /dev/null +++ b/internal/site/powerwork/power.go @@ -0,0 +1,323 @@ +// Package powerwork runs DevicePowerOperation over Redfish behind the site +// worker contract, as proposed in datum-cloud/fleet#173. A worker reads the +// server's power before it sends anything, sends at most one +// ComputerSystem.Reset, and reports Succeeded only for what it then +// observes. The framework owns the fence, journal, credential, pin, identity +// and deadline. +package powerwork + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// The worker's refusal reasons, declared on the DevicePowerOperation kind. +const ( + ReasonNotPoweredOn = custody.ReasonNotPoweredOn + ReasonPowerStateNotSettled = custody.ReasonPowerStateNotSettled + ReasonSystemUUIDMismatch = custody.ReasonSystemUUIDMismatch + ReasonResetTypeNotOffered = custody.ReasonResetTypeNotOffered +) + +// resetStep names the one journaled effect. +const resetStep = "reset" + +// Defaults, from #173: the worker must start within two minutes of +// admission, and the outcome must be observed within three minutes of the +// command. +const ( + DefaultStartBy = 2 * time.Minute + DefaultObserveTimeout = 3 * time.Minute + defaultPoll = 2 * time.Second + defaultOutage = time.Minute +) + +// Power is the DevicePowerOperation worker. +type Power struct { + // Poll is how often the worker reads the server while it waits. It + // defaults to two seconds. + Poll time.Duration + // ObserveTimeout bounds how long after the command the requested state + // may take to appear. It defaults to three minutes. + ObserveTimeout time.Duration + // Outage bounds how long the BMC may be unreadable while the worker + // waits. It defaults to one minute. + Outage time.Duration + Now func() time.Time +} + +var ( + _ site.Kind = Power{} + _ site.StartBy = Power{} +) + +func (p Power) now() time.Time { + if p.Now != nil { + return p.Now().UTC() + } + return time.Now().UTC() +} + +func positive(value, fallback time.Duration) time.Duration { + if value > 0 { + return value + } + return fallback +} + +// StartBy is the #173 start window. A worker that starts later, with +// nothing sent, refuses as Stale. +func (Power) StartBy() time.Duration { return DefaultStartBy } + +// payload is what the reset step journals before it is sent: when the one +// command was sent, the power read before it, and the BMC's reset-time +// baseline that proves a restart. +type payload struct { + RequestSentAt time.Time `json:"requestSentAt"` + Before observation `json:"before"` + LastResetTime time.Time `json:"lastResetTime,omitzero"` + Action ops.PowerAction `json:"action"` +} + +type observation struct { + State ops.ObservedPowerState `json:"state"` + ObservedAt time.Time `json:"observedAt"` +} + +func connection(work *site.Work) *site.RedfishConnection { + connection, _ := work.Connection.(*site.RedfishConnection) + return connection +} + +func spec(work *site.Work) (ops.DevicePowerOperationSpec, error) { + var spec ops.DevicePowerOperationSpec + err := json.Unmarshal(work.Inputs, &spec) + return spec, err +} + +func refuse(reason, format string, args ...any) *custody.Refusal { + return &custody.Refusal{Reason: reason, Message: fmt.Sprintf(format, args...)} +} + +// Check runs after the framework verified the credential, the pin and the +// System's identity. It re-checks the power inputs against what the BMC +// offers now and changes nothing. +func (Power) Check(_ context.Context, work *site.Work) *custody.Refusal { + conn := connection(work) + if conn == nil { + return refuse(site.ReasonUnsupportedKind, "this site does not reach the server over Redfish") + } + spec, err := spec(work) + if err != nil || !slices.Contains(ops.PowerActions, spec.Action) { + return refuse(site.ReasonInputMismatch, "the admitted inputs are not a power operation") + } + if spec.ExpectedSystemUUID != "" && !strings.EqualFold(spec.ExpectedSystemUUID, conn.System.UUID) { + return refuse(ReasonSystemUUIDMismatch, "the BMC reports a system other than the one staff expected") + } + if !slices.Contains(conn.System.ResetTypes, string(spec.Action)) { + return refuse(ReasonResetTypeNotOffered, "the BMC does not offer %s", spec.Action) + } + return nil +} + +// Run reads the server's power, sends at most one reset, and returns the +// typed evidence of what it then observed. A resumed worker reads the +// journaled payload instead of reading the server's state before again, and +// observes instead of sending again. +func (p Power) Run(ctx context.Context, work *site.Work) (any, error) { + conn := connection(work) + spec, err := spec(work) + if err != nil { + return nil, refuse(site.ReasonInputMismatch, "the admitted inputs are not a power operation") + } + action := spec.Action + journaled, found, err := journaledPayload(work) + if err != nil { + return nil, err + } + var sent payload + if found { + sent = journaled + } else { + before, err := conn.Observe(ctx) + if errors.Is(err, redfish.ErrIdentity) { + return nil, refuse(ReasonSystemUUIDMismatch, "the BMC reports another system") + } + if err != nil { + return nil, err + } + read := observation{State: ops.ObservedPowerState(before.State), ObservedAt: p.now()} + switch { + case !read.State.Settled(): + // The BMC's string is never copied into a result. + return nil, refuse(ReasonPowerStateNotSettled, "the server reports a power state other than On or Off") + case action == ops.PowerOn && read.State == ops.PowerStateOn, action == ops.PowerForceOff && read.State == ops.PowerStateOff: + // Already in the requested state: nothing is sent. + return evidence(nil, read, read, ""), nil + case action.Resets() && read.State == ops.PowerStateOff: + return nil, refuse(ReasonNotPoweredOn, "a %s needs a server that is on", action) + } + sent = payload{RequestSentAt: p.now(), Before: read, LastResetTime: before.LastResetTime, Action: action} + } + var result *outcome + if err := work.Step(ctx, site.Step{ + Name: resetStep, + Payload: sent, + Send: func(ctx context.Context) error { return send(ctx, conn, action) }, + // After a crash or a lost response, the reset is never sent again: + // the worker watches for its effect instead. + Observe: func(ctx context.Context, _ json.RawMessage) (bool, error) { + found, err := p.watch(ctx, conn, sent) + result = found + return found != nil, err + }, + }); err != nil { + return nil, err + } + if result == nil { + if result, err = p.watch(ctx, conn, sent); err != nil { + return nil, err + } + } + if result == nil { + return nil, refuse(site.ReasonStep, "the requested power result was not observed within %s of the command", positive(p.ObserveTimeout, DefaultObserveTimeout)) + } + sentAt := sent.RequestSentAt + return evidence(&sentAt, sent.Before, result.after, result.proof), nil +} + +// journaledPayload returns the reset step's payload if an earlier worker for +// this admission journaled it. The journal is keyed by the operation and the +// fence it was admitted at. +func journaledPayload(work *site.Work) (payload, bool, error) { + journal, err := work.Store().Journal(work.Device) + if err != nil { + return payload{}, false, err + } + for _, entry := range journal { + if entry.Operation != work.Key() || entry.Step != resetStep { + continue + } + var recorded payload + if err := json.Unmarshal(entry.Payload, &recorded); err != nil { + return payload{}, false, fmt.Errorf("the journaled reset payload is unreadable: %w", err) + } + return recorded, true, nil + } + return payload{}, false, nil +} + +// send posts the one reset. A response the BMC returned refusing it is an +// error. A lost response is not: the command may have taken effect, so the +// worker watches for it instead. +func send(ctx context.Context, conn *site.RedfishConnection, action ops.PowerAction) error { + err := conn.Reset(ctx, string(action)) + var status redfish.Status + switch { + case err == nil: + return nil + case errors.As(err, &status), errors.Is(err, redfish.ErrUnauthorized), errors.Is(err, redfish.ErrUnsupported), + errors.Is(err, redfish.ErrIdentity), errors.Is(err, redfish.ErrPinMismatch): + return err + case ctx.Err() != nil: + return context.Cause(ctx) + } + return nil +} + +// outcome is a proven result: the power read at the end, and for a restart +// or power cycle, how the reset was proven. +type outcome struct { + after observation + proof ops.ResetEvidence +} + +// watch reads the server until the requested result appears or the +// observation window after the command closes, and returns nil then. For On +// and ForceOff the requested state must appear. A restart or power cycle is +// proven only by the BMC's reset time moving past the journaled baseline, or +// by seeing the server off, and then the server must be on again. Without a +// baseline, a reset time proves nothing: it may be a stale one the BMC hid +// before the command. +func (p Power) watch(ctx context.Context, conn *site.RedfishConnection, sent payload) (*outcome, error) { + poll := positive(p.Poll, defaultPoll) + closes := sent.RequestSentAt.Add(positive(p.ObserveTimeout, DefaultObserveTimeout)) + outage := positive(p.Outage, defaultOutage) + var failingSince time.Time + seenOff := false + for { + power, err := conn.Observe(ctx) + switch { + case errors.Is(err, redfish.ErrIdentity): + return nil, refuse(ReasonSystemUUIDMismatch, "the BMC began reporting another system") + case err != nil: + if ctx.Err() != nil { + return nil, context.Cause(ctx) + } + if failingSince.IsZero() { + failingSince = p.now() + } + if p.now().Sub(failingSince) > outage { + return nil, fmt.Errorf("the BMC was unreadable while the power result was observed: %w", err) + } + default: + failingSince = time.Time{} + read := observation{State: ops.ObservedPowerState(power.State), ObservedAt: p.now()} + switch sent.Action { + case ops.PowerOn, ops.PowerForceOff: + if (sent.Action == ops.PowerOn) == (read.State == ops.PowerStateOn) && read.State.Settled() { + return &outcome{after: read}, nil + } + default: + if read.State == ops.PowerStateOff { + seenOff = true + } + moved := !sent.LastResetTime.IsZero() && power.LastResetTime.After(sent.LastResetTime) + if (moved || seenOff) && read.State == ops.PowerStateOn { + proof := ops.ResetObservedOff + if moved { + proof = ops.ResetLastResetTime + } + return &outcome{after: read, proof: proof}, nil + } + } + } + if !p.now().Before(closes) { + return nil, nil + } + timer := time.NewTimer(poll) + select { + case <-ctx.Done(): + timer.Stop() + return nil, context.Cause(ctx) + case <-timer.C: + } + } +} + +func evidence(sentAt *time.Time, before, after observation, proof ops.ResetEvidence) ops.PowerEvidence { + out := ops.PowerEvidence{ + Power: &ops.PowerObservations{Before: observed(before), After: observed(after)}, + ResetEvidence: proof, + } + if sentAt != nil { + at := metav1.NewTime(*sentAt) + out.RequestSentAt = &at + } + return out +} + +func observed(value observation) *ops.PowerObservation { + return &ops.PowerObservation{State: value.State, ObservedAt: metav1.NewTime(value.ObservedAt)} +} diff --git a/internal/site/powerwork/power_test.go b/internal/site/powerwork/power_test.go new file mode 100644 index 00000000..6aad2cea --- /dev/null +++ b/internal/site/powerwork/power_test.go @@ -0,0 +1,556 @@ +package powerwork + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/json" + "errors" + "math/big" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/bmcdiscovery" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" +) + +const ( + uuid = "00000000-0000-4000-8000-0000000000a1" + otherUUID = "00000000-0000-4000-8000-0000000000b2" + device = "default/server-example-001" + systemID = "A" + path = "/redfish/v1/Systems/A" +) + +// bmc simulates one server behind a TLS Redfish BMC, with the lab's power +// faults. It counts every reset request it receives, applied or not. +type bmc struct { + mu sync.Mutex + power string + reset time.Time + resets int + // offReads is how many reads of the System a restart reports Off for + // before On. Counting reads, not time, keeps a slow worker from missing + // the Off. + offReads, offLeft int + // hideReset hides LastResetTime, as some BMCs do. + hideReset bool + // offered are the advertised reset types. + offered []string + // uuid is what the System reports; a swap changes it. + uuid string + // lose applies the reset and withholds the response; drop withholds it + // without applying it; refuse answers 400 without applying it. + lose, drop, refuse bool + hold time.Duration + // onReset runs after a reset request is counted. + onReset func() + server *httptest.Server +} + +func newBMC(t *testing.T, power string) *bmc { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}} + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + b := &bmc{power: power, reset: time.Now().Add(-time.Hour).UTC().Truncate(time.Second), offered: []string{"On", "ForceOff", "ForceRestart", "PowerCycle"}, uuid: uuid, hold: time.Second} + b.server = httptest.NewUnstartedServer(b) + b.server.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}} + b.server.StartTLS() + t.Cleanup(b.server.Close) + return b +} + +func (b *bmc) pin() string { + certificate, _ := x509.ParseCertificate(b.server.TLS.Certificates[0].Certificate[0]) + sum := sha256.Sum256(certificate.RawSubjectPublicKeyInfo) + return hex.EncodeToString(sum[:]) +} + +func (b *bmc) set(change func(*bmc)) { + b.mu.Lock() + defer b.mu.Unlock() + change(b) +} + +func (b *bmc) count() int { + b.mu.Lock() + defer b.mu.Unlock() + return b.resets +} + +// apply runs the reset's effect. Restarts and power cycles move the reset +// time and, when offReads is set, report Off for that many reads first. +func (b *bmc) apply(kind string) { + switch kind { + case "On": + if b.power == "Off" { + b.power, b.reset = "On", time.Now().UTC().Truncate(time.Second) + } + case "ForceOff": + b.power = "Off" + case "ForceRestart", "PowerCycle": + b.reset = time.Now().UTC().Add(time.Second).Truncate(time.Second) + if b.offReads <= 0 { + b.power = "On" + return + } + b.power, b.offLeft = "Off", b.offReads + } +} + +func (b *bmc) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && r.URL.Path == path+"/Actions/ComputerSystem.Reset" { + var body struct{ ResetType string } + json.NewDecoder(r.Body).Decode(&body) + b.mu.Lock() + b.resets++ + lose, drop, refuse, hold, hook := b.lose, b.drop, b.refuse, b.hold, b.onReset + if !drop && !refuse { + b.apply(body.ResetType) + } + b.mu.Unlock() + if hook != nil { + hook() + } + switch { + case refuse: + w.WriteHeader(http.StatusBadRequest) + case lose || drop: + time.Sleep(hold) + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusNoContent) + } + return + } + b.mu.Lock() + system := map[string]any{"@odata.id": path, "Id": systemID, "UUID": b.uuid, "PowerState": b.power, + "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": path + "/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": b.offered}}} + if !b.hideReset { + system["LastResetTime"] = b.reset.Format(time.RFC3339) + } + if b.offLeft > 0 && strings.TrimSuffix(r.URL.Path, "/") == path { + if b.offLeft--; b.offLeft == 0 { + b.power = "On" + } + } + b.mu.Unlock() + docs := map[string]any{ + "/redfish/v1": map[string]any{"@odata.id": "/redfish/v1", "Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}, + "/redfish/v1/Systems": map[string]any{"Members": []any{map[string]string{"@odata.id": path}}}, + path: system, + } + doc, ok := docs[strings.TrimSuffix(r.URL.Path, "/")] + if !ok { + w.WriteHeader(http.StatusNotFound) + return + } + json.NewEncoder(w).Encode(doc) +} + +type credentials struct{ pin string } + +func (c credentials) Lookup(context.Context, string) (bmcdiscovery.Credential, bool, error) { + return bmcdiscovery.Credential{Username: "operator", Password: "synthetic-secret", Pin: c.pin}, true, nil +} + +// runner is a site whose requests time out after 300ms, so a withheld +// response is a lost one. +func runner(t *testing.T, b *bmc) *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), + Access: site.RedfishAccess{Credentials: credentials{pin: b.pin()}, + Targets: site.StaticTargets{device: {Device: device, Endpoint: b.server.URL, SystemID: systemID, SystemUUID: uuid}}, + Dial: func(endpoint, username, password, pin string) (*redfish.Client, error) { + return redfish.NewPinnedClient(endpoint, username, password, pin, 300*time.Millisecond) + }}, + Kinds: map[string]site.Kind{"DevicePowerOperation": Power{Poll: 10 * time.Millisecond, ObserveTimeout: 2 * time.Second, Outage: time.Second}}, + Poll: 10 * time.Millisecond, + } +} + +func staff(action ops.PowerAction) ops.DevicePowerOperationSpec { + return ops.DevicePowerOperationSpec{OperationEnvelope: ops.OperationEnvelope{Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "qualification"}}}, + Action: action, ExpectedSystemUUID: uuid} +} + +func assignment(b *bmc, uid string, spec ops.DevicePowerOperationSpec) site.Assignment { + inputs, _ := json.Marshal(spec) + sum := sha256.Sum256(inputs) + return site.Assignment{ + Device: device, Operation: ops.OperationReference{Kind: "DevicePowerOperation", Name: "server-example-001-power-" + uid}, Fence: 1, + AdmittedAt: time.Now(), Deadline: time.Now().Add(time.Minute), + Snapshot: ops.DeviceSnapshot{BMCEndpoint: b.server.URL, SystemUUID: uuid, BMCPublicKeySHA256: b.pin()}, + InputDigest: "sha256:" + hex.EncodeToString(sum[:]), Inputs: inputs, + } +} + +// requireEvidence decodes the result's evidence and checks it against the +// coordinator's power evidence hook. +func requireEvidence(t *testing.T, result custody.SiteResult, spec ops.DevicePowerOperationSpec) ops.PowerEvidence { + t.Helper() + 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) + } + // A success the worker reports must be one the coordinator counts. + if result.Phase == ops.PhaseSucceeded { + 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 { + t.Fatal(err) + } + return evidence +} + +func TestEachActionSendsOneResetAndProvesItsResult(t *testing.T) { + for _, tc := range []struct { + name string + action ops.PowerAction + power, after string + offReads int + hideReset bool + resets int + proof ops.ResetEvidence + requestSentAt bool + }{ + {name: "On from off", action: ops.PowerOn, power: "Off", after: "On", resets: 1, requestSentAt: true}, + {name: "ForceOff from on", action: ops.PowerForceOff, power: "On", after: "Off", resets: 1, requestSentAt: true}, + {name: "On when already on sends nothing", action: ops.PowerOn, power: "On", after: "On"}, + {name: "ForceOff when already off sends nothing", action: ops.PowerForceOff, power: "Off", after: "Off"}, + {name: "ForceRestart proven by the reset time", action: ops.PowerForceRestart, power: "On", after: "On", resets: 1, proof: ops.ResetLastResetTime, requestSentAt: true}, + {name: "PowerCycle proven by the reset time", action: ops.PowerCycle, power: "On", after: "On", resets: 1, proof: ops.ResetLastResetTime, requestSentAt: true}, + {name: "ForceRestart proven by seeing the server off", action: ops.PowerForceRestart, power: "On", after: "On", offReads: 2, hideReset: true, resets: 1, proof: ops.ResetObservedOff, requestSentAt: true}, + } { + t.Run(tc.name, func(t *testing.T) { + b := newBMC(t, tc.power) + b.offReads, b.hideReset = tc.offReads, tc.hideReset + spec := staff(tc.action) + result, err := runner(t, b).Run(context.Background(), assignment(b, "op-1", spec)) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseSucceeded || b.count() != tc.resets { + t.Fatalf("result = %+v, %d resets, want Succeeded with %d", result, b.count(), tc.resets) + } + evidence := requireEvidence(t, result, spec) + if string(evidence.Power.Before.State) != tc.power || string(evidence.Power.After.State) != tc.after || evidence.ResetEvidence != tc.proof || (evidence.RequestSentAt != nil) != tc.requestSentAt { + t.Fatalf("evidence = %s", result.Evidence) + } + }) + } +} + +// A refusal never carries the BMC's own text. +func TestARefusalNeverCopiesTheBMCsPowerState(t *testing.T) { + hostile := "PoweringOn https://bmc.example.invalid/secret" + b := newBMC(t, hostile) + result, err := runner(t, b).Run(context.Background(), assignment(b, "op-1", staff(ops.PowerOn))) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseFailed || result.Reason != ReasonPowerStateNotSettled || strings.Contains(result.Message, "example.invalid") || strings.Contains(result.Message, "PoweringOn") { + t.Fatalf("result = %+v", result) + } +} + +func TestRefusalsSendNothing(t *testing.T) { + for _, tc := range []struct { + name string + action ops.PowerAction + power string + setup func(*bmc, *site.Assignment) + reason string + }{ + {name: "a restart of a server that is off", action: ops.PowerForceRestart, power: "Off", reason: ReasonNotPoweredOn}, + {name: "a power cycle of a server that is off", action: ops.PowerCycle, power: "Off", reason: ReasonNotPoweredOn}, + {name: "a server powering on", action: ops.PowerForceOff, power: "PoweringOn", reason: ReasonPowerStateNotSettled}, + {name: "a server powering off", action: ops.PowerOn, power: "PoweringOff", reason: ReasonPowerStateNotSettled}, + {name: "an action the BMC no longer offers", action: ops.PowerCycle, power: "On", reason: ReasonResetTypeNotOffered, + setup: func(b *bmc, _ *site.Assignment) { b.offered = []string{"On", "ForceOff", "ForceRestart"} }}, + {name: "a worker that starts after the start-by window", action: ops.PowerOn, power: "Off", reason: site.ReasonStale, + setup: func(_ *bmc, a *site.Assignment) { a.AdmittedAt = time.Now().Add(-DefaultStartBy - time.Second) }}, + {name: "a BMC that reports another system", action: ops.PowerOn, power: "Off", reason: custody.ReasonDeviceIdentityMismatch, + setup: func(b *bmc, _ *site.Assignment) { b.uuid = otherUUID }}, + } { + t.Run(tc.name, func(t *testing.T) { + b := newBMC(t, tc.power) + work := assignment(b, "op-1", staff(tc.action)) + if tc.setup != nil { + tc.setup(b, &work) + } + result, err := runner(t, b).Run(context.Background(), work) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseFailed || result.Reason != tc.reason || b.count() != 0 { + t.Fatalf("result = %+v, %d resets, want Failed %s with none", result, b.count(), tc.reason) + } + // The coordinator records the reason only if the worker may raise + // it. + registry, err := custody.DefaultRegistry() + if err != nil { + t.Fatal(err) + } + if !registry.Declared("DevicePowerOperation", tc.reason, custody.RaisedByWorker) { + t.Fatalf("%s is not declared for the power worker", tc.reason) + } + }) + } +} + +// The expected system UUID is checked again at the site, against the +// System whose identity the framework verified. +func TestAnExpectedUUIDOtherThanTheVerifiedSystemIsRefused(t *testing.T) { + b := newBMC(t, "Off") + spec := staff(ops.PowerOn) + spec.ExpectedSystemUUID = otherUUID + result, err := runner(t, b).Run(context.Background(), assignment(b, "op-1", spec)) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseFailed || result.Reason != ReasonSystemUUIDMismatch || b.count() != 0 { + t.Fatalf("result = %+v, %d resets", result, b.count()) + } +} + +func TestALostResponseIsObservedAndNeverResent(t *testing.T) { + b := newBMC(t, "Off") + b.lose = true + spec := staff(ops.PowerOn) + result, err := runner(t, b).Run(context.Background(), assignment(b, "op-1", spec)) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseSucceeded || b.count() != 1 { + t.Fatalf("result = %+v, %d resets", result, b.count()) + } + requireEvidence(t, result, spec) +} + +func TestAResetThatNeverTookEffectIsUnknown(t *testing.T) { + for name, fault := range map[string]func(*bmc){ + "a request withheld and never applied": func(b *bmc) { b.drop = true }, + "a restart the BMC cannot prove": func(b *bmc) { b.hideReset = true }, + "a request the BMC refused": func(b *bmc) { b.refuse = true }, + // The BMC hid its reset time before the command and shows a stale + // one after it. Without a baseline, that proves nothing. + "a reset time with no baseline": func(b *bmc) { + b.hideReset, b.drop = true, true + b.onReset = func() { b.set(func(b *bmc) { b.hideReset = false }) } + }, + } { + t.Run(name, func(t *testing.T) { + b := newBMC(t, "On") + fault(b) + result, err := runner(t, b).Run(context.Background(), assignment(b, "op-1", staff(ops.PowerForceRestart))) + if err != nil { + t.Fatal(err) + } + // Something may have reached the server, and nothing proves what + // it did, so the outcome is unknown and only one reset was sent. + if result.Phase != ops.PhaseOutcomeUnknown || b.count() != 1 { + t.Fatalf("result = %+v, %d resets", result, b.count()) + } + }) + } +} + +func TestASwapAfterTheResetIsUnknown(t *testing.T) { + b := newBMC(t, "Off") + b.onReset = func() { b.set(func(b *bmc) { b.uuid, b.power = otherUUID, "Off" }) } + result, err := runner(t, b).Run(context.Background(), assignment(b, "op-1", staff(ops.PowerOn))) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseOutcomeUnknown || result.Reason != ReasonSystemUUIDMismatch || b.count() != 1 { + t.Fatalf("result = %+v, %d resets", result, b.count()) + } +} + +// A worker stopped right after it sent the reset stores no result. Its +// replacement reads the journaled payload, observes the effect, and sends +// nothing. +func TestAResumedWorkerObservesInsteadOfResending(t *testing.T) { + for name, fault := range map[string]func(*bmc){ + "the reset took effect": func(*bmc) {}, + "the reset response was lost": func(b *bmc) { b.lose = true }, + } { + t.Run(name, func(t *testing.T) { + b := newBMC(t, "On") + fault(b) + r := runner(t, b) + spec := staff(ops.PowerForceRestart) + work := assignment(b, "op-1", spec) + ctx, cancel := context.WithCancel(context.Background()) + b.onReset = cancel + if _, err := r.Run(ctx, work); !errors.Is(err, context.Canceled) { + t.Fatalf("interrupted: %v", err) + } + b.set(func(b *bmc) { b.onReset = nil }) + result, err := r.Run(context.Background(), work) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseSucceeded || b.count() != 1 { + t.Fatalf("resumed result = %+v, %d resets", result, b.count()) + } + evidence := requireEvidence(t, result, spec) + if evidence.ResetEvidence != ops.ResetLastResetTime || evidence.Power.Before.State != ops.PowerStateOn { + t.Fatalf("evidence = %s", result.Evidence) + } + }) + } +} + +// A resumed worker whose reset never took effect does not send again: the +// outcome is unknown. +func TestAResumedWorkerNeverSendsASecondReset(t *testing.T) { + b := newBMC(t, "On") + b.drop = true + r := runner(t, b) + work := assignment(b, "op-1", staff(ops.PowerForceOff)) + ctx, cancel := context.WithCancel(context.Background()) + b.onReset = cancel + if _, err := r.Run(ctx, work); !errors.Is(err, context.Canceled) { + t.Fatalf("interrupted: %v", err) + } + b.set(func(b *bmc) { b.onReset, b.drop = nil, false }) + result, err := r.Run(context.Background(), work) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseOutcomeUnknown || b.count() != 1 { + t.Fatalf("resumed result = %+v, %d resets", result, b.count()) + } +} + +// The journal is keyed by the operation and its admission fence, so a +// reset journaled under an earlier fence is never taken for this admission: +// the worker reads the server again and finds it already off. +func TestAResetJournaledUnderAnotherFenceIsNotReused(t *testing.T) { + b := newBMC(t, "On") + r := runner(t, b) + spec := staff(ops.PowerForceOff) + earlier := assignment(b, "op-1", spec) + ctx, cancel := context.WithCancel(context.Background()) + b.onReset = cancel + if _, err := r.Run(ctx, earlier); !errors.Is(err, context.Canceled) { + t.Fatalf("interrupted: %v", err) + } + b.set(func(b *bmc) { b.onReset = nil }) + later := assignment(b, "op-1", spec) + later.Fence = 2 + result, err := r.Run(context.Background(), later) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseSucceeded || b.count() != 1 { + t.Fatalf("result = %+v, %d resets", result, b.count()) + } + // The earlier fence's journal would carry its send time and its read of + // the server on. + if evidence := requireEvidence(t, result, spec); evidence.RequestSentAt != nil || evidence.Power.Before.State != ops.PowerStateOff { + t.Fatalf("evidence = %s", result.Evidence) + } +} + +// Two workers for one assignment, such as a cloned Pod, send one reset +// between them. +func TestTwoWorkersForOneAssignmentSendOneReset(t *testing.T) { + b := newBMC(t, "On") + b.offReads = 3 + r := runner(t, b) + work := assignment(b, "op-1", staff(ops.PowerForceRestart)) + var group sync.WaitGroup + results := make([]custody.SiteResult, 2) + errs := make([]error, 2) + for index := range 2 { + group.Add(1) + go func() { + defer group.Done() + results[index], errs[index] = r.Run(context.Background(), work) + }() + } + group.Wait() + succeeded := 0 + for index := range 2 { + switch { + case errs[index] == nil && results[index].Phase == ops.PhaseSucceeded: + succeeded++ + case errors.Is(errs[index], site.ErrAlreadyRunning): + default: + t.Fatalf("worker %d: %+v, %v", index, results[index], errs[index]) + } + } + if succeeded == 0 || b.count() != 1 { + t.Fatalf("%d succeeded, %d resets", succeeded, b.count()) + } +} + +// TestALiveReadDecidesWhenDiscoveryRecordedNoResetTypes covers an admission +// whose snapshot names no offered actions, because discovery could not read +// them. The worker's live read of the BMC decides: an offered action runs, +// and one the BMC does not offer ends Failed with nothing sent. +func TestALiveReadDecidesWhenDiscoveryRecordedNoResetTypes(t *testing.T) { + for name, offered := range map[string][]string{ + "the BMC offers the action": {"On", "ForceOff", "ForceRestart", "PowerCycle"}, + "the BMC does not offer the action": {"On", "ForceOff"}, + } { + t.Run(name, func(t *testing.T) { + b := newBMC(t, "On") + b.offered = offered + spec := staff(ops.PowerForceRestart) + work := assignment(b, "op-1", spec) + work.Snapshot.Extra = map[string]string{custody.SnapshotResetTypes: "", custody.SnapshotSystemID: "System-1"} + result, err := runner(t, b).Run(context.Background(), work) + if err != nil { + t.Fatal(err) + } + if len(offered) == 4 { + if result.Phase != ops.PhaseSucceeded || b.count() != 1 { + t.Fatalf("result = %+v, %d resets", result, b.count()) + } + requireEvidence(t, result, spec) + return + } + if result.Phase != ops.PhaseFailed || result.Reason != ReasonResetTypeNotOffered || b.count() != 0 { + t.Fatalf("result = %+v, %d resets, want Failed %s with none sent", result, b.count(), ReasonResetTypeNotOffered) + } + }) + } +}