diff --git a/config/README.md b/config/README.md index b1cb911b..949cf765 100644 --- a/config/README.md +++ b/config/README.md @@ -63,15 +63,15 @@ legacy management-cluster install and will be removed. See [Planning and registering physical devices](../docs/operations/physical-inventory.md). `config/components/device-operations` registers `DeviceCustody`, the Device -operation kinds, their ProtectedResources, the coordinator, requester, viewer -and recovery operator roles, and the creator webhook. `config/milo` includes all -of it, and the `fleet-registration` server serves the webhook at -`/validate-operation-creator`. `config/milo-synthetic` includes the kinds, -ProtectedResources and roles without the webhook, because it installs no -registration webhook. `config/standalone` includes only the CRDs and enforces the -creator rule with a ValidatingAdmissionPolicy. Including the kinds installs no -coordinator: the production manager has no provider, so nothing creates -custody operations there. See [device custody](../docs/development/device-custody.md#cutover-increment-c). +operation kinds, their ProtectedResources, the coordinator, requester, viewer, +recovery operator and power operator roles, and the creator webhook. +`config/milo` includes all of it, and the `fleet-registration` server serves +the webhook at `/validate-operation-creator`. `config/milo-synthetic` includes +the kinds, ProtectedResources and roles without the webhook, because it +installs no registration webhook. `config/standalone` includes only the CRDs +and enforces the creator rule with a ValidatingAdmissionPolicy. Including the +kinds installs no coordinator: the production manager has no provider, so +nothing creates custody operations there. See [device custody](../docs/development/device-custody.md#cutover-increment-c). `config/base/bmc-discovery` runs read-only BMC discovery for one Milo project in a cluster that can reach the BMC network: one replica, no leader election, diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 42fc7e92..679e78ff 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -810,6 +810,256 @@ spec: --- apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition +metadata: + name: devicepoweroperations.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DevicePowerOperation + listKind: DevicePowerOperationList + plural: devicepoweroperations + singular: devicepoweroperation + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Action + type: string + jsonPath: .spec.action + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + - uid + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + authority: + type: object + properties: + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + serviceRequest: + type: object + properties: + reason: + type: string + minLength: 1 + maxLength: 512 + required: + - reason + x-kubernetes-validations: + - rule: has(self.allocationRef) != has(self.serviceRequest) + message: set exactly one of allocationRef and serviceRequest + action: + type: string + enum: + - "On" + - ForceOff + - ForceRestart + - PowerCycle + expectedSystemUUID: + type: string + pattern: ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ + machineGeneration: + type: integer + format: int64 + minimum: 1 + required: + - creator + - deviceRef + - authority + - action + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + - rule: has(self.authority.serviceRequest) == has(self.expectedSystemUUID) + message: a staff operation sets expectedSystemUUID, and a provider operation omits it + - rule: has(self.authority.allocationRef) == has(self.machineGeneration) + message: a provider operation sets machineGeneration, and a staff operation omits it + - rule: '!has(self.authority.allocationRef) || size(self.authority.allocationRef.name) <= 200' + message: a provider operation's allocation name is at most 200 characters, so its name and retry names fit + status: + type: object + properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence + phase: + type: string + enum: + - Pending + - Admitted + - Dispatched + - Verifying + - Succeeded + - Failed + - Cancelled + - OutcomeUnknown + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 1024 + fence: + type: integer + format: int64 + minimum: 0 + admittedAt: + type: string + format: date-time + deadline: + type: string + format: date-time + finishedAt: + type: string + format: date-time + inputDigest: + type: string + maxLength: 128 + snapshot: + type: object + properties: + bmcEndpoint: + type: string + maxLength: 2048 + systemUUID: + type: string + maxLength: 64 + bootMACAddress: + type: string + maxLength: 32 + bmcPublicKeySHA256: + type: string + maxLength: 128 + deviceGeneration: + type: integer + format: int64 + discoveryObservedAt: + type: string + maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + evidence: + type: object + properties: + requestSentAt: + type: string + format: date-time + power: + type: object + properties: + before: + type: object + properties: + state: + type: string + enum: + - "On" + - "Off" + - PoweringOn + - PoweringOff + - Paused + observedAt: + type: string + format: date-time + required: + - state + - observedAt + after: + type: object + properties: + state: + type: string + enum: + - "On" + - "Off" + - PoweringOn + - PoweringOff + - Paused + observedAt: + type: string + format: date-time + required: + - state + - observedAt + resetEvidence: + type: string + enum: + - LastResetTime + - ObservedOff + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Admitted'': [''Admitted'', ''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Dispatched'': [''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Verifying'': [''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Succeeded'': [''Succeeded''], ''Failed'': [''Failed''], ''Cancelled'': [''Cancelled''], ''OutcomeUnknown'': [''OutcomeUnknown'']}[oldSelf.phase])' + message: operation phases move forward only, and an ended phase is final + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition metadata: name: devicerecoveries.fleet.datumapis.com annotations: diff --git a/config/components/device-operations/protected-resources/devicepoweroperation.yaml b/config/components/device-operations/protected-resources/devicepoweroperation.yaml new file mode 100644 index 00000000..e701646c --- /dev/null +++ b/config/components/device-operations/protected-resources/devicepoweroperation.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicepoweroperation +spec: + serviceRef: + name: fleet.datumapis.com + kind: DevicePowerOperation + plural: devicepoweroperations + singular: devicepoweroperation + # Status has one writer, the coordinator. With subresource authorization + # enabled, status writes use devicepoweroperations/status.update and + # devicepoweroperations/status.patch instead of updateStatus. + permissions: [list, get, watch, create, update, patch, delete, updateStatus] + subresources: + - name: status + permissions: [update, patch] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/kustomization.yaml b/config/components/device-operations/protected-resources/kustomization.yaml index 7b5e6674..dbf15c50 100644 --- a/config/components/device-operations/protected-resources/kustomization.yaml +++ b/config/components/device-operations/protected-resources/kustomization.yaml @@ -4,4 +4,5 @@ resources: - devicecustody.yaml - deviceinstallation.yaml - devicewipe.yaml + - devicepoweroperation.yaml - devicerecovery.yaml diff --git a/config/components/device-operations/roles/coordinator.yaml b/config/components/device-operations/roles/coordinator.yaml index facbdbdd..009b2766 100644 --- a/config/components/device-operations/roles/coordinator.yaml +++ b/config/components/device-operations/roles/coordinator.yaml @@ -26,6 +26,12 @@ spec: - fleet.datumapis.com/devicewipes.delete - fleet.datumapis.com/devicewipes.updateStatus - fleet.datumapis.com/devicewipes/status.update + - fleet.datumapis.com/devicepoweroperations.get + - fleet.datumapis.com/devicepoweroperations.list + - fleet.datumapis.com/devicepoweroperations.watch + - fleet.datumapis.com/devicepoweroperations.delete + - fleet.datumapis.com/devicepoweroperations.updateStatus + - fleet.datumapis.com/devicepoweroperations/status.update - fleet.datumapis.com/devicerecoveries.get - fleet.datumapis.com/devicerecoveries.list - fleet.datumapis.com/devicerecoveries.watch diff --git a/config/components/device-operations/roles/kustomization.yaml b/config/components/device-operations/roles/kustomization.yaml index 0deb9bd5..8a5c90b2 100644 --- a/config/components/device-operations/roles/kustomization.yaml +++ b/config/components/device-operations/roles/kustomization.yaml @@ -6,3 +6,5 @@ resources: - recovery-operator.yaml - installation-requester.yaml - wipe-requester.yaml + - power-operator.yaml + - power-requester.yaml diff --git a/config/components/device-operations/roles/power-operator.yaml b/config/components/device-operations/roles/power-operator.yaml new file mode 100644 index 00000000..85992605 --- /dev/null +++ b/config/components/device-operations/roles/power-operator.yaml @@ -0,0 +1,13 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-power-operator + annotations: + kubernetes.io/display-name: Fleet Device Power Operator + kubernetes.io/description: Power a Device on or off, or reset it, while no customer holds it. Creates only DevicePowerOperations, and does not read MachineAllocations. +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-device-operations-viewer + includedPermissions: + - fleet.datumapis.com/devicepoweroperations.create diff --git a/config/components/device-operations/roles/power-requester.yaml b/config/components/device-operations/roles/power-requester.yaml new file mode 100644 index 00000000..f0fd80db --- /dev/null +++ b/config/components/device-operations/roles/power-requester.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-power-requester + annotations: + kubernetes.io/display-name: Fleet Device Power Requester + kubernetes.io/description: The Fleet provider for Metal. Creates DevicePowerOperations from Machine power intent and reads custody. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/devicepoweroperations.create + - fleet.datumapis.com/devicepoweroperations.get + - fleet.datumapis.com/devicepoweroperations.list + - fleet.datumapis.com/devicepoweroperations.watch + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch diff --git a/config/components/device-operations/roles/viewer.yaml b/config/components/device-operations/roles/viewer.yaml index 7a1e5100..a2180ba0 100644 --- a/config/components/device-operations/roles/viewer.yaml +++ b/config/components/device-operations/roles/viewer.yaml @@ -17,6 +17,9 @@ spec: - fleet.datumapis.com/devicewipes.get - fleet.datumapis.com/devicewipes.list - fleet.datumapis.com/devicewipes.watch + - fleet.datumapis.com/devicepoweroperations.get + - fleet.datumapis.com/devicepoweroperations.list + - fleet.datumapis.com/devicepoweroperations.watch - fleet.datumapis.com/devicerecoveries.get - fleet.datumapis.com/devicerecoveries.list - fleet.datumapis.com/devicerecoveries.watch diff --git a/config/components/device-operations/webhook.yaml b/config/components/device-operations/webhook.yaml index 3958a845..b4a7c6a1 100644 --- a/config/components/device-operations/webhook.yaml +++ b/config/components/device-operations/webhook.yaml @@ -20,5 +20,5 @@ webhooks: - apiGroups: [fleet.datumapis.com] apiVersions: [v1alpha1] operations: [CREATE, UPDATE] - resources: [deviceinstallations, devicewipes, devicerecoveries] + resources: [deviceinstallations, devicewipes, devicepoweroperations, devicerecoveries] scope: Namespaced diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 3bb23d60..c6534990 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -641,6 +641,10 @@ spec: serialNumber: {type: string, maxLength: 253} sku: {type: string, maxLength: 253} powerState: {type: string, maxLength: 63} + resetTypes: + type: array + maxItems: 16 + items: {type: string, minLength: 1, maxLength: 63} networkInterfaces: type: array maxItems: 32 diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index 3c5e477b..b8708c56 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -133,10 +133,10 @@ rules: resources: [devicecustodies] verbs: [get, list, watch, create, update, delete] - apiGroups: [fleet.datumapis.com] - resources: [deviceinstallations, devicewipes, devicerecoveries] + resources: [deviceinstallations, devicewipes, devicepoweroperations, devicerecoveries] verbs: [get, list, watch, delete] - apiGroups: [fleet.datumapis.com] - resources: [deviceinstallations/status, devicewipes/status, devicerecoveries/status] + resources: [deviceinstallations/status, devicewipes/status, devicepoweroperations/status, devicerecoveries/status] verbs: [get, update] - apiGroups: [metal.datumapis.com] resources: [machineallocations] diff --git a/config/standalone/site.yaml b/config/standalone/site.yaml index a14c38c8..593a50e3 100644 --- a/config/standalone/site.yaml +++ b/config/standalone/site.yaml @@ -50,7 +50,7 @@ spec: - apiGroups: [fleet.datumapis.com] apiVersions: ["*"] operations: [CREATE, UPDATE] - resources: [deviceinstallations, devicewipes, devicerecoveries] + resources: [deviceinstallations, devicewipes, devicepoweroperations, devicerecoveries] validations: - expression: "request.operation != 'CREATE' || (object.spec.creator.username == request.userInfo.username && object.spec.creator.uid == request.userInfo.uid)" message: spec.creator must be the authenticated caller's username and UID diff --git a/docs/development/README.md b/docs/development/README.md index faf64def..e2a209bb 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -37,6 +37,8 @@ Increment C, the cutover. Every mode allocates, installs and releases on Secret-backed coordinator, its private records and the old executors are deleted, and an allocation's private facts live on its MachineAllocation. The standalone smoke verifies it. The end-to-end failure scenarios (Increment D) are proposed. +The [power kind's control plane](device-custody.md#device-power-operations) +is implemented on the same custody, and nothing creates power operations yet. The opt-in [multi-plane acceptance harness](../operations/multiplane.md) composes the [local VM site](../operations/local-vm.md) with native Milo project APIs, the diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 9e7cd13d..764713f1 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -16,10 +16,12 @@ marked **implemented and verified**, **implemented and inert**, or | B: site execution | Per-Device fence store and journal, older-worker stop with a confirmation, deadlines, fenced typed results, per-Device credentials, pinned TLS, identity checks, the handoff payload, the site fence report, and the Redfish install and wipe phases behind the worker contract | **Implemented and verified.** Unit tested, including against TLS BMC stubs. Increment C delivers to it. | | C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the delivery loop, the simulator, local VM and Redfish sites, the creator webhook in the production Milo root, the manager's power projector, and deletion of the Secret-backed records and executors. See [Cutover](#cutover-increment-c). | **Implemented.** Verified by unit tests, tests against a real API server, and the standalone smoke (`task standalone:test`). Verification of the two multi-plane runs, local VM and Redfish, is pending. | | D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests | **Proposed** | +| 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 fills the reset-type field in a separate change. | +| Power P2 to P4 | The site worker (on B), customer power from `Machine.spec.powerState` (on C), and the UI | **Proposed** | ## What Increment A adds -- **Kinds.** `DeviceCustody` and three operation kinds in +- **Kinds.** `DeviceCustody` and the operation kinds in `fleet.datumapis.com`, served only in provider project control planes. The component that registers them, with their ProtectedResources, roles and webhook, is in the production Milo root. The synthetic Milo root has it @@ -512,6 +514,7 @@ Each decision lists the open point from the implementation brief it settles. | --- | --- | | `DeviceInstallation` | 40 minutes, the Redfish executor's install bound | | `DeviceWipe` | 40 minutes, the Redfish executor's cleanup bound | +| `DevicePowerOperation` | 8 minutes: the two-minute start-by window, four BMC requests of at most 30 seconds, the three-minute observation, and a minute of margin | | `DeviceRecovery` | 10 minutes to collect the sites' fence reports | The worker stops at the deadline exactly (Increment B). The coordinator @@ -877,6 +880,55 @@ Test the kind with the shared harness in `internal/custody`: register it beside the defaults, and run its refusals, admission, results and holds against a real API server. +## Device power operations + +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 +`TestEveryOperationKindIsGoverned` requires every operation kind to be +governed. + +| Piece | Decision | +| --- | --- | +| Inputs | `action` is `On`, `ForceOff`, `ForceRestart` or `PowerCycle`. A staff operation requires `expectedSystemUUID`, in lowercase canonical form. Its reason is the envelope's `serviceRequest.reason`, which is already required, rather than a second field. A provider operation omits `expectedSystemUUID` and requires `machineGeneration`. CEL enforces both. | +| Names | The kind's rule is a generated name, which the staff rows use. The provider row sets its own rule: `-power-`, so its allocation name is at most 200 characters. A retry takes the foundation's retry name, and a staff retry created before its `Retry` waits in `Pending`. | +| Rows | The Fleet provider for Metal, with `allocationRef`, from holder `Allocation`, queued. Staff, with `serviceRequest`, from holder `None`, and from `Service` only to settle a power hold. | +| Admission checks | `SystemUUIDMismatch` compares `expectedSystemUUID` with the recorded UUID. `DiscoveryNotCurrent` requires the inventory read to come from the current BMC endpoint, within twice the discovery interval on the injected clock, and to include the recorded system. `ResetTypeNotOffered` requires that system to offer the action. `SystemUUIDNotRecorded` refuses a staff request for a Device with no recorded UUID. These run before rules 5 and 6, so their reasons are the ones reported. | +| Snapshot | `resetTypes`, the power actions the system offered; `systemID`; and `resetTypesObservedAt`, when discovery read them. | +| Replacement | The kind sets `Supersedes`, so a newer pending provider operation for the same allocation replaces an older one. It never replaces another kind's operation or the operation that settles a hold. Under a hold, newer operations wait in `Pending`. Only an operation the provider row admits replaces anything, so staff requests, and a staff request naming a customer's allocation, replace nothing. | +| Holds | A power success settles only a power hold, and only after a `DeviceRecovery` with `Retry`. Power is `Retryable`. | +| Settle | The Device's discovery must have read the BMC after the held operation ended, from its current endpoint, and read the recorded system `On` or `Off`. The recovery must cite that state in `evidence.data.powerState`, with an `observedAt` after the operation ended. Otherwise the recovery ends `Failed` with `PowerEvidenceNotCurrent`, `PowerEvidenceWrongEndpoint`, `PowerStateNotSettled` or `PowerEvidenceMismatch`. | +| Evidence | `requestSentAt`, `power.before`, `power.after` and `resetEvidence`, typed in the CRD and decoded strictly, at most 1 KiB, and required for a `Succeeded` result. Observations are in time order. `resetEvidence` needs a sent command, and only a restart or power cycle may carry it. They are recorded in `status.evidence`, where every kind's evidence lives, not at the top level of status as #173's example shows. | +| 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. This change adds only that field, in the Go type and the CRD. BMC discovery starts recording it, with GETs only, in a separate change. Until then every action is refused with `ResetTypeNotOffered`. | + +The worker reasons `Stale`, `NotPoweredOn` and `PowerStateNotSettled` before +a command, the start-by window and the journal payload arrive with the worker +in B. + +### Gaps that remain + +Both need a change in the foundation, and neither is worked around here. + +- **A kind check cannot wait.** Rule 7 now runs before rule 5, and a kind + check can only refuse. A provider power operation whose discovery is not + current therefore ends `Failed` with `DiscoveryNotCurrent`. #174 says it + waits in `Pending`, as it did when rule 5 refused it first. Because a + provider operation is named from the Machine generation, a short discovery + lapse fails that generation's power change for good: it is not created + again until the generation changes. +- **The evidence hook does not see the result's phase.** It also validates + `Failed` and `OutcomeUnknown` evidence, where the server did not change. So + it cannot require what only a success must prove: reset proof for a restart + or power cycle, and `power.after` in the requested state. A `Succeeded` + restart with no reset proof is accepted, and so is a `Succeeded` result + whose evidence is the empty object `{}`. + ## Tests Run `task test:envtest`. It runs these tests with the race detector against @@ -899,6 +951,8 @@ a real API server: | Seams, rows, principals, ordering, evidence bounds, capacity for every input | `TestRegistryRejectsIncompleteKindsAndRows`, `TestAddingRowsLeavesExistingRowsAlone`, `TestPrincipals`, `TestCandidatesOrderOldestFirstWithADeterministicTieBreak`, `TestEvidenceIsTypedAndBounded`, `TestCapacityProjection` | | Creator recording and caller preservation | `TestHandler`, `TestCreatorAgainstAPIServer` | | CRD contract, roles, and that nothing ships the component or the test-only kinds | `TestCRDContract`, `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`, `TestComponentIsInert` | +| 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 | `TestPowerOperations` | +| Power: CEL inputs and evidence pruning, checks, input digest, evidence bounds, registration | `TestPowerCRDRules`, `TestPowerChecks`, `TestPowerInputDigestIsStable`, `TestPowerEvidenceIsTypedAndBounded`, `TestPowerRegistration` | Increment A has no site, so "nothing was sent" means custody admitted nothing and the fence did not rise. Increment D proves it with the lab BMC audit. diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index 3c2e50f1..f4eb22fa 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -90,8 +90,8 @@ field or view. as one quiet **Record** line ("Record example-rack-a01 · created 2026-10-01"), plus any fact the page shows nowhere else. The namespace (always `default`), the UID and a per-record verification row are not - shown. No page has a History tab; it returns when an activity timeline - exists. The breadcrumb is the way back; there is no separate back link. + shown. No page has a general History tab; it returns when an activity + timeline exists. A Device's Operations tab lists its power operations. The breadcrumb is the way back; there is no separate back link. 2. **One primary view per kind**, above the fold: | Kind | Primary view | @@ -831,8 +831,9 @@ plain: there is no green. Every reason is a tooltip and accessible text. "BMC key shared"); else "BMC ?" in amber. - **Hardware: expected next to observed.** When discovery has read a System, a Field | Expected | Observed table replaces the reported model - and system UUID facts: Serial, Model, Manufacturer, System UUID, SKU and - Power (Redfish `powerState` as a short word). Expected is `spec.identity` + and system UUID facts: Serial, Model, Manufacturer, System UUID and SKU. + The observed power state is in the header strip (see + [Device page: power](#device-page-power-implemented-in-the-ui)). Expected is `spec.identity` and is blank where spec does not record the field. The compared System is the one reporting the spec system UUID, else the spec serial (as serial number or SKU), else the only System; with several candidates the table is @@ -893,6 +894,81 @@ Cables. `inventory-record-layout.test.tsx` covers the drawn and tiled pictures on the fixture pages, the header strip and the Edit button's description. +### Device page: power (implemented in the UI) + +Staff power a Device on or off, or reset it, from the Device page by creating a +staff `DevicePowerOperation` (proposed in #173; the kind is in #179). The UI is +implemented and tested against synthetic data. Its effects are not: no site +worker runs power operations yet, and discovery does not record reset types +yet, so on real servers the control stays disabled. The coordinator decides +admission. The page repeats only the checks its records show; discovery age +is left to the coordinator, because the page does not know the configured +discovery interval. + +- **Header.** The identity strip shows **Power** with the observed state of the + System discovery compares (amber when read from another endpoint). The latest + power operation follows it as a badge while it runs, for an hour after it + ends, and while custody holds it for an unknown outcome. +- **Power button.** It sits in the header actions. Users for whom a + SelfSubjectAccessReview does not allow `create` on `devicepoweroperations` in + `default` do not see it. The answer is cached and rechecked on + **Refresh inventory**, like the inventory management checks. The button is + disabled, with the reason as its tooltip and accessible description, when: + discovery has not read the inventory, read another BMC endpoint, or has not + read the System with the recorded system UUID; no system UUID is recorded; + the System offers no power action; IdentityMatched is not True at the + Device's generation; the BMC key was not read at the recorded endpoint, or + another Device shares it; custody is missing, unreadable or + Unverified; the holder is `Allocation` or `Release` ("Allocated to a + customer") or `Retired`; custody has a recovery hold ("Held") or an active + operation; the holder is `Service` without either; a power operation for the + Device has not ended; the caller's + identity or the operations list cannot be read. +- **Dialog.** The user chooses an action and enters a required reason (at + most 512 characters). The actions are those the System with the recorded + system UUID lists in `resetTypes`, in the order On, Force off, Force restart, + Power cycle. `ForceOff`, `ForceRestart` and `PowerCycle` ask again: the + confirmation and its button name the server ("Force restart Compute + a01-01"). +- **Request.** One POST with `metadata.generateName`, the + `fleet.datumapis.com/device-uid` label set to the Device's UID, `spec.creator` + set to the caller's username and UID from a SelfSubjectReview through the + same proxy, `spec.deviceRef` with the Device's name, + `spec.authority.serviceRequest.reason`, `spec.action`, and + `spec.expectedSystemUUID` set to the recorded system UUID in lower case. The + creator is the only object UID in the spec. No field is typed by hand except + the reason. A denied (401, 403) or rejected + (422) create, or a failure before the POST is sent, reports that nothing + was created. Any other failure after sending is an unknown outcome: because + the name is generated, a second POST would be a second operation, so the + control stays disabled until the Device page is opened again. As in the + location correction, leaving the page, a session or navigation change, or a + changed Device closes an open request without sending it. +- **Operations tab.** Up to 20 power operations for the Device, newest first: + Time, Action, Result, Power (before → after, with when the command was sent + and the reset evidence as the tooltip), Creator, Reason. The tab carries the + count, or an amber `?` when the list is unreadable. Results: Pending, + Admitted, Sent and Verifying (dashed); Succeeded (plain); Refused (red, a + `Failed` that sent no command) or Failed (red, sent); Expired (amber, + `Cancelled` with `Expired`) or Cancelled (amber); Outcome unknown (red), + with "· held" and the hold time when custody's hold names that operation's + kind and name and the fence it was admitted at. A same-name operation + created later has no admission at that fence, so it is never shown as held. + The reason and message are the tooltip. +- **Updates.** Operations and custody are polled every 10 seconds, and every + 2 seconds while an operation runs; a failed read keeps polling. Operations + are listed with a selector on the Device's `device-uid` label, and kept only + when they name the Device. Custody counts as the Device's only when its + `device-uid` label is the Device's UID. + +Fixture builds grant the power permission, use a synthetic caller, and keep a +created operation in memory as `Pending`; nothing is sent. a01-01 is free with +a history covering each result, a01-02 is allocated, and a01-05 is held for a +power cycle whose outcome is unknown. `device-power.test.tsx` and +`device-power.test.ts` cover the offered actions, the required reason, the +destructive confirmation, the exact request body, the hidden and each disabled +state, each phase and result, the hold, and the unknown create outcome. + ### Names Views never show a generated resource name (`netbox-ca213d185ea9153b853f295e`, diff --git a/hack/multiplane/custody_crd_rules.py b/hack/multiplane/custody_crd_rules.py index 5de1a16b..a7e7c9a4 100644 --- a/hack/multiplane/custody_crd_rules.py +++ b/hack/multiplane/custody_crd_rules.py @@ -18,7 +18,7 @@ # controller to finish deleting one. namespace = 'fleet-rules' objects = (('devicerecovery', 'rules-recovery'), ('devicecustody', 'server-example-001')) -names = ('devicecustodies', 'deviceinstallations', 'devicewipes', 'devicerecoveries') +names = ('devicecustodies', 'deviceinstallations', 'devicewipes', 'devicepoweroperations', 'devicerecoveries') def kubectl(*args, stdin=None, check=True): diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index a7d01022..6113d962 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -53,7 +53,7 @@ def device_dir(device=DEVICE): FINAL_STEPS = {'DeviceInstallation': ('disk-verified',), 'DeviceWipe': ('wipe', 'wipe-verified')} # Provider-project custody records, read with the provider's bootstrap credential. CUSTODY_KINDS = ('devicecustodies.fleet.datumapis.com', 'deviceinstallations.fleet.datumapis.com', 'devicewipes.fleet.datumapis.com', - 'devicerecoveries.fleet.datumapis.com', 'machineallocations.metal.datumapis.com') + 'devicepoweroperations.fleet.datumapis.com', 'devicerecoveries.fleet.datumapis.com', 'machineallocations.metal.datumapis.com') def now(): diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 5e5ee1c2..fb19b5e2 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -92,8 +92,8 @@ def wait(fn,seconds,what): {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations'],'verbs':['get','list','watch','create']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies'],'verbs':['get','list','watch']}] components={ 'coordinator':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list','watch']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get','list','watch','create','update','delete']}, - {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicerecoveries'],'verbs':['get','list','watch','delete']}, - {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicerecoveries/status'],'verbs':['get','update']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicepoweroperations','devicerecoveries'],'verbs':['get','list','watch','delete']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicepoweroperations/status','devicerecoveries/status'],'verbs':['get','update']}, {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}], 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}], 'discovery':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices/status'],'verbs':['get','update']}]} diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index dfdd281b..fa1f2f9b 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -52,7 +52,7 @@ for crd in installations machineallocations machinecapacities machineclasses mac exit 1 fi done -for crd in devices devicecustodies deviceinstallations devicewipes devicerecoveries; do +for crd in devices devicecustodies deviceinstallations devicewipes devicepoweroperations devicerecoveries; do if kubectl --context "$context" get crd "$crd.fleet.datumapis.com" >/dev/null 2>&1; then echo "fixed Fleet CRD $crd already exists; use a fresh dedicated kind cluster" >&2 exit 1 @@ -143,7 +143,7 @@ test "$(kubectl --context "$context" -n fleet-project-b get machine allocation - for project in fleet-project-a fleet-project-b; do subject="system:serviceaccount:$project:default" - for resource in devicecustodies deviceinstallations devicewipes devicerecoveries machineallocations; do + for resource in devicecustodies deviceinstallations devicewipes devicepoweroperations devicerecoveries machineallocations; do for verb in get list watch create update patch delete; do if [ "$(kubectl --context "$context" auth can-i "$verb" "$resource" --as="$subject" -n fleet-provider)" != "no" ]; then echo "$subject unexpectedly has $verb access to $resource" >&2 diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 973e9433..562a23f9 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -256,7 +256,8 @@ type ObservedManager struct { } // ObservedSystem is one Redfish ComputerSystem. PowerState is an observation -// only; discovery never changes power. +// only; discovery never changes power. ResetTypes are the ComputerSystem.Reset +// types the BMC advertises for the System, read but never invoked. type ObservedSystem struct { ID string `json:"id"` UUID string `json:"uuid,omitempty"` @@ -266,6 +267,7 @@ type ObservedSystem struct { SKU string `json:"sku,omitempty"` PowerState string `json:"powerState,omitempty"` NetworkInterfaces []ObservedNetworkInterface `json:"networkInterfaces,omitempty"` + ResetTypes []string `json:"resetTypes,omitempty"` } // ObservedNetworkInterface is one Redfish EthernetInterface. diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index 815171f7..e8b37bcc 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -7,6 +7,7 @@ import ( "io/fs" "os" "path/filepath" + "reflect" "slices" "strings" "testing" @@ -20,7 +21,7 @@ import ( var ( configRoot = filepath.Join("..", "..", "..", "..", "config") componentRoot = filepath.Join(configRoot, "components", "device-operations") - operationKinds = []string{"DeviceInstallation", "DeviceWipe", "DeviceRecovery"} + operationKinds = []string{"DeviceInstallation", "DeviceWipe", "DevicePowerOperation", "DeviceRecovery"} ) func decodeAll[T any](t *testing.T, path string) []T { @@ -69,8 +70,8 @@ func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { func TestCRDContract(t *testing.T) { crds := loadCRDs(t) - if len(crds) != 4 || crds["DeviceCustody"] == nil { - t.Fatalf("got %d CRDs, want DeviceCustody and three operation kinds", len(crds)) + if len(crds) != 1+len(operationKinds) || crds["DeviceCustody"] == nil { + t.Fatalf("got %d CRDs, want DeviceCustody and %d operation kinds", len(crds), len(operationKinds)) } for kind, crd := range crds { version := crd.Spec.Versions[0] @@ -114,6 +115,36 @@ func TestCRDContract(t *testing.T) { if len(bootstrap.Properties) != 2 || bootstrap.Properties["ref"].Type != "string" || bootstrap.Properties["digest"].Pattern == "" { t.Fatalf("bootstrap = %+v", bootstrap.Properties) } + // Every operation kind repeats the same envelope and shared status, so a + // field the coordinator writes, such as status.admission, is never pruned + // from one kind. + reference := crds["DeviceWipe"].Spec.Versions[0].Schema.OpenAPIV3Schema + for _, kind := range operationKinds { + schema := crds[kind].Spec.Versions[0].Schema.OpenAPIV3Schema + for _, field := range []string{"creator", "deviceRef", "authority"} { + if !reflect.DeepEqual(schema.Properties["spec"].Properties[field], reference.Properties["spec"].Properties[field]) { + t.Fatalf("%s spec.%s differs from the shared envelope", kind, field) + } + } + for field, want := range reference.Properties["status"].Properties { + if got, ok := schema.Properties["status"].Properties[field]; field != "evidence" && (!ok || !reflect.DeepEqual(got, want)) { + t.Fatalf("%s status.%s differs from the shared status", kind, field) + } + } + } + // Power evidence is typed, so the API server prunes anything else. + power := crds["DevicePowerOperation"].Spec.Versions[0].Schema.OpenAPIV3Schema + evidence := power.Properties["status"].Properties["evidence"] + if evidence.XPreserveUnknownFields != nil || len(evidence.Properties) != 3 || len(evidence.Properties["power"].Properties) != 2 || len(evidence.Properties["resetEvidence"].Enum) != 2 { + t.Fatalf("power evidence = %+v", evidence) + } + rules := map[string]bool{} + for _, rule := range power.Properties["spec"].XValidations { + rules[rule.Rule] = true + } + if !rules["has(self.authority.serviceRequest) == has(self.expectedSystemUUID)"] || !rules["has(self.authority.allocationRef) == has(self.machineGeneration)"] { + t.Fatalf("power spec rules = %v", power.Properties["spec"].XValidations) + } } type protectedResource struct { @@ -188,13 +219,15 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { group := GroupVersion.Group + "/" read := []string{"get", "list", "watch"} want := map[string][]string{ - "fleet.datumapis.com-device-operations-viewer": slices.Concat(p(group+"devicecustodies", read...), p(group+"deviceinstallations", read...), p(group+"devicewipes", read...), p(group+"devicerecoveries", read...)), + "fleet.datumapis.com-device-operations-viewer": slices.Concat(p(group+"devicecustodies", read...), p(group+"deviceinstallations", read...), p(group+"devicewipes", read...), p(group+"devicepoweroperations", read...), p(group+"devicerecoveries", read...)), + "fleet.datumapis.com-device-power-operator": p(group+"devicepoweroperations", "create"), + "fleet.datumapis.com-device-power-requester": slices.Concat(p(group+"devicepoweroperations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), "fleet.datumapis.com-device-recovery-operator": slices.Concat(p(group+"devicerecoveries", "create"), p("metal.datumapis.com/machineallocations", read...)), "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), } coordinator := slices.Concat(p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...)) - for _, plural := range []string{"deviceinstallations", "devicewipes", "devicerecoveries"} { + for _, plural := range []string{"deviceinstallations", "devicewipes", "devicepoweroperations", "devicerecoveries"} { coordinator = slices.Concat(coordinator, p(group+plural, "get", "list", "watch", "delete", "updateStatus"), []string{group + plural + "/status.update"}) } want["fleet.datumapis.com-device-coordinator"] = coordinator @@ -213,9 +246,9 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { t.Fatalf("%s = %v, want %v", name, actual, expected) } inherits := len(current.Spec.Inherited) != 0 - if name == "fleet.datumapis.com-device-recovery-operator" { + if name == "fleet.datumapis.com-device-recovery-operator" || name == "fleet.datumapis.com-device-power-operator" { if len(current.Spec.Inherited) != 1 || current.Spec.Inherited[0].Name != "fleet.datumapis.com-device-operations-viewer" { - t.Fatal("the recovery operator inherits only the viewer") + t.Fatalf("%s inherits only the viewer", name) } } else if inherits { t.Fatalf("%s must not inherit", name) @@ -233,12 +266,24 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { } } } - // Staff can never create provider or release kinds. - for _, staff := range []string{"fleet.datumapis.com-device-operations-viewer", "fleet.datumapis.com-device-recovery-operator"} { - for _, permission := range roles[staff].Spec.Included { - if strings.HasSuffix(permission, ".create") && permission != group+"devicerecoveries.create" { + // Each staff role creates at most its own kind, and never a provider or + // release kind. Staff power does not read MachineAllocations. + for staff, own := range map[string]string{ + "fleet.datumapis.com-device-operations-viewer": "", + "fleet.datumapis.com-device-recovery-operator": group + "devicerecoveries.create", + "fleet.datumapis.com-device-power-operator": group + "devicepoweroperations.create", + } { + permissions := slices.Clone(roles[staff].Spec.Included) + for _, inherited := range roles[staff].Spec.Inherited { + permissions = append(permissions, roles[inherited.Name].Spec.Included...) + } + for _, permission := range permissions { + if strings.HasSuffix(permission, ".create") && permission != own { t.Fatalf("%s may create %s", staff, permission) } + if staff == "fleet.datumapis.com-device-power-operator" && strings.Contains(permission, "machineallocations") { + t.Fatalf("%s reads %s", staff, permission) + } } } } diff --git a/internal/api/operations/v1alpha1/power.go b/internal/api/operations/v1alpha1/power.go new file mode 100644 index 00000000..a809f3f7 --- /dev/null +++ b/internal/api/operations/v1alpha1/power.go @@ -0,0 +1,113 @@ +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// DevicePowerOperation powers a Device on or off, or resets it, with one +// command, as proposed in datum-cloud/fleet#173. Staff create it with a +// serviceRequest; the Fleet provider for Metal creates it with an +// allocationRef from Machine power intent. +type DevicePowerOperation struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DevicePowerOperationSpec `json:"spec"` + Status OperationStatus `json:"status,omitempty"` +} + +// PowerAction is the one command a power operation sends. Each value is the +// Redfish ComputerSystem.Reset type of the same name. +type PowerAction string + +const ( + PowerOn PowerAction = "On" + PowerForceOff PowerAction = "ForceOff" + PowerForceRestart PowerAction = "ForceRestart" + PowerCycle PowerAction = "PowerCycle" +) + +// PowerActions is every action, in the order the staff menu lists them. +var PowerActions = []PowerAction{PowerOn, PowerForceOff, PowerForceRestart, PowerCycle} + +// Resets reports whether the action resets a running server. +func (a PowerAction) Resets() bool { return a == PowerForceRestart || a == PowerCycle } + +type DevicePowerOperationSpec struct { + OperationEnvelope `json:",inline"` + Action PowerAction `json:"action"` + // ExpectedSystemUUID is the server staff expect behind the BMC. A staff + // operation requires it, with serviceRequest.reason; a provider + // operation omits it. + ExpectedSystemUUID string `json:"expectedSystemUUID,omitempty"` + // MachineGeneration is the Machine generation whose power intent a + // provider operation carries out. The name is derived from it, so a + // refused operation is not created again until the generation changes. + // A staff operation omits it. + MachineGeneration int64 `json:"machineGeneration,omitempty"` +} + +// ObservedPowerState is a Redfish ComputerSystem PowerState. +type ObservedPowerState string + +const ( + PowerStateOn ObservedPowerState = "On" + PowerStateOff ObservedPowerState = "Off" + PowerStatePoweringOn ObservedPowerState = "PoweringOn" + PowerStatePoweringOff ObservedPowerState = "PoweringOff" + PowerStatePaused ObservedPowerState = "Paused" +) + +// Settled reports whether the state is one a power result or a recovery can +// rest on: On or Off. +func (s ObservedPowerState) Settled() bool { return s == PowerStateOn || s == PowerStateOff } + +// ResetEvidence is how the worker proved a restart or power cycle happened. +type ResetEvidence string + +const ( + // ResetLastResetTime means the BMC reported a reset after the request. + ResetLastResetTime ResetEvidence = "LastResetTime" + // ResetObservedOff means the worker saw the server off. + ResetObservedOff ResetEvidence = "ObservedOff" +) + +// PowerEvidence is the result evidence of a DevicePowerOperation. It never +// carries a credential or BMC response content. +type PowerEvidence struct { + // RequestSentAt is when the one command was sent. Absent if none was. + RequestSentAt *metav1.Time `json:"requestSentAt,omitempty"` + // Power is the state the worker read before the command and at the end. + Power *PowerObservations `json:"power,omitempty"` + // ResetEvidence is set for a restart or power cycle the worker proved. + ResetEvidence ResetEvidence `json:"resetEvidence,omitempty"` +} + +type PowerObservations struct { + Before *PowerObservation `json:"before,omitempty"` + After *PowerObservation `json:"after,omitempty"` +} + +// PowerObservation is one read of the server's power state. +type PowerObservation struct { + State ObservedPowerState `json:"state"` + ObservedAt metav1.Time `json:"observedAt"` +} + +type DevicePowerOperationList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DevicePowerOperation `json:"items"` +} + +func (in *DevicePowerOperation) Envelope() *OperationEnvelope { return &in.Spec.OperationEnvelope } +func (in *DevicePowerOperation) OperationStatus() *OperationStatus { return &in.Status } +func (in *DevicePowerOperation) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DevicePowerOperationList) DeepCopyObject() runtime.Object { + return deepCopy(in) +} + +func addPower(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &DevicePowerOperation{}, &DevicePowerOperationList{}) + return nil +} diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 40190461..d1b3b685 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -460,6 +460,9 @@ type DeviceRecoveryList struct { func addKnown(s *runtime.Scheme) error { s.AddKnownTypes(GroupVersion, &DeviceCustody{}, &DeviceCustodyList{}, &DeviceInstallation{}, &DeviceInstallationList{}, &DeviceWipe{}, &DeviceWipeList{}, &DeviceRecovery{}, &DeviceRecoveryList{}) + if err := addPower(s); err != nil { + return err + } metav1.AddToGroupVersion(s, GroupVersion) return nil } diff --git a/internal/custody/creatorwebhook/handler.go b/internal/custody/creatorwebhook/handler.go index e615cd53..a55ef77d 100644 --- a/internal/custody/creatorwebhook/handler.go +++ b/internal/custody/creatorwebhook/handler.go @@ -27,7 +27,7 @@ import ( const Path = "/validate-operation-creator" // Resources are the operation plurals whose creator the webhook governs. -var Resources = []string{"deviceinstallations", "devicewipes", "devicerecoveries"} +var Resources = []string{"deviceinstallations", "devicewipes", "devicepoweroperations", "devicerecoveries"} // Handler admits creates whose creator is the caller and updates that leave // the creator unchanged. diff --git a/internal/custody/creatorwebhook/resources_test.go b/internal/custody/creatorwebhook/resources_test.go new file mode 100644 index 00000000..dd21c5f3 --- /dev/null +++ b/internal/custody/creatorwebhook/resources_test.go @@ -0,0 +1,86 @@ +package creatorwebhook + +import ( + "bufio" + "bytes" + "io" + "os" + "path/filepath" + "slices" + "testing" + + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/util/yaml" +) + +// TestEveryOperationKindIsGoverned requires the webhook's Go resource list, +// the packaged webhook, and standalone's admission policy to name every +// operation kind the custody CRDs define, so a new kind cannot ship with an +// unchecked creator. +func TestEveryOperationKindIsGoverned(t *testing.T) { + root := filepath.Join("..", "..", "..") + var kinds []string + for _, document := range documents(t, filepath.Join(root, "config", "components", "device-operations", "crds", "fleet.datumapis.com.yaml")) { + var crd extensionsv1.CustomResourceDefinition + if err := yaml.Unmarshal(document, &crd); err != nil { + t.Fatal(err) + } + if crd.Spec.Names.Kind != "DeviceCustody" { + kinds = append(kinds, crd.Spec.Names.Plural) + } + } + want := sorted(kinds) + if got := sorted(Resources); !slices.Equal(got, want) { + t.Fatalf("Resources = %v, want every operation kind %v", got, want) + } + var webhooks admissionregistrationv1.ValidatingWebhookConfiguration + if err := yaml.Unmarshal(documents(t, filepath.Join(root, "config", "components", "device-operations", "webhook.yaml"))[0], &webhooks); err != nil { + t.Fatal(err) + } + if got := sorted(webhooks.Webhooks[0].Rules[0].Resources); !slices.Equal(got, want) { + t.Fatalf("the packaged webhook governs %v, want %v", got, want) + } + found := false + for _, document := range documents(t, filepath.Join(root, "config", "standalone", "site.yaml")) { + var policy admissionregistrationv1.ValidatingAdmissionPolicy + if yaml.Unmarshal(document, &policy) != nil || policy.Kind != "ValidatingAdmissionPolicy" || policy.Name != "fleet-operation-creator" { + continue + } + found = true + if got := sorted(policy.Spec.MatchConstraints.ResourceRules[0].Resources); !slices.Equal(got, want) { + t.Fatalf("the standalone creator policy governs %v, want %v", got, want) + } + } + if !found { + t.Fatal("standalone has no fleet-operation-creator policy") + } +} + +func sorted(values []string) []string { + out := slices.Clone(values) + slices.Sort(out) + return out +} + +func documents(t *testing.T, path string) [][]byte { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + reader := yaml.NewYAMLReader(bufio.NewReader(bytes.NewReader(data))) + var out [][]byte + for { + document, err := reader.Read() + if err == io.EOF { + return out + } + if err != nil { + t.Fatal(err) + } + if len(bytes.TrimSpace(document)) != 0 { + out = append(out, document) + } + } +} diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 19ab1a19..0b39f8ac 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -328,12 +328,12 @@ func applyRecovery(ctx context.Context, apply *ApplyContext) (*ops.DeviceCustody // for them. func DefaultRegistry() (*Registry, error) { registry := NewRegistry() - for _, kind := range []Kind{DeviceInstallationKind(), DeviceWipeKind(), DeviceRecoveryKind()} { + for _, kind := range []Kind{DeviceInstallationKind(), DeviceWipeKind(), DevicePowerOperationKind(), DeviceRecoveryKind()} { if err := registry.Register(kind); err != nil { return nil, err } } - for _, rule := range DefaultRules() { + for _, rule := range slices.Concat(DefaultRules(), PowerRules()) { if err := registry.AddRule(rule); err != nil { return nil, err } @@ -341,7 +341,8 @@ func DefaultRegistry() (*Registry, error) { return registry, nil } -// DefaultRules is the operations table of #174 for the built-in kinds. +// DefaultRules is the operations table of #174 for installation, wipe and +// recovery. PowerRules holds the power rows. func DefaultRules() []Rule { return []Rule{ {Kind: "DeviceInstallation", Creator: CreatorMetalProvider, Authority: AuthorityAllocation, Holders: []ops.HolderType{ops.HolderAllocation}, Queue: true}, diff --git a/internal/custody/power.go b/internal/custody/power.go new file mode 100644 index 00000000..1308b319 --- /dev/null +++ b/internal/custody/power.go @@ -0,0 +1,269 @@ +package custody + +import ( + "context" + "errors" + "slices" + "strconv" + "strings" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// PowerDeadline bounds one power operation at the site: the two-minute +// start-by window, four BMC requests of at most 30 seconds each, the +// 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. +const ( + ReasonSystemUUIDNotRecorded = "SystemUUIDNotRecorded" + ReasonSystemUUIDMismatch = "SystemUUIDMismatch" + ReasonDiscoveryNotCurrent = "DiscoveryNotCurrent" + ReasonResetTypeNotOffered = "ResetTypeNotOffered" + // The reasons a DeviceRecovery Settle of a power hold is refused with. + ReasonPowerEvidenceNotCurrent = "PowerEvidenceNotCurrent" + ReasonPowerEvidenceWrongEndpoint = "PowerEvidenceWrongEndpoint" + ReasonPowerStateNotSettled = "PowerStateNotSettled" + ReasonPowerEvidenceMismatch = "PowerEvidenceMismatch" +) + +// Snapshot fields power adds at admission. +const ( + SnapshotResetTypes = "resetTypes" + SnapshotSystemID = "systemID" + SnapshotResetTypesObservedAt = "resetTypesObservedAt" +) + +// SettlePowerState is the DeviceRecovery evidence field that cites the +// settled power state discovery read. +const SettlePowerState = "powerState" + +const powerEvidenceLimit = 1024 + +// PowerName is the only name a provider power operation may have: its +// allocation and the Machine generation whose power intent it carries out. +func PowerName(allocation string, machineGeneration int64) string { + return allocation + "-power-" + strconv.FormatInt(machineGeneration, 10) +} + +func providerPowerName(operation ops.Operation) string { + return PowerName(allocationName(operation), operation.(*ops.DevicePowerOperation).Spec.MachineGeneration) +} + +// DevicePowerOperationKind is the registry entry for DevicePowerOperation. +func DevicePowerOperationKind() Kind { + return Kind{ + GVK: gv.WithKind("DevicePowerOperation"), + New: func() ops.Operation { return &ops.DevicePowerOperation{} }, + NewList: func() client.ObjectList { return &ops.DevicePowerOperationList{} }, + Items: func(list client.ObjectList) []ops.Operation { + return items(list.(*ops.DevicePowerOperationList).Items) + }, + Digest: func(operation ops.Operation) (string, error) { + return SpecDigest(operation.(*ops.DevicePowerOperation).Spec) + }, + // Staff operations have generated names. The provider row names its + // operations from the Machine generation instead. + Naming: GeneratedName, + Deadline: PowerDeadline, + Effectful: true, + // A newer pending provider operation for the same allocation + // replaces an older one, so only the latest power intent runs. + Supersedes: true, + Check: checkPower, + // A power success settles only a power hold, and only after a + // DeviceRecovery with Retry. It settles no other kind's hold. + Settles: []SettleRule{{Held: "DevicePowerOperation", RequiresRetry: true}}, + Retryable: true, + Reasons: []Reason{ + {Name: ReasonSystemUUIDNotRecorded, RaisedBy: RaisedByCoordinator}, + {Name: ReasonSystemUUIDMismatch, RaisedBy: RaisedByBoth}, + {Name: ReasonDiscoveryNotCurrent, RaisedBy: RaisedByCoordinator}, + {Name: ReasonResetTypeNotOffered, RaisedBy: RaisedByBoth}, + {Name: ReasonPowerEvidenceNotCurrent, RaisedBy: RaisedByCoordinator}, + {Name: ReasonPowerEvidenceWrongEndpoint, RaisedBy: RaisedByCoordinator}, + {Name: ReasonPowerStateNotSettled, RaisedBy: RaisedByCoordinator}, + {Name: ReasonPowerEvidenceMismatch, RaisedBy: RaisedByCoordinator}, + }, + SnapshotExtra: powerSnapshot, + Evidence: StrictEvidence(powerEvidenceLimit, validatePowerEvidence), + EvidenceRequired: true, + RecoverySettle: settlePower, + } +} + +// PowerRules are the two power rows of the #174 operations table. The staff +// row "None, or Service under a power hold" is two rows. +func PowerRules() []Rule { + return []Rule{ + {Kind: "DevicePowerOperation", Creator: CreatorMetalProvider, Authority: AuthorityAllocation, Holders: []ops.HolderType{ops.HolderAllocation}, Queue: true, + Naming: DeterministicName, Name: providerPowerName}, + {Kind: "DevicePowerOperation", Creator: CreatorStaff, Authority: AuthorityService, Holders: []ops.HolderType{ops.HolderNone}}, + {Kind: "DevicePowerOperation", Creator: CreatorStaff, Authority: AuthorityService, Holders: []ops.HolderType{ops.HolderService}, Hold: HoldSettlesRequired}, + } +} + +// discoveredSystem returns the system discovery read with the Device's +// recorded system UUID, or nil. +func discoveredSystem(device *inventory.Device) *inventory.ObservedSystem { + discovery := device.Status.Discovery + uuid := device.Spec.Identity.SystemUUID + if discovery == nil || discovery.Inventory == nil || uuid == "" { + return nil + } + for index := range discovery.Inventory.Systems { + if system := &discovery.Inventory.Systems[index]; strings.EqualFold(system.UUID, uuid) { + return system + } + } + return nil +} + +// checkPower is power's rule 7: its own inputs, and the discovery facts +// they are checked against. +func checkPower(_ context.Context, admission *Admission) *Refusal { + power := admission.Operation.(*ops.DevicePowerOperation) + device := admission.Device + recorded := device.Spec.Identity.SystemUUID + if power.Spec.Authority.ServiceRequest != nil { + if recorded == "" { + return refuse(ReasonSystemUUIDNotRecorded, "the Device has no system UUID on record") + } + if !strings.EqualFold(power.Spec.ExpectedSystemUUID, recorded) { + return refuse(ReasonSystemUUIDMismatch, "expectedSystemUUID %s is not the recorded system UUID", power.Spec.ExpectedSystemUUID) + } + } + // The facts below must come from a read of the current BMC within twice + // the discovery interval. + discovery := device.Status.Discovery + maxAge := 2 * admission.DiscoveryInterval + if discovery == nil || discovery.Inventory == nil || device.Spec.BMC == nil || discovery.Inventory.Endpoint != device.Spec.BMC.Endpoint { + return refuse(ReasonDiscoveryNotCurrent, "discovery has not read the inventory at the current BMC endpoint") + } + if age := admission.Now.Sub(discovery.Inventory.ObservedAt.Time); age > maxAge { + return refuse(ReasonDiscoveryNotCurrent, "discovery last read the BMC %s ago; the limit is %s", age.Truncate(time.Second), maxAge) + } + system := discoveredSystem(device) + if system == nil { + return refuse(ReasonDiscoveryNotCurrent, "discovery has not read the system with the recorded UUID") + } + if !slices.Contains(system.ResetTypes, string(power.Spec.Action)) { + return refuse(ReasonResetTypeNotOffered, "the BMC does not offer %s for system %s", power.Spec.Action, system.ID) + } + return nil +} + +// powerSnapshot records what the reset-type check read: the power actions +// the system offered, the system, and when discovery read them. +func powerSnapshot(admission *Admission) map[string]string { + system := discoveredSystem(admission.Device) + if system == nil { + return nil + } + var offered []string + for _, action := range ops.PowerActions { + if slices.Contains(system.ResetTypes, string(action)) { + offered = append(offered, string(action)) + } + } + return map[string]string{ + SnapshotResetTypes: strings.Join(offered, ","), + SnapshotSystemID: system.ID, + SnapshotResetTypesObservedAt: admission.Device.Status.Discovery.Inventory.ObservedAt.UTC().Format(time.RFC3339), + } +} + +// validatePowerEvidence bounds power result evidence and checks it against +// the operation's action. The hook does not see the result's phase, so it +// checks only what holds for a success and a refusal alike. +func validatePowerEvidence(operation ops.Operation, evidence *ops.PowerEvidence) error { + observation := func(name string, value *ops.PowerObservation) error { + if value == nil { + return nil + } + switch value.State { + case ops.PowerStateOn, ops.PowerStateOff, ops.PowerStatePoweringOn, ops.PowerStatePoweringOff, ops.PowerStatePaused: + default: + return errors.New("power." + name + ".state is not a Redfish power state") + } + if value.ObservedAt.IsZero() { + return errors.New("power." + name + ".observedAt is required") + } + return nil + } + var before, after *ops.PowerObservation + if evidence.Power != nil { + before, after = evidence.Power.Before, evidence.Power.After + } + if err := observation("before", before); err != nil { + return err + } + if err := observation("after", after); err != nil { + return err + } + sent := evidence.RequestSentAt + switch { + case sent != nil && sent.IsZero(): + return errors.New("requestSentAt is set but empty") + case before != nil && after != nil && after.ObservedAt.Before(&before.ObservedAt): + return errors.New("power.after was observed before power.before") + case sent != nil && before != nil && sent.Before(&before.ObservedAt): + return errors.New("the command was sent before power.before was read") + case sent != nil && after != nil && after.ObservedAt.Before(sent): + return errors.New("power.after was read before the command was sent") + } + switch evidence.ResetEvidence { + case "": + case ops.ResetLastResetTime, ops.ResetObservedOff: + if sent == nil { + return errors.New("resetEvidence needs the command it proves") + } + if action := operation.(*ops.DevicePowerOperation).Spec.Action; !action.Resets() { + return errors.New("resetEvidence proves a restart or power cycle, not " + string(action)) + } + default: + return errors.New("resetEvidence is LastResetTime or ObservedOff") + } + return nil +} + +// settlePower accepts a DeviceRecovery Settle of a power hold only when the +// Device's discovery, read after the held operation ended, from the Device's +// current BMC endpoint, shows a settled power state, and the recovery cites +// that state. +func settlePower(_ context.Context, settle *RecoverySettleContext) *Refusal { + device := settle.Device + if device == nil || device.Spec.BMC == nil || device.Status.Discovery == nil || device.Status.Discovery.Inventory == nil { + return refuse(ReasonPowerEvidenceNotCurrent, "discovery has not read the BMC since the power operation ended") + } + read := device.Status.Discovery.Inventory + if !read.ObservedAt.After(settle.Hold.Since.Time) { + return refuse(ReasonPowerEvidenceNotCurrent, "discovery last read the BMC at %s, before the power operation ended at %s", read.ObservedAt.UTC().Format(time.RFC3339), settle.Hold.Since.UTC().Format(time.RFC3339)) + } + if read.Endpoint != device.Spec.BMC.Endpoint { + return refuse(ReasonPowerEvidenceWrongEndpoint, "discovery read %s, not the Device's current BMC endpoint", read.Endpoint) + } + system := discoveredSystem(device) + if system == nil { + return refuse(ReasonPowerEvidenceNotCurrent, "discovery has not read the system with the recorded UUID") + } + state := ops.ObservedPowerState(system.PowerState) + if !state.Settled() { + return refuse(ReasonPowerStateNotSettled, "discovery reads power state %q; it must be On or Off", system.PowerState) + } + evidence := settle.Recovery.Spec.Evidence + if evidence.Data[SettlePowerState] != string(state) { + return refuse(ReasonPowerEvidenceMismatch, "the recovery cites power state %q; discovery reads %s", evidence.Data[SettlePowerState], state) + } + if !evidence.ObservedAt.After(settle.Hold.Since.Time) || read.ObservedAt.Before(&evidence.ObservedAt) { + return refuse(ReasonPowerEvidenceMismatch, "the recovery must cite a discovery read made after the operation ended") + } + return nil +} diff --git a/internal/custody/power_test.go b/internal/custody/power_test.go new file mode 100644 index 00000000..6145f6e1 --- /dev/null +++ b/internal/custody/power_test.go @@ -0,0 +1,852 @@ +package custody + +import ( + "context" + "errors" + "fmt" + "reflect" + "slices" + "strings" + "sync" + "testing" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const powerKind = "DevicePowerOperation" + +var allActions = []string{"On", "ForceOff", "ForceRestart", "PowerCycle", "GracefulShutdown"} + +// discoverPower records a discovery that read the recorded system with its +// power state and offered reset types, as BMC discovery would. +func (e *env) discoverPower(device *inventory.Device, key string, at time.Time, state string, resetTypes []string, mutate func(*inventory.DeviceDiscovery)) { + e.t.Helper() + e.discover(device, key, at) + discovery := device.Status.Discovery + discovery.Inventory.Systems = []inventory.ObservedSystem{{ID: "1", UUID: device.Spec.Identity.SystemUUID, PowerState: state, ResetTypes: resetTypes}} + if mutate != nil { + mutate(discovery) + } + if err := e.admin.Status().Update(e.ctx, device); err != nil { + e.t.Fatal(err) + } +} + +// powered creates a Verified Device whose discovery offers every power +// action and reads it On. +func (e *env) powered(n int) (*inventory.Device, string) { + e.t.Helper() + key := fmt.Sprintf("%064x", n) + device := e.verified(fmt.Sprintf("server-power-%03d", n), uid(n), key) + e.discoverPower(device, key, e.clock.Now(), "On", allActions, nil) + return device, key +} + +func (e *env) staffPower(device *inventory.Device, action ops.PowerAction, expected string) *ops.DevicePowerOperation { + e.t.Helper() + operation := &ops.DevicePowerOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: device.Name + "-power-", Namespace: "default"}, Spec: ops.DevicePowerOperationSpec{ + OperationEnvelope: envelope(device, staffUser, service("hung in firmware during qualification")), Action: action, ExpectedSystemUUID: expected, + }} + e.create(operation) + return operation +} + +// namedStaffPower creates a staff power operation with an explicit name, such +// as a retry's. +func (e *env) namedStaffPower(device *inventory.Device, name string, action ops.PowerAction) *ops.DevicePowerOperation { + e.t.Helper() + operation := &ops.DevicePowerOperation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: ops.DevicePowerOperationSpec{ + OperationEnvelope: envelope(device, staffUser, service("retry after recovery")), Action: action, ExpectedSystemUUID: device.Spec.Identity.SystemUUID, + }} + e.create(operation) + return operation +} + +func (e *env) providerPower(device *inventory.Device, allocation string, generation int64, action ops.PowerAction, name string) *ops.DevicePowerOperation { + e.t.Helper() + if name == "" { + name = PowerName(allocation, generation) + } + operation := &ops.DevicePowerOperation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: ops.DevicePowerOperationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated(allocation)), Action: action, MachineGeneration: generation, + }} + e.create(operation) + return operation +} + +// requireCustodyUnchanged fails if anything in custody changed. +func (e *env) requireCustodyUnchanged(name string, before ops.DeviceCustodySpec) { + e.t.Helper() + if after := e.custody(name).Spec; !reflect.DeepEqual(after, before) { + e.t.Fatalf("custody changed:\n before %+v\n after %+v", before, after) + } +} + +// powerHold runs an admitted power operation to OutcomeUnknown and returns +// the hold. +func (e *env) powerHold(device *inventory.Device, operation *ops.DevicePowerOperation) ops.RecoveryHold { + e.t.Helper() + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseAdmitted, "") + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + e.t.Fatal(err) + } + e.settle(device.Name) + hold := e.custody(device.Name).Spec.RecoveryHold + if hold == nil || hold.Kind != powerKind || hold.Name != operation.Name { + e.t.Fatalf("hold = %+v", hold) + } + return *hold +} + +// applyRecovery admits a recovery and lets the site confirm its fence. +func (e *env) applyRecovery(device *inventory.Device, recovery *ops.DeviceRecovery) ops.OperationStatus { + e.t.Helper() + e.settle(device.Name) + if active := e.custody(device.Name).Spec.ActiveOperation; active != nil { + e.sites.report(device.Name, active.Fence) + e.settle(device.Name) + } + return e.status(recovery) +} + +func powerEvidence(at time.Time, before, after string, reset ops.ResetEvidence) string { + sent := at.Add(time.Second) + evidence := fmt.Sprintf(`{"requestSentAt":%q,"power":{"before":{"state":%q,"observedAt":%q},"after":{"state":%q,"observedAt":%q}}`, + sent.Format(time.RFC3339), before, at.Format(time.RFC3339), after, sent.Add(30*time.Second).Format(time.RFC3339)) + if reset != "" { + evidence += fmt.Sprintf(`,"resetEvidence":%q`, reset) + } + return evidence + "}" +} + +func TestPowerOperations(t *testing.T) { + e := startEnv(t) + n := 1100 + fresh := func(e *env) (*inventory.Device, string) { + n++ + return e.powered(n) + } + + t.Run("staff power is admitted from None with its inputs and what the reset-type check read", func(t *testing.T) { + e := e.sub(t) + device, _ := fresh(e) + before := e.custody(device.Name).Spec.Fence + operation := e.staffPower(device, ops.PowerForceRestart, device.Spec.Identity.SystemUUID) + e.settle(device.Name) + custody := e.custody(device.Name) + active := custody.Spec.ActiveOperation + if active == nil || active.Kind != powerKind || active.Fence != before+1 || custody.Spec.Holder.Type != ops.HolderService { + t.Fatalf("custody after admission = %+v", custody.Spec) + } + digest, _ := SpecDigest(operation.Spec) + if active.InputDigest != digest || !active.Deadline.Time.Equal(e.clock.Now().Add(PowerDeadline)) { + t.Fatalf("active = %+v", active) + } + want := map[string]string{SnapshotResetTypes: "On,ForceOff,ForceRestart,PowerCycle", SnapshotSystemID: "1", SnapshotResetTypesObservedAt: e.clock.Now().Format(time.RFC3339)} + if !reflect.DeepEqual(active.Snapshot.Extra, want) || active.Snapshot.SystemUUID != device.Spec.Identity.SystemUUID { + t.Fatalf("snapshot = %+v", active.Snapshot) + } + status := e.requirePhase(operation, ops.PhaseAdmitted, "") + if status.Snapshot == nil || !reflect.DeepEqual(status.Snapshot.Extra, want) { + t.Fatalf("status snapshot = %+v", status.Snapshot) + } + // The site's evidence is recorded in custody and copied to status. + if err := e.result(device.Name, ops.PhaseSucceeded, powerEvidence(e.clock.Now(), "On", "On", ops.ResetLastResetTime)); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + status = e.requirePhase(operation, ops.PhaseSucceeded, "") + var evidence ops.PowerEvidence + if err := jsonUnmarshal(status.Evidence.Raw, &evidence); err != nil || evidence.ResetEvidence != ops.ResetLastResetTime || evidence.Power.After.State != ops.PowerStateOn { + t.Fatalf("evidence = %s (%v)", status.Evidence.Raw, err) + } + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderNone { + t.Fatalf("holder = %s", holder) + } + }) + + t.Run("each power refusal admits nothing and leaves custody unchanged", func(t *testing.T) { + for _, refusal := range []struct { + name, reason string + action ops.PowerAction + expected func(*inventory.Device) string + discovery func(*inventory.DeviceDiscovery) + }{ + {name: "the expected system UUID is not the recorded one", reason: ReasonSystemUUIDMismatch, expected: func(*inventory.Device) string { return uid(9999) }}, + {name: "discovery read the inventory at another endpoint", reason: ReasonDiscoveryNotCurrent, discovery: func(d *inventory.DeviceDiscovery) { d.Inventory.Endpoint = "https://[2001:db8::99]" }}, + {name: "discovery did not read the recorded system", reason: ReasonDiscoveryNotCurrent, discovery: func(d *inventory.DeviceDiscovery) { d.Inventory.Systems[0].UUID = uid(9998) }}, + {name: "the BMC does not offer the action", reason: ReasonResetTypeNotOffered, action: ops.PowerCycle, discovery: func(d *inventory.DeviceDiscovery) { + d.Inventory.Systems[0].ResetTypes = []string{"On", "ForceOff", "ForceRestart"} + }}, + {name: "discovery offers no reset types", reason: ReasonResetTypeNotOffered, discovery: func(d *inventory.DeviceDiscovery) { d.Inventory.Systems[0].ResetTypes = nil }}, + } { + t.Run(refusal.name, func(t *testing.T) { + e := e.sub(t) + device, key := fresh(e) + if refusal.discovery != nil { + e.discoverPower(device, key, e.clock.Now(), "On", allActions, refusal.discovery) + } + before := e.custody(device.Name).Spec + action, expected := ops.PowerOn, device.Spec.Identity.SystemUUID + if refusal.action != "" { + action = refusal.action + } + if refusal.expected != nil { + expected = refusal.expected(device) + } + operation := e.staffPower(device, action, expected) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, refusal.reason) + e.requireCustodyUnchanged(device.Name, before) + }) + } + }) + + t.Run("DiscoveryNotCurrent uses the injected clock and twice the discovery interval", func(t *testing.T) { + e := e.sub(t) + device, key := fresh(e) + // Power needs a read within twice the ten-minute interval. Its check + // runs before rule 5, so its reason is the one reported. + e.discoverPower(device, key, e.clock.Now().Add(-30*time.Minute), "On", allActions, nil) + coordinator := e.coordinator(e.admin) + coordinator.Config.DiscoveryInterval = 10 * time.Minute + before := e.custody(device.Name).Spec + stale := e.staffPower(device, ops.PowerOn, device.Spec.Identity.SystemUUID) + settleWith(t, e.ctx, coordinator, device.Name) + e.requirePhase(stale, ops.PhaseFailed, ReasonDiscoveryNotCurrent) + e.requireCustodyUnchanged(device.Name, before) + // The same read is current for an operation decided ten minutes + // earlier on the injected clock. + e.clock.Advance(-11 * time.Minute) + current := e.staffPower(device, ops.PowerOn, device.Spec.Identity.SystemUUID) + settleWith(t, e.ctx, coordinator, device.Name) + e.requirePhase(current, ops.PhaseAdmitted, "") + }) + + t.Run("a staff request for a Device with no recorded system UUID is refused SystemUUIDNotRecorded", func(t *testing.T) { + e := e.sub(t) + n++ + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("server-power-%03d", n), Namespace: "default"}, Spec: inventory.DeviceSpec{ + ClaimRef: inventory.LocalReference{Name: "claim-power"}, Identity: inventory.DeviceIdentity{Model: "example", Serial: "serial-power"}, + BMC: &inventory.BMC{Endpoint: "https://[2001:db8::10]"}, + }} + e.create(device) + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now()) + e.settle(device.Name) + e.sites.report(device.Name, 0) + e.settle(device.Name) + before := e.custody(device.Name).Spec + operation := e.staffPower(device, ops.PowerOn, uid(n)) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonSystemUUIDNotRecorded) + e.requireCustodyUnchanged(device.Name, before) + }) + + t.Run("power uses the shared reasons for a shared key, a holder and an expired request", func(t *testing.T) { + e := e.sub(t) + device, key := fresh(e) + e.device(fmt.Sprintf("server-twin-%03d", n), uid(5000+n), key) + before := e.custody(device.Name).Spec + shared := e.staffPower(device, ops.PowerOn, device.Spec.Identity.SystemUUID) + e.settle(device.Name) + e.requirePhase(shared, ops.PhaseFailed, ReasonSharedPublicKey) + e.requireCustodyUnchanged(device.Name, before) + + allocated, _ := fresh(e) + if err := e.coord.Claim(e.ctx, allocated.Name, allocated.UID, "alloc-held"); err != nil { + t.Fatal(err) + } + before = e.custody(allocated.Name).Spec + customer := e.staffPower(allocated, ops.PowerOn, allocated.Spec.Identity.SystemUUID) + e.settle(allocated.Name) + e.requirePhase(customer, ops.PhaseFailed, ReasonHolderMismatch) + e.requireCustodyUnchanged(allocated.Name, before) + + late, _ := fresh(e) + before = e.custody(late.Name).Spec + expired := e.staffPower(late, ops.PowerOn, late.Spec.Identity.SystemUUID) + // Expiry counts from the server's creation time, which can be ahead + // of the injected clock. + e.clock.Advance(expired.CreationTimestamp.Add(DefaultStaffExpiry).Sub(e.clock.Now()) + time.Second) + e.settle(late.Name) + e.requirePhase(expired, ops.PhaseCancelled, ReasonExpired) + e.requireCustodyUnchanged(late.Name, before) + }) + + t.Run("only the two power rows admit; every other creator and authority pair is refused", func(t *testing.T) { + e := e.sub(t) + device, _ := fresh(e) + allocation := "alloc-rows-" + device.Name + if err := e.coord.Claim(e.ctx, device.Name, device.UID, allocation); err != nil { + t.Fatal(err) + } + before := e.custody(device.Name).Spec + var refused []*ops.DevicePowerOperation + for _, pair := range []struct { + user string + authority ops.Authority + }{ + {staffUser, allocated(allocation)}, + {releaseUser, allocated(allocation)}, + {providerUser, service("not staff")}, + {releaseUser, service("not staff")}, + } { + operation := &ops.DevicePowerOperation{ObjectMeta: metav1.ObjectMeta{Name: PowerName(allocation, int64(len(refused)+1)), Namespace: "default"}, Spec: ops.DevicePowerOperationSpec{ + OperationEnvelope: envelope(device, pair.user, pair.authority), Action: ops.PowerOn, + }} + if pair.authority.ServiceRequest != nil { + operation.Name, operation.GenerateName = "", device.Name+"-power-" + operation.Spec.ExpectedSystemUUID = device.Spec.Identity.SystemUUID + } else { + operation.Spec.MachineGeneration = int64(len(refused) + 1) + } + e.create(operation) + refused = append(refused, operation) + } + // Pending together, none replaces another: replacement runs only + // for operations a row admits. + e.settle(device.Name) + for _, operation := range refused { + e.requirePhase(operation, ops.PhaseFailed, ReasonCreatorNotPermitted) + } + e.requireCustodyUnchanged(device.Name, before) + // The provider row: allocationRef, holder Allocation, named from the + // Machine generation. + misnamed := e.providerPower(device, allocation, 7, ops.PowerOn, allocation+"-power-other") + e.settle(device.Name) + e.requirePhase(misnamed, ops.PhaseFailed, ReasonNameMismatch) + provider := e.providerPower(device, allocation, 8, ops.PowerForceOff, "") + e.settle(device.Name) + e.requirePhase(provider, ops.PhaseAdmitted, "") + if holder := e.custody(device.Name).Spec.Holder; holder.Type != ops.HolderAllocation || holder.AllocationRef.Name != allocation { + t.Fatalf("holder = %+v", holder) + } + // The staff row needs a generated name. + free, _ := fresh(e) + named := e.namedStaffPower(free, free.Name+"-chosen", ops.PowerOn) + e.settle(free.Name) + e.requirePhase(named, ops.PhaseFailed, ReasonNameMismatch) + }) + + t.Run("staff power races an allocation and exactly one takes the server", func(t *testing.T) { + e := e.sub(t) + for range 5 { + device, _ := fresh(e) + operation := e.staffPower(device, ops.PowerOn, device.Spec.Identity.SystemUUID) + coordinator := e.coordinator(e.client()) + allocator := e.coordinator(e.client()) + var claimErr, reconcileErr error + var group sync.WaitGroup + group.Add(2) + go func() { defer group.Done(); reconcileErr = settleQuiet(e.ctx, coordinator, device.Name) }() + go func() { + defer group.Done() + claimErr = allocator.Claim(e.ctx, device.Name, device.UID, "alloc-power-race") + }() + group.Wait() + if reconcileErr != nil { + t.Fatal(reconcileErr) + } + e.settle(device.Name) + status := e.status(operation) + custody := e.custody(device.Name) + switch { + case claimErr == nil: + if status.Phase != ops.PhaseFailed || status.Reason != ReasonHolderMismatch || custody.Spec.Holder.Type != ops.HolderAllocation || custody.Spec.ActiveOperation != nil { + t.Fatalf("claim won but power is %s/%s and custody %+v", status.Phase, status.Reason, custody.Spec) + } + case errors.Is(claimErr, ErrUnavailable): + if status.Phase != ops.PhaseAdmitted || custody.Spec.Holder.Type != ops.HolderService { + t.Fatalf("power won but is %s and custody %+v", status.Phase, custody.Spec) + } + default: + t.Fatal(claimErr) + } + } + }) + + t.Run("a newer pending provider power operation replaces an older one, never an installation", func(t *testing.T) { + e := e.sub(t) + device, _ := fresh(e) + allocation := "alloc-replace-" + device.Name + if err := e.coord.Claim(e.ctx, device.Name, device.UID, allocation); err != nil { + t.Fatal(err) + } + running := e.installation(device, allocation, "request-a") + e.settle(device.Name) + e.requirePhase(running, ops.PhaseAdmitted, "") + older := e.providerPower(device, allocation, 1, ops.PowerOn, "") + e.clock.Advance(time.Second) + pendingInstall := e.installation(device, allocation, "request-b") + newer := e.providerPower(device, allocation, 2, ops.PowerForceOff, "") + e.settle(device.Name) + e.requirePhase(older, ops.PhaseCancelled, ReasonSuperseded) + e.requirePhase(newer, ops.PhasePending, ReasonOperationInProgress) + e.requirePhase(pendingInstall, ops.PhasePending, ReasonOperationInProgress) + e.requirePhase(running, ops.PhaseAdmitted, "") + }) + + t.Run("a staff request naming a customer's allocation never replaces the provider's pending operation", func(t *testing.T) { + e := e.sub(t) + device, _ := fresh(e) + allocation := "alloc-cust-" + device.Name + if err := e.coord.Claim(e.ctx, device.Name, device.UID, allocation); err != nil { + t.Fatal(err) + } + running := e.installation(device, allocation, "request-running") + e.settle(device.Name) + e.requirePhase(running, ops.PhaseAdmitted, "") + customer := e.providerPower(device, allocation, 1, ops.PowerOn, "") + e.settle(device.Name) + e.requirePhase(customer, ops.PhasePending, ReasonOperationInProgress) + // Newer by at least the API server's one-second timestamp. + time.Sleep(1100 * time.Millisecond) + staff := &ops.DevicePowerOperation{ObjectMeta: metav1.ObjectMeta{Name: PowerName(allocation, 2), Namespace: "default"}, Spec: ops.DevicePowerOperationSpec{ + OperationEnvelope: envelope(device, staffUser, allocated(allocation)), Action: ops.PowerForceOff, MachineGeneration: 2, + }} + e.create(staff) + e.settle(device.Name) + e.requirePhase(staff, ops.PhaseFailed, ReasonCreatorNotPermitted) + e.requirePhase(customer, ops.PhasePending, ReasonOperationInProgress) + }) + + t.Run("a newer staff power request never cancels an older one", func(t *testing.T) { + e := e.sub(t) + device, _ := fresh(e) + older := e.staffPower(device, ops.PowerOn, device.Spec.Identity.SystemUUID) + time.Sleep(1100 * time.Millisecond) + newer := e.staffPower(device, ops.PowerForceOff, device.Spec.Identity.SystemUUID) + e.settle(device.Name) + // Each is decided on its own: the older is admitted, and the newer + // then finds a Service holder. + e.requirePhase(older, ops.PhaseAdmitted, "") + e.requirePhase(newer, ops.PhaseFailed, ReasonHolderMismatch) + }) + + t.Run("under a provider power hold, newer operations wait and never replace the retry that settles it", func(t *testing.T) { + e := e.sub(t) + device, key := fresh(e) + allocation := "alloc-hold-" + device.Name + if err := e.coord.Claim(e.ctx, device.Name, device.UID, allocation); err != nil { + t.Fatal(err) + } + held := e.providerPower(device, allocation, 1, ops.PowerOn, "") + hold := e.powerHold(device, held) + waiting := e.providerPower(device, allocation, 2, ops.PowerForceOff, "") + e.settle(device.Name) + e.requirePhase(waiting, ops.PhasePending, ReasonRecoveryHold) + // A Retry lets the provider create one settling operation. + e.discoverPower(device, key, e.clock.Now(), "On", allActions, nil) + retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + if status := e.applyRecovery(device, retry); status.Phase != ops.PhaseSucceeded { + t.Fatalf("retry = %+v", status) + } + e.clock.Advance(time.Second) + newest := e.providerPower(device, allocation, 3, ops.PowerForceOff, "") + settling := e.providerPower(device, allocation, 1, ops.PowerOn, RetryName(hold, 1)) + e.settle(device.Name) + e.requirePhase(waiting, ops.PhaseCancelled, ReasonSuperseded) + e.requirePhase(newest, ops.PhasePending, ReasonRecoveryHold) + e.requirePhase(settling, ops.PhaseAdmitted, "") + if active := e.custody(device.Name).Spec.ActiveOperation; active.Settles == nil || *active.Settles != heldReference(hold) { + t.Fatalf("active = %+v", active) + } + if err := e.result(device.Name, ops.PhaseSucceeded, powerEvidence(e.clock.Now(), "Off", "On", "")); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + custody := e.custody(device.Name) + if custody.Spec.RecoveryHold != nil || custody.Spec.Holder.Type != ops.HolderAllocation { + t.Fatalf("after the retry succeeded: %+v", custody.Spec) + } + e.requirePhase(newest, ops.PhaseAdmitted, "") + }) + + t.Run("a staff power operation settles a staff power hold after Retry", func(t *testing.T) { + e := e.sub(t) + device, key := fresh(e) + hold := e.powerHold(device, e.staffPower(device, ops.PowerCycle, device.Spec.Identity.SystemUUID)) + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderService { + t.Fatalf("holder = %s", holder) + } + // From holder Service, a staff power operation that does not settle + // the hold is refused. + before := e.custody(device.Name).Spec + blocked := e.staffPower(device, ops.PowerOn, device.Spec.Identity.SystemUUID) + e.settle(device.Name) + e.requirePhase(blocked, ops.PhaseFailed, ReasonHolderMismatch) + e.requireCustodyUnchanged(device.Name, before) + // The staff operation named for the Retry repeats the held action. + // Created before the Retry is applied, it waits, even past the staff + // expiry, and is admitted once the Retry is. + retried := e.namedStaffPower(device, RetryName(hold, 1), ops.PowerCycle) + e.settle(device.Name) + e.requirePhase(retried, ops.PhasePending, ReasonRecoveryHold) + past := retried.CreationTimestamp.Add(DefaultStaffExpiry).Sub(e.clock.Now()) + time.Second + e.clock.Advance(past) + e.settle(device.Name) + e.requirePhase(retried, ops.PhasePending, ReasonRecoveryHold) + // Back to the present, so the staff Retry created next is current. + e.clock.Advance(-past) + e.discoverPower(device, key, e.clock.Now(), "On", allActions, nil) + retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + if status := e.applyRecovery(device, retry); status.Phase != ops.PhaseSucceeded { + t.Fatalf("retry = %+v", status) + } + e.settle(device.Name) + e.requirePhase(retried, ops.PhaseAdmitted, "") + if active := e.custody(device.Name).Spec.ActiveOperation; active.Settles == nil || *active.Settles != heldReference(hold) { + t.Fatalf("active = %+v", active) + } + if err := e.result(device.Name, ops.PhaseSucceeded, powerEvidence(e.clock.Now(), "On", "On", ops.ResetObservedOff)); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + custody := e.custody(device.Name) + if custody.Spec.RecoveryHold != nil || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("after the retry succeeded: %+v", custody.Spec) + } + }) + + t.Run("Settle accepts only discovery read after the operation ended, at the current endpoint, in a settled state", func(t *testing.T) { + for _, settle := range []struct { + name string + readAt time.Duration // after the hold began + state string + cited string + discovery func(*inventory.DeviceDiscovery) + reason string + }{ + {name: "fresh evidence", readAt: time.Minute, state: "Off", cited: "Off"}, + {name: "stale evidence", readAt: -time.Minute, state: "Off", cited: "Off", reason: ReasonPowerEvidenceNotCurrent}, + {name: "evidence from the wrong endpoint", readAt: time.Minute, state: "Off", cited: "Off", reason: ReasonPowerEvidenceWrongEndpoint, + discovery: func(d *inventory.DeviceDiscovery) { d.Inventory.Endpoint = "https://[2001:db8::99]" }}, + {name: "an unsettled state", readAt: time.Minute, state: "PoweringOn", cited: "PoweringOn", reason: ReasonPowerStateNotSettled}, + {name: "a cited state discovery did not read", readAt: time.Minute, state: "Off", cited: "On", reason: ReasonPowerEvidenceMismatch}, + } { + t.Run(settle.name, func(t *testing.T) { + e := e.sub(t) + device, key := fresh(e) + hold := e.powerHold(device, e.staffPower(device, ops.PowerForceOff, device.Spec.Identity.SystemUUID)) + e.clock.Advance(2 * time.Minute) + readAt := hold.Since.Time.Add(settle.readAt) + // Identity stays current, so only the settle hook decides. + e.discoverPower(device, key, readAt, settle.state, allActions, settle.discovery) + recovery := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: heldRef(hold), Evidence: ops.RecoveryEvidence{ + ObservedAt: metav1.NewTime(readAt), Summary: "discovery read the power state", Data: map[string]string{SettlePowerState: settle.cited}, + }}) + fence := e.custody(device.Name).Spec.Fence + status := e.applyRecovery(device, recovery) + custody := e.custody(device.Name) + if settle.reason == "" { + if status.Phase != ops.PhaseSucceeded || custody.Spec.RecoveryHold != nil || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("settle = %+v, custody %+v", status, custody.Spec) + } + return + } + e.requirePhase(recovery, ops.PhaseFailed, settle.reason) + if custody.Spec.RecoveryHold == nil || heldReference(*custody.Spec.RecoveryHold) != heldReference(hold) { + t.Fatalf("hold cleared: %+v", custody.Spec) + } + e.requireUntouched(device.Name, fence) + }) + } + }) + + t.Run("a success with no evidence, or evidence that does not fit the operation, proves nothing", func(t *testing.T) { + for name, evidence := range map[string]string{ + "no evidence": "", + "a field outside the schema": `{"power":{"after":{"state":"On","observedAt":"2026-01-02T03:04:05Z"}},"raw":"bmc body"}`, + "reset proof for a power-on": powerEvidence(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), "Off", "On", ops.ResetLastResetTime), + } { + t.Run(name, func(t *testing.T) { + e := e.sub(t) + device, _ := fresh(e) + operation := e.staffPower(device, ops.PowerOn, device.Spec.Identity.SystemUUID) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseSucceeded, evidence); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseOutcomeUnknown, ReasonInvalidEvidence) + if hold := e.custody(device.Name).Spec.RecoveryHold; hold == nil || hold.Name != operation.Name { + t.Fatalf("hold = %+v", hold) + } + }) + } + }) + + t.Run("a refusal needs no evidence", func(t *testing.T) { + e := e.sub(t) + device, _ := fresh(e) + operation := e.staffPower(device, ops.PowerForceRestart, device.Spec.Identity.SystemUUID) + e.settle(device.Name) + if err := e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: e.custody(device.Name).Spec.ActiveOperation.OperationReference, + Fence: e.custody(device.Name).Spec.Fence, Phase: ops.PhaseFailed, Reason: ReasonSystemUUIDMismatch}); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonSystemUUIDMismatch) + if custody := e.custody(device.Name); custody.Spec.RecoveryHold != nil || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("custody = %+v", custody.Spec) + } + }) +} + +// TestPowerCRDRules checks the power inputs the API server enforces. +func TestPowerCRDRules(t *testing.T) { + e := startEnv(t) + device, _ := e.powered(1300) + staff := func(mutate func(*ops.DevicePowerOperationSpec)) error { + spec := ops.DevicePowerOperationSpec{OperationEnvelope: envelope(device, staffUser, service("r")), Action: ops.PowerOn, ExpectedSystemUUID: device.Spec.Identity.SystemUUID} + mutate(&spec) + return e.admin.Create(e.ctx, &ops.DevicePowerOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: "p-", Namespace: "default"}, Spec: spec}) + } + for name, mutate := range map[string]func(*ops.DevicePowerOperationSpec){ + "staff without expectedSystemUUID": func(s *ops.DevicePowerOperationSpec) { s.ExpectedSystemUUID = "" }, + "staff with machineGeneration": func(s *ops.DevicePowerOperationSpec) { s.MachineGeneration = 1 }, + "staff without a reason": func(s *ops.DevicePowerOperationSpec) { s.Authority.ServiceRequest.Reason = "" }, + "provider with expectedSystemUUID": func(s *ops.DevicePowerOperationSpec) { s.Authority = allocated("alloc-a"); s.MachineGeneration = 1 }, + "provider without machineGeneration": func(s *ops.DevicePowerOperationSpec) { s.Authority = allocated("alloc-a"); s.ExpectedSystemUUID = "" }, + "provider with an allocation name too long to name it": func(s *ops.DevicePowerOperationSpec) { + s.Authority, s.ExpectedSystemUUID, s.MachineGeneration = allocated(strings.Repeat("a", 201)), "", 1 + }, + "an action that is not a power action": func(s *ops.DevicePowerOperationSpec) { s.Action = "GracefulShutdown" }, + "an expected UUID not in canonical form": func(s *ops.DevicePowerOperationSpec) { + s.ExpectedSystemUUID = "00000000-0000-4000-8000-00000000000A" + }, + } { + t.Run(name, func(t *testing.T) { + if err := staff(mutate); !apierrors.IsInvalid(err) { + t.Fatalf("want Invalid, got %v", err) + } + }) + } + t.Run("the spec is immutable", func(t *testing.T) { + operation := e.staffPower(device, ops.PowerOn, device.Spec.Identity.SystemUUID) + operation.Spec.Action = ops.PowerForceOff + if err := e.admin.Update(e.ctx, operation); !apierrors.IsInvalid(err) { + t.Fatalf("want Invalid, got %v", err) + } + }) + t.Run("evidence outside the schema is pruned from status", func(t *testing.T) { + operation := e.staffPower(device, ops.PowerOn, device.Spec.Identity.SystemUUID) + operation.Status.Phase = ops.PhasePending + operation.Status.Evidence = rawExtension([]byte(`{"resetEvidence":"ObservedOff","raw":"bmc body"}`)) + if err := e.admin.Status().Update(e.ctx, operation); err != nil { + t.Fatal(err) + } + stored := &ops.DevicePowerOperation{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), stored); err != nil { + t.Fatal(err) + } + if strings.Contains(string(stored.Status.Evidence.Raw), "raw") { + t.Fatalf("evidence = %s", stored.Status.Evidence.Raw) + } + }) +} + +// TestPowerChecks covers power's admission checks on their own. +func TestPowerChecks(t *testing.T) { + now := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + uuid := uid(1) + device := func() *inventory.Device { + return &inventory.Device{Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{SystemUUID: uuid}, BMC: &inventory.BMC{Endpoint: "https://[2001:db8::10]"}}, + Status: inventory.DeviceStatus{Discovery: &inventory.DeviceDiscovery{Inventory: &inventory.ObservedInventory{ObservedAt: metav1.NewTime(now.Add(-time.Hour)), Endpoint: "https://[2001:db8::10]", + Systems: []inventory.ObservedSystem{{ID: "1", UUID: strings.ToUpper(uuid), PowerState: "On", ResetTypes: []string{"On", "ForceOff"}}}}}}} + } + staff := func(action ops.PowerAction, expected string) ops.Operation { + return &ops.DevicePowerOperation{Spec: ops.DevicePowerOperationSpec{OperationEnvelope: ops.OperationEnvelope{Authority: service("r")}, Action: action, ExpectedSystemUUID: expected}} + } + provider := &ops.DevicePowerOperation{Spec: ops.DevicePowerOperationSpec{OperationEnvelope: ops.OperationEnvelope{Authority: allocated("alloc-a")}, Action: ops.PowerOn, MachineGeneration: 3}} + for _, check := range []struct { + name string + operation ops.Operation + device func(*inventory.Device) + now time.Time + want string + }{ + {name: "admitted", operation: staff(ops.PowerOn, uuid)}, + {name: "a provider operation names no UUID", operation: provider}, + {name: "no recorded UUID", operation: staff(ops.PowerOn, uuid), device: func(d *inventory.Device) { d.Spec.Identity.SystemUUID = "" }, want: ReasonSystemUUIDNotRecorded}, + {name: "another UUID", operation: staff(ops.PowerOn, uid(2)), want: ReasonSystemUUIDMismatch}, + {name: "older than twice the interval", operation: staff(ops.PowerOn, uuid), now: now.Add(61 * time.Minute), want: ReasonDiscoveryNotCurrent}, + {name: "no inventory", operation: provider, device: func(d *inventory.Device) { d.Status.Discovery.Inventory = nil }, want: ReasonDiscoveryNotCurrent}, + {name: "not offered", operation: staff(ops.PowerForceRestart, uuid), want: ReasonResetTypeNotOffered}, + } { + t.Run(check.name, func(t *testing.T) { + target := device() + if check.device != nil { + check.device(target) + } + at := now + if !check.now.IsZero() { + at = check.now + } + refusal := checkPower(context.Background(), &Admission{Operation: check.operation, Device: target, Now: at, DiscoveryInterval: time.Hour}) + if got := ""; refusal != nil { + got = refusal.Reason + if got != check.want { + t.Fatalf("refusal = %v, want %s", refusal, check.want) + } + } else if check.want != "" { + t.Fatalf("admitted, want %s", check.want) + } + }) + } + // The snapshot records only the power actions offered. + extra := powerSnapshot(&Admission{Device: device()}) + if extra[SnapshotResetTypes] != "On,ForceOff" || extra[SnapshotSystemID] != "1" || extra[SnapshotResetTypesObservedAt] != "2026-01-02T02:04:05Z" { + t.Fatalf("snapshot = %v", extra) + } +} + +// TestPowerInputDigestIsStable pins the digest of one input, so a change to +// the encoding or to the fields it covers is a deliberate one. +func TestPowerInputDigestIsStable(t *testing.T) { + spec := ops.DevicePowerOperationSpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: ops.Creator{Username: staffUser, UID: "staff-uid"}, DeviceRef: ops.DeviceReference{Name: "server-example-001"}, + Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "hung in firmware"}}}, + Action: ops.PowerForceRestart, ExpectedSystemUUID: uid(1), + } + kind := DevicePowerOperationKind() + digest, err := kind.Digest(&ops.DevicePowerOperation{Spec: spec}) + if err != nil { + t.Fatal(err) + } + const want = "sha256:48414d36478756aef5e66e75143abfb579c299061a875a3b887d014d55a78e86" + if digest != want { + t.Fatalf("digest = %s, want %s", digest, want) + } + // A round trip through JSON, as the API server stores it, keeps it. + data, _ := jsonMarshal(&ops.DevicePowerOperation{ObjectMeta: metav1.ObjectMeta{Name: "a", ResourceVersion: "7"}, Spec: spec}) + stored := &ops.DevicePowerOperation{} + if err := jsonUnmarshal(data, stored); err != nil { + t.Fatal(err) + } + if again, _ := kind.Digest(stored); again != digest { + t.Fatalf("digest changed across a round trip: %s", again) + } + changed := spec + changed.Action = ops.PowerCycle + if other, _ := kind.Digest(&ops.DevicePowerOperation{Spec: changed}); other == digest { + t.Fatal("the digest does not cover the action") + } +} + +func TestPowerEvidenceIsTypedAndBounded(t *testing.T) { + kind := DevicePowerOperationKind() + if !kind.EvidenceRequired { + t.Fatal("power evidence must be required") + } + operation := func(action ops.PowerAction) ops.Operation { + return &ops.DevicePowerOperation{Spec: ops.DevicePowerOperationSpec{Action: action}} + } + restart := operation(ops.PowerForceRestart) + validate := func(raw []byte) ([]byte, error) { return kind.Evidence(restart, raw) } + at := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + if _, err := validate([]byte(powerEvidence(at, "On", "On", ops.ResetLastResetTime))); err != nil { + t.Fatal(err) + } + // A refusal before the command carries only the state read before it. + if _, err := validate([]byte(`{"power":{"before":{"state":"Off","observedAt":"2026-01-02T03:04:05Z"}}}`)); err != nil { + t.Fatal(err) + } + // Reset proof belongs only to a restart or a power cycle. + for _, action := range []ops.PowerAction{ops.PowerOn, ops.PowerForceOff} { + if _, err := kind.Evidence(operation(action), []byte(powerEvidence(at, "Off", "On", ops.ResetObservedOff))); err == nil { + t.Errorf("%s accepted reset proof", action) + } + } + if _, err := kind.Evidence(operation(ops.PowerCycle), []byte(powerEvidence(at, "On", "On", ops.ResetObservedOff))); err != nil { + t.Fatal(err) + } + for name, evidence := range map[string]string{ + "an unknown field": `{"power":{},"bmcResponse":"x"}`, + "trailing data": `{} {}`, + "oversized": `{"resetEvidence":"` + strings.Repeat("x", 1100) + `"}`, + "an invented power state": `{"power":{"after":{"state":"Sleeping","observedAt":"2026-01-02T03:04:05Z"}}}`, + "an observation with no time": `{"power":{"after":{"state":"On"}}}`, + "an invented reset evidence": `{"requestSentAt":"2026-01-02T03:04:05Z","resetEvidence":"Guessed"}`, + "reset evidence with no command": `{"resetEvidence":"ObservedOff"}`, + "after read before before": `{"power":{"before":{"state":"On","observedAt":"2026-01-02T03:04:05Z"},"after":{"state":"On","observedAt":"2026-01-02T03:04:00Z"}}}`, + "the command sent before the state was read": `{"requestSentAt":"2026-01-02T03:04:00Z","power":{"before":{"state":"On","observedAt":"2026-01-02T03:04:05Z"}}}`, + "after read before the command": `{"requestSentAt":"2026-01-02T03:04:05Z","power":{"after":{"state":"On","observedAt":"2026-01-02T03:04:00Z"}}}`, + } { + if _, err := validate([]byte(evidence)); err == nil { + t.Errorf("%s: accepted %s", name, evidence) + } + } +} + +// TestPowerRegistration checks the registry entry and rows. +func TestPowerRegistration(t *testing.T) { + registry, err := DefaultRegistry() + if err != nil { + t.Fatal(err) + } + kind := registry.Kind(powerKind) + if kind == nil || !kind.Effectful || !kind.Supersedes || !kind.Retryable || !kind.EvidenceRequired || kind.Naming != GeneratedName || kind.RecoverySettle == nil || kind.Deadline != PowerDeadline { + t.Fatalf("kind = %+v", kind) + } + // A power success settles only a power hold, after a Retry. + if !reflect.DeepEqual(kind.Settles, []SettleRule{{Held: powerKind, RequiresRetry: true}}) { + t.Fatalf("settles = %+v", kind.Settles) + } + for _, other := range registry.Kinds() { + for _, rule := range other.Settles { + if rule.Held == powerKind && other.GVK.Kind != powerKind { + t.Fatalf("%s settles a power hold", other.GVK.Kind) + } + } + } + var rows []Rule + for _, rule := range registry.Rules() { + if rule.Kind == powerKind { + rows = append(rows, rule) + } + } + // Functions never compare equal, so compare the rows without their + // name rule and check that separately. + withoutName := func(rows []Rule) []Rule { + out := slices.Clone(rows) + for index := range out { + out[index].Name = nil + } + return out + } + if len(rows) != 3 || !reflect.DeepEqual(withoutName(rows), withoutName(PowerRules())) { + t.Fatalf("rows = %+v", rows) + } + for _, reason := range []string{ReasonSystemUUIDNotRecorded, ReasonSystemUUIDMismatch, ReasonDiscoveryNotCurrent, ReasonResetTypeNotOffered, ReasonPowerEvidenceNotCurrent, ReasonPowerEvidenceWrongEndpoint, ReasonPowerStateNotSettled, ReasonPowerEvidenceMismatch} { + if !registry.Declared(powerKind, reason, RaisedByCoordinator) { + t.Fatalf("%s is not declared", reason) + } + } + for _, reason := range []string{ReasonSystemUUIDMismatch, ReasonResetTypeNotOffered} { + if !registry.Declared(powerKind, reason, RaisedByWorker) { + t.Fatalf("%s is not declared for the worker", reason) + } + } + // Staff rows keep the kind's generated names; the provider row names + // its operations from the allocation and the Machine generation. + provider := &ops.DevicePowerOperation{Spec: ops.DevicePowerOperationSpec{OperationEnvelope: ops.OperationEnvelope{Authority: allocated("alloc-a")}, MachineGeneration: 4}} + for _, row := range rows { + switch row.Creator { + case CreatorMetalProvider: + if row.Naming != DeterministicName || row.Name(provider) != "alloc-a-power-4" { + t.Fatalf("provider row naming = %v", row.Naming) + } + default: + if row.Naming != KindNaming || row.Name != nil { + t.Fatalf("staff row naming = %v", row.Naming) + } + } + } +} diff --git a/internal/custody/seams_test.go b/internal/custody/seams_test.go index fa889693..68744768 100644 --- a/internal/custody/seams_test.go +++ b/internal/custody/seams_test.go @@ -56,6 +56,25 @@ func TestRegistryRejectsIncompleteKindsAndRows(t *testing.T) { // TestAddingRowsLeavesExistingRowsAlone registers the test kinds and rows on // top of the defaults and checks every built-in kind matches exactly the same // rows for every creator class, authority and variant. +// sameRows compares rows, with a row's Name rule compared by identity: +// reflect.DeepEqual never finds two non-nil functions equal. +func sameRows(left, right []Rule) bool { + if len(left) != len(right) { + return false + } + for index := range left { + a, b := left[index], right[index] + if (a.Name == nil) != (b.Name == nil) || (a.Name != nil && reflect.ValueOf(a.Name).Pointer() != reflect.ValueOf(b.Name).Pointer()) { + return false + } + a.Name, b.Name = nil, nil + if !reflect.DeepEqual(a, b) { + return false + } + } + return true +} + func TestAddingRowsLeavesExistingRowsAlone(t *testing.T) { base, err := DefaultRegistry() if err != nil { @@ -74,7 +93,7 @@ func TestAddingRowsLeavesExistingRowsAlone(t *testing.T) { } before := base.matchRows(kind, operation, class) after := extended.matchRows(extended.Kind(kind.GVK.Kind), operation, class) - if !reflect.DeepEqual(before, after) { + if !sameRows(before, after) { t.Fatalf("%s %s %+v: rows changed from %v to %v", kind.GVK.Kind, class, authority, before, after) } } diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 7301d619..fbc223d8 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -43,7 +43,7 @@ custody](../../docs/development/device-custody.md#tests). | --- | --- | --- | | Two allocators race for one server; one wins | `TestConcurrency`, `TestConcurrentAllocatorsOneWinner` | Envtest verified; the standalone smoke verifies two consumers contending for one server | | An allocator retries after a lost response and claims no second server | `TestConcurrency`, `TestAnAllocationThatLostItsDeviceIsReplaced` | Envtest verified; the allocation is named from the Machine UID, so a retry finds the same one | -| A staff operation names a customer allocation and is refused | `TestAdmissionPreconditions`, with the test-only staff kind | Envtest verified; end to end deferred to power | +| A staff operation names a customer allocation and is refused | `TestAdmissionPreconditions`, with the test-only staff kind; `TestPowerOperations` | Envtest verified, including for staff power; end to end deferred to the power worker | | A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope; the mechanism is envtest verified | | A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery` | Envtest verified; end to end proposed | | A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery` | Envtest verified with a fake site; end to end proposed | diff --git a/ui/provider/README.md b/ui/provider/README.md index 935b49c3..88fa9b1f 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -109,6 +109,10 @@ fixture build replaces every API read with synthetic data: - Inventory writes are disabled: permission checks answer "not allowed", so management and capacity-registration controls stay hidden or read-only. Nothing is sent to the API. +- Device power reads synthetic custody and power operations + (`src/lib/power-fixtures.ts`). The power permission is granted so the + control shows; an operation created on the page stays in memory as + Pending. Nothing is sent to the API. Add `?fixture=` to a preview URL to deny whole collections, as a 403 would: `power-feeds-denied`, `devices-denied` or `cables-denied` diff --git a/ui/provider/scripts/screenshot-pages.ts b/ui/provider/scripts/screenshot-pages.ts index 874b8cf3..b943e3d4 100644 --- a/ui/provider/scripts/screenshot-pages.ts +++ b/ui/provider/scripts/screenshot-pages.ts @@ -71,6 +71,11 @@ export const PAGES: CapturePage[] = [ { name: 'device-discovery-mismatch', path: record('Device', 'example-srv-a01-02', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-discovery-chips', element: '.inventory-record-tabs', viewports: ['desktop-light', 'phone'] }, { name: 'device-discovery-pin', path: record('Device', 'example-srv-a01-05', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-discovery-chips', viewports: ['desktop-light', 'phone'] }, { name: 'device-discovery-none', path: record('Device', 'example-srv-a02-02', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-fact-section', element: '.inventory-record-tabs', viewports: ['desktop-light', 'phone'] }, + // Staff power: the header control and fact, the dialog and its destructive confirmation, the Operations tab, and a held server. + { name: 'device-power-header', path: record('Device', 'example-srv-a01-01'), ready: '.inventory-power-control button', element: '.inventory-record-header', viewports: ['desktop-light', 'desktop-dark', 'phone'] }, + { name: 'device-power-dialog', path: record('Device', 'example-srv-a01-01'), ready: '.inventory-power-control button:not([disabled])', click: '.inventory-power-control button', viewports: ['desktop-light', 'phone'] }, + { name: 'device-power-operations', path: record('Device', 'example-srv-a01-01', '&tab=operations'), ready: '[data-tab="operations"] table', element: '.inventory-record-tabs', viewports: ['desktop-light', 'desktop-dark', 'phone'] }, + { name: 'device-power-held', path: record('Device', 'example-srv-a01-05', '&tab=operations'), ready: '[data-tab="operations"] table', viewports: ['desktop-light', 'phone'] }, { name: 'device-location', path: record('Device', 'example-srv-a01-01', '&tab=location'), ready: '[data-tab="location"] .inventory-fields', element: '.inventory-record-tabs', viewports: ['desktop-light', 'phone'] }, { name: 'record-footer', path: record('Device', 'example-srv-a01-01'), ready: '.inventory-record-footer', element: '.inventory-record-footer', viewports: ['desktop-light', 'phone'] }, // Device detail for a model without a layout (grouped tiles), and the one component table. diff --git a/ui/provider/src/components/device-discovery.test.tsx b/ui/provider/src/components/device-discovery.test.tsx index 41ab82ad..8e173251 100644 --- a/ui/provider/src/components/device-discovery.test.tsx +++ b/ui/provider/src/components/device-discovery.test.tsx @@ -31,7 +31,9 @@ describe('Device page: expected next to observed identity', () => { expect(cells('Identity', 'Model').map(cell => cell.textContent)).toEqual(['Model', 'EX-C1', 'Example EX-C1']); // Spec records no SKU or power state: the expected cell is blank. expect(cells('Identity', 'SKU').map(cell => cell.textContent)).toEqual(['SKU', '', 'SYNTH-SKU-1']); - expect(cells('Identity', 'Power')[2]).toHaveTextContent(/^On$/); + // Power is stated once, in the header strip. + expect(within(table('Identity')).queryByRole('cell', { name: 'Power' })).toBeNull(); + expect(within(screen.getByLabelText('Identity', { selector: 'dl' })).getByText('Power', { selector: 'dt' }).nextElementSibling).toHaveTextContent(/^On/); expect(table('Identity').querySelector('[data-tone]')).toBeNull(); expect(hardware()).not.toHaveTextContent(/verified/i); // The table states the system UUID; the plain fact is not repeated. diff --git a/ui/provider/src/components/device-power.test.tsx b/ui/provider/src/components/device-power.test.tsx new file mode 100644 index 00000000..17e29640 --- /dev/null +++ b/ui/provider/src/components/device-power.test.tsx @@ -0,0 +1,412 @@ +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Device, DeviceCustody, DevicePowerOperation } from '../../../shared/fleet-api'; +import { FIXTURE_NAMES, inventoryFixture } from '../lib/inventory-fixtures'; +import { fixtureCustody, fixturePowerOperations } from '../lib/power-fixtures'; +import { chooseValue, selectOptions } from '../test/field-select'; +import { InventoryOperationContext, InventoryOperationScope } from '../lib/inventory-operation'; +import { DevicePowerControl, DevicePowerFact, DevicePowerHistory } from './device-power'; + +const named = (name: string) => structuredClone(inventoryFixture.devices.find(device => device.metadata.name === name)!); +const SERVER = FIXTURE_NAMES.server; +const UUID = named(SERVER).spec.identity.systemUUID!; +const NAME = named(SERVER).spec.displayName!; + +interface Api { + allowed?: boolean; + custody?: DeviceCustody | null | number; + operations?: DevicePowerOperation[] | number; + caller?: { username: string; uid: string } | number; + create?: (body: unknown) => Response | Promise; +} + +const json = (data: unknown, status = 200) => Response.json(status < 400 ? { data } : { error: typeof data === 'string' ? data : 'Failed' }, { status }); + +function stub(api: Api = {}) { + const { allowed = true, custody = fixtureCustody(SERVER), operations = [], caller = { username: 'staff@example.com', uid: 'staff-uid' } } = api; + const fetch = vi.fn(async (url: string, init: RequestInit = {}) => { + if (url.includes('selfsubjectaccessreviews')) return json({ status: { allowed } }); + if (url.includes('selfsubjectreviews')) return typeof caller === 'number' ? json('Failed', caller) : json({ status: { userInfo: caller } }); + if (url.includes('/devicecustodies/')) return typeof custody === 'number' ? json('Failed', custody) : custody === null ? json('Not found', 404) : json(custody); + if (url.includes('/devicepoweroperations') && init.method === 'POST') return api.create ? api.create(JSON.parse(String(init.body))) : json({ ...JSON.parse(String(init.body)), metadata: { name: 'created', uid: 'created-uid' } }, 201); + if (url.includes('/devicepoweroperations')) return typeof operations === 'number' ? json('Failed', operations) : json({ items: operations }); + throw new Error(`Unexpected request ${url}`); + }); + vi.stubGlobal('fetch', fetch); + return fetch; +} + +function show(device: Device, ui: 'control' | 'history' | 'fact' = 'control') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const node = ui === 'control' ? : ui === 'history' ? :
; + return { ...render({node}), client }; +} + +const powerButton = () => screen.findByRole('button', { name: 'Power' }); +async function enabledPower() { + const button = await powerButton(); + await waitFor(() => expect(button).toBeEnabled()); + return button; +} +async function openDialog() { + fireEvent.click(await enabledPower()); + return screen.getByRole('dialog'); +} +const actionField = () => screen.getByRole('combobox', { name: /^Action/ }); +const posts = (fetch: ReturnType) => fetch.mock.calls.filter(([url, init]) => url.includes('/devicepoweroperations') && init?.method === 'POST'); + +beforeEach(() => vi.stubGlobal('confirm', vi.fn(() => true))); +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); + +describe('Power control', () => { + it('offers only the actions discovery reports, in menu order', async () => { + stub(); + const device = named(SERVER); + device.status!.discovery!.inventory!.systems![0].resetTypes = ['PowerCycle', 'GracefulShutdown', 'On', 'Nmi']; + show(device); + await openDialog(); + expect(selectOptions(actionField()).map(option => [option.value, option.text])).toEqual([['On', 'Power on'], ['PowerCycle', 'Power cycle']]); + }); + + it('reads offered actions from the system with the recorded UUID, not another one', async () => { + stub(); + const device = named(SERVER); + const inventory = device.status!.discovery!.inventory!; + inventory.systems = [{ id: 'Other', uuid: '00000000-0000-4000-8000-00000000ffff', resetTypes: ['On', 'ForceOff', 'ForceRestart', 'PowerCycle'] }, { ...inventory.systems![0], uuid: UUID.toUpperCase(), resetTypes: ['ForceOff'] }]; + show(device); + await openDialog(); + expect(selectOptions(actionField()).map(option => option.value)).toEqual(['ForceOff']); + }); + + it('requires a reason and sends nothing without one', async () => { + const fetch = stub(); + show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + expect(await screen.findByRole('alert')).toHaveTextContent(/Reason/); + expect(screen.getByRole('textbox', { name: 'Reason' })).toHaveAttribute('aria-invalid', 'true'); + expect(posts(fetch)).toHaveLength(0); + }); + + it('sends the exact staff request: generated name, device-uid label, caller, Device name, reason and recorded system UUID', async () => { + const fetch = stub(); + const device = named(SERVER); + show(device); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: ' First power-on after racking ' } }); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(posts(fetch)).toHaveLength(1)); + const [url, init] = posts(fetch)[0]; + expect(url).toBe('/api/internal/apis/resourcemanager.miloapis.com/v1alpha1/projects/datum-cloud/control-plane/apis/fleet.datumapis.com/v1alpha1/namespaces/default/devicepoweroperations'); + expect(JSON.parse(String(init!.body))).toEqual({ + apiVersion: 'fleet.datumapis.com/v1alpha1', + kind: 'DevicePowerOperation', + metadata: { generateName: `${SERVER}-power-`, namespace: 'default', labels: { 'fleet.datumapis.com/device-uid': device.metadata.uid } }, + spec: { + // The creator is the only object UID a spec may carry; the Device incarnation is the label. + creator: { username: 'staff@example.com', uid: 'staff-uid' }, + deviceRef: { name: SERVER }, + authority: { serviceRequest: { reason: 'First power-on after racking' } }, + action: 'On', + expectedSystemUUID: UUID, + }, + }); + expect(await screen.findByRole('status')).toHaveTextContent('Power on requested'); + // The system UUID comes from the record: the dialog has no field for it. + expect(screen.queryByRole('textbox', { name: /UUID/ })).toBeNull(); + }); + + it.each([['ForceOff', 'Force off'], ['ForceRestart', 'Force restart'], ['PowerCycle', 'Power cycle']])('asks again before %s, naming the server', async (action, words) => { + const fetch = stub(); + show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), action); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Hung in firmware' } }); + fireEvent.click(screen.getByRole('button', { name: 'Continue' })); + expect(posts(fetch)).toHaveLength(0); + expect(screen.getByRole('alert')).toHaveTextContent(`${words} ${NAME}?`); + // Back returns to the form without sending. + fireEvent.click(screen.getByRole('button', { name: 'Back' })); + expect(screen.queryByText(`${words} ${NAME}?`)).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Continue' })); + fireEvent.click(screen.getByRole('button', { name: `${words} ${NAME}` })); + await waitFor(() => expect(posts(fetch)).toHaveLength(1)); + expect(JSON.parse(String(posts(fetch)[0][1]!.body)).spec.action).toBe(action); + }); + + it('powers on without a second question', async () => { + const fetch = stub(); + show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Racked' } }); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(posts(fetch)).toHaveLength(1)); + }); + + it('is hidden without the power operator permission', async () => { + const fetch = stub({ allowed: false }); + show(named(SERVER)); + await waitFor(() => expect(fetch.mock.calls.some(([url]) => url.includes('selfsubjectaccessreviews'))).toBe(true)); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + expect(screen.queryByRole('button', { name: 'Power' })).toBeNull(); + const review = JSON.parse(String(fetch.mock.calls.find(([url]) => url.includes('selfsubjectaccessreviews'))![1]!.body)); + expect(review.spec.resourceAttributes).toEqual({ group: 'fleet.datumapis.com', version: 'v1alpha1', resource: 'devicepoweroperations', namespace: 'default', verb: 'create' }); + // A user who cannot create is never asked for their identity. + expect(fetch.mock.calls.some(([url]) => url.includes('selfsubjectreviews'))).toBe(false); + }); + + const custodyWith = (spec: Partial) => ({ ...fixtureCustody(SERVER)!, spec: { ...fixtureCustody(SERVER)!.spec, ...spec } }); + const running = { ...fixturePowerOperations[0], status: { phase: 'Dispatched' as const } }; + it.each<[string, (device: Device) => void, Api]>([ + ['Allocated to a customer', () => undefined, { custody: custodyWith({ holder: { type: 'Allocation', allocationRef: { name: 'example-allocation' } } }) }], + ['Allocated to a customer', () => undefined, { custody: custodyWith({ holder: { type: 'Release', allocationRef: { name: 'example-allocation' }, openGates: ['Cleaning'] } }) }], + ['Held: DevicePowerOperation example-held outcome unknown', () => undefined, { custody: custodyWith({ holder: { type: 'Service' }, recoveryHold: { kind: 'DevicePowerOperation', name: 'example-held', fence: 3, since: '2026-01-02T03:04:05Z', reason: 'SiteCouldNotProve' } }) }], + ['DeviceWipe example-wipe is running', () => undefined, { custody: custodyWith({ activeOperation: { kind: 'DeviceWipe', name: 'example-wipe', fence: 5, phase: 'Dispatched', admittedAt: '', deadline: '', creator: { username: 'release', uid: 'r' } } }) }], + ['Force restart is in progress', () => undefined, { operations: [running] }], + ['Custody unverified', () => undefined, { custody: custodyWith({ state: 'Unverified' }) }], + ['Retired', () => undefined, { custody: custodyWith({ holder: { type: 'Retired' } }) }], + ['No custody record', () => undefined, { custody: null }], + ['No custody record', () => undefined, { custody: { ...fixtureCustody(SERVER)!, metadata: { ...fixtureCustody(SERVER)!.metadata, labels: { 'fleet.datumapis.com/device-uid': 'removed-device-uid' } } } }], + ['No custody record', () => undefined, { custody: { ...fixtureCustody(SERVER)!, metadata: { ...fixtureCustody(SERVER)!.metadata, labels: undefined } } }], + ['Custody unreadable', () => undefined, { custody: 403 }], + ['Not discovered', device => { device.status = undefined; }, {}], + ['No system UUID recorded', device => { device.spec.identity.systemUUID = undefined; }, {}], + ['The BMC offers no power actions', device => { device.status!.discovery!.inventory!.systems![0].resetTypes = undefined; }, {}], + ['Discovery read another BMC endpoint', device => { device.status!.discovery!.inventory!.endpoint = 'https://192.0.2.99:443'; }, {}], + ['Your username and UID could not be read', () => undefined, { caller: 500 }], + ['Power operations unreadable', () => undefined, { operations: 403 }], + ['Identity not matched', device => { device.status!.conditions = device.status!.conditions!.map(item => item.type === 'IdentityMatched' ? { ...item, status: 'False', reason: 'SerialMismatch' } : item); }, {}], + ['Identity not matched', device => { device.metadata.generation = 2; }, {}], + ['BMC key not read', device => { device.status!.discovery!.tls = undefined; }, {}], + ['BMC key not read', device => { device.status!.discovery!.tls!.endpoint = 'https://192.0.2.99:443'; }, {}], + ['BMC key shared', device => { device.status!.conditions = device.status!.conditions!.map(item => item.type === 'PublicKeyUnique' ? { ...item, status: 'False', reason: 'Shared' } : item); }, {}], + ['Held for a staff operation', () => undefined, { custody: custodyWith({ holder: { type: 'Service' } }) }], + ])('is disabled with the reason as its tooltip: %s', async (reason, change, api) => { + const fetch = stub(api); + const device = named(SERVER); + change(device); + show(device); + const button = await powerButton(); + await waitFor(() => expect(button).toHaveAccessibleDescription(reason)); + expect(button).toBeDisabled(); + expect(button.closest('[title]')).toHaveAttribute('title', reason); + fireEvent.click(button); + expect(screen.queryByRole('dialog')).toBeNull(); + expect(posts(fetch)).toHaveLength(0); + }); + + it('is not blocked by a free Device with disabled capacity: only custody decides', async () => { + stub({ custody: custodyWith({ holder: { type: 'None' } }) }); + show(named(SERVER)); + expect(await enabledPower()).not.toHaveAccessibleDescription(); + }); + + it('keeps the control off after an unknown outcome, even after operations are read again', async () => { + const fetch = stub({ create: () => json('Upstream timeout', 504) }); + const { client } = show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Racked' } }); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(screen.getAllByRole('status')[0]).toHaveTextContent('Outcome unknown. Check Operations before another request.')); + expect(posts(fetch)).toHaveLength(1); + // The submit is off until the list has been reread: a second POST would be a second operation. + expect(screen.getByRole('button', { name: 'Power on' })).toBeDisabled(); + fireEvent.submit(screen.getByRole('button', { name: 'Power on' }).closest('form')!); + expect(posts(fetch)).toHaveLength(1); + // A reread does not prove the create did not land: it may still be in flight. + await act(async () => { await client.refetchQueries(); }); + expect(screen.getByRole('button', { name: 'Power on' })).toBeDisabled(); + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + expect(screen.getByRole('button', { name: 'Power' })).toHaveAccessibleDescription('Outcome unknown · check Operations, then reopen this Device'); + expect(posts(fetch)).toHaveLength(1); + }); + + it('keeps polling after a failed read, so one blip does not leave the control off', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + let fail = true; + const fetch = stub(); + const base = fetch.getMockImplementation()!; + fetch.mockImplementation(async (url: string, init?: RequestInit) => url.includes('/devicepoweroperations') && init?.method !== 'POST' && fail ? json('Unavailable', 503) : base(url, init)); + show(named(SERVER)); + const button = await powerButton(); + await waitFor(() => expect(button).toHaveAccessibleDescription('Power operations unreadable')); + fail = false; + await act(async () => { await vi.advanceTimersByTimeAsync(11_000); }); + await waitFor(() => expect(button).toBeEnabled()); + } finally { vi.useRealTimers(); } + }); + + it('closes an open request when the Device changes, and sends nothing for the old one', async () => { + const fetch = stub(); + const device = named(SERVER); + const view = show(device); + await openDialog(); + chooseValue(actionField(), 'ForceOff'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Move' } }); + fireEvent.click(screen.getByRole('button', { name: 'Continue' })); + view.rerender(); + expect(screen.queryByRole('dialog')).toBeNull(); + expect(posts(fetch)).toHaveLength(0); + }); + + it('says nothing was sent when the request fails before the POST, and stays usable', async () => { + const fetch = stub(); + const base = fetch.getMockImplementation()!; + let reviews = 0; + // The permission is checked again at submit; that check fails on the network. + fetch.mockImplementation(async (url: string, init?: RequestInit) => url.includes('selfsubjectaccessreviews') && ++reviews > 1 ? Promise.reject(new TypeError('network')) : base(url, init)); + show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Racked' } }); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(within(screen.getByRole('dialog')).getByRole('status')).toHaveTextContent('Nothing was sent. Try again.')); + expect(posts(fetch)).toHaveLength(0); + expect(screen.getByRole('button', { name: 'Power on' })).toBeEnabled(); + }); + + it('reports a session change before sending as nothing sent', async () => { + const fetch = stub(); + const session = new InventoryOperationScope(); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render(); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Racked' } }); + session.invalidate(); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(within(screen.getByRole('dialog')).getByRole('status')).toHaveTextContent('The session changed. Nothing was sent.')); + expect(posts(fetch)).toHaveLength(0); + }); + + it('reports a denied create without calling it unknown', async () => { + stub({ create: () => json('forbidden', 403) }); + show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Racked' } }); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(within(screen.getByRole('dialog')).getByRole('status')).toHaveTextContent('Power operator access is no longer valid. Nothing was created.')); + expect(screen.getByRole('button', { name: 'Power on' })).toBeEnabled(); + }); +}); + +describe('Operations history', () => { + const operation = (name: string, phase: NonNullable['phase'], extra: Partial> = {}, created = '2026-01-02T03:04:05Z'): DevicePowerOperation => ({ + metadata: { name, namespace: 'default', uid: `${name}-uid`, creationTimestamp: created, labels: { 'fleet.datumapis.com/device-uid': named(SERVER).metadata.uid! } }, + spec: { creator: { username: 'staff@example.com', uid: 's' }, deviceRef: { name: SERVER }, authority: { serviceRequest: { reason: `Reason for ${name}` } }, action: 'ForceRestart', expectedSystemUUID: UUID }, + status: { phase, ...extra }, + }); + const rows = () => within(screen.getByRole('table', { name: 'Power operations' })).getAllByRole('row').slice(1); + const resultOf = (name: string) => rows().find(row => row.textContent?.includes(`Reason for ${name}`))!.querySelector('.inventory-power-outcome')!; + + it.each<[string, DevicePowerOperation['status'], string, string | undefined]>([ + ['Pending', { phase: 'Pending' }, 'Pending', 'progress'], + ['Admitted', { phase: 'Admitted' }, 'Admitted', 'progress'], + ['Dispatched', { phase: 'Dispatched' }, 'Sent', 'progress'], + ['Verifying', { phase: 'Verifying' }, 'Verifying', 'progress'], + ['Succeeded', { phase: 'Succeeded', evidence: { requestSentAt: '2026-01-02T03:04:06Z', power: { before: { state: 'On', observedAt: '2026-01-02T03:04:05Z' }, after: { state: 'On', observedAt: '2026-01-02T03:04:41Z' } }, resetEvidence: 'LastResetTime' } }, 'Succeeded', undefined], + ['refused', { phase: 'Failed', reason: 'SystemUUIDMismatch', message: 'expectedSystemUUID is not the recorded system UUID' }, 'Refused', 'danger'], + ['failed after sending', { phase: 'Failed', reason: 'BMCRefused', evidence: { requestSentAt: '2026-01-02T03:04:06Z' } }, 'Failed', 'danger'], + ['Cancelled Expired', { phase: 'Cancelled', reason: 'Expired', message: 'a staff operation must be admitted within 5m0s' }, 'Expired', 'warning'], + ['Cancelled', { phase: 'Cancelled', reason: 'Withdrawn' }, 'Cancelled', 'warning'], + ['OutcomeUnknown', { phase: 'OutcomeUnknown', reason: 'SiteCouldNotProve' }, 'Outcome unknown', 'danger'], + ])('shows %s with its tone and reason', async (_, status, label, tone) => { + stub({ operations: [operation('one', status!.phase!, status)] }); + show(named(SERVER), 'history'); + const result = await waitFor(() => resultOf('one')); + expect(result).toHaveTextContent(new RegExp(`^${label}`)); + expect(result.getAttribute('data-tone') ?? undefined).toBe(tone); + const reason = [status!.reason, status!.message].filter(Boolean).join(' · '); + if (reason) expect(result).toHaveAttribute('title', reason); + }); + + const holdOn = (name: string, fence: number) => ({ ...fixtureCustody(SERVER)!, spec: { ...fixtureCustody(SERVER)!.spec, holder: { type: 'Service' as const }, recoveryHold: { kind: 'DevicePowerOperation', name, fence, since: '2026-01-02T03:10:00Z', reason: 'SiteCouldNotProve' } } }); + + it('names the recovery hold on an unknown outcome custody holds, matched by kind, name and admission fence', async () => { + const held = operation('held', 'OutcomeUnknown', { reason: 'SiteCouldNotProve', admission: { fence: 3 } }); + stub({ operations: [held], custody: holdOn('held', 3) }); + show(named(SERVER), 'history'); + await waitFor(() => expect(resultOf('held')).toHaveTextContent('Outcome unknown · held')); + expect(resultOf('held')).toHaveAttribute('title', 'SiteCouldNotProve\nRecovery hold since 2026-01-02T03:10:00Z'); + }); + + it.each<[string, Partial>]>([ + ['a same-name operation created later, with no admission', {}], + ['a same-name operation admitted at another fence', { admission: { fence: 9 } }], + ])('does not claim the hold for %s', async (_, admission) => { + stub({ operations: [operation('held', 'OutcomeUnknown', { reason: 'SiteCouldNotProve', ...admission })], custody: holdOn('held', 3) }); + show(named(SERVER), 'history'); + await waitFor(() => expect(resultOf('held')).toHaveTextContent(/^Outcome unknown\. SiteCouldNotProve$/)); + expect(resultOf('held')).not.toHaveTextContent(/held/i); + }); + + it('does not claim a hold for an unknown outcome custody no longer holds', async () => { + stub({ operations: [operation('settled', 'OutcomeUnknown', { reason: 'SiteCouldNotProve' })] }); + show(named(SERVER), 'history'); + await waitFor(() => expect(resultOf('settled')).toHaveTextContent(/^Outcome unknown\. SiteCouldNotProve$/)); + expect(resultOf('settled')).not.toHaveTextContent(/held/i); + }); + + it('lists action, result, power before and after, creator and reason, newest first', async () => { + stub({ operations: fixturePowerOperations.filter(item => item.spec.deviceRef.name === SERVER).reverse() }); + show(named(SERVER), 'history'); + await waitFor(() => expect(rows()).toHaveLength(4)); + expect(within(screen.getByRole('table')).getAllByRole('columnheader').map(cell => cell.textContent)).toEqual(['Time', 'Action', 'Result', 'Power', 'Creator', 'Reason']); + const cells = rows().map(row => within(row).getAllByRole('cell').slice(1).map(cell => cell.textContent)); + expect(cells[0]).toEqual(['Force restart', 'Succeeded', expect.stringMatching(/^On → On\./), 'staff@example.com', 'Hung in firmware during qualification']); + expect(cells[1]).toEqual(['Power cycle', expect.stringMatching(/^Refused/), '', 'tech@example.com', 'Retry after the BMC replacement']); + expect(cells[2]).toEqual(['Force off', expect.stringMatching(/^Expired/), '', 'tech@example.com', 'Move to rack a02']); + expect(cells[3]).toEqual(['Power on', 'Succeeded', expect.stringMatching(/^Off → On\./), 'staff@example.com', 'First power-on after racking']); + expect(within(rows()[0]).getByText('On → On')).toHaveAttribute('title', expect.stringContaining('BMC reported a reset')); + }); + + it('lists by the device-uid label, and ignores operations for another Device of the same name', async () => { + const old = operation('old', 'Succeeded'); + const fetch = stub({ operations: [{ ...old, metadata: { ...old.metadata, labels: { 'fleet.datumapis.com/device-uid': 'removed-device-uid' } } }] }); + show(named(SERVER), 'history'); + expect(await screen.findByText('No power operations')).toBeInTheDocument(); + const list = fetch.mock.calls.find(([url, init]) => url.includes('/devicepoweroperations') && init?.method !== 'POST')![0]; + expect(new URL(list, 'http://x').searchParams.get('labelSelector')).toBe(`fleet.datumapis.com/device-uid=${named(SERVER).metadata.uid}`); + }); + + it('ignores an unlabelled operation', async () => { + const bare = operation('bare', 'Succeeded'); + stub({ operations: [{ ...bare, metadata: { ...bare.metadata, labels: undefined } }] }); + show(named(SERVER), 'history'); + expect(await screen.findByText('No power operations')).toBeInTheDocument(); + }); + + it('says the history is unreadable rather than empty', async () => { + stub({ operations: 403 }); + show(named(SERVER), 'history'); + expect(await screen.findByText('Power operations unreadable')).toBeInTheDocument(); + }); +}); + +describe('header power fact', () => { + it('shows the observed state and the running operation', async () => { + stub({ operations: [{ ...fixturePowerOperations[0], status: { phase: 'Verifying' } }] }); + show(named(SERVER), 'fact'); + await waitFor(() => expect(screen.getByRole('definition')).toHaveTextContent('On Force restart · Verifying')); + }); + + it('drops an operation that ended over an hour ago', async () => { + stub({ operations: [{ ...fixturePowerOperations[0], status: { phase: 'Succeeded', finishedAt: new Date(Date.now() - 2 * 3_600_000).toISOString() } }] }); + show(named(SERVER), 'fact'); + await waitFor(() => expect(screen.getByRole('definition')).toHaveTextContent(/^On$/)); + }); + + it('keeps an unknown outcome while custody holds it', async () => { + const held = { ...fixturePowerOperations[0], status: { phase: 'OutcomeUnknown' as const, admission: { fence: 2 }, finishedAt: new Date(Date.now() - 5 * 3_600_000).toISOString() } }; + stub({ operations: [held], custody: { ...fixtureCustody(SERVER)!, spec: { ...fixtureCustody(SERVER)!.spec, recoveryHold: { kind: 'DevicePowerOperation', name: held.metadata.name, fence: 2, since: held.status.finishedAt, reason: 'SiteCouldNotProve' } } } }); + show(named(SERVER), 'fact'); + await waitFor(() => expect(screen.getByRole('definition')).toHaveTextContent('On Force restart · Outcome unknown · held')); + }); +}); diff --git a/ui/provider/src/components/device-power.tsx b/ui/provider/src/components/device-power.tsx new file mode 100644 index 00000000..ed489edf --- /dev/null +++ b/ui/provider/src/components/device-power.tsx @@ -0,0 +1,209 @@ +// Staff power on the Device page: the observed power state and the latest +// operation in the header strip, the Power control in the header actions, and +// the Operations tab. See "Device page: power" in +// docs/development/staff-inventory-ui.md. +import { Button } from '@datum-cloud/datum-ui/button'; +import { Input } from '@datum-cloud/datum-ui/input'; +import { Label } from '@datum-cloud/datum-ui/label'; +import { useQueryClient } from '@tanstack/react-query'; +import { useContext, useEffect, useId, useLayoutEffect, useRef, useState, type FormEvent } from 'react'; +import type { Device, DeviceCustody, DevicePowerOperation, PowerAction } from '../../../shared/fleet-api'; +import { ApiError } from '../lib/api'; +import { comparedSystem, powerWord, staleReason } from '../lib/device-discovery'; +import { + ACTION_WORDS, createPowerOperation, destructive, evidenceNote, offeredActions, powerBlock, powerChange, powerOutcome, POWER_QUERY_KEY, + useCaller, useCustody, usePowerOperations, usePowerPermission, type PowerOutcome, +} from '../lib/device-power'; +import { displayLabel } from '../lib/display-names'; +import { InventoryOperationContext, InventoryOperationGenerationContext, InventoryOperationInvalidated, InventoryOperationReadyContext, InventoryOperationScope } from '../lib/inventory-operation'; +import { formatAge } from '../lib/telemetry'; +import { FieldSelect } from './field-select'; +import { InventoryDraftGuard, InventoryForm, InventoryFormSurface } from './inventory-form-surface'; +import { SmallTable } from './inventory-record-layout'; + +const HOUR = 3_600_000; + +/** A phase badge: the reason and any recovery hold are its tooltip and accessible text. */ +export function PowerOutcomeBadge({ outcome, prefix }: { outcome: PowerOutcome; prefix?: string }) { + const note = [outcome.reason, outcome.hold].filter(Boolean).join('\n') || undefined; + return + {prefix && <>{prefix} · }{outcome.label}{outcome.hold && } + {note && . {note}} + ; +} + +/** + * The header's power fact: the observed state, then the latest operation + * while it runs, for an hour after it ends, or while custody holds it. + */ +export function DevicePowerFact({ device }: { device: Device }) { + const operations = usePowerOperations(device); + const custody = useCustody(device); + const system = comparedSystem(device); + const stale = staleReason(device.status?.discovery?.inventory, device); + const state = powerWord(system?.powerState); + const latest = operations.data?.[0]; + const outcome = latest && powerOutcome(latest, custody.data); + const finished = latest?.status?.finishedAt ? Date.parse(latest.status.finishedAt) : NaN; + const recent = outcome && (outcome.tone === 'progress' || !!outcome.hold || !(Date.now() - finished > HOUR)); + if (!state && !recent) return null; + return
Power
+ {state && {state}{stale && . Check: {stale}}} + {recent && latest && <> } +
; +} + +function failureMessage(error: unknown, sent: boolean): { message: string; uncertain: boolean } { + if (error instanceof InventoryOperationInvalidated) return { message: error.dispatched ? 'Outcome unknown: the session changed after sending. Check Operations before another request.' : 'The session changed. Nothing was sent.', uncertain: error.dispatched }; + if (error instanceof ApiError && error.status === 422) return { message: `Rejected: ${error.message}`, uncertain: false }; + if (error instanceof ApiError && [401, 403].includes(error.status)) return { message: 'Power operator access is no longer valid. Nothing was created.', uncertain: false }; + // Before the POST went out, nothing can have been created. + if (!sent) return { message: 'Nothing was sent. Try again.', uncertain: false }; + return { message: 'Outcome unknown. Check Operations before another request.', uncertain: true }; +} + +/** + * The Power button and its dialog. Hidden without the power operator role; + * disabled, with the reason as its tooltip, when the Device cannot be powered + * now. A destructive action asks again, naming the server. + */ +export function DevicePowerControl({ device }: { device: Device }) { + const client = useQueryClient(); + const session = useContext(InventoryOperationContext); + const ready = useContext(InventoryOperationReadyContext); + const generation = useContext(InventoryOperationGenerationContext); + const permission = usePowerPermission(true); + const permitted = permission.data === true && !permission.error; + const caller = useCaller(permitted); + const custody = useCustody(device); + const operations = usePowerOperations(device); + const scope = useRef(new InventoryOperationScope()); + const [open, setOpen] = useState(false); + const [action, setAction] = useState(''); + const [reason, setReason] = useState(''); + const [confirming, setConfirming] = useState(false); + const [pending, setPending] = useState(false); + const [message, setMessage] = useState(''); + // A create whose outcome is unknown may still land, and a second POST would be a second + // operation, so the control stays off until the Device page is opened again. + const [uncertain, setUncertain] = useState(false); + const hintID = useId(); + useEffect(() => () => scope.current.invalidate(), []); + // As in the location editor: leaving the page, a new session or navigation, or a changed + // Device ends the open request, so a confirmation never names a state the page no longer shows. + useLayoutEffect(() => { + const invalidate = () => scope.current.invalidate(); + const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; + window.addEventListener('pagehide', invalidate); + document.addEventListener('visibilitychange', visibility); + return () => { window.removeEventListener('pagehide', invalidate); document.removeEventListener('visibilitychange', visibility); }; + }, []); + useLayoutEffect(() => { + scope.current.invalidate(); + setOpen(false); setAction(''); setReason(''); setConfirming(false); + }, [device.metadata.uid, device.metadata.resourceVersion, session, generation]); + if (!permitted) return null; + const server = displayLabel(device); + const offered = offeredActions(device); + const block = powerBlock(device, { custody: custody.data, custodyError: custody.error, operations: operations.data }) + ?? (caller.error ? 'Your username and UID could not be read' : !caller.data || !ready || permission.isFetching ? 'Checking access…' : undefined) + ?? (operations.error ? 'Power operations unreadable' : undefined) + ?? (uncertain ? 'Outcome unknown · check Operations, then reopen this Device' : undefined); + const chosen = offered.find(item => item === action); + const dirty = open && (!!action || !!reason); + function reset() { setAction(''); setReason(''); setConfirming(false); } + function dismiss() { + if (pending) return; + if (dirty && !uncertain && !window.confirm('Discard this power request?')) return; + scope.current.invalidate(); setOpen(false); reset(); + } + async function send() { + if (!chosen || !caller.data || pending || block) return; + const operation = scope.current.begin(session); + setPending(true); setMessage(''); + try { + await createPowerOperation(device, chosen, reason, caller.data, operation); + setOpen(false); reset(); setMessage(`${ACTION_WORDS[chosen]} requested`); + } catch (error) { + const failure = failureMessage(error, operation.sent); + setMessage(failure.message); + if (failure.uncertain) { setUncertain(true); setConfirming(false); } + } finally { + setPending(false); + await client.invalidateQueries({ queryKey: POWER_QUERY_KEY }); + } + } + function submit(event: FormEvent) { + event.preventDefault(); + if (!chosen || block) return; + if (destructive(chosen) && !confirming) { setConfirming(true); return; } + void send(); + } + const hint = block ? { id: hintID, text: block } : undefined; + const status =

{message}

; + const verb = chosen ? ACTION_WORDS[chosen] : 'Continue'; + return
+ {open && } + { if (block) return; scope.current = new InventoryOperationScope(); reset(); setMessage(''); setOpen(true); }}>Power}> + +
+ + +
+ {confirming && chosen &&

+ {ACTION_WORDS[chosen]} {server}? +

} +
+ + +
+
+
+
; +} + +const HISTORY_LIMIT = 20; + +function Time({ value, now }: { value?: string; now: number }) { + const at = value ? Date.parse(value) : NaN; + if (!Number.isFinite(at)) return null; + return ; +} + +function historyRow(operation: DevicePowerOperation, custody: DeviceCustody | null | undefined, now: number) { + const evidence = operation.status?.evidence; + const change = powerChange(evidence); + const note = evidenceNote(evidence); + const reason = operation.spec.authority.serviceRequest?.reason; + return [ +