diff --git a/config/README.md b/config/README.md index 59e7cfb7..a456ebc9 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 c5ca1033..0376e47f 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -807,6 +807,255 @@ 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 + 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 c42c594f..8f868515 100644 --- a/config/components/device-operations/protected-resources/kustomization.yaml +++ b/config/components/device-operations/protected-resources/kustomization.yaml @@ -4,6 +4,7 @@ resources: - devicecustody.yaml - deviceinstallation.yaml - devicewipe.yaml + - devicepoweroperation.yaml - devicerecovery.yaml - devicecommissioning.yaml - devicecommissioningplan.yaml diff --git a/config/components/device-operations/roles/coordinator.yaml b/config/components/device-operations/roles/coordinator.yaml index 77b5c27b..2773486d 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 ca35ee2b..75a3be27 100644 --- a/config/components/device-operations/roles/kustomization.yaml +++ b/config/components/device-operations/roles/kustomization.yaml @@ -10,3 +10,5 @@ resources: - device-commissioning-plan-author.yaml - device-commissioning-plan-approver.yaml - capacity-projector.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 49feb7c2..0be137c2 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 cc3ba1e7..04c2f8d6 100644 --- a/config/components/device-operations/webhook.yaml +++ b/config/components/device-operations/webhook.yaml @@ -22,5 +22,5 @@ webhooks: operations: [CREATE, UPDATE] # The same list as creatorwebhook.Resources and the standalone creator # policy; TestPackagedResourcesMatch keeps them in step. - resources: [deviceinstallations, devicewipes, devicerecoveries, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] + resources: [deviceinstallations, devicewipes, devicepoweroperations, devicerecoveries, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] scope: Namespaced diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index d1c89965..f7a4b957 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -130,10 +130,10 @@ rules: resources: [devicecustodies] verbs: [get, list, watch, create, update, delete] - apiGroups: [fleet.datumapis.com] - resources: [deviceinstallations, devicewipes, devicerecoveries, devicecommissionings] + resources: [deviceinstallations, devicewipes, devicepoweroperations, devicerecoveries, devicecommissionings] verbs: [get, list, watch, delete] - apiGroups: [fleet.datumapis.com] - resources: [deviceinstallations/status, devicewipes/status, devicerecoveries/status, devicecommissionings/status] + resources: [deviceinstallations/status, devicewipes/status, devicepoweroperations/status, devicerecoveries/status, devicecommissionings/status] verbs: [get, update] - apiGroups: [fleet.datumapis.com] resources: [devicecommissioningplans, devicecommissioningplanapprovals] diff --git a/config/standalone/site.yaml b/config/standalone/site.yaml index 156a7c6e..9ce143ba 100644 --- a/config/standalone/site.yaml +++ b/config/standalone/site.yaml @@ -57,7 +57,7 @@ spec: operations: [CREATE, UPDATE] # The same list as the packaged webhook; TestPackagedResourcesMatch # keeps them in step. - resources: [deviceinstallations, devicewipes, devicerecoveries, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] + resources: [deviceinstallations, devicewipes, devicepoweroperations, devicerecoveries, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] validations: - expression: "request.operation != 'CREATE' || (object.spec.creator.username == request.userInfo.username && (has(object.spec.creator.uid) ? object.spec.creator.uid : '') == (has(request.userInfo.uid) ? request.userInfo.uid : ''))" message: spec.creator must be the authenticated caller's username, and UID when it has one diff --git a/docs/development/README.md b/docs/development/README.md index a7f817f2..d29ccc22 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -38,6 +38,8 @@ 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 and both multi-plane runs verify it. The end-to-end failure scenarios (Increment D) are implemented, and both multi-plane runs verify them. +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 c3355627..3e8f7b08 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -17,10 +17,12 @@ marked **implemented and verified**, **implemented and inert**, or | 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, the standalone smoke (`task standalone:test`), and both multi-plane runs, local VM and Redfish. | | D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests, and the two site fixes they found. See [Failure scenarios](#failure-scenarios-increment-d). | **Implemented and verified** by unit tests and both multi-plane runs, local VM and Redfish. | | Commissioning, step 1 | `DeviceCommissioning`, `DeviceCommissioningPlan` and `DeviceCommissioningPlanApproval`: CRDs, ProtectedResources, roles, the creator webhook route, the kind and its rows, plan qualification and the current plan. See [Commissioning](#commissioning). | **Implemented and inert.** Verified by tests against a real API server. No site runs a commissioning worker yet, and no mode creates one. | +| Power P1: control plane | `DevicePowerOperation`, its registry entry, rows, checks, evidence and settle hook, its roles, and the Device field for offered reset types. See [Device power operations](#device-power-operations). | **Implemented.** The kind ships with the component in every root C wires, and the creator webhook, standalone's creator policy and each coordinator's access cover it. Nothing creates power operations yet. Discovery records the reset types each server offers. | +| Power P2 to P4 | The site worker (on B), customer power from `Machine.spec.powerState` (on C), and the UI | **Proposed** | ## 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 @@ -489,7 +491,11 @@ Each decision lists the open point from the implementation brief it settles. before the shared identity and key checks of rules 5 and 6, so a kind's more specific reason, such as power's `SystemUUIDNotRecorded`, is the one reported. All rules must hold either way; the order decides only the - reason. A staff + reason. A rule 7 refusal may wait instead, for a condition that can clear + by itself: an operation on a queue row then stays `Pending` with that + reason for a bounded time the refusal sets, counted from when the operation + was created or the Device's last operation finished, whichever is later, + and ends `Failed` only after that. A staff row never waits. A staff operation not admitted within five minutes ends `Cancelled` with reason `Expired`. This implementation adds `NameMismatch`, for an operation not named by its rule, and outcome reasons: `Superseded`, `Withdrawn`, @@ -565,6 +571,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 @@ -1141,7 +1148,9 @@ four seams. It needs no change to the coordinator. The test-only kinds in preconditions, before the custody update, and return a named refusal, such as power's `SystemUUIDMismatch` or `DiscoveryNotCurrent`. A check sees the same Device object the snapshot records, the coordinator's - injected clock as `Admission.Now`, and `Admission.DiscoveryInterval`; + injected clock as `Admission.Now`, and `Admission.DiscoveryInterval`. + A refusal whose condition can clear by itself sets `Wait`, the most a + queue row's operation waits for it in `Pending`; - `Reasons`, every refusal reason the kind raises, each marked as raised by the coordinator, the worker, or both. A refusal with a reason that is neither shared nor declared is recorded as `UndeclaredReason`; @@ -1179,10 +1188,12 @@ four seams. It needs no change to the coordinator. The test-only kinds in the site's `Runner.Kinds` under the kind's name. See `internal/site/redfishwork` and its tests. 4. **Define its evidence.** Set `Evidence` to `custody.StrictEvidence` over a - typed, bounded Go struct. Its validator receives the operation, so it can - require what that operation must prove, such as reset proof for a - restart. Set `EvidenceRequired` if a success without evidence proves - nothing. Unknown fields, oversized evidence and trailing + typed, bounded Go struct. Its validator receives the operation, and sees + the evidence of every phase, so it checks only what holds for all of them. + Set `EvidenceRequired` if a success without evidence proves nothing, and + `ProvesSuccess`, with `custody.TypedProof`, to require what only a success + must prove, such as reset proof for a restart. A success it rejects ends + `OutcomeUnknown` with `InvalidEvidence`, under a hold. Unknown fields, oversized evidence and trailing data are rejected, and the result then proves nothing. Evidence never carries a credential or a raw BMC response. If a `DeviceRecovery` `Settle` can settle a hold of the kind, set `RecoverySettle` to validate the staff @@ -1196,6 +1207,53 @@ 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` refuses only when discovery observed the system's reset actions and they lack this one. Otherwise, as when the BMC offers none or discovery could not read its ActionInfo, admission goes ahead and the worker checks the live BMC, ending `Failed` with nothing sent if the action is not offered. Discovery marks each system whose reset actions it read in that pass, even when the list is empty, and only that mark counts as observed. `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. Discovery can return, so a provider operation refused `DiscoveryNotCurrent` waits in `Pending` for up to twice the discovery interval, counted from when it was created or the Device's last operation finished, and only then ends `Failed`. A staff operation fails at once. | +| 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. A success must also prove itself: both reads, `power.after` in the requested state (`Off` for `ForceOff`, `On` otherwise), a sent command unless `power.before` already showed that state, and for a restart or power cycle, a sent command and `resetEvidence`. Anything less ends `OutcomeUnknown` with `InvalidEvidence`, under a hold. 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, which BMC discovery records with GETs only. | + +The worker reasons `Stale`, `NotPoweredOn` and `PowerStateNotSettled` before +a command, the start-by window and the journal payload arrive with the worker +in B. + +### Foundation seams power added + +Power needed two general seams in the foundation, and adds them rather than +working around their absence: + +- **A kind check can wait.** Rule 7 runs before rule 5, and a kind check + could only refuse, so a short discovery lapse failed a provider power + request for good: it is named from the Machine generation, and is not + created again until the generation changes. A check refusal now sets + `Wait` for a condition that can clear by itself, and a queue row's + operation waits for it in `Pending`, bounded as above. +- **A kind can require proof of a success.** The evidence hook sees every + phase's evidence, so it could not require what only a success proves, and + a `Succeeded` restart with no reset proof, or with the empty object `{}`, + was accepted. `ProvesSuccess` runs on a `Succeeded` result's evidence only. + ## Tests Run `task test:envtest`. It runs these tests with the race detector against @@ -1218,6 +1276,9 @@ 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, including callers whose credential carries no UID | `TestHandler`, `TestCreatorAgainstAPIServer`, `TestStandaloneCreatorPolicyAgainstAPIServer`, `TestCreatorIdentifiesTheCallerByUsername` | | 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, a provider request waiting for discovery (its bound, its replacement, and two coordinators admitting it once), and proof of a success, including a retry's | `TestPowerOperations` | +| A check refusal that waits only on a queue row, within its bound from when the Device was last free, and only with a declared reason; proof of success needs required evidence | `TestExtensionSeams`, `TestRegistryRequiresEvidenceForProofOfSuccess` | +| Power: CEL inputs and evidence pruning, checks, input digest, evidence bounds, registration | `TestPowerCRDRules`, `TestPowerChecks`, `TestPowerInputDigestIsStable`, `TestPowerEvidenceIsTypedAndBounded`, `TestPowerRegistration` | Increment A has no site, so "nothing was sent" means custody admitted nothing and the fence did not rise. Increment D's phases prove it end to end, with the diff --git a/hack/multiplane/custody_crd_rules.py b/hack/multiplane/custody_crd_rules.py index 7307959c..b6246d64 100644 --- a/hack/multiplane/custody_crd_rules.py +++ b/hack/multiplane/custody_crd_rules.py @@ -19,7 +19,7 @@ namespace = 'fleet-rules' objects = (('devicerecovery', 'rules-recovery'), ('devicecustody', 'server-example-001'), ('devicecommissioning', 'rules-commissioning'), ('devicecommissioningplanapproval', 'rules-plan-0123456789abcdef'), ('devicecommissioningplan', 'rules-plan')) -names = ('devicecustodies', 'deviceinstallations', 'devicewipes', 'devicerecoveries', 'devicecommissionings', 'devicecommissioningplans', +names = ('devicecustodies', 'deviceinstallations', 'devicewipes', 'devicepoweroperations', 'devicerecoveries', 'devicecommissionings', 'devicecommissioningplans', 'devicecommissioningplanapprovals') DIGEST = 'sha256:' + '0' * 64 diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index c783bfea..ae77b20c 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -76,7 +76,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', 'devicecommissionings.fleet.datumapis.com', 'devicecommissioningplans.fleet.datumapis.com', + 'devicepoweroperations.fleet.datumapis.com', 'devicerecoveries.fleet.datumapis.com', 'devicecommissionings.fleet.datumapis.com', 'devicecommissioningplans.fleet.datumapis.com', 'devicecommissioningplanapprovals.fleet.datumapis.com', 'machineallocations.metal.datumapis.com') diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 4e223e2f..58f2011b 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -97,8 +97,8 @@ def wait(fn,seconds,what): # coordinator.yaml: it lists and settles every registered operation kind. 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','devicecommissionings'],'verbs':['get','list','watch','delete']}, - {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicerecoveries/status','devicecommissionings/status'],'verbs':['get','update']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicepoweroperations','devicerecoveries','devicecommissionings'],'verbs':['get','list','watch','delete']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicepoweroperations/status','devicerecoveries/status','devicecommissionings/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}, {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}], 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}], diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index 7c6bcbf6..7507c90d 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 devicecommissionings devicecommissioningplans devicecommissioningplanapprovals; do +for crd in devices devicecustodies deviceinstallations devicewipes devicepoweroperations devicerecoveries devicecommissionings devicecommissioningplans devicecommissioningplanapprovals; 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 @@ -150,7 +150,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 devicecommissionings devicecommissioningplans devicecommissioningplanapprovals machineallocations; do + for resource in devicecustodies deviceinstallations devicewipes devicepoweroperations devicerecoveries devicecommissionings devicecommissioningplans devicecommissioningplanapprovals 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/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index 5d33b255..91b637b6 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", "DeviceCommissioning"} + operationKinds = []string{"DeviceInstallation", "DeviceWipe", "DevicePowerOperation", "DeviceRecovery", "DeviceCommissioning"} // planKinds are staff records, not operations: an immutable spec with a // creator, and no status. planKinds = []string{"DeviceCommissioningPlan", "DeviceCommissioningPlanApproval"} @@ -125,6 +126,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 { @@ -199,11 +230,13 @@ 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...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), "fleet.datumapis.com-device-commissioning-operator": p(group+"devicecommissionings", "create"), "fleet.datumapis.com-device-commissioning-plan-author": p(group+"devicecommissioningplans", "create", "delete"), "fleet.datumapis.com-device-commissioning-plan-approver": p(group+"devicecommissioningplanapprovals", "create", "delete"), + "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...), p(group+"devices", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), @@ -212,7 +245,7 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { "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", "devicecommissionings"} { + for _, plural := range []string{"deviceinstallations", "devicewipes", "devicepoweroperations", "devicerecoveries", "devicecommissionings"} { coordinator = slices.Concat(coordinator, p(group+plural, "get", "list", "watch", "delete", "updateStatus"), []string{group + plural + "/status.update"}) } coordinator = slices.Concat(coordinator, p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)) @@ -232,7 +265,7 @@ 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" || strings.HasPrefix(name, "fleet.datumapis.com-device-commissioning-") { + if name == "fleet.datumapis.com-device-recovery-operator" || name == "fleet.datumapis.com-device-power-operator" || strings.HasPrefix(name, "fleet.datumapis.com-device-commissioning-") { if len(current.Spec.Inherited) != 1 || current.Spec.Inherited[0].Name != "fleet.datumapis.com-device-operations-viewer" { t.Fatalf("%s inherits only the viewer", name) } @@ -256,13 +289,27 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { } } } - // Staff can never create provider or release kinds. - staffCreates := []string{group + "devicerecoveries.create", group + "devicecommissionings.create", group + "devicecommissioningplans.create", group + "devicecommissioningplanapprovals.create"} - for _, staff := range []string{"fleet.datumapis.com-device-operations-viewer", "fleet.datumapis.com-device-recovery-operator", "fleet.datumapis.com-device-commissioning-operator", "fleet.datumapis.com-device-commissioning-plan-author", "fleet.datumapis.com-device-commissioning-plan-approver"} { - for _, permission := range roles[staff].Spec.Included { - if strings.HasSuffix(permission, ".create") && !slices.Contains(staffCreates, permission) { + // 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", + "fleet.datumapis.com-device-commissioning-operator": group + "devicecommissionings.create", + "fleet.datumapis.com-device-commissioning-plan-author": group + "devicecommissioningplans.create", + "fleet.datumapis.com-device-commissioning-plan-approver": group + "devicecommissioningplanapprovals.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 a5aaa47d..2bb6cf52 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -461,6 +461,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 addCommissioning(s) } diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 125e94a4..bd35e444 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -787,6 +787,10 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } // Precondition 4: one active operation. if custody.Spec.ActiveOperation != nil || (row.Queue && queueAhead) { + if row.Queue && custody.Spec.ActiveOperation == nil { + // An older queued operation is waiting, such as for discovery. + return decision{phase: ops.PhasePending, reason: ReasonOperationInProgress, message: "waiting for an older queued operation"} + } if row.Queue { return decision{phase: ops.PhasePending, reason: ReasonOperationInProgress, message: "waiting for the running operation"} } @@ -798,6 +802,9 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper // that is not recorded, is the one reported. if kind.Check != nil { if refusal := c.Registry.declaredRefusal(kind.GVK.Kind, settleHookKind(kind, row, custody), kind.Check(ctx, admission)); refusal != nil { + if since := waitingSince(operation, custody); row.Queue && refusal.Wait > 0 && now.Before(since.Add(refusal.Wait)) { + return decision{phase: ops.PhasePending, reason: refusal.Reason, message: "waiting: " + refusal.Message} + } return fail(refusal.Reason, "%s", refusal.Message) } } @@ -825,6 +832,18 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper return decision{row: row, settles: settles, extra: extra} } +// waitingSince is when the operation could first have been admitted: when it +// was created, or when the Device's last operation finished, if later. A +// Check refusal that waits counts its bound from here, so time spent queued +// behind another operation or a hold does not use the bound up. +func waitingSince(operation ops.Operation, custody *ops.DeviceCustody) time.Time { + since := operation.GetCreationTimestamp().Time + if last := custody.Spec.LastResult; last != nil && last.FinishedAt.After(since) { + since = last.FinishedAt.Time + } + return since +} + // wait returns Pending for queue rows and Failed otherwise. func (c *Coordinator) wait(class CreatorClass, reason, message string) decision { if class != CreatorStaff { diff --git a/internal/custody/creatorwebhook/handler.go b/internal/custody/creatorwebhook/handler.go index 4164c418..75c9745c 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", "devicecommissionings", "devicecommissioningplans", "devicecommissioningplanapprovals"} +var Resources = []string{"deviceinstallations", "devicewipes", "devicepoweroperations", "devicerecoveries", "devicecommissionings", "devicecommissioningplans", "devicecommissioningplanapprovals"} // 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..93860eea --- /dev/null +++ b/internal/custody/creatorwebhook/resources_test.go @@ -0,0 +1,68 @@ +package creatorwebhook + +import ( + "bufio" + "bytes" + "io" + "os" + "path/filepath" + "slices" + "testing" + + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/util/yaml" +) + +// governed is every kind whose creator the webhook checks. A new operation +// kind is added here and to Resources. +var governed = []string{ + "deviceinstallations", "devicewipes", "devicepoweroperations", "devicerecoveries", + "devicecommissionings", "devicecommissioningplans", "devicecommissioningplanapprovals", +} + +// TestEveryOperationKindIsGoverned requires the webhook's resource list to +// name every kind the custody CRDs define except DeviceCustody, so a new kind +// cannot ship with an unchecked creator. TestPackagedResourcesMatch keeps the +// packaged webhook and standalone's policy in step with the list. +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 := slices.Sorted(slices.Values(governed)) + if got := slices.Sorted(slices.Values(kinds)); !slices.Equal(got, want) { + t.Fatalf("the custody CRDs define %v, want %v", got, want) + } + if got := slices.Sorted(slices.Values(Resources)); !slices.Equal(got, want) { + t.Fatalf("Resources = %v, want %v", got, want) + } +} + +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/extension_test.go b/internal/custody/extension_test.go index bae82818..631c1408 100644 --- a/internal/custody/extension_test.go +++ b/internal/custody/extension_test.go @@ -174,6 +174,84 @@ func TestExtensionSeams(t *testing.T) { } }) + t.Run("a check refusal that waits keeps a queue row Pending until it clears, and fails staff at once", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-wait"); err != nil { + t.Fatal(err) + } + before := e.custody(device.Name).Spec + waiting := e.providerOp(device, "alloc-wait", "wait") + e.settle(device.Name) + status := e.requirePhase(waiting, ops.PhasePending, reasonTestRefuse) + if !strings.Contains(status.Message, "waits for its Device") { + t.Fatalf("message = %s", status.Message) + } + e.requireUntouched(device.Name, before.Fence) + // A later queued operation waits behind it, and says so. Newer by + // at least the API server's one-second timestamp. + time.Sleep(1100 * time.Millisecond) + behind := e.installation(device, "alloc-wait", "request-behind") + e.settle(device.Name) + if status := e.requirePhase(behind, ops.PhasePending, ReasonOperationInProgress); !strings.Contains(status.Message, "older queued operation") { + t.Fatalf("message = %s", status.Message) + } + // The condition clears within the bound, and the operation is + // admitted on the next pass with nothing else changed. + e.clock.Advance(testWait - time.Minute) + ready(e, device) + e.settle(device.Name) + e.requirePhase(waiting, ops.PhaseAdmitted, "") + e.requirePhase(behind, ops.PhasePending, ReasonOperationInProgress) + + // A staff row never waits, even for a refusal that would. + staff := fresh() + refused := e.staffOp(staff, "wait") + e.settle(staff.Name) + e.requirePhase(refused, ops.PhaseFailed, reasonTestRefuse) + }) + + t.Run("a waiting refusal ends Failed after its bound, counted from when the Device was last free", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-bound"); err != nil { + t.Fatal(err) + } + running := e.providerOp(device, "alloc-bound", "ok") + e.settle(device.Name) + e.requirePhase(running, ops.PhaseAdmitted, "") + waiting := e.providerOp(device, "alloc-bound", "wait") + e.settle(device.Name) + e.requirePhase(waiting, ops.PhasePending, ReasonOperationInProgress) + // Queued behind the running operation for longer than the bound. + e.clock.Advance(testWait + 3*time.Minute) + if err := e.result(device.Name, ops.PhaseSucceeded, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(running, ops.PhaseSucceeded, "") + e.requirePhase(waiting, ops.PhasePending, reasonTestRefuse) + e.clock.Advance(testWait - time.Second) + e.settle(device.Name) + e.requirePhase(waiting, ops.PhasePending, reasonTestRefuse) + before := e.custody(device.Name).Spec + e.clock.Advance(2 * time.Second) + e.settle(device.Name) + e.requirePhase(waiting, ops.PhaseFailed, reasonTestRefuse) + e.requireUntouched(device.Name, before.Fence) + }) + + t.Run("a waiting refusal with a reason the kind never declared fails at once", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-undeclared-wait"); err != nil { + t.Fatal(err) + } + operation := e.providerOp(device, "alloc-undeclared-wait", "wait-undeclared") + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonUndeclared) + }) + t.Run("Retry applies only to a kind that declares it", func(t *testing.T) { e := e.sub(t) device := fresh() @@ -236,6 +314,33 @@ func TestExtensionSeams(t *testing.T) { }) } +// ready marks the Device ready for the test kinds' waiting check. +func ready(e *env, device *inventory.Device) { + e.t.Helper() + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + e.t.Fatal(err) + } + if device.Annotations == nil { + device.Annotations = map[string]string{} + } + device.Annotations[testReadyAnnotation] = "true" + if err := e.admin.Update(e.ctx, device); err != nil { + e.t.Fatal(err) + } +} + +func TestRegistryRequiresEvidenceForProofOfSuccess(t *testing.T) { + kind := testKinds()[0] + kind.ProvesSuccess = func(ops.Operation, []byte) error { return nil } + if err := NewRegistry().Register(kind); err == nil { + t.Fatal("registered proof of success without required evidence") + } + kind.EvidenceRequired = true + if err := NewRegistry().Register(kind); err != nil { + t.Fatal(err) + } +} + func TestRegistryValidatesDeclaredReasons(t *testing.T) { for name, reasons := range map[string][]Reason{ "not CamelCase": {{Name: "not-camel", RaisedBy: RaisedByCoordinator}}, diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 36aa7aa0..eb45f456 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(), DeviceCommissioningKind()} { + for _, kind := range []Kind{DeviceInstallationKind(), DeviceWipeKind(), DevicePowerOperationKind(), DeviceRecoveryKind(), DeviceCommissioningKind()} { if err := registry.Register(kind); err != nil { return nil, err } } - for _, rule := range append(DefaultRules(), CommissioningRules()...) { + for _, rule := range slices.Concat(DefaultRules(), CommissioningRules(), 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..29dc0ca4 --- /dev/null +++ b/internal/custody/power.go @@ -0,0 +1,316 @@ +package custody + +import ( + "context" + "errors" + "fmt" + "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, + ProvesSuccess: TypedProof(provePowerSuccess), + 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 that is not current can return, so + // a provider operation waits for it for as long again; a staff one + // fails at once. + discovery := device.Status.Discovery + maxAge := 2 * admission.DiscoveryInterval + notCurrent := func(format string, args ...any) *Refusal { + refusal := refuse(ReasonDiscoveryNotCurrent, format, args...) + refusal.Wait = maxAge + return refusal + } + if discovery == nil || discovery.Inventory == nil || device.Spec.BMC == nil || discovery.Inventory.Endpoint != device.Spec.BMC.Endpoint { + return notCurrent("discovery has not read the inventory at the current BMC endpoint") + } + if age := admission.Now.Sub(discovery.Inventory.ObservedAt.Time); age > maxAge { + return notCurrent("discovery last read the BMC %s ago; the limit is %s", age.Truncate(time.Second), maxAge) + } + system := discoveredSystem(device) + if system == nil { + return notCurrent("discovery has not read the system with the recorded UUID") + } + // Only reset actions discovery observed prove what the BMC offers. + // Otherwise the coordinator admits and the worker's live check at the + // BMC decides, with nothing sent if the action is not offered. + if resetTypesObserved(system) && !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 +} + +// resetTypesObserved reports whether this discovery pass read the system's +// advertised reset actions, even an empty list. Without that read, an +// omitted list may mean the BMC offers none or that the ActionInfo read +// failed. +func resetTypesObserved(system *inventory.ObservedSystem) bool { + return system.ResetTypesObserved +} + +// powerSnapshot records what the reset-type check read: the power actions +// the system offered, the system, and when discovery read them. An empty +// resetTypes means discovery recorded none. +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 +} + +// provePowerSuccess accepts a Succeeded result only with evidence of the +// requested power state, read after the command, and for a restart or power +// cycle, proof of the reset. A server already in the requested state needs +// no command: both reads then show that state. +func provePowerSuccess(operation ops.Operation, evidence *ops.PowerEvidence) error { + action := operation.(*ops.DevicePowerOperation).Spec.Action + want := ops.PowerStateOn + if action == ops.PowerForceOff { + want = ops.PowerStateOff + } + if evidence.Power == nil || evidence.Power.Before == nil || evidence.Power.After == nil { + return errors.New("a power success needs power.before and power.after") + } + before, after := evidence.Power.Before, evidence.Power.After + if after.State != want { + return fmt.Errorf("%s needs power.after %s, not %s", action, want, after.State) + } + switch { + case action.Resets() && (evidence.RequestSentAt == nil || evidence.ResetEvidence == ""): + return fmt.Errorf("%s needs the command and proof of the reset", action) + case evidence.RequestSentAt == nil && before.State != want: + return fmt.Errorf("the server was %s before, so %s needs the command", before.State, action) + } + 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..27376aba --- /dev/null +++ b/internal/custody/power_test.go @@ -0,0 +1,1070 @@ +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 + // A fixture read observes the reset actions whenever it names some; a + // test that needs otherwise sets ResetTypesObserved in mutate. + discovery.Inventory.Systems = []inventory.ObservedSystem{{ID: "1", UUID: device.Spec.Identity.SystemUUID, PowerState: state, ResetTypes: resetTypes, ResetTypesObserved: len(resetTypes) > 0}} + 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: "discovery observed that the BMC offers no reset types", reason: ReasonResetTypeNotOffered, discovery: func(d *inventory.DeviceDiscovery) { + d.Inventory.Systems[0].ResetTypes, d.Inventory.Systems[0].ResetTypesObserved = nil, true + }}, + {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"} + }}, + } { + 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("reset types not observed admit, and the worker's live check refuses at the BMC", func(t *testing.T) { + // Neither a nil nor an empty list shows that discovery read the reset + // actions: the BMC may offer none, or the ActionInfo read failed. + for name, recorded := range map[string][]string{"omitted": nil, "empty": {}} { + t.Run(name, func(t *testing.T) { + e := e.sub(t) + device, key := fresh(e) + e.discoverPower(device, key, e.clock.Now(), "On", recorded, nil) + operation := e.staffPower(device, ops.PowerForceRestart, device.Spec.Identity.SystemUUID) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseAdmitted, "") + active := e.custody(device.Name).Spec.ActiveOperation + if active == nil || active.Snapshot.Extra[SnapshotResetTypes] != "" { + t.Fatalf("active = %+v", active) + } + // The worker finds the action not offered at the BMC and sends + // nothing: the operation ends Failed, with no hold. + if err := e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: active.OperationReference, Fence: active.Fence, + Phase: ops.PhaseFailed, Reason: ReasonResetTypeNotOffered}); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonResetTypeNotOffered) + if custody := e.custody(device.Name); custody.Spec.RecoveryHold != nil || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("custody = %+v", custody.Spec) + } + }) + } + }) + + 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, "") + }) + + // lapsed claims a fresh Device for an allocation and leaves its last + // discovery 30 minutes old, past the 20 minutes a coordinator with a + // ten-minute discovery interval accepts. + lapsed := func(e *env, allocation string) (*inventory.Device, string, func(client.Client) *Coordinator) { + device, key := fresh(e) + if err := e.coord.Claim(e.ctx, device.Name, device.UID, allocation); err != nil { + e.t.Fatal(err) + } + e.discoverPower(device, key, e.clock.Now().Add(-30*time.Minute), "On", allActions, nil) + return device, key, func(api client.Client) *Coordinator { + coordinator := e.coordinator(api) + coordinator.Config.DiscoveryInterval = 10 * time.Minute + return coordinator + } + } + + t.Run("a provider request waits while discovery is not current and is admitted when it returns", func(t *testing.T) { + e := e.sub(t) + allocation := "alloc-lapse" + device, key, coordinator := lapsed(e, allocation) + before := e.custody(device.Name).Spec + operation := e.providerPower(device, allocation, 4, ops.PowerOn, "") + settleWith(t, e.ctx, coordinator(e.admin), device.Name) + e.requirePhase(operation, ops.PhasePending, ReasonDiscoveryNotCurrent) + e.requireCustodyUnchanged(device.Name, before) + // Still waiting, short of the bound, with nothing sent. + e.clock.Advance(15 * time.Minute) + settleWith(t, e.ctx, coordinator(e.admin), device.Name) + e.requirePhase(operation, ops.PhasePending, ReasonDiscoveryNotCurrent) + e.requireCustodyUnchanged(device.Name, before) + e.discoverPower(device, key, e.clock.Now(), "On", allActions, nil) + settleWith(t, e.ctx, coordinator(e.admin), device.Name) + e.requirePhase(operation, ops.PhaseAdmitted, "") + }) + + t.Run("a provider request fails DiscoveryNotCurrent only once discovery has been gone for twice the interval", func(t *testing.T) { + e := e.sub(t) + allocation := "alloc-gone" + device, _, coordinator := lapsed(e, allocation) + operation := e.providerPower(device, allocation, 5, ops.PowerForceOff, "") + settleWith(t, e.ctx, coordinator(e.admin), device.Name) + e.requirePhase(operation, ops.PhasePending, ReasonDiscoveryNotCurrent) + before := e.custody(device.Name).Spec + e.clock.Advance(20*time.Minute + time.Second) + settleWith(t, e.ctx, coordinator(e.admin), device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonDiscoveryNotCurrent) + e.requireCustodyUnchanged(device.Name, before) + }) + + t.Run("a newer Machine generation replaces a request waiting for discovery", func(t *testing.T) { + e := e.sub(t) + allocation := "alloc-lapse-newer" + device, key, coordinator := lapsed(e, allocation) + older := e.providerPower(device, allocation, 6, ops.PowerOn, "") + settleWith(t, e.ctx, coordinator(e.admin), device.Name) + e.requirePhase(older, ops.PhasePending, ReasonDiscoveryNotCurrent) + time.Sleep(1100 * time.Millisecond) + newer := e.providerPower(device, allocation, 7, ops.PowerForceOff, "") + e.discoverPower(device, key, e.clock.Now(), "On", allActions, nil) + settleWith(t, e.ctx, coordinator(e.admin), device.Name) + e.requirePhase(older, ops.PhaseCancelled, ReasonSuperseded) + e.requirePhase(newer, ops.PhaseAdmitted, "") + }) + + t.Run("two coordinators admit a request that waited for discovery exactly once", func(t *testing.T) { + e := e.sub(t) + allocation := "alloc-lapse-race" + device, key, coordinator := lapsed(e, allocation) + operation := e.providerPower(device, allocation, 8, ops.PowerOn, "") + settleWith(t, e.ctx, coordinator(e.admin), device.Name) + e.requirePhase(operation, ops.PhasePending, ReasonDiscoveryNotCurrent) + fence := e.custody(device.Name).Spec.Fence + e.discoverPower(device, key, e.clock.Now(), "On", allActions, nil) + var group sync.WaitGroup + for range 2 { + racer := coordinator(e.client()) + group.Add(1) + go func() { + defer group.Done() + if err := settleQuiet(e.ctx, racer, device.Name); err != nil { + t.Error(err) + } + }() + } + group.Wait() + e.requirePhase(operation, ops.PhaseAdmitted, "") + if custody := e.custody(device.Name); custody.Spec.Fence != fence+1 || custody.Spec.ActiveOperation == nil || custody.Spec.ActiveOperation.Name != operation.Name { + t.Fatalf("custody = %+v, want one admission at fence %d", custody.Spec, fence+1) + } + }) + + 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 success counts only with the requested power state and, for a reset, proof of it", func(t *testing.T) { + at := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + // unsent is evidence from a server already in the requested state: + // both reads, and no command. + unsent := func(before, after string) string { + return fmt.Sprintf(`{"power":{"before":{"state":%q,"observedAt":%q},"after":{"state":%q,"observedAt":%q}}}`, + before, at.Format(time.RFC3339), after, at.Add(time.Second).Format(time.RFC3339)) + } + for _, check := range []struct { + name string + action ops.PowerAction + evidence string + want ops.Phase + }{ + {"a power on read On after the command", ops.PowerOn, powerEvidence(at, "Off", "On", ""), ops.PhaseSucceeded}, + {"a power on of a server already on", ops.PowerOn, unsent("On", "On"), ops.PhaseSucceeded}, + {"a power off read Off after the command", ops.PowerForceOff, powerEvidence(at, "On", "Off", ""), ops.PhaseSucceeded}, + {"a restart proven by the reset time", ops.PowerForceRestart, powerEvidence(at, "On", "On", ops.ResetLastResetTime), ops.PhaseSucceeded}, + {"a power cycle proven by an Off read", ops.PowerCycle, powerEvidence(at, "On", "On", ops.ResetObservedOff), ops.PhaseSucceeded}, + {"the empty object", ops.PowerOn, `{}`, ops.PhaseOutcomeUnknown}, + {"no read after the command", ops.PowerOn, `{"power":{"before":{"state":"Off","observedAt":"2026-01-02T03:04:05Z"}}}`, ops.PhaseOutcomeUnknown}, + {"a power on read Off after the command", ops.PowerOn, powerEvidence(at, "Off", "Off", ""), ops.PhaseOutcomeUnknown}, + {"a power off read On after the command", ops.PowerForceOff, powerEvidence(at, "On", "On", ""), ops.PhaseOutcomeUnknown}, + {"a power off of a server that was on, with no command", ops.PowerForceOff, unsent("On", "Off"), ops.PhaseOutcomeUnknown}, + {"a restart with no reset proof", ops.PowerForceRestart, powerEvidence(at, "On", "On", ""), ops.PhaseOutcomeUnknown}, + {"a power cycle with no reset proof", ops.PowerCycle, powerEvidence(at, "On", "On", ""), ops.PhaseOutcomeUnknown}, + {"a restart with no command", ops.PowerForceRestart, unsent("On", "On"), ops.PhaseOutcomeUnknown}, + {"a restart left off", ops.PowerForceRestart, powerEvidence(at, "On", "Off", ops.ResetObservedOff), ops.PhaseOutcomeUnknown}, + } { + t.Run(check.name, func(t *testing.T) { + e := e.sub(t) + device, _ := fresh(e) + operation := e.staffPower(device, check.action, device.Spec.Identity.SystemUUID) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseSucceeded, check.evidence); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + custody := e.custody(device.Name) + if check.want == ops.PhaseSucceeded { + e.requirePhase(operation, ops.PhaseSucceeded, "") + if custody.Spec.RecoveryHold != nil || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("custody = %+v", custody.Spec) + } + return + } + status := e.requirePhase(operation, ops.PhaseOutcomeUnknown, ReasonInvalidEvidence) + if !strings.Contains(status.Message, "does not prove the success") { + t.Fatalf("message = %s", status.Message) + } + if hold := custody.Spec.RecoveryHold; hold == nil || hold.Name != operation.Name || custody.Spec.LastResult.Evidence == nil { + t.Fatalf("custody = %+v", custody.Spec) + } + }) + } + }) + + t.Run("a retry whose success proves nothing keeps the hold", func(t *testing.T) { + e := e.sub(t) + device, key := fresh(e) + hold := e.powerHold(device, e.staffPower(device, ops.PowerForceRestart, device.Spec.Identity.SystemUUID)) + 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) + } + retried := e.namedStaffPower(device, RetryName(hold, 1), ops.PowerForceRestart) + e.settle(device.Name) + e.requirePhase(retried, ops.PhaseAdmitted, "") + if err := e.result(device.Name, ops.PhaseSucceeded, powerEvidence(e.clock.Now(), "On", "On", "")); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(retried, ops.PhaseOutcomeUnknown, ReasonInvalidEvidence) + custody := e.custody(device.Name) + if next := custody.Spec.RecoveryHold; next == nil || next.Name != retried.Name || next.RetryName != hold.Name || custody.Spec.Holder.Type != ops.HolderService { + t.Fatalf("custody = %+v", custody.Spec) + } + }) + + 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"}, ResetTypesObserved: true}}}}}} + } + 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: "observed reset types with the action", operation: provider}, + {name: "observed reset types without the action", operation: staff(ops.PowerForceRestart, uuid), want: ReasonResetTypeNotOffered}, + {name: "observed and empty", operation: provider, device: func(d *inventory.Device) { d.Status.Discovery.Inventory.Systems[0].ResetTypes = nil }, want: ReasonResetTypeNotOffered}, + // Reset types not observed prove nothing, so the worker's live check + // decides. + {name: "not observed admits a staff request", operation: staff(ops.PowerForceRestart, uuid), device: func(d *inventory.Device) { + d.Status.Discovery.Inventory.Systems[0].ResetTypes, d.Status.Discovery.Inventory.Systems[0].ResetTypesObserved = nil, false + }}, + {name: "not observed admits a provider request", operation: provider, device: func(d *inventory.Device) { + d.Status.Discovery.Inventory.Systems[0].ResetTypes, d.Status.Discovery.Inventory.Systems[0].ResetTypesObserved = nil, false + }}, + {name: "a list not observed in this pass proves nothing", operation: staff(ops.PowerForceRestart, uuid), device: func(d *inventory.Device) { + d.Status.Discovery.Inventory.Systems[0].ResetTypesObserved = false + }}, + } { + 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/registry.go b/internal/custody/registry.go index 6e0c1e43..577cdd1f 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -88,7 +88,8 @@ type Kind struct { BootInterface func(ops.Operation) string // Check runs kind-specific admission checks after the shared // preconditions pass and before the custody update. A non-nil refusal - // ends the operation Failed with that reason, and nothing is sent. + // ends the operation Failed with that reason, and nothing is sent, + // unless the refusal sets Wait and the operation's row queues. Check func(context.Context, *Admission) *Refusal // Settles lists the held kinds a success of this kind settles. It may be // empty: a kind whose holds only a DeviceRecovery settles, such as power, @@ -111,13 +112,19 @@ type Kind struct { // It sees the same Device the checks saw. SnapshotExtra func(*Admission) map[string]string // Evidence validates the kind's typed, bounded result evidence against - // the operation it is for, such as requiring reset proof for a restart, - // and returns it in canonical form. Nil means the kind's results carry - // none. + // the operation it is for, and returns it in canonical form. It sees + // every phase's evidence, so it checks only what holds for all of them. + // Nil means the kind's results carry none. Evidence func(ops.Operation, []byte) ([]byte, error) // EvidenceRequired means a Succeeded result without evidence proves // nothing and ends OutcomeUnknown. EvidenceRequired bool + // ProvesSuccess, when set, checks that a Succeeded result's canonical + // evidence proves the success, such as reset proof for a restart. An + // error ends the operation OutcomeUnknown with InvalidEvidence, so a + // success it cannot prove never counts as one. It needs + // EvidenceRequired. + ProvesSuccess func(ops.Operation, []byte) error // RecoverySettle validates DeviceRecovery Settle evidence for a hold of // this kind. A kind without it cannot be settled by a DeviceRecovery. RecoverySettle func(context.Context, *RecoverySettleContext) *Refusal @@ -213,6 +220,16 @@ type ApplyContext struct { type Refusal struct { Reason string Message string + // Wait, on a Check refusal, means the condition can clear by itself, + // such as discovery that has not read the BMC lately. An operation on a + // queue row then waits in Pending with the reason, for at most Wait + // after it was created or the Device's last operation finished, + // whichever is later, and only then ends Failed. Rebuilt custody has no + // last operation, so the bound then counts from creation. A waiting + // operation holds back later queued operations on the Device, as one + // waiting for current discovery does. Any other row's operation ends + // Failed at once. Zero never waits. + Wait time.Duration } func (r *Refusal) Error() string { return r.Reason + ": " + r.Message } @@ -292,6 +309,9 @@ func (r *Registry) Register(kind Kind) error { if kind.EvidenceRequired && kind.Evidence == nil { return fmt.Errorf("%s: required evidence needs a validator", name) } + if kind.ProvesSuccess != nil && !kind.EvidenceRequired { + return fmt.Errorf("%s: proof of success needs required evidence", name) + } if !kind.Effectful && kind.Apply == nil { return fmt.Errorf("%s: a non-effectful kind needs Apply", name) } @@ -400,6 +420,18 @@ func SpecDigest(spec any) (string, error) { return "sha256:" + hex.EncodeToString(sum[:]), nil } +// TypedProof returns a ProvesSuccess function that decodes canonical evidence +// into T and runs prove with the operation the evidence is for. +func TypedProof[T any](prove func(ops.Operation, *T) error) func(ops.Operation, []byte) error { + return func(operation ops.Operation, canonical []byte) error { + value := new(T) + if err := json.Unmarshal(canonical, value); err != nil { + return fmt.Errorf("evidence does not match the kind's schema: %w", err) + } + return prove(operation, value) + } +} + // StrictEvidence returns an Evidence function that decodes into T, rejecting // unknown fields and anything over maxBytes, then runs validate with the // operation the evidence is for. diff --git a/internal/custody/results.go b/internal/custody/results.go index 9673bddc..034132df 100644 --- a/internal/custody/results.go +++ b/internal/custody/results.go @@ -174,6 +174,12 @@ func (c *Coordinator) AcceptResult(ctx context.Context, result SiteResult) error } evidence = canonical } + if result.Phase == ops.PhaseSucceeded && kind.ProvesSuccess != nil { + if err := kind.ProvesSuccess(operation, evidence); err != nil { + c.holdUnknown(custody, *active, ReasonInvalidEvidence, "the evidence does not prove the success: "+err.Error(), evidence) + return nil + } + } switch result.Phase { case ops.PhaseOutcomeUnknown: reason := result.Reason diff --git a/internal/custody/seams_test.go b/internal/custody/seams_test.go index 252c9207..f9f259d2 100644 --- a/internal/custody/seams_test.go +++ b/internal/custody/seams_test.go @@ -53,6 +53,25 @@ func TestRegistryRejectsIncompleteKindsAndRows(t *testing.T) { } } +// 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 +} + // 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. @@ -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/internal/custody/testkinds_test.go b/internal/custody/testkinds_test.go index 17fbd37e..0826d9c4 100644 --- a/internal/custody/testkinds_test.go +++ b/internal/custody/testkinds_test.go @@ -75,6 +75,9 @@ const ( reasonTestRefuse = "TestRefused" reasonTestUUID = "TestSystemUUIDNotRecorded" testDeadline = 10 * time.Minute + // testWait bounds the test kinds' waiting refusal. + testWait = 5 * time.Minute + testReadyAnnotation = "test.fleet.datumapis.com/ready" ) // testEvidence is the test kinds' typed result evidence. @@ -90,6 +93,18 @@ func testKinds() []Kind { return refuse(reasonTestRefuse, "the test kind refuses this input") case "undeclared": return refuse("Unlisted", "the test kind refuses with a reason it never declared") + case "wait": + // A condition that can clear by itself, as power's discovery + // that has not read the BMC lately. + if admission.Device.Annotations[testReadyAnnotation] == "" { + refusal := refuse(reasonTestRefuse, "the test kind waits for its Device to be ready") + refusal.Wait = testWait + return refusal + } + case "wait-undeclared": + refusal := refuse("Unlisted", "the test kind waits with a reason it never declared") + refusal.Wait = testWait + return refusal case "needs-uuid": // A kind's own, more specific reason, as power's // SystemUUIDNotRecorded. diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 997ceae8..bac3e045 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -49,7 +49,7 @@ status](../../docs/development/device-custody.md#status). | --- | --- | --- | | Two allocators race for one server; one wins | `TestConcurrency`, `TestConcurrentAllocatorsOneWinner`; the `verify-contention` phase | Envtest verified for true concurrency. The phase checks that two consumers contend and custody names the one MachineAllocation | | 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, the first staff kind with an effect | +| 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 phases below run the same hold and settle mechanism for an installation and a wipe | | A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery`; the `deadline-hold` phase | Envtest verified for all three. The phase runs one of them: a `DeviceRecovery` naming the held installation at the wrong fence, on a releasing Device, must be refused for `HoldMismatch` with custody unchanged and nothing sent | | A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery`, `TestAWorkerStoppedAtItsDeadlineClosesItsAdmission`; the `deadline-hold` and `deadline-settled` phases | The phases check that the installation ends `OutcomeUnknown` with `DeadlineExceeded`, that its worker Pods stopped, and that the settling wipe is admitted only after the worker stopped |