From 5ce169c30a83bed2934f4f467a8833baeb3ea3e1 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 18:09:36 -0600 Subject: [PATCH 01/19] feat(custody): Add Device custody and operation kinds Add DeviceCustody and the DeviceInstallation, DeviceWipe and DeviceRecovery operation kinds proposed in #174 at 3907eec. Every operation shares one envelope and one status. CEL keeps an operation's spec immutable, moves its phases forward only, keeps the custody fence from decreasing and keeps Retired terminal. The device-operations component also carries the ProtectedResources, the coordinator, requester, viewer and recovery operator roles, and the creator webhook configuration. No root includes it. Co-Authored-By: Claude Opus 5.5 --- .../crds/fleet.datumapis.com.yaml | 1031 +++++++++++++++++ .../device-operations/crds/kustomization.yaml | 3 + .../device-operations/kustomization.yaml | 10 + .../protected-resources/devicecustody.yaml | 16 + .../deviceinstallation.yaml | 20 + .../protected-resources/devicerecovery.yaml | 20 + .../protected-resources/devicewipe.yaml | 20 + .../protected-resources/kustomization.yaml | 7 + .../device-operations/roles/coordinator.yaml | 43 + .../roles/installation-requester.yaml | 17 + .../roles/kustomization.yaml | 8 + .../roles/recovery-operator.yaml | 16 + .../device-operations/roles/viewer.yaml | 22 + .../roles/wipe-requester.yaml | 17 + .../components/device-operations/webhook.yaml | 24 + .../api/operations/v1alpha1/config_test.go | 292 +++++ internal/api/operations/v1alpha1/types.go | 443 +++++++ 17 files changed, 2009 insertions(+) create mode 100644 config/components/device-operations/crds/fleet.datumapis.com.yaml create mode 100644 config/components/device-operations/crds/kustomization.yaml create mode 100644 config/components/device-operations/kustomization.yaml create mode 100644 config/components/device-operations/protected-resources/devicecustody.yaml create mode 100644 config/components/device-operations/protected-resources/deviceinstallation.yaml create mode 100644 config/components/device-operations/protected-resources/devicerecovery.yaml create mode 100644 config/components/device-operations/protected-resources/devicewipe.yaml create mode 100644 config/components/device-operations/protected-resources/kustomization.yaml create mode 100644 config/components/device-operations/roles/coordinator.yaml create mode 100644 config/components/device-operations/roles/installation-requester.yaml create mode 100644 config/components/device-operations/roles/kustomization.yaml create mode 100644 config/components/device-operations/roles/recovery-operator.yaml create mode 100644 config/components/device-operations/roles/viewer.yaml create mode 100644 config/components/device-operations/roles/wipe-requester.yaml create mode 100644 config/components/device-operations/webhook.yaml create mode 100644 internal/api/operations/v1alpha1/config_test.go create mode 100644 internal/api/operations/v1alpha1/types.go diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml new file mode 100644 index 00000000..58722c49 --- /dev/null +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -0,0 +1,1031 @@ +# DeviceCustody and the Device operation kinds proposed in #174 at 3907eec. +# The coordinator is the only writer of custody and of operation status. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicecustodies.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceCustody + listKind: DeviceCustodyList + plural: devicecustodies + singular: devicecustody + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + additionalPrinterColumns: + - name: State + type: string + jsonPath: .spec.state + - name: Holder + type: string + jsonPath: .spec.holder.type + - name: Fence + type: integer + jsonPath: .spec.fence + - name: Active + type: string + jsonPath: .spec.activeOperation.name + - name: Hold + type: string + jsonPath: .spec.recoveryHold.name + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + required: + - name + - uid + state: + type: string + enum: + - Verified + - Unverified + holder: + type: object + properties: + type: + type: string + enum: + - None + - Allocation + - Release + - Service + - Retired + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + openGates: + type: array + maxItems: 16 + items: + type: string + minLength: 1 + maxLength: 63 + x-kubernetes-list-type: set + required: + - type + x-kubernetes-validations: + - rule: (self.type == 'Allocation' || self.type == 'Release') == has(self.allocationRef) + message: allocationRef is set exactly for Allocation and Release + - rule: self.type == 'Release' || !has(self.openGates) || size(self.openGates) == 0 + message: only Release has open gates + fence: + type: integer + format: int64 + minimum: 0 + activeOperation: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + fence: + type: integer + format: int64 + minimum: 1 + phase: + type: string + enum: + - Admitted + - Dispatched + - Verifying + admittedAt: + type: string + format: date-time + deadline: + type: string + format: date-time + inputDigest: + type: string + minLength: 1 + 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 + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + - uid + settles: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + required: + - kind + - name + - uid + required: + - kind + - name + - uid + - fence + - phase + - admittedAt + - deadline + - inputDigest + - snapshot + - creator + lastResult: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + fence: + type: integer + format: int64 + minimum: 0 + phase: + type: string + enum: + - Pending + - Admitted + - Dispatched + - Verifying + - Succeeded + - Failed + - Cancelled + - OutcomeUnknown + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 1024 + finishedAt: + type: string + format: date-time + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + required: + - kind + - name + - uid + - fence + - phase + - finishedAt + recoveryHold: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + fence: + type: integer + format: int64 + minimum: 0 + since: + type: string + format: date-time + reason: + type: string + minLength: 1 + maxLength: 128 + retryAuthorizedBy: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + required: + - kind + - name + - uid + required: + - kind + - name + - uid + - fence + - since + - reason + conflicts: + type: array + maxItems: 16 + items: + type: string + minLength: 1 + maxLength: 63 + x-kubernetes-list-type: set + rejectedResults: + type: object + properties: + count: + type: integer + format: int64 + minimum: 0 + last: + type: object + properties: + kind: + type: string + maxLength: 63 + name: + type: string + maxLength: 253 + fence: + type: integer + format: int64 + site: + type: string + maxLength: 253 + rejectedAt: + type: string + format: date-time + required: + - count + - last + required: + - deviceRef + - state + - holder + - fence + x-kubernetes-validations: + - rule: self.deviceRef.name == oldSelf.deviceRef.name + message: custody names one Device + - rule: self.fence >= oldSelf.fence + message: the fence never decreases + - rule: oldSelf.holder.type != 'Retired' || self.holder.type == 'Retired' + message: Retired is terminal + - rule: '!has(self.activeOperation) || self.activeOperation.fence == self.fence' + message: the active operation carries the current fence + required: + - spec + x-kubernetes-validations: + - rule: self.metadata.name == self.spec.deviceRef.name + message: custody has the same name as its Device +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: deviceinstallations.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceInstallation + listKind: DeviceInstallationList + plural: deviceinstallations + singular: deviceinstallation + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + - uid + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + required: + - name + - uid + 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 + requestUID: + type: string + minLength: 1 + maxLength: 64 + image: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: + - name + - digest + bootstrap: + type: object + properties: + ref: + type: string + minLength: 1 + maxLength: 253 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: + - ref + - digest + bootInterface: + type: string + minLength: 1 + maxLength: 63 + targetDisks: + type: array + minItems: 1 + maxItems: 16 + items: + type: string + minLength: 1 + maxLength: 63 + x-kubernetes-list-type: set + required: + - creator + - deviceRef + - authority + - requestUID + - image + - bootInterface + - targetDisks + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + status: + type: object + properties: + 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 + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled''], ''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: devicewipes.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceWipe + listKind: DeviceWipeList + plural: devicewipes + singular: devicewipe + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + - uid + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + required: + - name + - uid + 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 + step: + type: integer + format: int32 + minimum: 1 + cleaningPolicyDigest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + targetDisks: + type: array + minItems: 1 + maxItems: 16 + items: + type: string + minLength: 1 + maxLength: 63 + x-kubernetes-list-type: set + required: + - creator + - deviceRef + - authority + - step + - cleaningPolicyDigest + - targetDisks + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + status: + type: object + properties: + 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 + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled''], ''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: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceRecovery + listKind: DeviceRecoveryList + plural: devicerecoveries + singular: devicerecovery + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + - uid + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + required: + - name + - uid + 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 + decision: + type: string + enum: + - Settle + - Retry + - Retire + - Resolve + hold: + type: object + properties: + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + fence: + type: integer + format: int64 + minimum: 0 + required: + - kind + - name + - fence + evidence: + type: object + properties: + observedAt: + type: string + format: date-time + summary: + type: string + minLength: 1 + maxLength: 1024 + data: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + required: + - observedAt + - summary + diskDisposal: + type: object + properties: + method: + type: string + enum: + - Destroyed + - Removed + reference: + type: string + minLength: 1 + maxLength: 256 + required: + - method + - reference + resolve: + type: object + properties: + holder: + type: string + enum: + - None + - Allocation + - Release + - Retired + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + required: + - holder + required: + - creator + - deviceRef + - authority + - decision + - evidence + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + - rule: (self.decision == 'Resolve') == has(self.resolve) + message: resolve is set exactly for Resolve + - rule: self.decision == 'Resolve' || has(self.hold) + message: Settle, Retry and Retire name the hold + - rule: '!has(self.diskDisposal) || self.decision == ''Retire''' + message: only Retire records disk disposal + status: + type: object + properties: + 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 + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled''], ''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 diff --git a/config/components/device-operations/crds/kustomization.yaml b/config/components/device-operations/crds/kustomization.yaml new file mode 100644 index 00000000..1f890b4c --- /dev/null +++ b/config/components/device-operations/crds/kustomization.yaml @@ -0,0 +1,3 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [fleet.datumapis.com.yaml] diff --git a/config/components/device-operations/kustomization.yaml b/config/components/device-operations/kustomization.yaml new file mode 100644 index 00000000..91954847 --- /dev/null +++ b/config/components/device-operations/kustomization.yaml @@ -0,0 +1,10 @@ +# Device custody and operations (#174 at 3907eec). Implemented and inert: no +# deployment root includes this component yet, so nothing serves these kinds +# or calls the webhook. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - crds + - protected-resources + - roles + - webhook.yaml diff --git a/config/components/device-operations/protected-resources/devicecustody.yaml b/config/components/device-operations/protected-resources/devicecustody.yaml new file mode 100644 index 00000000..1412df9c --- /dev/null +++ b/config/components/device-operations/protected-resources/devicecustody.yaml @@ -0,0 +1,16 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicecustody +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceCustody + plural: devicecustodies + singular: devicecustody + # Custody keeps its fields in spec, like a Lease, and has no status. Only + # the coordinator role holds a write verb. + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/deviceinstallation.yaml b/config/components/device-operations/protected-resources/deviceinstallation.yaml new file mode 100644 index 00000000..c3dfe734 --- /dev/null +++ b/config/components/device-operations/protected-resources/deviceinstallation.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-deviceinstallation +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceInstallation + plural: deviceinstallations + singular: deviceinstallation + # Status has one writer, the coordinator. With subresource authorization + # enabled, status writes use deviceinstallations/status.update and + # deviceinstallations/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/devicerecovery.yaml b/config/components/device-operations/protected-resources/devicerecovery.yaml new file mode 100644 index 00000000..5debf720 --- /dev/null +++ b/config/components/device-operations/protected-resources/devicerecovery.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicerecovery +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceRecovery + plural: devicerecoveries + singular: devicerecovery + # Status has one writer, the coordinator. With subresource authorization + # enabled, status writes use devicerecoveries/status.update and + # devicerecoveries/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/devicewipe.yaml b/config/components/device-operations/protected-resources/devicewipe.yaml new file mode 100644 index 00000000..c7fc7ddd --- /dev/null +++ b/config/components/device-operations/protected-resources/devicewipe.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicewipe +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceWipe + plural: devicewipes + singular: devicewipe + # Status has one writer, the coordinator. With subresource authorization + # enabled, status writes use devicewipes/status.update and + # devicewipes/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 new file mode 100644 index 00000000..7b5e6674 --- /dev/null +++ b/config/components/device-operations/protected-resources/kustomization.yaml @@ -0,0 +1,7 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - devicecustody.yaml + - deviceinstallation.yaml + - devicewipe.yaml + - devicerecovery.yaml diff --git a/config/components/device-operations/roles/coordinator.yaml b/config/components/device-operations/roles/coordinator.yaml new file mode 100644 index 00000000..facbdbdd --- /dev/null +++ b/config/components/device-operations/roles/coordinator.yaml @@ -0,0 +1,43 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-coordinator + annotations: + kubernetes.io/display-name: Fleet Device Coordinator + kubernetes.io/description: The only writer of Device custody and of operation status. Reads inventory and allocations to rebuild custody. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch + - fleet.datumapis.com/devicecustodies.create + - fleet.datumapis.com/devicecustodies.update + - fleet.datumapis.com/devicecustodies.delete + - fleet.datumapis.com/deviceinstallations.get + - fleet.datumapis.com/deviceinstallations.list + - fleet.datumapis.com/deviceinstallations.watch + - fleet.datumapis.com/deviceinstallations.delete + - fleet.datumapis.com/deviceinstallations.updateStatus + - fleet.datumapis.com/deviceinstallations/status.update + - fleet.datumapis.com/devicewipes.get + - fleet.datumapis.com/devicewipes.list + - fleet.datumapis.com/devicewipes.watch + - fleet.datumapis.com/devicewipes.delete + - fleet.datumapis.com/devicewipes.updateStatus + - fleet.datumapis.com/devicewipes/status.update + - fleet.datumapis.com/devicerecoveries.get + - fleet.datumapis.com/devicerecoveries.list + - fleet.datumapis.com/devicerecoveries.watch + - fleet.datumapis.com/devicerecoveries.delete + - fleet.datumapis.com/devicerecoveries.updateStatus + - fleet.datumapis.com/devicerecoveries/status.update + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.watch + - metal.datumapis.com/machineallocations.get + - metal.datumapis.com/machineallocations.list + - metal.datumapis.com/machineallocations.watch + - metal.datumapis.com/machinecapacities.get + - metal.datumapis.com/machinecapacities.list + - metal.datumapis.com/machinecapacities.watch diff --git a/config/components/device-operations/roles/installation-requester.yaml b/config/components/device-operations/roles/installation-requester.yaml new file mode 100644 index 00000000..1131652a --- /dev/null +++ b/config/components/device-operations/roles/installation-requester.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-installation-requester + annotations: + kubernetes.io/display-name: Fleet Device Installation Requester + kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations and reads custody. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/deviceinstallations.create + - fleet.datumapis.com/deviceinstallations.get + - fleet.datumapis.com/deviceinstallations.list + - fleet.datumapis.com/deviceinstallations.watch + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch diff --git a/config/components/device-operations/roles/kustomization.yaml b/config/components/device-operations/roles/kustomization.yaml new file mode 100644 index 00000000..0deb9bd5 --- /dev/null +++ b/config/components/device-operations/roles/kustomization.yaml @@ -0,0 +1,8 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - coordinator.yaml + - viewer.yaml + - recovery-operator.yaml + - installation-requester.yaml + - wipe-requester.yaml diff --git a/config/components/device-operations/roles/recovery-operator.yaml b/config/components/device-operations/roles/recovery-operator.yaml new file mode 100644 index 00000000..2ed16ee5 --- /dev/null +++ b/config/components/device-operations/roles/recovery-operator.yaml @@ -0,0 +1,16 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-recovery-operator + annotations: + kubernetes.io/display-name: Fleet Device Recovery Operator + kubernetes.io/description: Settle, retry, retire or resolve a Device whose operation outcome is unknown or whose custody is Unverified. Reads MachineAllocations to identify the customer. +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-device-operations-viewer + includedPermissions: + - fleet.datumapis.com/devicerecoveries.create + - metal.datumapis.com/machineallocations.get + - metal.datumapis.com/machineallocations.list + - metal.datumapis.com/machineallocations.watch diff --git a/config/components/device-operations/roles/viewer.yaml b/config/components/device-operations/roles/viewer.yaml new file mode 100644 index 00000000..7a1e5100 --- /dev/null +++ b/config/components/device-operations/roles/viewer.yaml @@ -0,0 +1,22 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-operations-viewer + annotations: + kubernetes.io/display-name: Fleet Device Operations Viewer + kubernetes.io/description: Read Device custody and operations. Does not read MachineAllocations, so it does not see which customer holds a Device. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch + - fleet.datumapis.com/deviceinstallations.get + - fleet.datumapis.com/deviceinstallations.list + - fleet.datumapis.com/deviceinstallations.watch + - fleet.datumapis.com/devicewipes.get + - fleet.datumapis.com/devicewipes.list + - fleet.datumapis.com/devicewipes.watch + - fleet.datumapis.com/devicerecoveries.get + - fleet.datumapis.com/devicerecoveries.list + - fleet.datumapis.com/devicerecoveries.watch diff --git a/config/components/device-operations/roles/wipe-requester.yaml b/config/components/device-operations/roles/wipe-requester.yaml new file mode 100644 index 00000000..ff7dce80 --- /dev/null +++ b/config/components/device-operations/roles/wipe-requester.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-wipe-requester + annotations: + kubernetes.io/display-name: Fleet Device Wipe Requester + kubernetes.io/description: The release controller. Creates DeviceWipes during release and reads custody. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/devicewipes.create + - fleet.datumapis.com/devicewipes.get + - fleet.datumapis.com/devicewipes.list + - fleet.datumapis.com/devicewipes.watch + - fleet.datumapis.com/devicecustodies.get + - fleet.datumapis.com/devicecustodies.list + - fleet.datumapis.com/devicecustodies.watch diff --git a/config/components/device-operations/webhook.yaml b/config/components/device-operations/webhook.yaml new file mode 100644 index 00000000..3958a845 --- /dev/null +++ b/config/components/device-operations/webhook.yaml @@ -0,0 +1,24 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: fleet-operation-creator +webhooks: + # Milo's root API server calls this webhook, because Milo does not evaluate + # admission policies stored in a project. It rejects a create whose + # spec.creator is not the authenticated caller, and any change to it. It is + # fail-closed. Status writes are not routed; only the coordinator role can + # make them. + - name: creator.operations.fleet.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: None + timeoutSeconds: 10 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-operation-creator + rules: + - apiGroups: [fleet.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE] + resources: [deviceinstallations, devicewipes, devicerecoveries] + scope: Namespaced diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go new file mode 100644 index 00000000..fa0efa32 --- /dev/null +++ b/internal/api/operations/v1alpha1/config_test.go @@ -0,0 +1,292 @@ +package v1alpha1 + +import ( + "bytes" + "context" + "io" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + crdvalidation "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation" + "k8s.io/apimachinery/pkg/util/yaml" +) + +var ( + configRoot = filepath.Join("..", "..", "..", "..", "config") + componentRoot = filepath.Join(configRoot, "components", "device-operations") + operationKinds = []string{"DeviceInstallation", "DeviceWipe", "DeviceRecovery"} +) + +func decodeAll[T any](t *testing.T, path string) []T { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + var out []T + for { + var item T + if err := decoder.Decode(&item); err == io.EOF { + return out + } else if err != nil { + t.Fatal(err) + } + out = append(out, item) + } +} + +func decodeDir[T any](t *testing.T, dir string) []T { + t.Helper() + files, err := filepath.Glob(filepath.Join(dir, "*.yaml")) + if err != nil { + t.Fatal(err) + } + var out []T + for _, file := range files { + if filepath.Base(file) != "kustomization.yaml" { + out = append(out, decodeAll[T](t, file)...) + } + } + return out +} + +func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { + t.Helper() + out := map[string]*extensionsv1.CustomResourceDefinition{} + for _, crd := range decodeAll[extensionsv1.CustomResourceDefinition](t, filepath.Join(componentRoot, "crds", "fleet.datumapis.com.yaml")) { + copied := crd + out[crd.Spec.Names.Kind] = &copied + } + return out +} + +func TestCRDContract(t *testing.T) { + crds := loadCRDs(t) + if len(crds) != 4 || crds["DeviceCustody"] == nil { + t.Fatalf("got %d CRDs, want DeviceCustody and three operation kinds", len(crds)) + } + for kind, crd := range crds { + version := crd.Spec.Versions[0] + if crd.Spec.Group != GroupVersion.Group || crd.Name != crd.Spec.Names.Plural+"."+GroupVersion.Group || crd.Spec.Scope != extensionsv1.NamespaceScoped || len(crd.Spec.Versions) != 1 || version.Name != GroupVersion.Version || !version.Served || !version.Storage { + t.Fatalf("%s identity", kind) + } + if crd.Annotations["discovery.miloapis.com/parent-contexts"] != "Project" { + t.Fatalf("%s must be served only in Milo project control planes", kind) + } + properties := version.Schema.OpenAPIV3Schema.Properties + if kind == "DeviceCustody" { + // Custody keeps its fields in spec, like a Lease. + if version.Subresources != nil || len(properties["status"].Properties) != 0 { + t.Fatal("DeviceCustody has no status") + } + } else { + if version.Subresources == nil || version.Subresources.Status == nil { + t.Fatalf("%s status must be a subresource, written only by the coordinator", kind) + } + spec := properties["spec"] + if !slices.Contains(spec.Required, "creator") || !slices.Contains(spec.Required, "deviceRef") || !slices.Contains(spec.Required, "authority") { + t.Fatalf("%s must carry the operation envelope", kind) + } + if len(spec.XValidations) == 0 || spec.XValidations[0].Rule != "self == oldSelf" { + t.Fatalf("%s spec must be immutable", kind) + } + } + defaulted := crd.DeepCopy() + extensionsv1.SetObjectDefaults_CustomResourceDefinition(defaulted) + defaulted.Status.StoredVersions = []string{GroupVersion.Version} + var internal apiextensions.CustomResourceDefinition + if err := extensionsv1.Convert_v1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(defaulted, &internal, nil); err != nil { + t.Fatal(err) + } + if errs := crdvalidation.ValidateCustomResourceDefinition(context.Background(), &internal); len(errs) > 0 { + t.Fatalf("%s: %v", kind, errs.ToAggregate()) + } + } + // Bootstrap is an opaque reference and a digest, never a payload. + bootstrap := crds["DeviceInstallation"].Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["spec"].Properties["bootstrap"] + if len(bootstrap.Properties) != 2 || bootstrap.Properties["ref"].Type != "string" || bootstrap.Properties["digest"].Pattern == "" { + t.Fatalf("bootstrap = %+v", bootstrap.Properties) + } +} + +type protectedResource struct { + Metadata struct{ Name string } `json:"metadata"` + Spec struct { + ServiceRef struct{ Name string } `json:"serviceRef"` + Kind string `json:"kind"` + Plural string `json:"plural"` + Permissions []string `json:"permissions"` + Subresource []struct { + Name string `json:"name"` + Permissions []string `json:"permissions"` + } `json:"subresources"` + } `json:"spec"` +} + +type role struct { + Metadata struct{ Name string } `json:"metadata"` + Spec struct { + Inherited []struct{ Name string } `json:"inheritedRoles"` + Included []string `json:"includedPermissions"` + } `json:"spec"` +} + +// declared returns every permission the ProtectedResources in dir declare. +func declared(t *testing.T, dir string, into map[string]bool) { + t.Helper() + for _, resource := range decodeDir[protectedResource](t, dir) { + for _, verb := range resource.Spec.Permissions { + into[resource.Spec.ServiceRef.Name+"/"+resource.Spec.Plural+"."+verb] = true + } + for _, sub := range resource.Spec.Subresource { + for _, verb := range sub.Permissions { + into[resource.Spec.ServiceRef.Name+"/"+resource.Spec.Plural+"/"+sub.Name+"."+verb] = true + } + } + } +} + +func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { + crds := loadCRDs(t) + resources := decodeDir[protectedResource](t, filepath.Join(componentRoot, "protected-resources")) + if len(resources) != len(crds) { + t.Fatalf("%d ProtectedResources for %d CRDs", len(resources), len(crds)) + } + for _, resource := range resources { + crd := crds[resource.Spec.Kind] + if crd == nil || resource.Spec.ServiceRef.Name != GroupVersion.Group || resource.Spec.Plural != crd.Spec.Names.Plural || resource.Metadata.Name != GroupVersion.Group+"-"+crd.Spec.Names.Singular { + t.Fatalf("ProtectedResource %s does not match a CRD", resource.Metadata.Name) + } + } + permissions := map[string]bool{} + declared(t, filepath.Join(componentRoot, "protected-resources"), permissions) + declared(t, filepath.Join(configRoot, "components", "inventory", "protected-resources"), permissions) + declared(t, filepath.Join(configRoot, "components", "iam", "protected-resources"), permissions) + roles := map[string]role{} + for _, r := range decodeDir[role](t, filepath.Join(componentRoot, "roles")) { + roles[r.Metadata.Name] = r + for _, permission := range r.Spec.Included { + if !permissions[permission] { + t.Fatalf("%s grants undeclared permission %s", r.Metadata.Name, permission) + } + } + } + p := func(resource string, verbs ...string) []string { + var out []string + for _, verb := range verbs { + out = append(out, resource+"."+verb) + } + return out + } + 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-recovery-operator": slices.Concat(p(group+"devicerecoveries", "create"), p("metal.datumapis.com/machineallocations", read...)), + "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), + "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), + } + coordinator := slices.Concat(p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...)) + for _, plural := range []string{"deviceinstallations", "devicewipes", "devicerecoveries"} { + coordinator = slices.Concat(coordinator, p(group+plural, "get", "list", "watch", "delete", "updateStatus"), []string{group + plural + "/status.update"}) + } + want["fleet.datumapis.com-device-coordinator"] = coordinator + if len(roles) != len(want) { + t.Fatalf("roles = %v", roles) + } + for name, expected := range want { + current, ok := roles[name] + if !ok { + t.Fatalf("missing role %s", name) + } + actual := slices.Clone(current.Spec.Included) + slices.Sort(actual) + slices.Sort(expected) + if !slices.Equal(actual, expected) { + t.Fatalf("%s = %v, want %v", name, actual, expected) + } + inherits := len(current.Spec.Inherited) != 0 + if name == "fleet.datumapis.com-device-recovery-operator" { + if len(current.Spec.Inherited) != 1 || current.Spec.Inherited[0].Name != "fleet.datumapis.com-device-operations-viewer" { + t.Fatal("the recovery operator inherits only the viewer") + } + } else if inherits { + t.Fatalf("%s must not inherit", name) + } + for _, permission := range actual { + parts := strings.SplitN(strings.TrimPrefix(permission, group), ".", 2) + resource, verb := parts[0], parts[1] + // Only the coordinator writes custody or operation status. + if name != "fleet.datumapis.com-device-coordinator" && (strings.Contains(permission, "/status.") || strings.HasSuffix(permission, ".updateStatus") || (resource == "devicecustodies" && !slices.Contains(read, verb))) { + t.Fatalf("%s writes custody or status: %s", name, permission) + } + // No role reads a sealed store, a Secret or a bootstrap payload. + if strings.Contains(permission, "secret") || strings.Contains(permission, "sealed") || strings.Contains(permission, "bootstrap") { + t.Fatalf("%s grants %s", name, permission) + } + } + } + // Staff can never create provider or release kinds. + for _, staff := range []string{"fleet.datumapis.com-device-operations-viewer", "fleet.datumapis.com-device-recovery-operator"} { + for _, permission := range roles[staff].Spec.Included { + if strings.HasSuffix(permission, ".create") && permission != group+"devicerecoveries.create" { + t.Fatalf("%s may create %s", staff, permission) + } + } + } +} + +// TestComponentIsInert proves Increment A wires nothing: no root includes the +// component, and the test-only kinds ship nowhere. +func TestComponentIsInert(t *testing.T) { + err := filepath.WalkDir(configRoot, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() || strings.HasPrefix(path, componentRoot+string(filepath.Separator)) { + return nil + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + if filepath.Base(path) == "kustomization.yaml" && strings.Contains(string(data), "device-operations") { + t.Errorf("%s includes the device-operations component", path) + } + if strings.Contains(string(data), "DeviceTest") || strings.Contains(string(data), "devicetest") { + t.Errorf("%s ships a test-only kind", path) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func TestPhases(t *testing.T) { + for _, phase := range []Phase{PhaseSucceeded, PhaseFailed, PhaseCancelled, PhaseOutcomeUnknown} { + if !phase.Ended() || phase.Running() { + t.Fatalf("%s must be ended", phase) + } + } + for _, phase := range []Phase{PhaseAdmitted, PhaseDispatched, PhaseVerifying} { + if phase.Ended() || !phase.Running() { + t.Fatalf("%s must be running", phase) + } + } + if PhasePending.Ended() || PhasePending.Running() { + t.Fatal("Pending is neither") + } + for _, kind := range operationKinds { + if _, ok := loadCRDs(t)[kind]; !ok { + t.Fatalf("missing %s", kind) + } + } +} diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go new file mode 100644 index 00000000..61ed4e33 --- /dev/null +++ b/internal/api/operations/v1alpha1/types.go @@ -0,0 +1,443 @@ +// Package v1alpha1 holds Device custody and the Device operation kinds in +// fleet.datumapis.com, as proposed in datum-cloud/fleet#174 at 3907eec. +// +// DeviceCustody is a coordination record, like a Lease: its fields live in +// spec and the coordinator is their only writer. Every operation kind shares +// one envelope (OperationEnvelope) and one status (OperationStatus). The +// coordinator is the only writer of operation status. Requesters write an +// operation's spec once, at create; it is immutable afterwards. +// +// Nothing here sends anything to a BMC. These kinds live only in the provider +// project and are never served to consumer projects. +package v1alpha1 + +import ( + "encoding/json" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +var GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} + +// CustodyFinalizer keeps custody until its holder is Retired. +const CustodyFinalizer = "fleet.datumapis.com/custody" + +// DeviceCustody names who holds one Device, the one operation running on it, +// and its fence. It has the same name and namespace as its Device. +type DeviceCustody struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceCustodySpec `json:"spec"` +} + +type CustodyState string + +const ( + CustodyVerified CustodyState = "Verified" + CustodyUnverified CustodyState = "Unverified" +) + +type HolderType string + +const ( + HolderNone HolderType = "None" + HolderAllocation HolderType = "Allocation" + HolderRelease HolderType = "Release" + HolderService HolderType = "Service" + HolderRetired HolderType = "Retired" +) + +// ReleaseGate is one machine lifecycle release obligation. The set is closed; +// a gate the coordinator does not know stays open. +type ReleaseGate string + +const ( + GateOperations ReleaseGate = "Operations" + GateAccess ReleaseGate = "Access" + GateNetwork ReleaseGate = "Network" + GateAddress ReleaseGate = "Address" + GateCleaning ReleaseGate = "Cleaning" + GateQuota ReleaseGate = "Quota" +) + +// ReleaseGates is every gate, in the order the machine lifecycle settles them. +var ReleaseGates = []ReleaseGate{GateOperations, GateAccess, GateNetwork, GateAddress, GateCleaning, GateQuota} + +type DeviceCustodySpec struct { + DeviceRef DeviceReference `json:"deviceRef"` + State CustodyState `json:"state"` + Holder Holder `json:"holder"` + // Fence rises when an operation is admitted and when custody is rebuilt. + Fence int64 `json:"fence"` + ActiveOperation *ActiveOperation `json:"activeOperation,omitempty"` + LastResult *OperationResult `json:"lastResult,omitempty"` + RecoveryHold *RecoveryHold `json:"recoveryHold,omitempty"` + // Conflicts says why Unverified custody cannot be verified yet. + Conflicts []string `json:"conflicts,omitempty"` + // RejectedResults counts site results refused for a stale fence. + RejectedResults *RejectedResults `json:"rejectedResults,omitempty"` +} + +type DeviceReference struct { + Name string `json:"name"` + UID string `json:"uid"` +} + +type LocalReference struct { + Name string `json:"name"` +} + +// Holder is who holds the Device. AllocationRef is set only for Allocation +// and Release, and OpenGates only for Release. +type Holder struct { + Type HolderType `json:"type"` + AllocationRef *LocalReference `json:"allocationRef,omitempty"` + OpenGates []ReleaseGate `json:"openGates,omitempty"` +} + +// OperationReference names one operation incarnation. +type OperationReference struct { + Kind string `json:"kind"` + Name string `json:"name"` + UID string `json:"uid"` +} + +// ActiveOperation is the one admitted operation. Custody retains its exact +// input digest and Device snapshot before anything is delivered, so delivery +// can be replayed from custody after a crash. +type ActiveOperation struct { + OperationReference `json:",inline"` + Fence int64 `json:"fence"` + Phase Phase `json:"phase"` + AdmittedAt metav1.Time `json:"admittedAt"` + Deadline metav1.Time `json:"deadline"` + InputDigest string `json:"inputDigest"` + Snapshot DeviceSnapshot `json:"snapshot"` + Creator Creator `json:"creator"` + // Settles names the recovery hold this operation was admitted to settle. + Settles *OperationReference `json:"settles,omitempty"` +} + +// DeviceSnapshot is what admission captured about the Device. The site +// checks the BMC against it before it sends anything. +type DeviceSnapshot struct { + BMCEndpoint string `json:"bmcEndpoint"` + SystemUUID string `json:"systemUUID"` + BootMACAddress string `json:"bootMACAddress,omitempty"` + BMCPublicKeySHA256 string `json:"bmcPublicKeySHA256"` + DeviceGeneration int64 `json:"deviceGeneration"` + DiscoveryObservedAt string `json:"discoveryObservedAt"` +} + +// OperationResult is how one operation ended, with its typed evidence. +type OperationResult struct { + OperationReference `json:",inline"` + Fence int64 `json:"fence"` + Phase Phase `json:"phase"` + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` + FinishedAt metav1.Time `json:"finishedAt"` + Evidence *runtime.RawExtension `json:"evidence,omitempty"` +} + +// RecoveryHold is an operation whose outcome is unknown. Only the settling +// operations its kind allows are admitted while it exists. +type RecoveryHold struct { + OperationReference `json:",inline"` + Fence int64 `json:"fence"` + Since metav1.Time `json:"since"` + Reason string `json:"reason"` + // RetryAuthorizedBy names the DeviceRecovery with Retry that lets the + // held operation's requester create one settling operation. + RetryAuthorizedBy *OperationReference `json:"retryAuthorizedBy,omitempty"` +} + +// RejectedResults records site results the coordinator refused because their +// fence did not match the active operation. Monitoring reads it. +type RejectedResults struct { + Count int64 `json:"count"` + Last RejectedResult `json:"last"` +} + +type RejectedResult struct { + Kind string `json:"kind"` + Name string `json:"name"` + Fence int64 `json:"fence"` + Site string `json:"site"` + RejectedAt metav1.Time `json:"rejectedAt"` +} + +// Phase is an operation phase. +type Phase string + +const ( + PhasePending Phase = "Pending" + PhaseAdmitted Phase = "Admitted" + PhaseDispatched Phase = "Dispatched" + PhaseVerifying Phase = "Verifying" + PhaseSucceeded Phase = "Succeeded" + PhaseFailed Phase = "Failed" + PhaseCancelled Phase = "Cancelled" + PhaseOutcomeUnknown Phase = "OutcomeUnknown" +) + +// Ended reports whether an operation in this phase has finished. +// OutcomeUnknown ends the operation; its hold lives on in custody. +func (p Phase) Ended() bool { + return p == PhaseSucceeded || p == PhaseFailed || p == PhaseCancelled || p == PhaseOutcomeUnknown +} + +// Running reports whether custody can name an operation in this phase as +// active. +func (p Phase) Running() bool { + return p == PhaseAdmitted || p == PhaseDispatched || p == PhaseVerifying +} + +// Creator is the authenticated caller that created an operation. A +// validating webhook rejects any other value and any change. +type Creator struct { + Username string `json:"username"` + UID string `json:"uid"` +} + +// Authority is why an operation may act. Exactly one field is set. +type Authority struct { + AllocationRef *LocalReference `json:"allocationRef,omitempty"` + ServiceRequest *ServiceRequest `json:"serviceRequest,omitempty"` +} + +// ServiceRequest is a staff request. Reason is required. +type ServiceRequest struct { + Reason string `json:"reason"` +} + +// OperationEnvelope is the spec every operation kind starts with. +type OperationEnvelope struct { + Creator Creator `json:"creator"` + DeviceRef DeviceReference `json:"deviceRef"` + Authority Authority `json:"authority"` +} + +// OperationStatus is the status every operation kind shares. The coordinator +// copies it from custody. +type OperationStatus struct { + Phase Phase `json:"phase,omitempty"` + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` + Fence int64 `json:"fence,omitempty"` + AdmittedAt *metav1.Time `json:"admittedAt,omitempty"` + Deadline *metav1.Time `json:"deadline,omitempty"` + FinishedAt *metav1.Time `json:"finishedAt,omitempty"` + InputDigest string `json:"inputDigest,omitempty"` + Snapshot *DeviceSnapshot `json:"snapshot,omitempty"` + // Evidence is the kind's typed result evidence, as recorded in custody. + Evidence *runtime.RawExtension `json:"evidence,omitempty"` +} + +// Operation is implemented by every operation kind. +type Operation interface { + runtime.Object + metav1.Object + Envelope() *OperationEnvelope + OperationStatus() *OperationStatus +} + +// DeviceInstallation installs an image on an allocated Device. The Fleet +// provider for Metal creates it from an Installation. +type DeviceInstallation struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceInstallationSpec `json:"spec"` + Status OperationStatus `json:"status,omitempty"` +} + +type DeviceInstallationSpec struct { + OperationEnvelope `json:",inline"` + // RequestUID is the UID of the Installation this fulfills. The name is + // derived from it, so a retried create collides. + RequestUID string `json:"requestUID"` + Image ImageInput `json:"image"` + Bootstrap *SealedInput `json:"bootstrap,omitempty"` + BootInterface string `json:"bootInterface"` + TargetDisks []string `json:"targetDisks"` +} + +type ImageInput struct { + Name string `json:"name"` + Digest string `json:"digest"` +} + +// SealedInput is an opaque reference into the sealed store and the digest of +// what it holds. Operations never carry the payload. +type SealedInput struct { + Ref string `json:"ref"` + Digest string `json:"digest"` +} + +// InstallationEvidence is the result evidence of a DeviceInstallation. +type InstallationEvidence struct { + Steps []StepEvidence `json:"steps,omitempty"` +} + +// StepEvidence records one journaled step. It never carries a BMC response. +type StepEvidence struct { + Name string `json:"name"` + CompletedAt metav1.Time `json:"completedAt"` +} + +// DeviceWipe cleans an allocation's disks during release. The release +// controller creates it. +type DeviceWipe struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceWipeSpec `json:"spec"` + Status OperationStatus `json:"status,omitempty"` +} + +type DeviceWipeSpec struct { + OperationEnvelope `json:",inline"` + // Step numbers the wipes of one release, from 1. The name is derived + // from it. + Step int32 `json:"step"` + // CleaningPolicyDigest is the digest of the cleaning policy record + // pinned at allocation. + CleaningPolicyDigest string `json:"cleaningPolicyDigest"` + TargetDisks []string `json:"targetDisks"` +} + +// WipeEvidence is the result evidence of a DeviceWipe. +type WipeEvidence struct { + Steps []StepEvidence `json:"steps,omitempty"` + WipedDisks []string `json:"wipedDisks,omitempty"` + PolicyDigest string `json:"policyDigest,omitempty"` +} + +// DeviceRecovery is a staff decision about a recovery hold or about +// Unverified custody. It sends nothing to the server. +type DeviceRecovery struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceRecoverySpec `json:"spec"` + Status OperationStatus `json:"status,omitempty"` +} + +type RecoveryDecision string + +const ( + DecisionSettle RecoveryDecision = "Settle" + DecisionRetry RecoveryDecision = "Retry" + DecisionRetire RecoveryDecision = "Retire" + DecisionResolve RecoveryDecision = "Resolve" +) + +type DeviceRecoverySpec struct { + OperationEnvelope `json:",inline"` + Decision RecoveryDecision `json:"decision"` + // Hold names the held operation the decision is about. Required for + // Settle, Retry and Retire under a hold. + Hold *HeldOperationReference `json:"hold,omitempty"` + // Evidence is what staff observed. The held kind validates it for Settle. + Evidence RecoveryEvidence `json:"evidence"` + // DiskDisposal is required to Retire from Release. + DiskDisposal *DiskDisposal `json:"diskDisposal,omitempty"` + // Resolve names the holder of Unverified custody. + Resolve *ResolveInput `json:"resolve,omitempty"` +} + +type HeldOperationReference struct { + Kind string `json:"kind"` + Name string `json:"name"` + Fence int64 `json:"fence"` +} + +// RecoveryEvidence is bounded, typed staff evidence. Data holds the held +// kind's own evidence fields; the kind validates them. +type RecoveryEvidence struct { + ObservedAt metav1.Time `json:"observedAt"` + Summary string `json:"summary"` + Data map[string]string `json:"data,omitempty"` +} + +type DiskDisposalMethod string + +const ( + DisposalDestroyed DiskDisposalMethod = "Destroyed" + DisposalRemoved DiskDisposalMethod = "Removed" +) + +type DiskDisposal struct { + Method DiskDisposalMethod `json:"method"` + Reference string `json:"reference"` +} + +type ResolveInput struct { + Holder HolderType `json:"holder"` + AllocationRef *LocalReference `json:"allocationRef,omitempty"` +} + +// RecoveryResultEvidence is the result evidence of a DeviceRecovery: the +// decision applied and the site fence that confirmed the held worker stopped. +type RecoveryResultEvidence struct { + Decision RecoveryDecision `json:"decision"` + ConfirmedFence int64 `json:"confirmedFence"` +} + +func (in *DeviceInstallation) Envelope() *OperationEnvelope { return &in.Spec.OperationEnvelope } +func (in *DeviceInstallation) OperationStatus() *OperationStatus { return &in.Status } +func (in *DeviceWipe) Envelope() *OperationEnvelope { return &in.Spec.OperationEnvelope } +func (in *DeviceWipe) OperationStatus() *OperationStatus { return &in.Status } +func (in *DeviceRecovery) Envelope() *OperationEnvelope { return &in.Spec.OperationEnvelope } +func (in *DeviceRecovery) OperationStatus() *OperationStatus { return &in.Status } + +type DeviceCustodyList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceCustody `json:"items"` +} + +type DeviceInstallationList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceInstallation `json:"items"` +} + +type DeviceWipeList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceWipe `json:"items"` +} + +type DeviceRecoveryList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceRecovery `json:"items"` +} + +func addKnown(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &DeviceCustody{}, &DeviceCustodyList{}, &DeviceInstallation{}, &DeviceInstallationList{}, &DeviceWipe{}, &DeviceWipeList{}, &DeviceRecovery{}, &DeviceRecoveryList{}) + metav1.AddToGroupVersion(s, GroupVersion) + return nil +} + +var AddToScheme = addKnown + +func (in *DeviceCustody) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DeviceCustodyList) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DeviceInstallation) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DeviceInstallationList) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DeviceWipe) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DeviceWipeList) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DeviceRecovery) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DeviceRecoveryList) DeepCopyObject() runtime.Object { return deepCopy(in) } + +// DeepCopy returns a copy of custody. +func (in *DeviceCustody) DeepCopy() *DeviceCustody { return deepCopy(in) } + +func deepCopy[T any](in *T) *T { + out := new(T) + b, _ := json.Marshal(in) + _ = json.Unmarshal(b, out) + return out +} From f8cc221eee1028657448ef3db6733c9c7aae98a8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 18:09:36 -0600 Subject: [PATCH 02/19] feat(custody): Admit Device operations through custody Add the coordinator, the only writer of custody and of operation status. It admits each operation with one conditional custody update, queues provider and release work, refuses staff work it cannot run now, and expires staff work after five minutes. It accepts only results that carry the active fence, moves unknown outcomes into a recovery hold, applies DeviceRecovery decisions after the sites confirm the raised fence, and rebuilds missing custody as Unverified. Kinds plug in through a registry entry and rows of the admission table. Test-only kinds prove each seam, against a real API server. Co-Authored-By: Claude Opus 5.5 --- go.mod | 2 +- internal/custody/admission_test.go | 282 +++++++ internal/custody/capacity.go | 88 ++ internal/custody/concurrency_test.go | 342 ++++++++ internal/custody/coordinator.go | 791 ++++++++++++++++++ internal/custody/harness_test.go | 376 +++++++++ internal/custody/kinds.go | 305 +++++++ internal/custody/lifecycle_test.go | 326 ++++++++ internal/custody/rebuild.go | 191 +++++ internal/custody/recovery_test.go | 502 +++++++++++ internal/custody/registry.go | 256 ++++++ internal/custody/results.go | 229 +++++ internal/custody/retention.go | 51 ++ internal/custody/rules.go | 150 ++++ internal/custody/seams_test.go | 268 ++++++ .../custody/testdata/crds/test-kinds.yaml | 353 ++++++++ internal/custody/testkinds_test.go | 171 ++++ 17 files changed, 4682 insertions(+), 1 deletion(-) create mode 100644 internal/custody/admission_test.go create mode 100644 internal/custody/capacity.go create mode 100644 internal/custody/concurrency_test.go create mode 100644 internal/custody/coordinator.go create mode 100644 internal/custody/harness_test.go create mode 100644 internal/custody/kinds.go create mode 100644 internal/custody/lifecycle_test.go create mode 100644 internal/custody/rebuild.go create mode 100644 internal/custody/recovery_test.go create mode 100644 internal/custody/registry.go create mode 100644 internal/custody/results.go create mode 100644 internal/custody/retention.go create mode 100644 internal/custody/rules.go create mode 100644 internal/custody/seams_test.go create mode 100644 internal/custody/testdata/crds/test-kinds.yaml create mode 100644 internal/custody/testkinds_test.go diff --git a/go.mod b/go.mod index ff1a5496..1bf7468f 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module go.datum.net/fleet go 1.26.4 require ( + github.com/go-logr/logr v1.4.4 github.com/prometheus/client_golang v1.24.0 github.com/prometheus/client_model v0.6.2 github.com/stmcginnis/gofish v0.27.0 @@ -69,7 +70,6 @@ require ( github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect github.com/fxamacker/cbor/v2 v2.9.1 // indirect - github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/zapr v1.3.0 // indirect github.com/go-openapi/jsonpointer v1.0.0 // indirect github.com/go-openapi/jsonreference v1.0.0 // indirect diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go new file mode 100644 index 00000000..6e9f5db9 --- /dev/null +++ b/internal/custody/admission_test.go @@ -0,0 +1,282 @@ +package custody + +import ( + "fmt" + "testing" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// requireUntouched fails if custody admitted anything or raised the fence. +func (e *env) requireUntouched(name string, fence int64) { + e.t.Helper() + custody := e.custody(name) + if custody.Spec.ActiveOperation != nil || custody.Spec.Fence != fence { + e.t.Fatalf("custody changed: active %+v fence %d, want fence %d", custody.Spec.ActiveOperation, custody.Spec.Fence, fence) + } +} + +func TestAdmissionPreconditions(t *testing.T) { + e := startEnv(t) + n := 0 + fresh := func() *inventory.Device { + n++ + return e.verified(fmt.Sprintf("server-example-%03d", n), uid(n), fmt.Sprintf("%064x", n)) + } + + t.Run("admission raises the fence, sets the deadline and retains inputs and snapshot", func(t *testing.T) { + e := e.sub(t) + device := fresh() + before := e.custody(device.Name).Spec.Fence + operation := e.staffOp(device, "ok") + e.settle(device.Name) + custody := e.custody(device.Name) + active := custody.Spec.ActiveOperation + if active == nil || active.Name != operation.Name || active.Fence != before+1 || custody.Spec.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(testDeadline)) || active.Creator.Username != staffUser { + t.Fatalf("active = %+v", active) + } + want := ops.DeviceSnapshot{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: device.Spec.Identity.SystemUUID, BMCPublicKeySHA256: fmt.Sprintf("%064x", n), DeviceGeneration: device.Generation, DiscoveryObservedAt: e.clock.Now().Format(time.RFC3339)} + if active.Snapshot != want { + t.Fatalf("snapshot = %+v, want %+v", active.Snapshot, want) + } + status := e.requirePhase(operation, ops.PhaseAdmitted, "") + if status.Fence != active.Fence || status.InputDigest != digest || status.Snapshot == nil || *status.Snapshot != want { + t.Fatalf("status copy = %+v", status) + } + }) + + t.Run("1: Unverified custody refuses staff and holds provider operations pending", func(t *testing.T) { + e := e.sub(t) + device := fresh() + custody := e.custody(device.Name) + custody.Spec.State = ops.CustodyUnverified + if err := e.admin.Update(e.ctx, custody); err != nil { + t.Fatal(err) + } + e.sites.forget(device.Name) + staff := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(staff, ops.PhaseFailed, ReasonUnverified) + e.requireUntouched(device.Name, custody.Spec.Fence) + }) + + t.Run("2: a creator and authority pair outside the table is refused", func(t *testing.T) { + e := e.sub(t) + device := fresh() + fence := e.custody(device.Name).Spec.Fence + // Staff cannot create a provider kind. + spoof := &DeviceTestProviderOperation{ObjectMeta: metav1.ObjectMeta{Name: "alloc-x-test-a", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Input: "a"}} + e.create(spoof) + // A service principal cannot create a staff kind. + service := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: "svc-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, providerUser, service("not staff")), Input: "a"}} + e.create(service) + // A staff kind that names an allocationRef. + named := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: "named-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Input: "a"}} + e.create(named) + // Staff cannot create the release kind either. + wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName("alloc-x", 1), Namespace: "default"}, Spec: ops.DeviceWipeSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Step: 1, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}}} + e.create(wipe) + e.settle(device.Name) + for _, operation := range []ops.Operation{spoof, service, named, wipe} { + e.requirePhase(operation, ops.PhaseFailed, ReasonNoMatchingRule) + } + e.requireUntouched(device.Name, fence) + }) + + t.Run("2: a staff operation on an allocated or releasing server is refused", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-held"); err != nil { + t.Fatal(err) + } + fence := e.custody(device.Name).Spec.Fence + allocatedOp := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(allocatedOp, ops.PhaseFailed, ReasonHolderMismatch) + if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-held"); err != nil { + t.Fatal(err) + } + releasingOp := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(releasingOp, ops.PhaseFailed, ReasonHolderMismatch) + e.requireUntouched(device.Name, fence) + }) + + t.Run("3: an allocationRef must name the holder's allocation", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-mine"); err != nil { + t.Fatal(err) + } + fence := e.custody(device.Name).Spec.Fence + other := e.providerOp(device, "alloc-other", "a") + e.settle(device.Name) + e.requirePhase(other, ops.PhaseFailed, ReasonHolderMismatch) + e.requireUntouched(device.Name, fence) + }) + + t.Run("4: one active operation; provider operations wait in order", func(t *testing.T) { + e := e.sub(t) + device := fresh() + first := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(first, ops.PhaseAdmitted, "") + // The first staff operation took the holder to Service. + second := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(second, ops.PhaseFailed, ReasonHolderMismatch) + + queued := fresh() + if err := e.coord.Claim(e.ctx, queued.Name, "alloc-queue"); err != nil { + t.Fatal(err) + } + running := e.providerOp(queued, "alloc-queue", "a") + e.settle(queued.Name) + e.requirePhase(running, ops.PhaseAdmitted, "") + waiting := e.providerOp(queued, "alloc-queue", "b") + e.settle(queued.Name) + e.requirePhase(waiting, ops.PhasePending, ReasonOperationActive) + if err := e.result(queued.Name, ops.PhaseSucceeded, ""); err != nil { + t.Fatal(err) + } + e.settle(queued.Name) + e.requirePhase(running, ops.PhaseSucceeded, "") + e.requirePhase(waiting, ops.PhaseAdmitted, "") + }) + + t.Run("5: the Device UID must match deviceRef.uid", func(t *testing.T) { + e := e.sub(t) + device := fresh() + fence := e.custody(device.Name).Spec.Fence + operation := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: "stale-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("old record")), Input: "a"}} + operation.Spec.DeviceRef.UID = "00000000-0000-4000-8000-ffffffffffff" + e.create(operation) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonIdentityMismatch) + e.requireUntouched(device.Name, fence) + }) + + t.Run("5: identity must match current discovery", func(t *testing.T) { + e := e.sub(t) + device := fresh() + fence := e.custody(device.Name).Spec.Fence + // Discovery older than the maximum age. + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now().Add(-DefaultDiscoveryMaxAge-time.Minute)) + old := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(old, ops.PhaseFailed, ReasonIdentityNotCurrent) + // Discovery that did not match identity. + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now()) + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + device.Status.Conditions[0].Status = metav1.ConditionFalse + if err := e.admin.Status().Update(e.ctx, device); err != nil { + t.Fatal(err) + } + mismatched := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(mismatched, ops.PhaseFailed, ReasonIdentityMismatch) + e.requireUntouched(device.Name, fence) + }) + + t.Run("6: no other live Device may record the same BMC key", func(t *testing.T) { + e := e.sub(t) + device := fresh() + key := fmt.Sprintf("%064x", n) + fence := e.custody(device.Name).Spec.Fence + twin := e.device(fmt.Sprintf("server-twin-%03d", n), uid(900+n), key) + shared := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(shared, ops.PhaseFailed, ReasonSharedPublicKey) + e.requireUntouched(device.Name, fence) + // A retired Device no longer counts. + for _, lifecycle := range []inventory.DeviceLifecycle{inventory.DeviceDecommissioning, inventory.DeviceRetired} { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(twin), twin); err != nil { + t.Fatal(err) + } + twin.Spec.Lifecycle = lifecycle + if err := e.admin.Update(e.ctx, twin); err != nil { + t.Fatal(err) + } + } + e.discover(device, key, e.clock.Now()) + admitted := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(admitted, ops.PhaseAdmitted, "") + }) + + t.Run("names: deterministic kinds must use their rule, staff kinds a generated name", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-name"); err != nil { + t.Fatal(err) + } + fence := e.custody(device.Name).Spec.Fence + wrong := &DeviceTestProviderOperation{ObjectMeta: metav1.ObjectMeta{Name: "authored-name", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, providerUser, allocated("alloc-name")), Input: "a"}} + e.create(wrong) + e.settle(device.Name) + e.requirePhase(wrong, ops.PhaseFailed, ReasonNameMismatch) + e.requireUntouched(device.Name, fence) + + free := fresh() + authored := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{Name: "authored-staff", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(free, staffUser, service("authored")), Input: "a"}} + e.create(authored) + e.settle(free.Name) + e.requirePhase(authored, ops.PhaseFailed, ReasonNameMismatch) + }) + + t.Run("kind-specific checks refuse with their own reason", func(t *testing.T) { + e := e.sub(t) + device := fresh() + fence := e.custody(device.Name).Spec.Fence + operation := e.staffOp(device, "refuse") + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, reasonTestRefuse) + e.requireUntouched(device.Name, fence) + }) + + t.Run("bootstrap stays refused", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-boot"); err != nil { + t.Fatal(err) + } + fence := e.custody(device.Name).Spec.Fence + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-boot", "request-1"), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated("alloc-boot")), RequestUID: "request-1", + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, Bootstrap: &ops.SealedInput{Ref: "sealed-example", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + }} + e.create(operation) + missing := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-boot", "request-2"), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated("alloc-boot")), RequestUID: "request-2", + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "absent", TargetDisks: []string{"disk-0"}, + }} + e.create(missing) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonBootstrapUnsupported) + e.requirePhase(missing, ops.PhaseFailed, ReasonBootInterfaceUnknown) + e.requireUntouched(device.Name, fence) + }) + + t.Run("a staff operation not admitted within five minutes expires", func(t *testing.T) { + e := e.sub(t) + device := fresh() + fence := e.custody(device.Name).Spec.Fence + operation := e.staffOp(device, "ok") + // The coordinator was down for five minutes. + e.clock.Advance(DefaultStaffExpiry + time.Minute) + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now()) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseCancelled, ReasonExpired) + e.requireUntouched(device.Name, fence) + }) +} diff --git a/internal/custody/capacity.go b/internal/custody/capacity.go new file mode 100644 index 00000000..bb842326 --- /dev/null +++ b/internal/custody/capacity.go @@ -0,0 +1,88 @@ +package custody + +import ( + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// MachineCapacity conditions the capacity projector derives. The projector +// is their only writer once it is wired; in Increment A it is a pure function +// and nothing calls it outside tests. +const ( + ConditionPrepared = "Prepared" + ConditionHealthy = "Healthy" + ConditionAvailable = "Available" +) + +// CommissioningEvidence is the latest succeeded commissioning of a Device. +type CommissioningEvidence struct { + // PlanDigest is the commissioning plan the run used. + PlanDigest string + // HealthCurrent says the run's health evidence is still current. + HealthCurrent bool +} + +// CapacityInputs is everything the projector reads. +type CapacityInputs struct { + Generation int64 + // Commissioning is nil when no commissioning has succeeded. + Commissioning *CommissioningEvidence + // CurrentPlanDigest is the plan the Device must be commissioned under. + CurrentPlanDigest string + // DiscoveryCurrent says BMC discovery evidence is current. + DiscoveryCurrent bool + // Custody is nil when the Device has no custody. + Custody *ops.DeviceCustodySpec + AllocationPolicyEnabled bool +} + +// ProjectCapacity derives Prepared, Healthy and Available. Available is +// advisory: the allocator decides with a conditional custody update. +func ProjectCapacity(in CapacityInputs) []metav1.Condition { + condition := func(kind string, ok bool, reason, message string) metav1.Condition { + status := metav1.ConditionFalse + if ok { + status = metav1.ConditionTrue + } + return metav1.Condition{Type: kind, Status: status, Reason: reason, Message: message, ObservedGeneration: in.Generation} + } + var prepared metav1.Condition + switch { + case in.Commissioning == nil: + prepared = condition(ConditionPrepared, false, "NotCommissioned", "no commissioning has succeeded") + case in.CurrentPlanDigest == "" || in.Commissioning.PlanDigest != in.CurrentPlanDigest: + prepared = condition(ConditionPrepared, false, "PlanChanged", "the last commissioning used a different plan") + default: + prepared = condition(ConditionPrepared, true, "Commissioned", "commissioning succeeded under the current plan") + } + var healthy metav1.Condition + switch { + case in.Commissioning == nil || !in.Commissioning.HealthCurrent: + healthy = condition(ConditionHealthy, false, "CommissioningEvidenceNotCurrent", "commissioning health evidence is missing or old") + case !in.DiscoveryCurrent: + healthy = condition(ConditionHealthy, false, "DiscoveryNotCurrent", "discovery evidence is missing or old") + default: + healthy = condition(ConditionHealthy, true, "EvidenceCurrent", "commissioning and discovery evidence are current") + } + var available metav1.Condition + custody := in.Custody + switch { + case prepared.Status != metav1.ConditionTrue: + available = condition(ConditionAvailable, false, "NotPrepared", "the Device is not prepared") + case healthy.Status != metav1.ConditionTrue: + available = condition(ConditionAvailable, false, "NotHealthy", "the Device is not healthy") + case custody == nil: + available = condition(ConditionAvailable, false, "CustodyMissing", "the Device has no custody") + case custody.State != ops.CustodyVerified: + available = condition(ConditionAvailable, false, "CustodyUnverified", "custody is Unverified") + case custody.RecoveryHold != nil: + available = condition(ConditionAvailable, false, "RecoveryHold", "an operation outcome is unknown") + case custody.Holder.Type != ops.HolderNone || custody.ActiveOperation != nil: + available = condition(ConditionAvailable, false, "Held", "the holder is "+string(custody.Holder.Type)) + case !in.AllocationPolicyEnabled: + available = condition(ConditionAvailable, false, "AllocationDisabled", "the allocation policy is not enabled") + default: + available = condition(ConditionAvailable, true, "Available", "the Device can be allocated") + } + return []metav1.Condition{prepared, healthy, available} +} diff --git a/internal/custody/concurrency_test.go b/internal/custody/concurrency_test.go new file mode 100644 index 00000000..2869e3df --- /dev/null +++ b/internal/custody/concurrency_test.go @@ -0,0 +1,342 @@ +package custody + +import ( + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + "testing" + + 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" +) + +// client returns a separate client, so concurrent callers use separate +// connections. +func (e *env) client() client.Client { + e.t.Helper() + api, err := client.New(e.config, client.Options{Scheme: e.scheme}) + if err != nil { + e.t.Fatal(err) + } + return api +} + +// settleQuiet reconciles until nothing changes, returning the first error. +func settleQuiet(ctx context.Context, coord *Coordinator, name string) error { + for range 60 { + outcome, err := coord.Reconcile(ctx, name) + if err != nil { + return err + } + if !outcome.Changed { + return nil + } + } + return errors.New("did not settle") +} + +func TestConcurrency(t *testing.T) { + e := startEnv(t) + n := 400 + fresh := func() *inventory.Device { + n++ + return e.verified(fmt.Sprintf("server-example-%03d", n), uid(n), fmt.Sprintf("%064x", n)) + } + + t.Run("two allocators race for one server and exactly one wins", func(t *testing.T) { + e := e.sub(t) + device := fresh() + var wins atomic.Int32 + var group sync.WaitGroup + for index := range 8 { + allocator := e.coordinator(e.client()) + group.Add(1) + go func() { + defer group.Done() + err := allocator.Claim(e.ctx, device.Name, fmt.Sprintf("alloc-race-%d", index)) + switch { + case err == nil: + wins.Add(1) + case !errors.Is(err, ErrUnavailable): + t.Errorf("claim: %v", err) + } + }() + } + group.Wait() + if wins.Load() != 1 || e.custody(device.Name).Spec.Holder.Type != ops.HolderAllocation { + t.Fatalf("%d allocators won", wins.Load()) + } + }) + + t.Run("an allocator races a staff operation and exactly one takes the server", func(t *testing.T) { + e := e.sub(t) + for range 5 { + device := fresh() + operation := e.staffOp(device, "ok") + 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, "alloc-staff-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 the staff operation 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("staff won but the operation is %s and custody %+v", status.Phase, custody.Spec) + } + default: + t.Fatal(claimErr) + } + } + }) + + t.Run("two coordinators admit from one custody exactly once", func(t *testing.T) { + e := e.sub(t) + device := fresh() + before := e.custody(device.Name).Spec.Fence + var operations []*DeviceTestStaffOperation + for range 3 { + operations = append(operations, e.staffOp(device, "ok")) + } + var group sync.WaitGroup + for range 2 { + coordinator := e.coordinator(e.client()) + group.Add(1) + go func() { + defer group.Done() + if err := settleQuiet(e.ctx, coordinator, device.Name); err != nil { + t.Error(err) + } + }() + } + group.Wait() + e.settle(device.Name) + custody := e.custody(device.Name) + admitted := 0 + for _, operation := range operations { + if status := e.status(operation); status.Phase == ops.PhaseAdmitted { + admitted++ + } else if status.Phase != ops.PhaseFailed && status.Phase != ops.PhaseCancelled { + t.Fatalf("%s is %s", operation.Name, status.Phase) + } + } + if admitted != 1 || custody.Spec.Fence != before+1 || custody.Spec.ActiveOperation == nil { + t.Fatalf("%d admitted, fence %d from %d", admitted, custody.Spec.Fence, before) + } + }) + + t.Run("an admission races a holder change", func(t *testing.T) { + e := e.sub(t) + for range 5 { + device := fresh() + allocation := "alloc-hc-" + device.Name + if err := e.coord.Claim(e.ctx, device.Name, allocation); err != nil { + t.Fatal(err) + } + before := e.custody(device.Name).Spec.Fence + operation := e.installation(device, allocation, "request-race") + coordinator := e.coordinator(e.client()) + releaser := e.coordinator(e.client()) + var releaseErr, 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(); releaseErr = releaser.BeginRelease(e.ctx, device.Name, allocation) }() + group.Wait() + if reconcileErr != nil || releaseErr != nil { + t.Fatal(reconcileErr, releaseErr) + } + e.settle(device.Name) + status := e.status(operation) + custody := e.custody(device.Name) + if custody.Spec.Holder.Type != ops.HolderRelease { + t.Fatalf("holder = %s", custody.Spec.Holder.Type) + } + switch status.Phase { + case ops.PhaseAdmitted: + // Admitted under Allocation, then released while running. + if custody.Spec.ActiveOperation == nil || custody.Spec.ActiveOperation.UID != string(operation.UID) || custody.Spec.Fence != before+1 { + t.Fatalf("admitted but custody %+v", custody.Spec) + } + case ops.PhaseFailed, ops.PhaseCancelled: + if status.Reason != ReasonHolderMismatch || custody.Spec.ActiveOperation != nil || custody.Spec.Fence != before { + t.Fatalf("refused %s but custody %+v", status.Reason, custody.Spec) + } + default: + t.Fatalf("operation is %s", status.Phase) + } + } + }) + + t.Run("operations on two Devices do not block each other", func(t *testing.T) { + e := e.sub(t) + first, second := fresh(), fresh() + a, b := e.staffOp(first, "ok"), e.staffOp(second, "ok") + var group sync.WaitGroup + for _, device := range []*inventory.Device{first, second} { + coordinator := e.coordinator(e.client()) + group.Add(1) + go func() { + defer group.Done() + if err := settleQuiet(e.ctx, coordinator, device.Name); err != nil { + t.Error(err) + } + }() + } + group.Wait() + e.requirePhase(a, ops.PhaseAdmitted, "") + e.requirePhase(b, ops.PhaseAdmitted, "") + }) + + t.Run("an allocator retries after a lost response and claims no second server", func(t *testing.T) { + e := e.sub(t) + device, other := fresh(), fresh() + lossy := &faultClient{Client: e.client(), failAt: 1, lost: true} + allocator := e.coordinator(lossy) + if err := allocator.Claim(e.ctx, device.Name, "alloc-lost"); err == nil { + t.Fatal("the lost response was not reported") + } + if err := allocator.Claim(e.ctx, device.Name, "alloc-lost"); err != nil { + t.Fatalf("retry: %v", err) + } + if holder := e.custody(device.Name).Spec.Holder; holder.Type != ops.HolderAllocation || holder.AllocationRef.Name != "alloc-lost" { + t.Fatalf("holder = %+v", holder) + } + if holder := e.custody(other.Name).Spec.Holder.Type; holder != ops.HolderNone { + t.Fatalf("a second server was claimed: %s", holder) + } + }) +} + +// errInjected is the fault faultClient returns. +var errInjected = errors.New("injected fault") + +// faultClient fails the failAt-th write. A dropped write is not performed; +// a lost write is performed and its response lost. +type faultClient struct { + client.Client + mu sync.Mutex + writes int + failAt int + lost bool +} + +func (f *faultClient) fault(write func() error) error { + f.mu.Lock() + f.writes++ + hit := f.writes == f.failAt + f.mu.Unlock() + if !hit { + return write() + } + if f.lost { + if err := write(); err != nil { + return err + } + } + return errInjected +} + +func (f *faultClient) Create(ctx context.Context, object client.Object, options ...client.CreateOption) error { + return f.fault(func() error { return f.Client.Create(ctx, object, options...) }) +} + +func (f *faultClient) Update(ctx context.Context, object client.Object, options ...client.UpdateOption) error { + return f.fault(func() error { return f.Client.Update(ctx, object, options...) }) +} + +func (f *faultClient) Delete(ctx context.Context, object client.Object, options ...client.DeleteOption) error { + return f.fault(func() error { return f.Client.Delete(ctx, object, options...) }) +} + +func (f *faultClient) Status() client.SubResourceWriter { + return &faultStatus{SubResourceWriter: f.Client.Status(), parent: f} +} + +type faultStatus struct { + client.SubResourceWriter + parent *faultClient +} + +func (s *faultStatus) Update(ctx context.Context, object client.Object, options ...client.SubResourceUpdateOption) error { + return s.parent.fault(func() error { return s.SubResourceWriter.Update(ctx, object, options...) }) +} + +// TestWriteOrderCrashRecovery crashes between each pair of writes in "admit +// or finish an operation" (custody, then operation status) and in result +// acceptance, then finishes with a healthy coordinator. The outcome must be +// the same as a run without a crash. +func TestWriteOrderCrashRecovery(t *testing.T) { + e := startEnv(t) + n := 500 + for _, lost := range []bool{false, true} { + // Writes: 1 admit custody, 2 Admitted status, 3 result custody, + // 4 Succeeded status. + for failAt := 1; failAt <= 4; failAt++ { + t.Run(fmt.Sprintf("lost=%v crash at write %d", lost, failAt), func(t *testing.T) { + e := e.sub(t) + n++ + device := e.verified(fmt.Sprintf("server-example-%03d", n), uid(n), fmt.Sprintf("%064x", n)) + before := e.custody(device.Name).Spec.Fence + operation := e.staffOp(device, "ok") + faulty := e.coordinator(&faultClient{Client: e.client(), failAt: failAt, lost: lost}) + crashed := false + for range 10 { + if _, err := faulty.Reconcile(e.ctx, device.Name); err != nil { + if !errors.Is(err, errInjected) { + t.Fatal(err) + } + crashed = true + break + } + } + if !crashed { + active := e.custody(device.Name).Spec.ActiveOperation + err := faulty.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseSucceeded, Evidence: []byte(`{"after":"On"}`)}) + if err != nil && !errors.Is(err, errInjected) { + t.Fatal(err) + } + for range 10 { + if _, err := faulty.Reconcile(e.ctx, device.Name); err != nil { + if !errors.Is(err, errInjected) { + t.Fatal(err) + } + break + } + } + } + // A healthy coordinator recovers from custody; the site retries + // its result. + e.settle(device.Name) + if active := e.custody(device.Name).Spec.ActiveOperation; active != nil { + if err := e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseSucceeded, Evidence: []byte(`{"after":"On"}`)}); err != nil { + t.Fatal(err) + } + } else if err := e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: reference(testStaffKind, operation), Fence: before + 1, Phase: ops.PhaseSucceeded, Evidence: []byte(`{"after":"On"}`)}); err != nil { + t.Fatalf("a retried result after a lost response: %v", err) + } + e.settle(device.Name) + status := e.requirePhase(operation, ops.PhaseSucceeded, "") + custody := e.custody(device.Name) + if custody.Spec.Fence != before+1 || custody.Spec.Holder.Type != ops.HolderNone || custody.Spec.ActiveOperation != nil || custody.Spec.RejectedResults != nil || status.Fence != before+1 || evidenceOf(t, status.Evidence.Raw).After != "On" { + t.Fatalf("after recovery: custody %+v status %+v", custody.Spec, status) + } + }) + } + } +} diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go new file mode 100644 index 00000000..a0710dd8 --- /dev/null +++ b/internal/custody/coordinator.go @@ -0,0 +1,791 @@ +package custody + +import ( + "context" + "fmt" + "reflect" + "slices" + "sort" + "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" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// Sites reports what each site serving a Device has stored. Delivery and +// results are added in Increment B; until then tests supply a fake. +type Sites interface { + // Serving returns the sites explicitly configured to serve the Device. + // The coordinator never infers a site from placement. + Serving(device *inventory.Device) []string + // Fence returns the highest fence the site has stored for the Device, + // and false if the site has not reported one. + Fence(ctx context.Context, site string, device *inventory.Device) (int64, bool, error) +} + +// Config holds the coordinator's tunable values. Zero values take the +// documented defaults. +type Config struct { + // Namespace is the Device namespace in the provider project. + Namespace string + Principals Principals + // StaffExpiry is how long a staff operation may wait for admission. + StaffExpiry time.Duration + // SkewMargin is added to a deadline before the coordinator declares + // OutcomeUnknown, so a site whose clock runs behind still stops first. + SkewMargin time.Duration + // Retention is how long finished operations are kept. + Retention time.Duration + // DiscoveryMaxAge is how old the last complete discovery may be for + // identity to count as current. + DiscoveryMaxAge time.Duration +} + +const ( + DefaultStaffExpiry = 5 * time.Minute + DefaultSkewMargin = 2 * time.Minute + DefaultRetention = 30 * 24 * time.Hour + DefaultDiscoveryMaxAge = 2 * time.Hour +) + +func (c Config) withDefaults() Config { + if c.Namespace == "" { + c.Namespace = "default" + } + if c.StaffExpiry == 0 { + c.StaffExpiry = DefaultStaffExpiry + } + if c.SkewMargin == 0 { + c.SkewMargin = DefaultSkewMargin + } + if c.Retention == 0 { + c.Retention = DefaultRetention + } + if c.DiscoveryMaxAge == 0 { + c.DiscoveryMaxAge = DefaultDiscoveryMaxAge + } + return c +} + +// Coordinator admits operations by updating custody. It is the only writer +// of custody and of operation status. +type Coordinator struct { + // Client must read through to the API server: decisions are made on the + // resourceVersion just read, never on a cache. + Client client.Client + Registry *Registry + Sites Sites + Config Config + // Now is the clock. Tests inject one. + Now func() time.Time +} + +func (c *Coordinator) now() time.Time { + if c.Now != nil { + return c.Now().UTC() + } + return time.Now().UTC() +} + +func (c *Coordinator) config() Config { return c.Config.withDefaults() } + +// Outcome reports what one reconcile did. +type Outcome struct { + // Changed is set when the reconcile wrote anything. Call again. + Changed bool + // RequeueAfter is when a time-based decision next falls due. + RequeueAfter time.Duration +} + +// Reconcile makes at most one custody write for the named Device and copies +// operation status from custody. Callers repeat it while Changed is set. +func (c *Coordinator) Reconcile(ctx context.Context, name string) (Outcome, error) { + cfg := c.config() + device, err := c.device(ctx, name) + if err != nil { + return Outcome{}, err + } + custody := &ops.DeviceCustody{} + if err := c.Client.Get(ctx, client.ObjectKey{Namespace: cfg.Namespace, Name: name}, custody); apierrors.IsNotFound(err) { + if device == nil { + return Outcome{}, nil + } + return c.rebuild(ctx, device) + } else if err != nil { + return Outcome{}, err + } + // Deleting custody only removes the finalizer once the holder is + // Retired. Until then custody keeps working, so deadlines still pass. + if !custody.DeletionTimestamp.IsZero() && custody.Spec.Holder.Type == ops.HolderRetired { + if slices.Contains(custody.Finalizers, ops.CustodyFinalizer) { + custody.Finalizers = slices.DeleteFunc(custody.Finalizers, func(f string) bool { return f == ops.CustodyFinalizer }) + return c.writeCustody(ctx, custody) + } + return Outcome{}, nil + } + if device == nil { + if custody.Spec.Holder.Type == ops.HolderRetired { + if err := c.Client.Delete(ctx, custody, client.Preconditions{UID: &custody.UID, ResourceVersion: &custody.ResourceVersion}); err != nil && !apierrors.IsNotFound(err) && !apierrors.IsConflict(err) { + return Outcome{}, err + } + return Outcome{Changed: true}, nil + } + return c.markUnverified(ctx, custody, ConflictDeviceMissing) + } + if changed, err := c.copyStatus(ctx, custody); err != nil || changed { + return Outcome{Changed: changed}, err + } + if custody.Spec.DeviceRef.UID != string(device.UID) && !slices.Contains(custody.Spec.Conflicts, ConflictDeviceUID) { + return c.markUnverified(ctx, custody, ConflictDeviceUID) + } + var requeue time.Duration + steps := []func() (Outcome, error){ + func() (Outcome, error) { + if custody.Spec.State != ops.CustodyUnverified || len(custody.Spec.Conflicts) != 0 { + return Outcome{}, nil + } + return c.verify(ctx, custody, device) + }, + func() (Outcome, error) { + if custody.Spec.ActiveOperation == nil { + return Outcome{}, nil + } + return c.progressActive(ctx, custody, device) + }, + func() (Outcome, error) { return c.settleHolder(ctx, custody, device) }, + func() (Outcome, error) { return c.admit(ctx, custody, device) }, + } + for _, step := range steps { + outcome, err := step() + if err != nil || outcome.Changed { + return outcome, err + } + requeue = earliest(requeue, outcome.RequeueAfter) + } + return Outcome{RequeueAfter: requeue}, nil +} + +// earliest returns the sooner of two requeue delays; zero means none. +func earliest(a, b time.Duration) time.Duration { + if a == 0 || (b != 0 && b < a) { + return b + } + return a +} + +func (c *Coordinator) device(ctx context.Context, name string) (*inventory.Device, error) { + device := &inventory.Device{} + if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.config().Namespace, Name: name}, device); apierrors.IsNotFound(err) { + return nil, nil + } else if err != nil { + return nil, err + } + return device, nil +} + +// writeCustody is the only custody write. It carries the resourceVersion the +// caller read. A conflict is not an error: the next reconcile reads again and +// decides again. +func (c *Coordinator) writeCustody(ctx context.Context, custody *ops.DeviceCustody) (Outcome, error) { + if err := c.Client.Update(ctx, custody); err != nil { + if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { + return Outcome{Changed: true}, nil + } + return Outcome{}, err + } + return Outcome{Changed: true}, nil +} + +func (c *Coordinator) markUnverified(ctx context.Context, custody *ops.DeviceCustody, conflict string) (Outcome, error) { + if custody.Spec.State == ops.CustodyUnverified && slices.Contains(custody.Spec.Conflicts, conflict) { + return Outcome{}, nil + } + custody.Spec.State = ops.CustodyUnverified + if !slices.Contains(custody.Spec.Conflicts, conflict) { + custody.Spec.Conflicts = append(custody.Spec.Conflicts, conflict) + } + return c.writeCustody(ctx, custody) +} + +// settleHolder moves a holder whose work is done back to None, and retires a +// free Device that inventory retired. +func (c *Coordinator) settleHolder(ctx context.Context, custody *ops.DeviceCustody, device *inventory.Device) (Outcome, error) { + spec := &custody.Spec + if spec.State != ops.CustodyVerified || spec.ActiveOperation != nil || spec.RecoveryHold != nil { + return Outcome{}, nil + } + switch { + case spec.Holder.Type == ops.HolderService, + spec.Holder.Type == ops.HolderRelease && len(spec.Holder.OpenGates) == 0: + spec.Holder = ops.Holder{Type: ops.HolderNone} + return c.writeCustody(ctx, custody) + case spec.Holder.Type == ops.HolderNone && inventory.LifecycleOf(device) == inventory.DeviceRetired: + spec.Holder = ops.Holder{Type: ops.HolderRetired} + return c.writeCustody(ctx, custody) + } + return Outcome{}, nil +} + +// get reads one operation. It returns nil if it does not exist or is a +// different incarnation. +func (c *Coordinator) get(ctx context.Context, reference ops.OperationReference) (ops.Operation, *Kind, error) { + kind := c.Registry.Kind(reference.Kind) + if kind == nil { + return nil, nil, fmt.Errorf("custody names unregistered kind %s", reference.Kind) + } + operation := kind.New() + if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.config().Namespace, Name: reference.Name}, operation); apierrors.IsNotFound(err) { + return nil, kind, nil + } else if err != nil { + return nil, kind, err + } + if reference.UID != "" && string(operation.GetUID()) != reference.UID { + return nil, kind, nil + } + return operation, kind, nil +} + +// copyStatus copies the active operation and the last result from custody to +// operation status. Custody is written first, so after a crash this copies +// again. A missing operation is skipped. +func (c *Coordinator) copyStatus(ctx context.Context, custody *ops.DeviceCustody) (bool, error) { + if result := custody.Spec.LastResult; result != nil { + operation, _, err := c.get(ctx, result.OperationReference) + if err != nil { + return false, err + } + // An ended status is final. It differs from the result only when a + // racing refusal ended an operation that custody then withdrew. + if operation != nil && !(operation.OperationStatus().Phase.Ended() && operation.OperationStatus().Phase != result.Phase) { + want := resultStatus(*result, operation.OperationStatus()) + if changed, err := c.writeStatus(ctx, operation, want); err != nil || changed { + return changed, err + } + } + } + active := custody.Spec.ActiveOperation + if active == nil { + return false, nil + } + operation, _, err := c.get(ctx, active.OperationReference) + if err != nil { + return false, err + } + // An operation refused by a racing coordinator, or deleted, before its + // admission was copied has been delivered nowhere: delivery waits for + // the Admitted status. Withdraw it. + if active.Phase == ops.PhaseAdmitted && (operation == nil || operation.OperationStatus().Phase.Ended()) { + custody.Spec.ActiveOperation = nil + custody.Spec.LastResult = &ops.OperationResult{OperationReference: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseCancelled, Reason: ReasonWithdrawn, Message: "the operation ended or was deleted before its admission was recorded", FinishedAt: metav1.NewTime(c.now())} + _, err := c.writeCustody(ctx, custody) + return true, err + } + if operation == nil { + return false, nil + } + return c.writeStatus(ctx, operation, activeStatus(*active)) +} + +func activeStatus(active ops.ActiveOperation) ops.OperationStatus { + snapshot := active.Snapshot + admitted, deadline := active.AdmittedAt, active.Deadline + return ops.OperationStatus{Phase: active.Phase, Fence: active.Fence, AdmittedAt: &admitted, Deadline: &deadline, InputDigest: active.InputDigest, Snapshot: &snapshot} +} + +func resultStatus(result ops.OperationResult, current *ops.OperationStatus) ops.OperationStatus { + finished := result.FinishedAt + status := ops.OperationStatus{Phase: result.Phase, Reason: result.Reason, Message: result.Message, Fence: result.Fence, FinishedAt: &finished, Evidence: result.Evidence} + // Keep what admission recorded. + status.AdmittedAt, status.Deadline, status.InputDigest, status.Snapshot = current.AdmittedAt, current.Deadline, current.InputDigest, current.Snapshot + return status +} + +// writeStatus is the only operation status write. It carries the +// resourceVersion read with the operation. +func (c *Coordinator) writeStatus(ctx context.Context, operation ops.Operation, want ops.OperationStatus) (bool, error) { + if statusEqual(*operation.OperationStatus(), want) { + return false, nil + } + *operation.OperationStatus() = want + if err := c.Client.Status().Update(ctx, operation); err != nil { + if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { + return true, nil + } + return false, err + } + return true, nil +} + +func statusEqual(left, right ops.OperationStatus) bool { + normalize := func(status ops.OperationStatus) ops.OperationStatus { + for _, value := range []**metav1.Time{&status.AdmittedAt, &status.Deadline, &status.FinishedAt} { + if *value != nil { + truncated := metav1.NewTime((*value).Time.UTC().Truncate(time.Second)) + *value = &truncated + } + } + if status.Evidence != nil { + status.Evidence = status.Evidence.DeepCopy() + status.Evidence.Object = nil + } + return status + } + return reflect.DeepEqual(normalize(left), normalize(right)) +} + +// progressActive ends an active operation whose deadline has passed, and +// applies a non-effectful operation once every site confirms its fence. +func (c *Coordinator) progressActive(ctx context.Context, custody *ops.DeviceCustody, device *inventory.Device) (Outcome, error) { + cfg := c.config() + active := *custody.Spec.ActiveOperation + kind := c.Registry.Kind(active.Kind) + if kind == nil { + return Outcome{}, fmt.Errorf("custody names unregistered kind %s", active.Kind) + } + now := c.now() + due := active.Deadline.Add(cfg.SkewMargin) + if !now.Before(due) { + if kind.Effectful { + c.holdUnknown(custody, active, ReasonDeadlineExceeded, "the deadline passed without a proven result", nil) + } else { + c.finishActive(custody, active, ops.PhaseFailed, ReasonSiteNotConfirmed, "no site confirmed the fence before the deadline; nothing was applied", nil) + } + return c.writeCustody(ctx, custody) + } + if kind.Effectful { + return Outcome{RequeueAfter: due.Sub(now)}, nil + } + confirmed, highest, ok, err := c.siteFence(ctx, device, active.Fence) + if err != nil || !ok { + return Outcome{RequeueAfter: min(due.Sub(now), 5*time.Second)}, err + } + operation, _, err := c.get(ctx, active.OperationReference) + if err != nil { + return Outcome{}, err + } + if operation == nil { + c.finishActive(custody, active, ops.PhaseCancelled, ReasonWithdrawn, "the operation was deleted before it was applied", nil) + return c.writeCustody(ctx, custody) + } + spec, refusal := kind.Apply(ctx, &ApplyContext{Operation: operation, Custody: custody.DeepCopy(), Device: device, Registry: c.Registry, ConfirmedFence: confirmed, HighestFence: highest, Now: now}) + if refusal != nil { + c.finishActive(custody, active, ops.PhaseFailed, refusal.Reason, refusal.Message, nil) + return c.writeCustody(ctx, custody) + } + spec.ActiveOperation = nil + evidence, err := rawEvidence(ops.RecoveryResultEvidence{Decision: ops.RecoveryDecision(variantOf(kind, operation)), ConfirmedFence: confirmed}) + if err != nil { + return Outcome{}, err + } + spec.LastResult = &ops.OperationResult{OperationReference: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseSucceeded, FinishedAt: metav1.NewTime(now), Evidence: evidence} + custody.Spec = *spec + return c.writeCustody(ctx, custody) +} + +func variantOf(kind *Kind, operation ops.Operation) string { + if kind.Variant == nil { + return "" + } + return kind.Variant(operation) +} + +// siteFence reports whether every site serving the Device has stored at +// least the fence, and the lowest and highest fences they report. A Device +// with no configured site is never confirmed. +func (c *Coordinator) siteFence(ctx context.Context, device *inventory.Device, fence int64) (int64, int64, bool, error) { + lowest, highest := int64(-1), fence + sites := c.Sites.Serving(device) + if len(sites) == 0 { + return 0, 0, false, nil + } + for _, site := range sites { + stored, reported, err := c.Sites.Fence(ctx, site, device) + if err != nil || !reported || stored < fence { + return 0, 0, false, err + } + if lowest < 0 || stored < lowest { + lowest = stored + } + highest = max(highest, stored) + } + return lowest, highest, true, nil +} + +// finishActive ends the active operation without a hold. A staff holder +// with nothing left to settle returns to None. +func (c *Coordinator) finishActive(custody *ops.DeviceCustody, active ops.ActiveOperation, phase ops.Phase, reason, message string, evidence []byte) { + spec := &custody.Spec + spec.ActiveOperation = nil + spec.LastResult = &ops.OperationResult{OperationReference: active.OperationReference, Fence: active.Fence, Phase: phase, Reason: reason, Message: message, FinishedAt: metav1.NewTime(c.now())} + if evidence != nil { + spec.LastResult.Evidence = rawExtension(evidence) + } + if spec.Holder.Type == ops.HolderService && spec.RecoveryHold == nil { + spec.Holder = ops.Holder{Type: ops.HolderNone} + } +} + +// holdUnknown moves the active operation into the recovery hold. The holder +// stays. A settling operation that itself ends unknown replaces the hold it +// was settling. +func (c *Coordinator) holdUnknown(custody *ops.DeviceCustody, active ops.ActiveOperation, reason, message string, evidence []byte) { + spec := &custody.Spec + now := metav1.NewTime(c.now()) + spec.ActiveOperation = nil + spec.RecoveryHold = &ops.RecoveryHold{OperationReference: active.OperationReference, Fence: active.Fence, Since: now, Reason: reason} + spec.LastResult = &ops.OperationResult{OperationReference: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseOutcomeUnknown, Reason: reason, Message: message, FinishedAt: now} + if evidence != nil { + spec.LastResult.Evidence = rawExtension(evidence) + } +} + +// candidate is one operation that has not ended, with its kind. +type candidate struct { + operation ops.Operation + kind *Kind +} + +// candidates returns the operations for the Device that have not ended and +// that custody does not name as active, oldest first. Ties break on kind, +// name, then UID, so every coordinator orders them the same way. +func (c *Coordinator) candidates(ctx context.Context, custody *ops.DeviceCustody) ([]candidate, error) { + var out []candidate + for _, kind := range c.Registry.Kinds() { + list := kind.NewList() + if err := c.Client.List(ctx, list, client.InNamespace(c.config().Namespace)); err != nil { + if meta.IsNoMatchError(err) { + continue + } + return nil, err + } + for _, operation := range kind.Items(list) { + if operation.Envelope().DeviceRef.Name != custody.Name || operation.OperationStatus().Phase.Ended() || !operation.GetDeletionTimestamp().IsZero() { + continue + } + if active := custody.Spec.ActiveOperation; active != nil && active.Kind == kind.GVK.Kind && active.UID == string(operation.GetUID()) { + continue + } + out = append(out, candidate{operation: operation, kind: kind}) + } + } + orderCandidates(out) + return out, nil +} + +// orderCandidates sorts oldest first. Ties break on kind, name, then UID. +func orderCandidates(out []candidate) { + sort.SliceStable(out, func(i, j int) bool { + a, b := out[i], out[j] + at, bt := a.operation.GetCreationTimestamp(), b.operation.GetCreationTimestamp() + if !at.Equal(&bt) { + return at.Before(&bt) + } + if a.kind.GVK.Kind != b.kind.GVK.Kind { + return a.kind.GVK.Kind < b.kind.GVK.Kind + } + if a.operation.GetName() != b.operation.GetName() { + return a.operation.GetName() < b.operation.GetName() + } + return a.operation.GetUID() < b.operation.GetUID() + }) +} + +// decision is what admission decided for one candidate. +type decision struct { + phase ops.Phase // Pending, Failed or Cancelled; empty to admit + reason string + message string + row Rule + settles *ops.OperationReference +} + +// admit evaluates pending candidates and admits at most one with a single +// conditional custody update. +func (c *Coordinator) admit(ctx context.Context, custody *ops.DeviceCustody, device *inventory.Device) (Outcome, error) { + candidates, err := c.candidates(ctx, custody) + if err != nil { + return Outcome{}, err + } + superseded := c.superseded(candidates) + queued := false + changed := false + for _, candidate := range candidates { + operation, kind := candidate.operation, candidate.kind + var d decision + if superseded[operation.GetUID()] { + d = decision{phase: ops.PhaseCancelled, reason: ReasonSuperseded, message: "a newer pending operation for the same authority replaced it"} + } else { + d = c.decide(ctx, kind, operation, custody, device, queued) + } + if d.phase == "" { + // Every precondition holds on the custody just read. + outcome, err := c.admitOne(ctx, custody, device, kind, operation, d) + outcome.Changed = true + return outcome, err + } + if d.phase == ops.PhasePending { + queued = true + } + wrote, err := c.mark(ctx, operation, d) + if err != nil { + return Outcome{}, err + } + changed = changed || wrote + } + return Outcome{Changed: changed}, nil +} + +// superseded returns pending operations replaced by a newer one of the same +// superseding kind and authority. +func (c *Coordinator) superseded(candidates []candidate) map[types.UID]bool { + out := map[types.UID]bool{} + newest := map[string]ops.Operation{} + for _, candidate := range candidates { + operation, kind := candidate.operation, candidate.kind + if !kind.Supersedes { + continue + } + key := kind.GVK.Kind + "/" + authorityKey(operation.Envelope().Authority) + if previous, ok := newest[key]; ok { + out[previous.GetUID()] = true + } + newest[key] = operation + } + return out +} + +func authorityKey(authority ops.Authority) string { + if authority.AllocationRef != nil { + return "allocation:" + authority.AllocationRef.Name + } + return "service" +} + +// mark records a decision that is not an admission. It never writes custody. +func (c *Coordinator) mark(ctx context.Context, operation ops.Operation, d decision) (bool, error) { + current := operation.OperationStatus() + want := ops.OperationStatus{Phase: d.phase, Reason: d.reason, Message: d.message} + if d.phase.Ended() { + finished := metav1.NewTime(c.now()) + want.FinishedAt = &finished + } else if current.Phase == d.phase && current.Reason == d.reason { + return false, nil + } + return c.writeStatus(ctx, operation, want) +} + +// decide evaluates the admission preconditions for one candidate in order. +// The first that fails decides. Queue rows wait in Pending for conditions +// that can clear; staff rows and everything else end. +func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Operation, custody *ops.DeviceCustody, device *inventory.Device, queueAhead bool) decision { + cfg := c.config() + now := c.now() + envelope := operation.Envelope() + class := cfg.Principals.Classify(envelope.Creator) + pending := operation.OperationStatus().Phase == ops.PhasePending + fail := func(reason, format string, args ...any) decision { + return decision{phase: ops.PhaseFailed, reason: reason, message: fmt.Sprintf(format, args...)} + } + if class == CreatorStaff && !now.Before(operation.GetCreationTimestamp().Add(cfg.StaffExpiry)) { + return decision{phase: ops.PhaseCancelled, reason: ReasonExpired, message: "a staff operation must be admitted within " + cfg.StaffExpiry.String()} + } + rows := c.Registry.matchRows(kind, operation, class) + if len(rows) == 0 { + return fail(ReasonNoMatchingRule, "no row admits %s from a %s creator with this authority", kind.GVK.Kind, class) + } + switch kind.Naming { + case DeterministicName: + if want := kind.Name(operation); operation.GetName() != want { + return fail(ReasonNameMismatch, "the operation must be named %s", want) + } + case GeneratedName: + if operation.GetGenerateName() == "" { + return fail(ReasonNameMismatch, "a staff operation must be created with a generated name") + } + } + if envelope.DeviceRef.UID != string(device.UID) { + return fail(ReasonIdentityMismatch, "deviceRef.uid does not match the Device") + } + // Precondition 1: custody state. + rows = slices.DeleteFunc(rows, func(rule Rule) bool { return rule.custodyState() != custody.Spec.State }) + if len(rows) == 0 { + return c.wait(class, ReasonUnverified, "custody is Unverified and admits only a DeviceRecovery with Resolve") + } + // Preconditions 2 and 3: holder and allocation. + holder := custody.Spec.Holder + rows = slices.DeleteFunc(rows, func(rule Rule) bool { return !rule.admitsHolder(holder.Type) }) + if len(rows) == 0 || (envelope.Authority.AllocationRef != nil && (holder.AllocationRef == nil || holder.AllocationRef.Name != envelope.Authority.AllocationRef.Name)) { + d := fail(ReasonHolderMismatch, "the holder is %s; this operation needs a different holder or allocation", holder.Type) + if pending { + d.phase = ops.PhaseCancelled + } + return d + } + row := rows[0] + // Recovery holds. + var settles *ops.OperationReference + switch hold := custody.Spec.RecoveryHold; { + case row.Hold == HoldIgnored: + case row.Hold == HoldRequired && hold == nil: + return fail(ReasonRecoveryHold, "this operation decides a recovery hold, and there is none") + case row.Hold == HoldRequired: + case hold != nil: + if !c.settlesHold(kind, *hold) { + return fail(ReasonRecoveryHold, "%s %s is held; only its settling operations are admitted", hold.Kind, hold.Name) + } + reference := hold.OperationReference + settles = &reference + } + // Precondition 4: one active operation. + if custody.Spec.ActiveOperation != nil || (row.Queue && queueAhead) { + if row.Queue { + return decision{phase: ops.PhasePending, reason: ReasonOperationActive, message: "waiting for the running operation"} + } + return fail(ReasonOperationActive, "another operation is running, and staff operations never wait") + } + // Preconditions 5 and 6 concern what can reach the BMC. + if kind.Effectful { + if refusal := c.identityCurrent(device, now); refusal != nil { + if row.Queue { + return decision{phase: ops.PhasePending, reason: refusal.Reason, message: refusal.Message} + } + return fail(refusal.Reason, "%s", refusal.Message) + } + if refusal := c.sharedKey(ctx, device); refusal != nil { + return fail(refusal.Reason, "%s", refusal.Message) + } + } + if kind.Check != nil { + if refusal := kind.Check(ctx, &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Now: now}); refusal != nil { + return fail(refusal.Reason, "%s", refusal.Message) + } + } + return decision{row: row, settles: settles} +} + +// wait returns Pending for queue rows and Failed otherwise. +func (c *Coordinator) wait(class CreatorClass, reason, message string) decision { + if class != CreatorStaff { + return decision{phase: ops.PhasePending, reason: reason, message: message} + } + return decision{phase: ops.PhaseFailed, reason: reason, message: message} +} + +func (c *Coordinator) settlesHold(kind *Kind, hold ops.RecoveryHold) bool { + for _, rule := range kind.Settles { + if rule.Held == hold.Kind && (!rule.RequiresRetry || hold.RetryAuthorizedBy != nil) { + return true + } + } + return false +} + +// identityCurrent is precondition 5's discovery half. Identity is current when +// BMC discovery matched the recorded identity against this Device +// generation, completed an inventory read within DiscoveryMaxAge, and +// recorded the BMC key at the current endpoint. +func (c *Coordinator) identityCurrent(device *inventory.Device, now time.Time) *Refusal { + if device.Spec.BMC == nil || device.Spec.Identity.SystemUUID == "" { + return refuse(ReasonIdentityNotCurrent, "the Device records no BMC endpoint or system UUID") + } + condition := meta.FindStatusCondition(device.Status.Conditions, inventory.ConditionIdentityMatched) + if condition == nil || condition.Status != metav1.ConditionTrue || condition.ObservedGeneration != device.Generation { + return refuse(ReasonIdentityMismatch, "discovery has not matched the Device identity at its current generation") + } + discovery := device.Status.Discovery + if discovery == nil || discovery.Inventory == nil || now.Sub(discovery.Inventory.ObservedAt.Time) > c.config().DiscoveryMaxAge { + return refuse(ReasonIdentityNotCurrent, "discovery is older than %s", c.config().DiscoveryMaxAge) + } + if discovery.TLS == nil || discovery.TLS.PublicKeySHA256 == "" || discovery.TLS.Endpoint != device.Spec.BMC.Endpoint { + return refuse(ReasonIdentityNotCurrent, "discovery has not recorded the BMC key at the current endpoint") + } + return nil +} + +// sharedKey is precondition 6: no other Device that is not retired records +// the same BMC key digest. +func (c *Coordinator) sharedKey(ctx context.Context, device *inventory.Device) *Refusal { + digest := device.Status.Discovery.TLS.PublicKeySHA256 + var devices inventory.DeviceList + if err := c.Client.List(ctx, &devices); err != nil { + return refuse(ReasonSharedPublicKey, "the other Devices could not be read, so the BMC key cannot be shown unique") + } + for index := range devices.Items { + other := &devices.Items[index] + if other.UID == device.UID || inventory.LifecycleOf(other) == inventory.DeviceRetired { + continue + } + if discovery := other.Status.Discovery; discovery != nil && discovery.TLS != nil && discovery.TLS.PublicKeySHA256 == digest { + return refuse(ReasonSharedPublicKey, "another Device records the same BMC key") + } + } + return nil +} + +// admitOne writes the admission: one conditional custody update that names +// the operation, raises the fence, sets the deadline and retains the exact +// inputs and Device snapshot. Status is copied on the next reconcile. +func (c *Coordinator) admitOne(ctx context.Context, custody *ops.DeviceCustody, device *inventory.Device, kind *Kind, operation ops.Operation, d decision) (Outcome, error) { + digest, err := kind.Digest(operation) + if err != nil { + return Outcome{}, err + } + now := c.now() + spec := &custody.Spec + spec.Fence++ + active := &ops.ActiveOperation{ + OperationReference: ops.OperationReference{Kind: kind.GVK.Kind, Name: operation.GetName(), UID: string(operation.GetUID())}, + Fence: spec.Fence, + Phase: ops.PhaseAdmitted, + AdmittedAt: metav1.NewTime(now), + Deadline: metav1.NewTime(now.Add(kind.Deadline)), + InputDigest: digest, + Snapshot: snapshot(kind, operation, device), + Creator: operation.Envelope().Creator, + Settles: d.settles, + } + spec.ActiveOperation = active + if d.row.Creator == CreatorStaff && spec.Holder.Type == ops.HolderNone { + spec.Holder = ops.Holder{Type: ops.HolderService} + } + // A Retry authorizes one settling operation. + if hold := spec.RecoveryHold; hold != nil && d.settles != nil { + for _, rule := range kind.Settles { + if rule.Held == hold.Kind && rule.RequiresRetry { + hold.RetryAuthorizedBy = nil + } + } + } + outcome, err := c.writeCustody(ctx, custody) + outcome.RequeueAfter = 0 + return outcome, err +} + +func snapshot(kind *Kind, operation ops.Operation, device *inventory.Device) ops.DeviceSnapshot { + out := ops.DeviceSnapshot{SystemUUID: device.Spec.Identity.SystemUUID, DeviceGeneration: device.Generation} + if device.Spec.BMC != nil { + out.BMCEndpoint = device.Spec.BMC.Endpoint + } + if discovery := device.Status.Discovery; discovery != nil { + if discovery.TLS != nil { + out.BMCPublicKeySHA256 = discovery.TLS.PublicKeySHA256 + } + if discovery.Inventory != nil { + out.DiscoveryObservedAt = discovery.Inventory.ObservedAt.UTC().Format(time.RFC3339) + } + } + if kind.BootInterface != nil { + name := kind.BootInterface(operation) + for _, iface := range device.Spec.Interfaces { + if iface.Name == name { + out.BootMACAddress = iface.MACAddress + } + } + } + return out +} diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go new file mode 100644 index 00000000..a7b72647 --- /dev/null +++ b/internal/custody/harness_test.go @@ -0,0 +1,376 @@ +package custody + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/go-logr/logr" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + ctrllog "sigs.k8s.io/controller-runtime/pkg/log" +) + +func jsonMarshal(value any) ([]byte, error) { return json.Marshal(value) } +func jsonUnmarshal(data []byte, out any) error { return json.Unmarshal(data, out) } + +const ( + providerUser = "system:serviceaccount:fleet-system:metal-provider" + releaseUser = "system:serviceaccount:fleet-system:release-controller" + staffUser = "staff-example@example.com" + testSite = "site-example-a" + testKeyA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + imageDigest = "sha256:9f4ad8d8b8a6000000000000000000000000000000000000000000000000beef" + policyDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" +) + +func testPrincipals() Principals { + return Principals{CreatorMetalProvider: {{Username: providerUser}}, CreatorReleaseController: {{Username: releaseUser}}} +} + +// clock is an injectable, advanceable clock. +type clock struct { + mu sync.Mutex + now time.Time +} + +func (c *clock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *clock) Advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = c.now.Add(d) +} + +// fakeSites is the site-fence source for Increment A. +type fakeSites struct { + mu sync.Mutex + serving map[string][]string + fences map[string]int64 +} + +func newFakeSites() *fakeSites { + return &fakeSites{serving: map[string][]string{}, fences: map[string]int64{}} +} + +func (s *fakeSites) Serving(device *inventory.Device) []string { + s.mu.Lock() + defer s.mu.Unlock() + if sites, ok := s.serving[device.Name]; ok { + return append([]string(nil), sites...) + } + return []string{testSite} +} + +func (s *fakeSites) Fence(_ context.Context, site string, device *inventory.Device) (int64, bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + fence, ok := s.fences[site+"/"+device.Name] + return fence, ok, nil +} + +// report stores the fence a site reports for a Device. +func (s *fakeSites) report(device string, fence int64) { + s.mu.Lock() + defer s.mu.Unlock() + s.fences[testSite+"/"+device] = fence +} + +func (s *fakeSites) forget(device string) { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.fences, testSite+"/"+device) +} + +type env struct { + t *testing.T + config *rest.Config + scheme *runtime.Scheme + admin client.Client + clock *clock + sites *fakeSites + coord *Coordinator + ctx context.Context +} + +func newScheme(t *testing.T) *runtime.Scheme { + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, ops.AddToScheme, addTestKinds, admissionregistrationv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + return scheme +} + +// startEnv starts a real API server with the metal, inventory, custody and +// test-only CRDs. +func startEnv(t *testing.T) *env { + t.Helper() + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctrllog.SetLogger(logr.Discard()) + root := filepath.Join("..", "..") + environment := &envtest.Environment{CRDDirectoryPaths: []string{ + filepath.Join(root, "config", "base", "crd"), + filepath.Join(root, "config", "components", "inventory", "crds"), + filepath.Join(root, "config", "components", "device-operations", "crds"), + filepath.Join("testdata", "crds"), + }, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := newScheme(t) + admin, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + e := &env{t: t, config: config, scheme: scheme, admin: admin, clock: &clock{now: time.Now().UTC().Truncate(time.Second)}, sites: newFakeSites(), ctx: context.Background()} + e.coord = e.coordinator(admin) + return e +} + +// sub returns the environment for a subtest, with its own clock and +// coordinator, so helpers fail the subtest and clock moves stay in it. +func (e *env) sub(t *testing.T) *env { + copied := *e + copied.t = t + copied.clock = &clock{now: time.Now().UTC().Truncate(time.Second)} + copied.coord = copied.coordinator(copied.admin) + return &copied +} + +func (e *env) coordinator(api client.Client) *Coordinator { + return &Coordinator{Client: api, Registry: testRegistry(e.t), Sites: e.sites, Config: Config{Principals: testPrincipals()}, Now: e.clock.Now} +} + +// device creates a discovered Device ready for operations. +func (e *env) device(name, uuid, key string) *inventory.Device { + e.t.Helper() + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: inventory.DeviceSpec{ + ClaimRef: inventory.LocalReference{Name: "claim-" + name}, + Identity: inventory.DeviceIdentity{Model: "example", Serial: "serial-" + name, SystemUUID: uuid}, + BMC: &inventory.BMC{Endpoint: "https://[2001:db8::10]"}, + Interfaces: []inventory.Interface{{Name: "primary", MACAddress: macFor(name)}}, + }} + if err := e.admin.Create(e.ctx, device); err != nil { + e.t.Fatal(err) + } + e.discover(device, key, e.clock.Now()) + return device +} + +var macs sync.Map + +func macFor(name string) string { + value, _ := macs.LoadOrStore(name, fmt.Sprintf("02:00:00:00:%02x:%02x", len(name), int(name[len(name)-1]))) + return value.(string) +} + +// discover records a successful discovery, as BMC discovery would. +func (e *env) discover(device *inventory.Device, key string, at time.Time) { + e.t.Helper() + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + e.t.Fatal(err) + } + observed := metav1.NewTime(at) + device.Status.Discovery = &inventory.DeviceDiscovery{ + TLS: &inventory.ObservedTLS{ObservedAt: observed, Endpoint: device.Spec.BMC.Endpoint, PublicKeySHA256: key}, + Inventory: &inventory.ObservedInventory{ObservedAt: observed, Endpoint: device.Spec.BMC.Endpoint}, + } + device.Status.Conditions = []metav1.Condition{{Type: inventory.ConditionIdentityMatched, Status: metav1.ConditionTrue, Reason: "Matched", ObservedGeneration: device.Generation, LastTransitionTime: observed}} + if err := e.admin.Status().Update(e.ctx, device); err != nil { + e.t.Fatal(err) + } +} + +// settle reconciles until nothing changes. +func (e *env) settle(name string) Outcome { + e.t.Helper() + return settleWith(e.t, e.ctx, e.coord, name) +} + +func settleWith(t *testing.T, ctx context.Context, coord *Coordinator, name string) Outcome { + t.Helper() + for range 60 { + outcome, err := coord.Reconcile(ctx, name) + if err != nil { + t.Fatal(err) + } + if !outcome.Changed { + return outcome + } + } + t.Fatalf("reconcile of %s did not settle", name) + return Outcome{} +} + +func (e *env) custody(name string) *ops.DeviceCustody { + e.t.Helper() + custody := &ops.DeviceCustody{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: "default", Name: name}, custody); err != nil { + e.t.Fatal(err) + } + return custody +} + +// verified creates a Device and brings its custody to Verified, holder None. +func (e *env) verified(name, uuid, key string) *inventory.Device { + e.t.Helper() + device := e.device(name, uuid, key) + e.settle(name) + e.sites.report(name, 0) + e.settle(name) + if custody := e.custody(name); custody.Spec.State != ops.CustodyVerified || custody.Spec.Holder.Type != ops.HolderNone { + e.t.Fatalf("custody did not verify: %+v", custody.Spec) + } + return device +} + +func envelope(device *inventory.Device, user string, authority ops.Authority) ops.OperationEnvelope { + return ops.OperationEnvelope{Creator: ops.Creator{Username: user, UID: user + "-uid"}, DeviceRef: ops.DeviceReference{Name: device.Name, UID: string(device.UID)}, Authority: authority} +} + +func service(reason string) ops.Authority { + return ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: reason}} +} + +func allocated(name string) ops.Authority { + return ops.Authority{AllocationRef: &ops.LocalReference{Name: name}} +} + +func (e *env) create(object client.Object) { + e.t.Helper() + if err := e.admin.Create(e.ctx, object); err != nil { + e.t.Fatal(err) + } +} + +func (e *env) staffOp(device *inventory.Device, input string) *DeviceTestStaffOperation { + e.t.Helper() + operation := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: device.Name + "-staff-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("qualification")), Input: input}} + e.create(operation) + return operation +} + +func (e *env) providerOp(device *inventory.Device, allocation, input string) *DeviceTestProviderOperation { + e.t.Helper() + operation := &DeviceTestProviderOperation{ObjectMeta: metav1.ObjectMeta{Name: allocation + "-test-" + input, Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, providerUser, allocated(allocation)), Input: input}} + e.create(operation) + return operation +} + +func (e *env) installation(device *inventory.Device, allocation, request string) *ops.DeviceInstallation { + e.t.Helper() + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, request), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated(allocation)), RequestUID: request, + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + }} + e.create(operation) + return operation +} + +func (e *env) wipe(device *inventory.Device, allocation string, step int32) *ops.DeviceWipe { + e.t.Helper() + operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName(allocation, step), Namespace: "default"}, Spec: ops.DeviceWipeSpec{ + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, + }} + e.create(operation) + return operation +} + +func (e *env) recovery(device *inventory.Device, spec ops.DeviceRecoverySpec) *ops.DeviceRecovery { + e.t.Helper() + spec.OperationEnvelope = envelope(device, staffUser, service("recovery")) + if spec.Evidence.Summary == "" { + spec.Evidence = ops.RecoveryEvidence{ObservedAt: metav1.NewTime(e.clock.Now()), Summary: "observed by staff"} + } + operation := &ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: device.Name + "-recovery-", Namespace: "default"}, Spec: spec} + e.create(operation) + return operation +} + +// status reads an operation's status. +func (e *env) status(operation ops.Operation) ops.OperationStatus { + e.t.Helper() + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + e.t.Fatal(err) + } + return *operation.OperationStatus() +} + +func (e *env) requirePhase(operation ops.Operation, phase ops.Phase, reason string) ops.OperationStatus { + e.t.Helper() + status := e.status(operation) + if status.Phase != phase || (reason != "" && status.Reason != reason) { + e.t.Fatalf("%s: phase %s reason %s (%s), want %s %s", operation.GetName(), status.Phase, status.Reason, status.Message, phase, reason) + } + return status +} + +func reference(kind string, operation ops.Operation) ops.OperationReference { + return ops.OperationReference{Kind: kind, Name: operation.GetName(), UID: string(operation.GetUID())} +} + +// result reports a site result for the active operation. +func (e *env) result(device string, phase ops.Phase, evidence string) error { + e.t.Helper() + active := e.custody(device).Spec.ActiveOperation + if active == nil { + e.t.Fatalf("%s has no active operation", device) + } + var raw []byte + if evidence != "" { + raw = []byte(evidence) + } + return e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device, Operation: active.OperationReference, Fence: active.Fence, Phase: phase, Evidence: raw}) +} + +// allocation creates a MachineCapacity for the Device and a MachineAllocation +// naming it, as the allocator will in Increment C. +func (e *env) allocation(device *inventory.Device, name, phase string) *metal.MachineAllocation { + e.t.Helper() + capacityName := "capacity-" + name + capacity := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: capacityName, Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if err := e.admin.Create(e.ctx, capacity); err != nil && !apierrors.IsAlreadyExists(err) { + e.t.Fatal(err) + } + allocation := &metal.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: metal.MachineAllocationSpec{ + MachineRef: metal.ProjectNamespacedReference{Project: "consumer-example", Namespace: "default", Name: "machine-" + name}, MachineCapacityRef: metal.NamespacedReference{Namespace: "default", Name: capacityName}, + }} + e.create(allocation) + if phase != "" { + allocation.Status.Phase = phase + if err := e.admin.Status().Update(e.ctx, allocation); err != nil { + e.t.Fatal(err) + } + } + return allocation +} + +func uid(n int) string { return fmt.Sprintf("00000000-0000-4000-8000-%012d", n) } diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go new file mode 100644 index 00000000..28cbfe04 --- /dev/null +++ b/internal/custody/kinds.go @@ -0,0 +1,305 @@ +package custody + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "slices" + "strconv" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// Per-kind deadlines. The site worker stops at the deadline exactly; the +// coordinator declares OutcomeUnknown only after the deadline plus +// Config.SkewMargin. +const ( + // InstallationDeadline matches the Redfish executor's install bound. + InstallationDeadline = 40 * time.Minute + // WipeDeadline matches the Redfish executor's cleanup bound. + WipeDeadline = 40 * time.Minute + // RecoveryDeadline bounds how long a recovery waits for the sites to + // confirm its fence. + RecoveryDeadline = 10 * time.Minute +) + +// Kind-specific refusal reasons. +const ( + ReasonBootstrapUnsupported = "BootstrapUnsupported" + ReasonBootInterfaceUnknown = "BootInterfaceUnknown" + ReasonHoldMismatch = "HoldMismatch" + ReasonNotSettleable = "NotSettleable" + ReasonNotRetryable = "NotRetryable" + ReasonRetryAuthorized = "RetryAlreadyAuthorized" + ReasonDisposalRequired = "DisposalRequired" + ReasonInvalidResolve = "InvalidResolve" +) + +const evidenceLimit = 4096 + +var gv = ops.GroupVersion + +// InstallationName is the only name a DeviceInstallation may have: its +// allocation and the Installation it fulfills. +func InstallationName(allocation, requestUID string) string { + sum := sha256.Sum256([]byte(requestUID)) + return allocation + "-install-" + hex.EncodeToString(sum[:])[:12] +} + +// WipeName is the only name a DeviceWipe may have: its allocation and step. +func WipeName(allocation string, step int32) string { + return allocation + "-wipe-" + strconv.Itoa(int(step)) +} + +func allocationName(operation ops.Operation) string { + if reference := operation.Envelope().Authority.AllocationRef; reference != nil { + return reference.Name + } + return "" +} + +func validateSteps(steps []ops.StepEvidence) error { + if len(steps) > 8 { + return errors.New("evidence records at most 8 steps") + } + for _, step := range steps { + if step.Name == "" || len(step.Name) > 63 { + return errors.New("a step name is 1 to 63 characters") + } + } + return nil +} + +// DeviceInstallationKind is the registry entry for DeviceInstallation. +func DeviceInstallationKind() Kind { + return Kind{ + GVK: gv.WithKind("DeviceInstallation"), + New: func() ops.Operation { return &ops.DeviceInstallation{} }, + NewList: func() client.ObjectList { return &ops.DeviceInstallationList{} }, + Items: func(list client.ObjectList) []ops.Operation { + return items(list.(*ops.DeviceInstallationList).Items) + }, + Digest: func(operation ops.Operation) (string, error) { + return SpecDigest(operation.(*ops.DeviceInstallation).Spec) + }, + Naming: DeterministicName, + Name: func(operation ops.Operation) string { + return InstallationName(allocationName(operation), operation.(*ops.DeviceInstallation).Spec.RequestUID) + }, + Deadline: InstallationDeadline, + Effectful: true, + BootInterface: func(operation ops.Operation) string { return operation.(*ops.DeviceInstallation).Spec.BootInterface }, + Check: func(_ context.Context, admission *Admission) *Refusal { + installation := admission.Operation.(*ops.DeviceInstallation) + // Bootstrap stays refused until the sealed store exists. + if installation.Spec.Bootstrap != nil { + return refuse(ReasonBootstrapUnsupported, "bootstrap payloads need the sealed store, which is not implemented") + } + for _, iface := range admission.Device.Spec.Interfaces { + if iface.Name == installation.Spec.BootInterface && iface.MACAddress != "" { + return nil + } + } + return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", installation.Spec.BootInterface) + }, + Settles: []SettleRule{{Held: "DeviceInstallation"}}, + Evidence: StrictEvidence(evidenceLimit, func(evidence *ops.InstallationEvidence) error { + return validateSteps(evidence.Steps) + }), + } +} + +// DeviceWipeKind is the registry entry for DeviceWipe. +func DeviceWipeKind() Kind { + return Kind{ + GVK: gv.WithKind("DeviceWipe"), + New: func() ops.Operation { return &ops.DeviceWipe{} }, + NewList: func() client.ObjectList { return &ops.DeviceWipeList{} }, + Items: func(list client.ObjectList) []ops.Operation { + return items(list.(*ops.DeviceWipeList).Items) + }, + Digest: func(operation ops.Operation) (string, error) { + return SpecDigest(operation.(*ops.DeviceWipe).Spec) + }, + Naming: DeterministicName, + Name: func(operation ops.Operation) string { + return WipeName(allocationName(operation), operation.(*ops.DeviceWipe).Spec.Step) + }, + Deadline: WipeDeadline, + Effectful: true, + // A wipe after release settles an installation hold. A held wipe is + // settled by a later wipe only after a DeviceRecovery with Retry. + Settles: []SettleRule{{Held: "DeviceInstallation"}, {Held: "DeviceWipe", RequiresRetry: true}}, + Evidence: StrictEvidence(evidenceLimit, func(evidence *ops.WipeEvidence) error { + if len(evidence.WipedDisks) > 16 { + return errors.New("evidence records at most 16 disks") + } + return validateSteps(evidence.Steps) + }), + } +} + +// DeviceRecoveryKind is the registry entry for DeviceRecovery. It sends +// nothing to the server. It is admitted like any operation, raising the +// fence, and applied only after every serving site reports that fence, so +// the held worker has stopped first. +func DeviceRecoveryKind() Kind { + return Kind{ + GVK: gv.WithKind("DeviceRecovery"), + New: func() ops.Operation { return &ops.DeviceRecovery{} }, + NewList: func() client.ObjectList { return &ops.DeviceRecoveryList{} }, + Items: func(list client.ObjectList) []ops.Operation { + return items(list.(*ops.DeviceRecoveryList).Items) + }, + Digest: func(operation ops.Operation) (string, error) { + return SpecDigest(operation.(*ops.DeviceRecovery).Spec) + }, + Naming: GeneratedName, + Deadline: RecoveryDeadline, + Variant: func(operation ops.Operation) string { return string(operation.(*ops.DeviceRecovery).Spec.Decision) }, + Check: func(ctx context.Context, admission *Admission) *Refusal { + return checkRecovery(ctx, admission.Operation.(*ops.DeviceRecovery), admission.Custody, admission.Registry, admission) + }, + Apply: applyRecovery, + Retires: func(operation ops.Operation) bool { + spec := operation.(*ops.DeviceRecovery).Spec + return spec.Decision == ops.DecisionRetire || (spec.Decision == ops.DecisionResolve && spec.Resolve != nil && spec.Resolve.Holder == ops.HolderRetired) + }, + } +} + +func checkRecovery(ctx context.Context, recovery *ops.DeviceRecovery, custody *ops.DeviceCustody, registry *Registry, admission *Admission) *Refusal { + spec := recovery.Spec + if spec.Decision == ops.DecisionResolve { + resolve := spec.Resolve + switch { + case resolve == nil: + return refuse(ReasonInvalidResolve, "Resolve needs the holder to record") + case resolve.Holder == ops.HolderAllocation || resolve.Holder == ops.HolderRelease: + if resolve.AllocationRef == nil || resolve.AllocationRef.Name == "" { + return refuse(ReasonInvalidResolve, "an %s holder needs its allocation", resolve.Holder) + } + case resolve.Holder == ops.HolderNone || resolve.Holder == ops.HolderRetired: + if resolve.AllocationRef != nil { + return refuse(ReasonInvalidResolve, "a %s holder has no allocation", resolve.Holder) + } + default: + return refuse(ReasonInvalidResolve, "Resolve cannot record holder %s", resolve.Holder) + } + return nil + } + hold := custody.Spec.RecoveryHold + if hold == nil || spec.Hold == nil || spec.Hold.Kind != hold.Kind || spec.Hold.Name != hold.Name || spec.Hold.Fence != hold.Fence { + return refuse(ReasonHoldMismatch, "the recovery does not name the current hold") + } + switch spec.Decision { + case ops.DecisionSettle: + held := registry.Kind(hold.Kind) + if held == nil || held.RecoverySettle == nil { + return refuse(ReasonNotSettleable, "a %s hold is settled by its settling operations, not by a recovery", hold.Kind) + } + return held.RecoverySettle(ctx, &RecoverySettleContext{Hold: *hold, Recovery: recovery, Device: admission.Device, Custody: custody, Now: admission.Now}) + case ops.DecisionRetry: + if hold.RetryAuthorizedBy != nil { + return refuse(ReasonRetryAuthorized, "a retry is already authorized for this hold") + } + for _, kind := range registry.Kinds() { + for _, rule := range kind.Settles { + if rule.Held == hold.Kind && rule.RequiresRetry { + return nil + } + } + } + return refuse(ReasonNotRetryable, "no kind settles a %s hold after a retry", hold.Kind) + case ops.DecisionRetire: + if custody.Spec.Holder.Type == ops.HolderRelease && (spec.DiskDisposal == nil || spec.DiskDisposal.Reference == "") { + return refuse(ReasonDisposalRequired, "retiring from Release records how the disks were disposed of") + } + return nil + } + return refuse(ReasonNoMatchingRule, "unknown decision %q", spec.Decision) +} + +// applyRecovery applies a confirmed recovery. It re-checks against the +// custody read now, because custody may have changed since admission. +func applyRecovery(ctx context.Context, apply *ApplyContext) (*ops.DeviceCustodySpec, *Refusal) { + recovery := apply.Operation.(*ops.DeviceRecovery) + custody := apply.Custody + if refusal := checkRecovery(ctx, recovery, custody, apply.Registry, &Admission{Operation: recovery, Custody: custody, Device: apply.Device, Registry: apply.Registry, Now: apply.Now}); refusal != nil { + return nil, refusal + } + spec := custody.Spec + reference := ops.OperationReference{Kind: "DeviceRecovery", Name: recovery.Name, UID: string(recovery.UID)} + switch recovery.Spec.Decision { + case ops.DecisionSettle: + spec.RecoveryHold = nil + if spec.Holder.Type == ops.HolderService { + spec.Holder = ops.Holder{Type: ops.HolderNone} + } + case ops.DecisionRetry: + hold := *spec.RecoveryHold + hold.RetryAuthorizedBy = &reference + spec.RecoveryHold = &hold + case ops.DecisionRetire: + spec.RecoveryHold = nil + spec.Holder = ops.Holder{Type: ops.HolderRetired} + case ops.DecisionResolve: + resolve := recovery.Spec.Resolve + spec.State = ops.CustodyVerified + spec.Conflicts = nil + spec.DeviceRef.UID = string(apply.Device.UID) + spec.Fence = max(spec.Fence, apply.HighestFence) + spec.Holder = ops.Holder{Type: resolve.Holder} + if resolve.AllocationRef != nil { + spec.Holder.AllocationRef = &ops.LocalReference{Name: resolve.AllocationRef.Name} + } + if resolve.Holder == ops.HolderRelease { + spec.Holder.OpenGates = slices.Clone(ops.ReleaseGates) + } + } + return &spec, nil +} + +// DefaultRegistry registers the built-in kinds and the operations table rows +// for them. +func DefaultRegistry() (*Registry, error) { + registry := NewRegistry() + for _, kind := range []Kind{DeviceInstallationKind(), DeviceWipeKind(), DeviceRecoveryKind()} { + if err := registry.Register(kind); err != nil { + return nil, err + } + } + for _, rule := range DefaultRules() { + if err := registry.AddRule(rule); err != nil { + return nil, err + } + } + return registry, nil +} + +// DefaultRules is the operations table of #174 for the built-in kinds. +func DefaultRules() []Rule { + return []Rule{ + {Kind: "DeviceInstallation", Creator: CreatorMetalProvider, Authority: AuthorityAllocation, Holders: []ops.HolderType{ops.HolderAllocation}, Queue: true}, + {Kind: "DeviceWipe", Creator: CreatorReleaseController, Authority: AuthorityAllocation, Holders: []ops.HolderType{ops.HolderRelease}, Queue: true}, + {Kind: "DeviceRecovery", Variant: string(ops.DecisionSettle), Creator: CreatorStaff, Authority: AuthorityService, Hold: HoldRequired}, + {Kind: "DeviceRecovery", Variant: string(ops.DecisionRetry), Creator: CreatorStaff, Authority: AuthorityService, Hold: HoldRequired}, + {Kind: "DeviceRecovery", Variant: string(ops.DecisionRetire), Creator: CreatorStaff, Authority: AuthorityService, Holders: []ops.HolderType{ops.HolderService, ops.HolderRelease}, Hold: HoldRequired}, + {Kind: "DeviceRecovery", Variant: string(ops.DecisionResolve), Creator: CreatorStaff, Authority: AuthorityService, Custody: ops.CustodyUnverified, Hold: HoldIgnored}, + } +} + +// items adapts a typed item slice to operations. +func items[T any, P interface { + *T + ops.Operation +}](list []T) []ops.Operation { + out := make([]ops.Operation, 0, len(list)) + for index := range list { + out = append(out, P(&list[index])) + } + return out +} diff --git a/internal/custody/lifecycle_test.go b/internal/custody/lifecycle_test.go new file mode 100644 index 00000000..5a3851ed --- /dev/null +++ b/internal/custody/lifecycle_test.go @@ -0,0 +1,326 @@ +package custody + +import ( + "errors" + "fmt" + "slices" + "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" +) + +func TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing(t *testing.T) { + e := startEnv(t) + device := e.device("server-example-001", uid(1), testKeyA) + e.settle(device.Name) + custody := e.custody(device.Name) + if custody.Spec.State != ops.CustodyUnverified || custody.Spec.Holder.Type != ops.HolderNone || custody.Spec.ActiveOperation != nil || custody.Spec.DeviceRef.UID != string(device.UID) { + t.Fatalf("new custody = %+v", custody.Spec) + } + if len(custody.Finalizers) != 1 || custody.Finalizers[0] != ops.CustodyFinalizer { + t.Fatalf("finalizers = %v", custody.Finalizers) + } + if err := e.coord.Claim(e.ctx, device.Name, "alloc-example"); !errors.Is(err, ErrUnavailable) { + t.Fatalf("Unverified custody was claimed: %v", err) + } + conditions := ProjectCapacity(CapacityInputs{Custody: &custody.Spec, AllocationPolicyEnabled: true, DiscoveryCurrent: true}) + if conditions[2].Status != metav1.ConditionFalse { + t.Fatal("imported Device became Available") + } + // No configured site: nothing can fence the Device yet. + e.sites.mu.Lock() + e.sites.serving[device.Name] = nil + e.sites.mu.Unlock() + e.sites.report(device.Name, 7) + e.settle(device.Name) + if state := e.custody(device.Name).Spec.State; state != ops.CustodyUnverified { + t.Fatalf("custody verified with no serving site: %s", state) + } + e.sites.mu.Lock() + delete(e.sites.serving, device.Name) + e.sites.mu.Unlock() + e.settle(device.Name) + custody = e.custody(device.Name) + if custody.Spec.State != ops.CustodyVerified || custody.Spec.Fence != 8 { + t.Fatalf("verified custody = %+v", custody.Spec) + } +} + +func TestLifecycle(t *testing.T) { + e := startEnv(t) + n := 100 + fresh := func() *inventory.Device { + n++ + return e.verified(fmt.Sprintf("server-example-%03d", n), uid(n), fmt.Sprintf("%064x", n)) + } + + t.Run("holder transitions None Allocation Release None", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-a"); err != nil { + t.Fatal(err) + } + if err := e.coord.Claim(e.ctx, device.Name, "alloc-b"); !errors.Is(err, ErrUnavailable) { + t.Fatalf("a second allocation claimed the server: %v", err) + } + if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-b"); !errors.Is(err, ErrUnavailable) { + t.Fatalf("another allocation released the server: %v", err) + } + if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-a"); err != nil { + t.Fatal(err) + } + custody := e.custody(device.Name) + if custody.Spec.Holder.Type != ops.HolderRelease || !slices.Equal(custody.Spec.Holder.OpenGates, ops.ReleaseGates) { + t.Fatalf("release holder = %+v", custody.Spec.Holder) + } + if err := e.coord.CloseGate(e.ctx, device.Name, "alloc-a", "Invented"); !errors.Is(err, ErrUnavailable) { + t.Fatalf("an unknown gate closed: %v", err) + } + for index, gate := range ops.ReleaseGates { + e.settle(device.Name) + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderRelease { + t.Fatalf("left Release with %d gates open: %s", len(ops.ReleaseGates)-index, holder) + } + if err := e.coord.CloseGate(e.ctx, device.Name, "alloc-a", gate); err != nil { + t.Fatal(err) + } + } + e.settle(device.Name) + if holder := e.custody(device.Name).Spec.Holder; holder.Type != ops.HolderNone || holder.AllocationRef != nil { + t.Fatalf("holder after release = %+v", holder) + } + }) + + t.Run("holder transitions None Service None and Service Retired", func(t *testing.T) { + e := e.sub(t) + device := fresh() + operation := e.staffOp(device, "ok") + e.settle(device.Name) + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderService { + t.Fatalf("holder = %s", holder) + } + if err := e.result(device.Name, ops.PhaseSucceeded, `{"before":"Off","after":"On"}`); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + custody := e.custody(device.Name) + status := e.requirePhase(operation, ops.PhaseSucceeded, "") + if custody.Spec.Holder.Type != ops.HolderNone || custody.Spec.LastResult == nil || evidenceOf(t, custody.Spec.LastResult.Evidence.Raw) != (testEvidence{Before: "Off", After: "On"}) || status.Evidence == nil || evidenceOf(t, status.Evidence.Raw) != (testEvidence{Before: "Off", After: "On"}) { + t.Fatalf("after success: custody %+v status %+v", custody.Spec, status) + } + + held := fresh() + e.staffOp(held, "ok") + e.settle(held.Name) + if err := e.result(held.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(held.Name) + hold := e.custody(held.Name).Spec.RecoveryHold + retire := e.recovery(held, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: &ops.HeldOperationReference{Kind: hold.Kind, Name: hold.Name, Fence: hold.Fence}}) + e.settle(held.Name) + e.sites.report(held.Name, e.custody(held.Name).Spec.Fence) + e.settle(held.Name) + e.requirePhase(retire, ops.PhaseSucceeded, "") + if custody := e.custody(held.Name); custody.Spec.Holder.Type != ops.HolderRetired || custody.Spec.RecoveryHold != nil { + t.Fatalf("after Retire: %+v", custody.Spec) + } + }) + + t.Run("inventory retirement of a free Device, finalizer removal and deletion", func(t *testing.T) { + e := e.sub(t) + device := fresh() + for _, lifecycle := range []inventory.DeviceLifecycle{inventory.DeviceDecommissioning, inventory.DeviceRetired} { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + device.Spec.Lifecycle = lifecycle + if err := e.admin.Update(e.ctx, device); err != nil { + t.Fatal(err) + } + } + e.settle(device.Name) + custody := e.custody(device.Name) + if custody.Spec.Holder.Type != ops.HolderRetired { + t.Fatalf("holder = %s", custody.Spec.Holder.Type) + } + // Retired is terminal. + custody.Spec.Holder = ops.Holder{Type: ops.HolderNone} + if err := e.admin.Update(e.ctx, custody); !apierrors.IsInvalid(err) { + t.Fatalf("custody left Retired: %v", err) + } + if err := e.admin.Delete(e.ctx, device); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(custody), &ops.DeviceCustody{}); !apierrors.IsNotFound(err) { + t.Fatalf("custody survived its retired Device: %v", err) + } + }) + + t.Run("custody being deleted keeps its finalizer until Retired", func(t *testing.T) { + e := e.sub(t) + device := fresh() + custody := e.custody(device.Name) + if err := e.admin.Delete(e.ctx, custody); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + if custody = e.custody(device.Name); custody.DeletionTimestamp.IsZero() || !slices.Contains(custody.Finalizers, ops.CustodyFinalizer) { + t.Fatalf("finalizer removed from a live holder: %+v", custody.ObjectMeta) + } + }) + + t.Run("pending operations are admitted oldest first", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-q"); err != nil { + t.Fatal(err) + } + e.providerOp(device, "alloc-q", "first") + e.settle(device.Name) + // Creation times have one-second resolution. + time.Sleep(1100 * time.Millisecond) + second := e.installation(device, "alloc-q", "request-second") + time.Sleep(1100 * time.Millisecond) + third := e.installation(device, "alloc-q", "request-third") + e.settle(device.Name) + e.requirePhase(second, ops.PhasePending, ReasonOperationActive) + e.requirePhase(third, ops.PhasePending, ReasonOperationActive) + if err := e.result(device.Name, ops.PhaseSucceeded, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(second, ops.PhaseAdmitted, "") + e.requirePhase(third, ops.PhasePending, ReasonOperationActive) + }) + + t.Run("a newer pending operation supersedes an older one for the same authority", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-s"); err != nil { + t.Fatal(err) + } + running := e.installation(device, "alloc-s", "request-running") + e.settle(device.Name) + e.requirePhase(running, ops.PhaseAdmitted, "") + older := e.providerOp(device, "alloc-s", "older") + time.Sleep(1100 * time.Millisecond) + newer := e.providerOp(device, "alloc-s", "newer") + e.settle(device.Name) + e.requirePhase(older, ops.PhaseCancelled, ReasonSuperseded) + e.requirePhase(newer, ops.PhasePending, ReasonOperationActive) + }) + + t.Run("a holder change cancels pending operations that no longer match", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-c"); err != nil { + t.Fatal(err) + } + running := e.installation(device, "alloc-c", "request-a") + e.settle(device.Name) + pending := e.installation(device, "alloc-c", "request-b") + e.settle(device.Name) + e.requirePhase(pending, ops.PhasePending, ReasonOperationActive) + // The Machine is deleted while the installation runs. + if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-c"); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(pending, ops.PhaseCancelled, ReasonHolderMismatch) + // The running installation still reports under its fence. + if err := e.result(device.Name, ops.PhaseSucceeded, `{"steps":[{"name":"Installer","completedAt":"2026-01-02T03:04:05Z"}]}`); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(running, ops.PhaseSucceeded, "") + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderRelease { + t.Fatalf("holder = %s", holder) + } + }) + + t.Run("a result with a stale fence is rejected and recorded", func(t *testing.T) { + e := e.sub(t) + device := fresh() + e.staffOp(device, "ok") + e.settle(device.Name) + custody := e.custody(device.Name) + active := custody.Spec.ActiveOperation + stale := SiteResult{Site: testSite, Device: device.Name, Operation: active.OperationReference, Fence: active.Fence - 1, Phase: ops.PhaseSucceeded} + if err := e.coord.AcceptResult(e.ctx, stale); !errors.Is(err, ErrStaleFence) { + t.Fatalf("stale result: %v", err) + } + other := stale + other.Fence = active.Fence + other.Operation.UID = "00000000-0000-4000-8000-000000000999" + if err := e.coord.AcceptResult(e.ctx, other); !errors.Is(err, ErrStaleFence) { + t.Fatalf("result for another incarnation: %v", err) + } + after := e.custody(device.Name) + if after.Spec.ActiveOperation == nil || after.Spec.Holder.Type != custody.Spec.Holder.Type || after.Spec.RejectedResults == nil || after.Spec.RejectedResults.Count != 2 || after.Spec.RejectedResults.Last.Fence != active.Fence || after.Spec.RejectedResults.Last.Site != testSite { + t.Fatalf("after stale results: %+v", after.Spec) + } + }) + + t.Run("results move phases forward only and check evidence", func(t *testing.T) { + e := e.sub(t) + device := fresh() + operation := e.staffOp(device, "ok") + e.settle(device.Name) + for _, phase := range []ops.Phase{ops.PhaseDispatched, ops.PhaseVerifying, ops.PhaseDispatched} { + if err := e.result(device.Name, phase, ""); err != nil { + t.Fatal(err) + } + } + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseVerifying, "") + if err := e.result(device.Name, ops.PhaseSucceeded, `{"before":"On","password":"secret"}`); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + // Evidence outside the kind's schema proves nothing. + e.requirePhase(operation, ops.PhaseOutcomeUnknown, "InvalidEvidence") + if hold := e.custody(device.Name).Spec.RecoveryHold; hold == nil || hold.Name != operation.Name { + t.Fatalf("hold = %+v", hold) + } + }) + + t.Run("a passed deadline is OutcomeUnknown and a hold, never Failed or retried", func(t *testing.T) { + e := e.sub(t) + device := fresh() + operation := e.staffOp(device, "ok") + e.settle(device.Name) + active := *e.custody(device.Name).Spec.ActiveOperation + e.clock.Advance(testDeadline + DefaultSkewMargin - time.Second) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseAdmitted, "") + e.clock.Advance(time.Second) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseOutcomeUnknown, ReasonDeadlineExceeded) + custody := e.custody(device.Name) + hold := custody.Spec.RecoveryHold + if custody.Spec.ActiveOperation != nil || hold == nil || hold.Name != operation.Name || hold.Fence != active.Fence || custody.Spec.Holder.Type != ops.HolderService || custody.Spec.Fence != active.Fence { + t.Fatalf("after the deadline: %+v", custody.Spec) + } + // A late result for the held operation proves nothing. + late := SiteResult{Site: testSite, Device: device.Name, Operation: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseSucceeded} + if err := e.coord.AcceptResult(e.ctx, late); !errors.Is(err, ErrStaleFence) { + t.Fatalf("late result: %v", err) + } + }) +} + +func evidenceOf(t *testing.T, raw []byte) testEvidence { + t.Helper() + var evidence testEvidence + if err := jsonUnmarshal(raw, &evidence); err != nil { + t.Fatal(err) + } + return evidence +} diff --git a/internal/custody/rebuild.go b/internal/custody/rebuild.go new file mode 100644 index 00000000..d6d3ee59 --- /dev/null +++ b/internal/custody/rebuild.go @@ -0,0 +1,191 @@ +package custody + +import ( + "context" + "encoding/json" + "slices" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// Conflicts that keep custody Unverified until an operator resolves them with +// a DeviceRecovery Resolve. +const ( + ConflictDeviceMissing = "DeviceMissing" + ConflictDeviceUID = "DeviceUIDMismatch" + ConflictHolderSources = "HolderSourcesDisagree" + ConflictMultipleAllocations = "MultipleAllocations" + ConflictMultipleUnfinished = "MultipleUnfinishedOperations" +) + +// ReasonRebuilt is the hold reason for an operation found unfinished when +// custody was rebuilt. +const ReasonRebuilt = "Rebuilt" + +// rebuild creates missing custody as Unverified from the Device's inventory +// lifecycle and Retire recoveries, its live MachineAllocations, and its +// operations that have not ended. Site fences are added when it is verified. +func (c *Coordinator) rebuild(ctx context.Context, device *inventory.Device) (Outcome, error) { + spec, err := c.rebuiltSpec(ctx, device) + if err != nil { + return Outcome{}, err + } + custody := &ops.DeviceCustody{ObjectMeta: metav1.ObjectMeta{Name: device.Name, Namespace: device.Namespace, Finalizers: []string{ops.CustodyFinalizer}}, Spec: spec} + if err := c.Client.Create(ctx, custody); err != nil && !apierrors.IsAlreadyExists(err) { + return Outcome{}, err + } + return Outcome{Changed: true}, nil +} + +func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) (ops.DeviceCustodySpec, error) { + spec := ops.DeviceCustodySpec{DeviceRef: ops.DeviceReference{Name: device.Name, UID: string(device.UID)}, State: ops.CustodyUnverified, Holder: ops.Holder{Type: ops.HolderNone}} + holders := map[ops.HolderType]bool{} + if inventory.LifecycleOf(device) == inventory.DeviceRetired { + holders[ops.HolderRetired] = true + } + allocations, err := c.liveAllocations(ctx, device) + if err != nil { + return spec, err + } + if len(allocations) > 1 { + spec.Conflicts = append(spec.Conflicts, ConflictMultipleAllocations) + } + for _, allocation := range allocations { + if allocation.Status.Phase == "Releasing" { + holders[ops.HolderRelease] = true + spec.Holder = ops.Holder{Type: ops.HolderRelease, AllocationRef: &ops.LocalReference{Name: allocation.Name}, OpenGates: slices.Clone(ops.ReleaseGates)} + } else { + holders[ops.HolderAllocation] = true + spec.Holder = ops.Holder{Type: ops.HolderAllocation, AllocationRef: &ops.LocalReference{Name: allocation.Name}} + } + } + var unfinished []ops.Operation + var unfinishedKinds []string + for _, kind := range c.Registry.Kinds() { + list := kind.NewList() + if err := c.Client.List(ctx, list, client.InNamespace(device.Namespace)); err != nil { + return spec, err + } + for _, operation := range kind.Items(list) { + envelope := operation.Envelope() + if envelope.DeviceRef.Name != device.Name || envelope.DeviceRef.UID != string(device.UID) { + continue + } + status := operation.OperationStatus() + spec.Fence = max(spec.Fence, status.Fence) + if kind.Retires != nil && status.Phase == ops.PhaseSucceeded && kind.Retires(operation) { + holders[ops.HolderRetired] = true + } + if status.Phase.Ended() { + continue + } + unfinished = append(unfinished, operation) + unfinishedKinds = append(unfinishedKinds, kind.GVK.Kind) + switch { + case envelope.Authority.ServiceRequest != nil && kind.Effectful: + holders[ops.HolderService] = true + case envelope.Authority.AllocationRef != nil: + if spec.Holder.AllocationRef == nil || spec.Holder.AllocationRef.Name != envelope.Authority.AllocationRef.Name { + spec.Conflicts = appendOnce(spec.Conflicts, ConflictHolderSources) + } + } + } + } + // Every unfinished operation, even one whose status says Pending, may + // already have been admitted and executed, so it is held. + switch len(unfinished) { + case 0: + case 1: + operation := unfinished[0] + spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: unfinishedKinds[0], Name: operation.GetName(), UID: string(operation.GetUID())}, Fence: operation.OperationStatus().Fence, Since: metav1.NewTime(c.now()), Reason: ReasonRebuilt} + default: + spec.Conflicts = appendOnce(spec.Conflicts, ConflictMultipleUnfinished) + } + if len(holders) > 1 { + spec.Conflicts = appendOnce(spec.Conflicts, ConflictHolderSources) + } + switch { + case holders[ops.HolderRetired]: + spec.Holder = ops.Holder{Type: ops.HolderRetired} + case holders[ops.HolderService]: + spec.Holder = ops.Holder{Type: ops.HolderService} + } + return spec, nil +} + +func appendOnce(list []string, value string) []string { + if slices.Contains(list, value) { + return list + } + return append(list, value) +} + +// liveAllocations returns the MachineAllocations that are not Released and +// whose MachineCapacity is backed by the Device. +func (c *Coordinator) liveAllocations(ctx context.Context, device *inventory.Device) ([]metal.MachineAllocation, error) { + var allocations metal.MachineAllocationList + if err := c.Client.List(ctx, &allocations); err != nil { + return nil, err + } + var out []metal.MachineAllocation + for _, allocation := range allocations.Items { + if allocation.Status.Phase == "Released" { + continue + } + capacity := &metal.MachineCapacity{} + reference := allocation.Spec.MachineCapacityRef + if err := c.Client.Get(ctx, client.ObjectKey{Namespace: reference.Namespace, Name: reference.Name}, capacity); apierrors.IsNotFound(err) { + continue + } else if err != nil { + return nil, err + } + if capacity.Namespace == device.Namespace && capacity.Spec.DeviceRef.Name == device.Name { + out = append(out, allocation) + } + } + return out, nil +} + +// verify marks Unverified custody without conflicts Verified once every site +// serving the Device reports its stored fence. The new fence is above every +// fence already used. +func (c *Coordinator) verify(ctx context.Context, custody *ops.DeviceCustody, device *inventory.Device) (Outcome, error) { + highest := custody.Spec.Fence + sites := c.Sites.Serving(device) + // A Device no configured site serves has nothing to fence it, so it + // stays Unverified and unallocatable until a site is configured. + if len(sites) == 0 { + return Outcome{RequeueAfter: verifyPoll}, nil + } + for _, site := range sites { + stored, reported, err := c.Sites.Fence(ctx, site, device) + if err != nil { + return Outcome{}, err + } + if !reported { + return Outcome{RequeueAfter: verifyPoll}, nil + } + highest = max(highest, stored) + } + custody.Spec.State = ops.CustodyVerified + custody.Spec.Fence = highest + 1 + return c.writeCustody(ctx, custody) +} + +func rawEvidence(value any) (*runtime.RawExtension, error) { + data, err := json.Marshal(value) + if err != nil { + return nil, err + } + return rawExtension(data), nil +} + +func rawExtension(data []byte) *runtime.RawExtension { + return &runtime.RawExtension{Raw: append([]byte(nil), data...)} +} diff --git a/internal/custody/recovery_test.go b/internal/custody/recovery_test.go new file mode 100644 index 00000000..9e59dbe1 --- /dev/null +++ b/internal/custody/recovery_test.go @@ -0,0 +1,502 @@ +package custody + +import ( + "fmt" + "slices" + "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" +) + +// holdOn runs a test staff operation to OutcomeUnknown and returns the hold. +func (e *env) holdOn(device *inventory.Device) ops.RecoveryHold { + e.t.Helper() + e.staffOp(device, "ok") + e.settle(device.Name) + 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 { + e.t.Fatal("no hold") + } + return *hold +} + +func heldRef(hold ops.RecoveryHold) *ops.HeldOperationReference { + return &ops.HeldOperationReference{Kind: hold.Kind, Name: hold.Name, Fence: hold.Fence} +} + +func TestRecovery(t *testing.T) { + e := startEnv(t) + n := 200 + fresh := func() *inventory.Device { + n++ + return e.verified(fmt.Sprintf("server-example-%03d", n), uid(n), fmt.Sprintf("%064x", n)) + } + + t.Run("a hold settles only after the site confirms the raised fence", func(t *testing.T) { + e := e.sub(t) + device := fresh() + hold := e.holdOn(device) + e.clock.Advance(time.Minute) + settle := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: heldRef(hold), Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(e.clock.Now()), Summary: "discovery read the state", Data: map[string]string{"state": "On"}}}) + e.settle(device.Name) + custody := e.custody(device.Name) + if custody.Spec.ActiveOperation == nil || custody.Spec.ActiveOperation.Fence != hold.Fence+1 || custody.Spec.RecoveryHold == nil { + t.Fatalf("recovery not admitted under the hold: %+v", custody.Spec) + } + // The site still runs the held worker at the old fence. + e.sites.report(device.Name, hold.Fence) + e.settle(device.Name) + e.requirePhase(settle, ops.PhaseAdmitted, "") + if e.custody(device.Name).Spec.RecoveryHold == nil { + t.Fatal("hold settled before the site stopped the held worker") + } + e.sites.report(device.Name, hold.Fence+1) + e.settle(device.Name) + status := e.requirePhase(settle, ops.PhaseSucceeded, "") + custody = e.custody(device.Name) + if custody.Spec.RecoveryHold != nil || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("after Settle: %+v", custody.Spec) + } + var evidence ops.RecoveryResultEvidence + if err := jsonUnmarshal(status.Evidence.Raw, &evidence); err != nil || evidence.Decision != ops.DecisionSettle || evidence.ConfirmedFence != hold.Fence+1 { + t.Fatalf("recovery evidence = %s", status.Evidence.Raw) + } + }) + + t.Run("settle evidence is validated by the held kind", func(t *testing.T) { + e := e.sub(t) + device := fresh() + hold := e.holdOn(device) + // Evidence observed before the hold began proves nothing. + stale := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: heldRef(hold), Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(e.clock.Now().Add(-time.Hour)), Summary: "old", Data: map[string]string{"state": "On"}}}) + e.settle(device.Name) + e.requirePhase(stale, ops.PhaseFailed, "EvidenceNotCurrent") + if e.custody(device.Name).Spec.RecoveryHold == nil { + t.Fatal("hold cleared by stale evidence") + } + }) + + t.Run("a recovery that does not name the hold is refused and changes nothing", func(t *testing.T) { + e := e.sub(t) + device := fresh() + hold := e.holdOn(device) + fence := e.custody(device.Name).Spec.Fence + wrong := heldRef(hold) + wrong.Fence-- + refused := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: wrong, Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(e.clock.Now().Add(time.Minute)), Summary: "s", Data: map[string]string{"state": "On"}}}) + e.settle(device.Name) + e.requirePhase(refused, ops.PhaseFailed, ReasonHoldMismatch) + e.requireUntouched(device.Name, fence) + // A recovery with no hold to decide is refused too. + free := fresh() + none := e.recovery(free, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: wrong}) + e.settle(free.Name) + e.requirePhase(none, ops.PhaseFailed, ReasonRecoveryHold) + // A staff operation that cannot settle the hold is refused. + blocked := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(blocked, ops.PhaseFailed, ReasonHolderMismatch) + }) + + t.Run("a recovery whose sites never confirm ends Failed and keeps the hold", func(t *testing.T) { + e := e.sub(t) + device := fresh() + hold := e.holdOn(device) + e.clock.Advance(time.Minute) + settle := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: heldRef(hold), Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(e.clock.Now()), Summary: "s", Data: map[string]string{"state": "On"}}}) + e.settle(device.Name) + e.clock.Advance(RecoveryDeadline + DefaultSkewMargin) + e.settle(device.Name) + e.requirePhase(settle, ops.PhaseFailed, ReasonSiteNotConfirmed) + if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.UID != hold.UID { + t.Fatalf("hold = %+v", got) + } + }) + + t.Run("a wipe after release settles an installation hold", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-i"); err != nil { + t.Fatal(err) + } + install := e.installation(device, "alloc-i", "request-1") + e.settle(device.Name) + // The Machine is deleted during the installer phase. + if err := e.result(device.Name, ops.PhaseDispatched, ""); err != nil { + t.Fatal(err) + } + if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-i"); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + // Release waits for the installation's outcome or its deadline. + e.clock.Advance(InstallationDeadline + DefaultSkewMargin) + e.settle(device.Name) + e.requirePhase(install, ops.PhaseOutcomeUnknown, ReasonDeadlineExceeded) + custody := e.custody(device.Name) + if custody.Spec.Holder.Type != ops.HolderRelease || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.Kind != "DeviceInstallation" { + t.Fatalf("after the install deadline: %+v", custody.Spec) + } + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now()) + wipe := e.wipe(device, "alloc-i", 1) + e.settle(device.Name) + e.requirePhase(wipe, ops.PhaseAdmitted, "") + if active := e.custody(device.Name).Spec.ActiveOperation; active.Settles == nil || active.Settles.UID != string(install.UID) { + t.Fatalf("wipe does not record what it settles: %+v", active) + } + if err := e.result(device.Name, ops.PhaseSucceeded, `{"wipedDisks":["disk-0"],"policyDigest":"`+policyDigest+`"}`); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(wipe, ops.PhaseSucceeded, "") + if hold := e.custody(device.Name).Spec.RecoveryHold; hold != nil { + t.Fatalf("hold survived the wipe: %+v", hold) + } + for _, gate := range ops.ReleaseGates { + if err := e.coord.CloseGate(e.ctx, device.Name, "alloc-i", gate); err != nil { + t.Fatal(err) + } + } + e.settle(device.Name) + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderNone { + t.Fatalf("holder = %s", holder) + } + }) + + t.Run("a held wipe settles only after a Retry, which authorizes one wipe", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-w"); err != nil { + t.Fatal(err) + } + if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-w"); err != nil { + t.Fatal(err) + } + first := e.wipe(device, "alloc-w", 1) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, "BMCResponseLost"); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(first, ops.PhaseOutcomeUnknown, "") + hold := *e.custody(device.Name).Spec.RecoveryHold + blocked := e.wipe(device, "alloc-w", 2) + e.settle(device.Name) + e.requirePhase(blocked, ops.PhaseFailed, ReasonRecoveryHold) + // Settle is not how a wipe hold ends. + settle := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: heldRef(hold)}) + e.settle(device.Name) + e.requirePhase(settle, ops.PhaseFailed, ReasonNotSettleable) + retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + e.settle(device.Name) + e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) + e.settle(device.Name) + e.requirePhase(retry, ops.PhaseSucceeded, "") + if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy == nil || got.RetryAuthorizedBy.UID != string(retry.UID) { + t.Fatalf("retry not recorded: %+v", got) + } + second := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + e.settle(device.Name) + e.requirePhase(second, ops.PhaseFailed, ReasonRetryAuthorized) + third := e.wipe(device, "alloc-w", 3) + e.settle(device.Name) + e.requirePhase(third, ops.PhaseAdmitted, "") + if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy != nil { + t.Fatalf("the retry was not consumed: %+v", got) + } + if err := e.result(device.Name, ops.PhaseSucceeded, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + if got := e.custody(device.Name).Spec.RecoveryHold; got != nil { + t.Fatalf("hold survived the retried wipe: %+v", got) + } + }) + + t.Run("retiring from Release records disk disposal", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-r"); err != nil { + t.Fatal(err) + } + if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-r"); err != nil { + t.Fatal(err) + } + e.wipe(device, "alloc-r", 1) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + hold := *e.custody(device.Name).Spec.RecoveryHold + bare := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(hold)}) + e.settle(device.Name) + e.requirePhase(bare, ops.PhaseFailed, ReasonDisposalRequired) + retire := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(hold), DiskDisposal: &ops.DiskDisposal{Method: ops.DisposalDestroyed, Reference: "ticket-example-1"}}) + e.settle(device.Name) + e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) + e.settle(device.Name) + e.requirePhase(retire, ops.PhaseSucceeded, "") + if custody := e.custody(device.Name); custody.Spec.Holder.Type != ops.HolderRetired || custody.Spec.RecoveryHold != nil { + t.Fatalf("after Retire: %+v", custody.Spec) + } + // An allocated server cannot be retired. + allocated := fresh() + if err := e.coord.Claim(e.ctx, allocated.Name, "alloc-live"); err != nil { + t.Fatal(err) + } + e.providerOp(allocated, "alloc-live", "a") + e.settle(allocated.Name) + if err := e.result(allocated.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(allocated.Name) + held := *e.custody(allocated.Name).Spec.RecoveryHold + refused := e.recovery(allocated, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(held), DiskDisposal: &ops.DiskDisposal{Method: ops.DisposalRemoved, Reference: "ticket-example-2"}}) + e.settle(allocated.Name) + e.requirePhase(refused, ops.PhaseFailed, ReasonHolderMismatch) + }) + + t.Run("finished operations are kept 30 days, held ones until settled", func(t *testing.T) { + e := e.sub(t) + device := fresh() + done := e.staffOp(device, "ok") + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseSucceeded, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + hold := e.holdOn(device) + e.clock.Advance(DefaultRetention - time.Hour) + if _, err := e.coord.SweepRetention(e.ctx); err != nil { + t.Fatal(err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(done), done); err != nil { + t.Fatalf("deleted before 30 days: %v", err) + } + e.clock.Advance(2 * time.Hour) + if _, err := e.coord.SweepRetention(e.ctx); err != nil { + t.Fatal(err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(done), done); !apierrors.IsNotFound(err) { + t.Fatalf("kept after 30 days: %v", err) + } + held := &DeviceTestStaffOperation{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: "default", Name: hold.Name}, held); err != nil { + t.Fatalf("held operation deleted: %v", err) + } + }) +} + +func TestRebuild(t *testing.T) { + e := startEnv(t) + n := 300 + next := func() (string, string, string) { + n++ + return fmt.Sprintf("server-example-%03d", n), uid(n), fmt.Sprintf("%064x", n) + } + + t.Run("custody deleted and restored is unallocatable until rebuilt above the site fence", func(t *testing.T) { + e := e.sub(t) + name, id, key := next() + device := e.verified(name, id, key) + e.staffOp(device, "ok") + e.settle(name) + if err := e.result(name, ops.PhaseSucceeded, ""); err != nil { + t.Fatal(err) + } + e.settle(name) + used := e.custody(name).Spec.Fence + e.sites.report(name, used) + // The harness admin removes the finalizer and deletes custody. + custody := e.custody(name) + custody.Finalizers = nil + if err := e.admin.Update(e.ctx, custody); err != nil { + t.Fatal(err) + } + if err := e.admin.Delete(e.ctx, custody); err != nil { + t.Fatal(err) + } + e.sites.forget(name) + e.settle(name) + rebuilt := e.custody(name) + if rebuilt.Spec.State != ops.CustodyUnverified { + t.Fatalf("rebuilt = %+v", rebuilt.Spec) + } + if err := e.coord.Claim(e.ctx, name, "alloc-new"); err == nil { + t.Fatal("rebuilt custody was allocatable before verification") + } + e.sites.report(name, used) + e.settle(name) + rebuilt = e.custody(name) + if rebuilt.Spec.State != ops.CustodyVerified || rebuilt.Spec.Fence <= used { + t.Fatalf("verified fence %d, site stored %d", rebuilt.Spec.Fence, used) + } + if err := e.coord.Claim(e.ctx, name, "alloc-new"); err != nil { + t.Fatal(err) + } + }) + + // rebuildFrom deletes custody and rebuilds it with the site reporting. + rebuildFrom := func(e *env, name string, siteFence int64) *ops.DeviceCustody { + e.t.Helper() + custody := &ops.DeviceCustody{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: "default", Name: name}, custody); err == nil { + custody.Finalizers = nil + if err := e.admin.Update(e.ctx, custody); err != nil { + e.t.Fatal(err) + } + if err := e.admin.Delete(e.ctx, custody); err != nil { + e.t.Fatal(err) + } + } + e.sites.report(name, siteFence) + e.settle(name) + return e.custody(name) + } + + t.Run("from inventory: a retired Device rebuilds Retired", func(t *testing.T) { + e := e.sub(t) + name, id, key := next() + device := e.device(name, id, key) + for _, lifecycle := range []inventory.DeviceLifecycle{inventory.DeviceDecommissioning, inventory.DeviceRetired} { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + device.Spec.Lifecycle = lifecycle + if err := e.admin.Update(e.ctx, device); err != nil { + t.Fatal(err) + } + } + if custody := rebuildFrom(e, name, 3); custody.Spec.Holder.Type != ops.HolderRetired || custody.Spec.State != ops.CustodyVerified || custody.Spec.Fence != 4 { + t.Fatalf("rebuilt = %+v", custody.Spec) + } + }) + + t.Run("from allocations: a live allocation rebuilds Allocation, a releasing one Release with every gate open", func(t *testing.T) { + e := e.sub(t) + name, id, key := next() + device := e.device(name, id, key) + e.allocation(device, "alloc-live-"+name, "Active") + if custody := rebuildFrom(e, name, 0); custody.Spec.Holder.Type != ops.HolderAllocation || custody.Spec.Holder.AllocationRef.Name != "alloc-live-"+name || custody.Spec.State != ops.CustodyVerified { + t.Fatalf("rebuilt = %+v", custody.Spec) + } + name, id, key = next() + device = e.device(name, id, key) + e.allocation(device, "alloc-old-"+name, "Released") + e.allocation(device, "alloc-rel-"+name, "Releasing") + custody := rebuildFrom(e, name, 0) + if custody.Spec.Holder.Type != ops.HolderRelease || !slices.Equal(custody.Spec.Holder.OpenGates, ops.ReleaseGates) || custody.Spec.State != ops.CustodyVerified { + t.Fatalf("rebuilt = %+v", custody.Spec) + } + }) + + t.Run("from operations: an unfinished operation, even Pending, is held", func(t *testing.T) { + e := e.sub(t) + name, id, key := next() + device := e.device(name, id, key) + operation := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: name + "-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("restore")), Input: "a"}} + e.create(operation) + operation.Status = ops.OperationStatus{Phase: ops.PhasePending, Fence: 9} + if err := e.admin.Status().Update(e.ctx, operation); err != nil { + t.Fatal(err) + } + custody := rebuildFrom(e, name, 4) + if hold := custody.Spec.RecoveryHold; hold == nil || hold.UID != string(operation.UID) || hold.Reason != ReasonRebuilt || custody.Spec.Holder.Type != ops.HolderService || custody.Spec.Fence != 10 { + t.Fatalf("rebuilt = %+v", custody.Spec) + } + }) + + t.Run("from recoveries: a succeeded Retire rebuilds Retired", func(t *testing.T) { + e := e.sub(t) + name, id, key := next() + device := e.device(name, id, key) + recovery := &ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: name + "-", Namespace: "default"}, Spec: ops.DeviceRecoverySpec{OperationEnvelope: envelope(device, staffUser, service("retired")), Decision: ops.DecisionRetire, Hold: &ops.HeldOperationReference{Kind: testStaffKind, Name: "x", Fence: 1}, Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(e.clock.Now()), Summary: "s"}}} + e.create(recovery) + finished := metav1.NewTime(e.clock.Now()) + recovery.Status = ops.OperationStatus{Phase: ops.PhaseSucceeded, Fence: 2, FinishedAt: &finished} + if err := e.admin.Status().Update(e.ctx, recovery); err != nil { + t.Fatal(err) + } + if custody := rebuildFrom(e, name, 0); custody.Spec.Holder.Type != ops.HolderRetired || custody.Spec.Fence != 3 { + t.Fatalf("rebuilt = %+v", custody.Spec) + } + }) + + conflict := func(t *testing.T, e *env, name, want string) { + t.Helper() + custody := rebuildFrom(e, name, 0) + if custody.Spec.State != ops.CustodyUnverified || !slices.Contains(custody.Spec.Conflicts, want) { + t.Fatalf("rebuilt = %+v, want conflict %s", custody.Spec, want) + } + if err := e.coord.Claim(e.ctx, name, "alloc-any"); err == nil { + t.Fatal("conflicted custody was claimed") + } + } + + t.Run("conflict: two live allocations", func(t *testing.T) { + e := e.sub(t) + name, id, key := next() + device := e.device(name, id, key) + e.allocation(device, "alloc-one-"+name, "Active") + e.allocation(device, "alloc-two-"+name, "Active") + conflict(t, e, name, ConflictMultipleAllocations) + }) + + t.Run("conflict: an allocation and a staff operation disagree", func(t *testing.T) { + e := e.sub(t) + name, id, key := next() + device := e.device(name, id, key) + e.allocation(device, "alloc-"+name, "Active") + e.create(&DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: name + "-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("x")), Input: "a"}}) + conflict(t, e, name, ConflictHolderSources) + }) + + t.Run("conflict: two unfinished operations", func(t *testing.T) { + e := e.sub(t) + name, id, key := next() + device := e.device(name, id, key) + for range 2 { + e.create(&DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: name + "-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("x")), Input: "a"}}) + } + conflict(t, e, name, ConflictMultipleUnfinished) + }) + + t.Run("conflict: the Device UID differs from deviceRef.uid, then Resolve", func(t *testing.T) { + e := e.sub(t) + name, id, key := next() + device := e.verified(name, id, key) + // The Device is replaced under the same name while custody remains. + if err := e.admin.Delete(e.ctx, device); err != nil { + t.Fatal(err) + } + replacement := e.device(name, uid(n+500), key) + e.settle(name) + custody := e.custody(name) + if custody.Spec.State != ops.CustodyUnverified || !slices.Contains(custody.Spec.Conflicts, ConflictDeviceUID) { + t.Fatalf("custody = %+v", custody.Spec) + } + // Only a Resolve recovery is admitted. + staff := e.staffOp(replacement, "ok") + e.settle(name) + e.requirePhase(staff, ops.PhaseFailed, ReasonUnverified) + resolve := e.recovery(replacement, ops.DeviceRecoverySpec{Decision: ops.DecisionResolve, Resolve: &ops.ResolveInput{Holder: ops.HolderNone}}) + e.settle(name) + e.sites.report(name, e.custody(name).Spec.Fence) + e.settle(name) + e.requirePhase(resolve, ops.PhaseSucceeded, "") + custody = e.custody(name) + if custody.Spec.State != ops.CustodyVerified || custody.Spec.Holder.Type != ops.HolderNone || custody.Spec.DeviceRef.UID != string(replacement.UID) || len(custody.Spec.Conflicts) != 0 { + t.Fatalf("after Resolve: %+v", custody.Spec) + } + }) +} diff --git a/internal/custody/registry.go b/internal/custody/registry.go new file mode 100644 index 00000000..b635650d --- /dev/null +++ b/internal/custody/registry.go @@ -0,0 +1,256 @@ +// Package custody implements Device custody and coordinator admission, as +// proposed in datum-cloud/fleet#174 at 3907eec. +// +// The Coordinator is the only writer of DeviceCustody and of operation status. +// Every custody change is one Update carrying the resourceVersion it read; on +// a conflict it reads again and decides again. Operation kinds plug in through +// a Registry entry (Kind) and rows of the admission Rules table, so a new kind +// changes neither the core nor how existing rows are evaluated. +// +// Increment A is inert: nothing wires this package into a deployment root. +package custody + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "sort" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// Naming is how an operation kind's objects are named. +type Naming int + +const ( + // DeterministicName kinds are named from their authority and request, so + // a retried create collides instead of making a second operation. + DeterministicName Naming = iota + // GeneratedName kinds are staff requests. Each one is new, so each must + // be created with metadata.generateName. + GeneratedName +) + +// Kind is the registry entry for one operation kind. The core reads only +// these fields; it never switches on a kind name. +type Kind struct { + GVK schema.GroupVersionKind + // New returns an empty object of the kind, and NewList an empty list. + New func() ops.Operation + NewList func() client.ObjectList + // Items returns the operations in a list made by NewList. + Items func(client.ObjectList) []ops.Operation + // Digest returns the digest of the operation's exact inputs. + Digest func(ops.Operation) (string, error) + Naming Naming + // Name returns the only name a DeterministicName operation may have. + Name func(ops.Operation) string + // Deadline is how long the site may work on an admitted operation. + Deadline time.Duration + // Effectful kinds can reach the server. A non-effectful kind, such as + // DeviceRecovery, that passes its deadline ends Failed: nothing it does + // can leave the server in an unknown state. + Effectful bool + // Supersedes means a newer pending operation of this kind for the same + // authority cancels an older pending one. + Supersedes bool + // Variant, when set, selects among this kind's rows, such as a recovery + // decision. An empty row Variant matches every operation of the kind. + Variant func(ops.Operation) string + // BootInterface names the Device interface whose MAC the snapshot + // captures, if the kind boots the server. + 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. + Check func(context.Context, *Admission) *Refusal + // Settles lists the held kinds a success of this kind settles. + Settles []SettleRule + // Evidence validates the kind's typed, bounded result evidence and + // returns it in canonical form. Nil means the kind's results carry none. + Evidence func([]byte) ([]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 + // Apply runs when an admitted operation of a non-effectful kind is + // confirmed by its site fence. It returns the custody to write. + Apply func(context.Context, *ApplyContext) (*ops.DeviceCustodySpec, *Refusal) + // Retires reports whether a succeeded operation of this kind retired the + // Device. Rebuild reads it. + Retires func(ops.Operation) bool +} + +// SettleRule says a success of the owning kind settles a hold of Held. When +// RequiresRetry is set, a DeviceRecovery with Retry must first authorize it. +type SettleRule struct { + Held string + RequiresRetry bool +} + +// Admission is what a kind-specific check sees. +type Admission struct { + Operation ops.Operation + Custody *ops.DeviceCustody + Device *inventory.Device + Row Rule + Registry *Registry + Now time.Time +} + +// RecoverySettleContext is what a held kind's settle hook sees. +type RecoverySettleContext struct { + Hold ops.RecoveryHold + Recovery *ops.DeviceRecovery + Device *inventory.Device + Custody *ops.DeviceCustody + Now time.Time +} + +// ApplyContext is what a non-effectful kind's Apply sees. +type ApplyContext struct { + Operation ops.Operation + Custody *ops.DeviceCustody + Device *inventory.Device + Registry *Registry + // ConfirmedFence is the lowest fence the serving sites report, and + // HighestFence the highest. Both are at least the operation's fence. + ConfirmedFence int64 + HighestFence int64 + Now time.Time +} + +// Refusal is a named reason an operation was not admitted or applied. +type Refusal struct { + Reason string + Message string +} + +func (r *Refusal) Error() string { return r.Reason + ": " + r.Message } + +func refuse(reason, format string, args ...any) *Refusal { + return &Refusal{Reason: reason, Message: fmt.Sprintf(format, args...)} +} + +// Shared refusal and cancellation reasons. Kinds add their own; the set is +// open. +const ( + ReasonUnverified = "Unverified" + ReasonNoMatchingRule = "NoMatchingRule" + ReasonHolderMismatch = "HolderMismatch" + ReasonOperationActive = "OperationActive" + ReasonIdentityMismatch = "IdentityMismatch" + ReasonIdentityNotCurrent = "IdentityNotCurrent" + ReasonSharedPublicKey = "SharedPublicKey" + ReasonRecoveryHold = "RecoveryHold" + ReasonNameMismatch = "NameMismatch" + ReasonExpired = "Expired" + ReasonSuperseded = "Superseded" + ReasonWithdrawn = "Withdrawn" + ReasonDeadlineExceeded = "DeadlineExceeded" + ReasonSiteNotConfirmed = "SiteNotConfirmed" + ReasonSiteUnknown = "SiteCouldNotProve" + ReasonInvalidEvidence = "InvalidEvidence" +) + +// Registry holds the operation kinds and the admission rules. +type Registry struct { + kinds map[string]*Kind + order []string + rules []Rule +} + +func NewRegistry() *Registry { return &Registry{kinds: map[string]*Kind{}} } + +// Register adds a kind. Registering a kind twice is an error. +func (r *Registry) Register(kind Kind) error { + name := kind.GVK.Kind + if name == "" || kind.New == nil || kind.NewList == nil || kind.Items == nil || kind.Digest == nil || kind.Deadline <= 0 { + return errors.New("a kind needs a GVK, constructors, a digest and a deadline") + } + if kind.Naming == DeterministicName && kind.Name == nil { + return fmt.Errorf("%s: a deterministic name rule is required", name) + } + if !kind.Effectful && kind.Apply == nil { + return fmt.Errorf("%s: a non-effectful kind needs Apply", name) + } + if _, ok := r.kinds[name]; ok { + return fmt.Errorf("%s is already registered", name) + } + r.kinds[name] = &kind + r.order = append(r.order, name) + sort.Strings(r.order) + return nil +} + +// AddRule appends an admission row. Rows are evaluated independently, so +// adding one never changes how another is evaluated. +func (r *Registry) AddRule(rule Rule) error { + if _, ok := r.kinds[rule.Kind]; !ok { + return fmt.Errorf("rule for unregistered kind %s", rule.Kind) + } + if rule.Creator == "" || (rule.Authority != AuthorityAllocation && rule.Authority != AuthorityService) { + return errors.New("a rule needs a creator class and an authority type") + } + if rule.Queue && rule.Creator == CreatorStaff { + return errors.New("staff operations never queue") + } + r.rules = append(r.rules, rule) + return nil +} + +func (r *Registry) Kind(name string) *Kind { return r.kinds[name] } + +// Kinds returns every registered kind, sorted by name. +func (r *Registry) Kinds() []*Kind { + out := make([]*Kind, 0, len(r.order)) + for _, name := range r.order { + out = append(out, r.kinds[name]) + } + return out +} + +func (r *Registry) Rules() []Rule { return append([]Rule(nil), r.rules...) } + +// SpecDigest is the default input digest: sha256 over the canonical JSON of +// the object's spec. encoding/json orders struct fields and sorts map keys, so +// the encoding is stable. +func SpecDigest(spec any) (string, error) { + data, err := json.Marshal(spec) + if err != nil { + return "", err + } + sum := sha256.Sum256(data) + return "sha256:" + hex.EncodeToString(sum[:]), nil +} + +// StrictEvidence returns an Evidence function that decodes into T, rejecting +// unknown fields and anything over maxBytes, then runs validate. +func StrictEvidence[T any](maxBytes int, validate func(*T) error) func([]byte) ([]byte, error) { + return func(raw []byte) ([]byte, error) { + if len(raw) > maxBytes { + return nil, fmt.Errorf("evidence is %d bytes; the limit is %d", len(raw), maxBytes) + } + value := new(T) + decoder := json.NewDecoder(bytesReader(raw)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(value); err != nil { + return nil, fmt.Errorf("evidence does not match the kind's schema: %w", err) + } + if decoder.More() { + return nil, errors.New("evidence has trailing data") + } + if validate != nil { + if err := validate(value); err != nil { + return nil, err + } + } + return json.Marshal(value) + } +} diff --git a/internal/custody/results.go b/internal/custody/results.go new file mode 100644 index 00000000..e77e40ae --- /dev/null +++ b/internal/custody/results.go @@ -0,0 +1,229 @@ +package custody + +import ( + "context" + "errors" + "fmt" + "slices" + "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 ( + verifyPoll = 5 * time.Second + maxConflicts = 8 +) + +var ( + // ErrStaleFence means the result's fence or operation does not match + // the active operation. The site deletes its copy; custody records the + // rejection for monitoring and never changes the holder for it. + ErrStaleFence = errors.New("result does not match the active operation's fence") + // ErrUnavailable means custody does not allow the holder change now. + ErrUnavailable = errors.New("custody does not allow this change") + // errContended means custody kept changing under every attempt. + errContended = errors.New("custody changed under every attempt") +) + +// SiteResult is what a site reports for one operation. It always carries the +// operation's fence. +type SiteResult struct { + Site string + Device string + Operation ops.OperationReference + Fence int64 + // Phase is Dispatched, Verifying, Succeeded, Failed or OutcomeUnknown. + Phase ops.Phase + Reason string + Message string + Evidence []byte +} + +// update reads custody, applies change and writes it with the +// resourceVersion just read. On a conflict it reads again and calls change +// again on the new custody: it never retries a stale decision. +func (c *Coordinator) update(ctx context.Context, name string, change func(*ops.DeviceCustody) error) error { + for range maxConflicts { + custody := &ops.DeviceCustody{} + if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.config().Namespace, Name: name}, custody); err != nil { + return err + } + if err := change(custody); err != nil { + return err + } + if err := c.Client.Update(ctx, custody); err == nil { + return nil + } else if !apierrors.IsConflict(err) { + return err + } + } + return errContended +} + +// errNoChange stops update without writing. +var errNoChange = errors.New("no change") + +func ignoreNoChange(err error) error { + if errors.Is(err, errNoChange) { + return nil + } + return err +} + +// AcceptResult records a site result in custody. A result whose fence or +// operation does not match the active operation is rejected and recorded as +// a rejected fence; ErrStaleFence is returned either way, so the site +// deletes its copy. +func (c *Coordinator) AcceptResult(ctx context.Context, result SiteResult) error { + stale := false + err := c.update(ctx, result.Device, func(custody *ops.DeviceCustody) error { + stale = false + spec := &custody.Spec + active := spec.ActiveOperation + kind := c.Registry.Kind(result.Operation.Kind) + // A retry after a lost response to an accepted result is accepted + // again without a write. + if last := spec.LastResult; active == nil && last != nil && last.OperationReference == result.Operation && last.Fence == result.Fence && last.Phase == result.Phase { + return errNoChange + } + if active == nil || active.OperationReference != result.Operation || active.Fence != result.Fence || kind == nil || !kind.Effectful { + stale = true + count := int64(1) + if spec.RejectedResults != nil { + count = spec.RejectedResults.Count + 1 + } + spec.RejectedResults = &ops.RejectedResults{Count: count, Last: ops.RejectedResult{Kind: result.Operation.Kind, Name: result.Operation.Name, Fence: result.Fence, Site: result.Site, RejectedAt: metav1.NewTime(c.now())}} + return nil + } + switch result.Phase { + case ops.PhaseDispatched, ops.PhaseVerifying: + if progressRank(result.Phase) <= progressRank(active.Phase) { + return errNoChange + } + active.Phase = result.Phase + return nil + case ops.PhaseSucceeded, ops.PhaseFailed, ops.PhaseOutcomeUnknown: + default: + return fmt.Errorf("a site cannot report phase %q", result.Phase) + } + var evidence []byte + if len(result.Evidence) != 0 { + if kind.Evidence == nil { + c.holdUnknown(custody, *active, ReasonInvalidEvidence, "the kind records no evidence, and the site sent some", nil) + return nil + } + canonical, err := kind.Evidence(result.Evidence) + if err != nil { + c.holdUnknown(custody, *active, ReasonInvalidEvidence, err.Error(), nil) + return nil + } + evidence = canonical + } + switch result.Phase { + case ops.PhaseOutcomeUnknown: + reason := result.Reason + if reason == "" { + reason = ReasonSiteUnknown + } + c.holdUnknown(custody, *active, reason, result.Message, evidence) + case ops.PhaseFailed: + c.finishActive(custody, *active, ops.PhaseFailed, result.Reason, result.Message, evidence) + case ops.PhaseSucceeded: + if hold := spec.RecoveryHold; hold != nil && active.Settles != nil && *active.Settles == hold.OperationReference { + spec.RecoveryHold = nil + } + c.finishActive(custody, *active, ops.PhaseSucceeded, result.Reason, result.Message, evidence) + } + return nil + }) + if err := ignoreNoChange(err); err != nil { + return err + } + if stale { + return ErrStaleFence + } + return nil +} + +func progressRank(phase ops.Phase) int { + return slices.Index([]ops.Phase{ops.PhaseAdmitted, ops.PhaseDispatched, ops.PhaseVerifying}, phase) +} + +// Claim moves a free Device to the allocation with one conditional update. +// The allocator decides with this update, never with the advisory Available +// condition. A claim that already names the allocation succeeds, so a retry +// after a lost response does not claim a second server. +func (c *Coordinator) Claim(ctx context.Context, deviceName, allocation string) error { + device, err := c.device(ctx, deviceName) + if err != nil { + return err + } + if device == nil || inventory.LifecycleOf(device) != inventory.DeviceActive { + return fmt.Errorf("%w: the Device is not Active", ErrUnavailable) + } + return ignoreNoChange(c.update(ctx, deviceName, func(custody *ops.DeviceCustody) error { + spec := &custody.Spec + if spec.Holder.Type == ops.HolderAllocation && spec.Holder.AllocationRef != nil && spec.Holder.AllocationRef.Name == allocation { + return errNoChange + } + switch { + case !custody.DeletionTimestamp.IsZero(), spec.DeviceRef.UID != string(device.UID): + return fmt.Errorf("%w: custody is for another Device incarnation", ErrUnavailable) + case spec.State != ops.CustodyVerified: + return fmt.Errorf("%w: custody is Unverified", ErrUnavailable) + case spec.Holder.Type != ops.HolderNone: + return fmt.Errorf("%w: the holder is %s", ErrUnavailable, spec.Holder.Type) + case spec.RecoveryHold != nil, spec.ActiveOperation != nil: + return fmt.Errorf("%w: the Device is held or busy", ErrUnavailable) + } + spec.Holder = ops.Holder{Type: ops.HolderAllocation, AllocationRef: &ops.LocalReference{Name: allocation}} + return nil + })) +} + +// BeginRelease moves an allocated Device to Release with every gate open. A +// hold moves with it, and an active operation keeps running under the same +// fence. +func (c *Coordinator) BeginRelease(ctx context.Context, deviceName, allocation string) error { + return ignoreNoChange(c.update(ctx, deviceName, func(custody *ops.DeviceCustody) error { + spec := &custody.Spec + if spec.Holder.AllocationRef == nil || spec.Holder.AllocationRef.Name != allocation { + return fmt.Errorf("%w: the allocation does not hold the Device", ErrUnavailable) + } + switch spec.Holder.Type { + case ops.HolderRelease: + return errNoChange + case ops.HolderAllocation: + default: + return fmt.Errorf("%w: the holder is %s", ErrUnavailable, spec.Holder.Type) + } + spec.Holder = ops.Holder{Type: ops.HolderRelease, AllocationRef: spec.Holder.AllocationRef, OpenGates: slices.Clone(ops.ReleaseGates)} + return nil + })) +} + +// CloseGate removes one release gate after the release controller reports +// its evidence. A gate the coordinator does not know stays open. The Device +// returns to None on a later reconcile, once no gate, hold or operation +// remains. +func (c *Coordinator) CloseGate(ctx context.Context, deviceName, allocation string, gate ops.ReleaseGate) error { + if !slices.Contains(ops.ReleaseGates, gate) { + return fmt.Errorf("%w: unknown release gate %q stays open", ErrUnavailable, gate) + } + return ignoreNoChange(c.update(ctx, deviceName, func(custody *ops.DeviceCustody) error { + spec := &custody.Spec + if spec.Holder.Type != ops.HolderRelease || spec.Holder.AllocationRef == nil || spec.Holder.AllocationRef.Name != allocation { + return fmt.Errorf("%w: the allocation is not releasing the Device", ErrUnavailable) + } + if !slices.Contains(spec.Holder.OpenGates, gate) { + return errNoChange + } + spec.Holder.OpenGates = slices.DeleteFunc(slices.Clone(spec.Holder.OpenGates), func(open ops.ReleaseGate) bool { return open == gate }) + return nil + })) +} diff --git a/internal/custody/retention.go b/internal/custody/retention.go new file mode 100644 index 00000000..7abf3e4c --- /dev/null +++ b/internal/custody/retention.go @@ -0,0 +1,51 @@ +package custody + +import ( + "context" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// SweepRetention deletes operations that finished more than +// Config.Retention ago. An operation custody still names, as active or as +// its recovery hold, is kept. Platform audit records keep the history after +// that. +func (c *Coordinator) SweepRetention(ctx context.Context) (int, error) { + cfg := c.config() + cutoff := c.now().Add(-cfg.Retention) + referenced := map[types.UID]bool{} + var custodies ops.DeviceCustodyList + if err := c.Client.List(ctx, &custodies, client.InNamespace(cfg.Namespace)); err != nil { + return 0, err + } + for _, custody := range custodies.Items { + if active := custody.Spec.ActiveOperation; active != nil { + referenced[types.UID(active.UID)] = true + } + if hold := custody.Spec.RecoveryHold; hold != nil { + referenced[types.UID(hold.UID)] = true + } + } + deleted := 0 + for _, kind := range c.Registry.Kinds() { + list := kind.NewList() + if err := c.Client.List(ctx, list, client.InNamespace(cfg.Namespace)); err != nil { + return deleted, err + } + for _, operation := range kind.Items(list) { + status := operation.OperationStatus() + if !status.Phase.Ended() || status.FinishedAt == nil || !status.FinishedAt.Time.Before(cutoff) || referenced[operation.GetUID()] { + continue + } + uid := operation.GetUID() + if err := c.Client.Delete(ctx, operation, client.Preconditions{UID: &uid}); err != nil && !apierrors.IsNotFound(err) { + return deleted, err + } + deleted++ + } + } + return deleted, nil +} diff --git a/internal/custody/rules.go b/internal/custody/rules.go new file mode 100644 index 00000000..4001f8a7 --- /dev/null +++ b/internal/custody/rules.go @@ -0,0 +1,150 @@ +package custody + +import ( + "bytes" + "errors" + "fmt" + "io" + "slices" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// CreatorClass is the requester class a row admits. +type CreatorClass string + +const ( + // CreatorMetalProvider is the Fleet provider for Metal. + CreatorMetalProvider CreatorClass = "MetalProvider" + // CreatorReleaseController is the release controller. + CreatorReleaseController CreatorClass = "ReleaseController" + // CreatorStaff is every creator that is not a configured service + // principal. IAM decides which staff may create which kind; the API + // server has already authorized the create. + CreatorStaff CreatorClass = "Staff" +) + +// AuthorityType is which authority field an operation sets. +type AuthorityType string + +const ( + AuthorityAllocation AuthorityType = "Allocation" + AuthorityService AuthorityType = "ServiceRequest" +) + +// HoldBehavior is how a row treats a recovery hold. +type HoldBehavior string + +const ( + // HoldSettles admits the operation under a hold only if its kind settles + // the held kind. This is the default. + HoldSettles HoldBehavior = "" + // HoldRequired admits the operation only while a hold exists. + HoldRequired HoldBehavior = "Required" + // HoldIgnored admits the operation whether or not a hold exists. + HoldIgnored HoldBehavior = "Ignored" +) + +// Rule is one row of the operations table in #174. +type Rule struct { + Kind string + Variant string + Creator CreatorClass + // Authority is the authority type the operation must set. + Authority AuthorityType + // Holders are the holders the row admits from. Empty admits any holder. + Holders []ops.HolderType + // Custody is the custody state the row admits from. Empty is Verified. + Custody ops.CustodyState + Hold HoldBehavior + // Queue rows wait in Pending while another operation runs. Staff rows + // never queue: admission refuses what cannot run now. + Queue bool +} + +func (r Rule) custodyState() ops.CustodyState { + if r.Custody == "" { + return ops.CustodyVerified + } + return r.Custody +} + +func (r Rule) admitsHolder(holder ops.HolderType) bool { + return len(r.Holders) == 0 || slices.Contains(r.Holders, holder) +} + +// Principal is one configured service identity. An empty UID matches any UID +// for the username. +type Principal struct { + Username string `json:"username"` + UID string `json:"uid,omitempty"` +} + +// Principals maps service creator classes to their identities. Staff is never +// configured: it is every other creator. +type Principals map[CreatorClass][]Principal + +// Validate rejects a configuration that names Staff, an empty username, or +// one identity in two classes. +func (p Principals) Validate() error { + seen := map[string]CreatorClass{} + for class, principals := range p { + if class == CreatorStaff || class == "" { + return errors.New("staff is every unconfigured creator and cannot be configured") + } + for _, principal := range principals { + if principal.Username == "" { + return fmt.Errorf("%s: a principal needs a username", class) + } + if other, ok := seen[principal.Username]; ok && other != class { + return fmt.Errorf("%s is configured for both %s and %s", principal.Username, other, class) + } + seen[principal.Username] = class + } + } + return nil +} + +// Classify returns the class of an authenticated creator. +func (p Principals) Classify(creator ops.Creator) CreatorClass { + for class, principals := range p { + for _, principal := range principals { + if principal.Username == creator.Username && (principal.UID == "" || principal.UID == creator.UID) { + return class + } + } + } + return CreatorStaff +} + +func authorityType(authority ops.Authority) (AuthorityType, bool) { + switch { + case authority.AllocationRef != nil && authority.ServiceRequest == nil: + return AuthorityAllocation, true + case authority.ServiceRequest != nil && authority.AllocationRef == nil: + return AuthorityService, true + } + return "", false +} + +// matchRows returns the rows for the operation's kind, variant, creator class +// and authority type. +func (r *Registry) matchRows(kind *Kind, operation ops.Operation, class CreatorClass) []Rule { + authority, ok := authorityType(operation.Envelope().Authority) + if !ok { + return nil + } + variant := "" + if kind.Variant != nil { + variant = kind.Variant(operation) + } + var out []Rule + for _, rule := range r.rules { + if rule.Kind == kind.GVK.Kind && (rule.Variant == "" || rule.Variant == variant) && rule.Creator == class && rule.Authority == authority { + out = append(out, rule) + } + } + return out +} + +func bytesReader(data []byte) io.Reader { return bytes.NewReader(data) } diff --git a/internal/custody/seams_test.go b/internal/custody/seams_test.go new file mode 100644 index 00000000..0a7151ab --- /dev/null +++ b/internal/custody/seams_test.go @@ -0,0 +1,268 @@ +package custody + +import ( + "context" + "fmt" + "reflect" + "slices" + "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" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func TestRegistryRejectsIncompleteKindsAndRows(t *testing.T) { + registry := NewRegistry() + staff := testKinds()[0] + if err := registry.Register(staff); err != nil { + t.Fatal(err) + } + if err := registry.Register(staff); err == nil { + t.Fatal("a kind registered twice") + } + noDeadline := testKinds()[1] + noDeadline.Deadline = 0 + if err := registry.Register(noDeadline); err == nil { + t.Fatal("a kind without a deadline registered") + } + noName := testKinds()[1] + noName.Name = nil + if err := registry.Register(noName); err == nil { + t.Fatal("a deterministic kind without a name rule registered") + } + inert := testKinds()[1] + inert.Effectful = false + if err := registry.Register(inert); err == nil { + t.Fatal("a non-effectful kind without Apply registered") + } + if err := registry.AddRule(Rule{Kind: testStaffKind, Creator: CreatorStaff, Authority: AuthorityService, Queue: true}); err == nil { + t.Fatal("a staff row that queues was added") + } + if err := registry.AddRule(Rule{Kind: "Unregistered", Creator: CreatorStaff, Authority: AuthorityService}); err == nil { + t.Fatal("a row for an unregistered kind was added") + } +} + +// 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. +func TestAddingRowsLeavesExistingRowsAlone(t *testing.T) { + base, err := DefaultRegistry() + if err != nil { + t.Fatal(err) + } + extended := testRegistry(t) + device := &inventory.Device{} + for _, kind := range base.Kinds() { + for _, class := range []CreatorClass{CreatorMetalProvider, CreatorReleaseController, CreatorStaff, "Other"} { + for _, authority := range []ops.Authority{allocated("alloc-a"), service("r")} { + for _, decision := range []ops.RecoveryDecision{ops.DecisionSettle, ops.DecisionRetry, ops.DecisionRetire, ops.DecisionResolve} { + operation := kind.New() + *operation.Envelope() = envelope(device, "u", authority) + if recovery, ok := operation.(*ops.DeviceRecovery); ok { + recovery.Spec.Decision = decision + } + before := base.matchRows(kind, operation, class) + after := extended.matchRows(extended.Kind(kind.GVK.Kind), operation, class) + if !reflect.DeepEqual(before, after) { + t.Fatalf("%s %s %+v: rows changed from %v to %v", kind.GVK.Kind, class, authority, before, after) + } + } + } + } + } +} + +func TestPrincipals(t *testing.T) { + principals := Principals{CreatorMetalProvider: {{Username: "svc-a", UID: "uid-a"}}, CreatorReleaseController: {{Username: "svc-b"}}} + if err := principals.Validate(); err != nil { + t.Fatal(err) + } + cases := map[ops.Creator]CreatorClass{ + {Username: "svc-a", UID: "uid-a"}: CreatorMetalProvider, + {Username: "svc-a", UID: "forged"}: CreatorStaff, + {Username: "svc-b", UID: "any"}: CreatorReleaseController, + {Username: "person", UID: "person"}: CreatorStaff, + } + for creator, want := range cases { + if got := principals.Classify(creator); got != want { + t.Fatalf("%+v classified %s, want %s", creator, got, want) + } + } + for _, bad := range []Principals{{CreatorStaff: {{Username: "x"}}}, {CreatorMetalProvider: {{}}}, {CreatorMetalProvider: {{Username: "x"}}, CreatorReleaseController: {{Username: "x"}}}} { + if bad.Validate() == nil { + t.Fatalf("%v validated", bad) + } + } +} + +func TestCandidatesOrderOldestFirstWithADeterministicTieBreak(t *testing.T) { + registry := testRegistry(t) + at := func(seconds int) metav1.Time { return metav1.NewTime(time.Unix(1_700_000_000+int64(seconds), 0)) } + newCandidate := func(kind, name, uid string, created metav1.Time) candidate { + k := registry.Kind(kind) + operation := k.New() + operation.SetName(name) + operation.SetUID(typesUID(uid)) + operation.SetCreationTimestamp(created) + return candidate{operation: operation, kind: k} + } + list := []candidate{ + newCandidate("DeviceWipe", "b", "2", at(1)), + newCandidate("DeviceInstallation", "z", "9", at(1)), + newCandidate("DeviceWipe", "b", "1", at(1)), + newCandidate("DeviceWipe", "a", "3", at(1)), + newCandidate("DeviceInstallation", "y", "8", at(0)), + } + for range 5 { + shuffled := slices.Clone(list) + slices.Reverse(shuffled) + orderCandidates(shuffled) + var got []string + for _, c := range shuffled { + got = append(got, fmt.Sprintf("%s/%s/%s", c.kind.GVK.Kind, c.operation.GetName(), c.operation.GetUID())) + } + want := []string{"DeviceInstallation/y/8", "DeviceInstallation/z/9", "DeviceWipe/a/3", "DeviceWipe/b/1", "DeviceWipe/b/2"} + if !slices.Equal(got, want) { + t.Fatalf("order = %v", got) + } + } +} + +func TestEvidenceIsTypedAndBounded(t *testing.T) { + kind := DeviceWipeKind() + if _, err := kind.Evidence([]byte(`{"wipedDisks":["disk-0"]}`)); err != nil { + t.Fatal(err) + } + for _, bad := range []string{`{"bmcResponse":"raw"}`, `{"wipedDisks":["disk-0"]} {}`, `{"steps":[{"name":""}]}`, fmt.Sprintf(`{"policyDigest":"%0*d"}`, evidenceLimit, 0)} { + if _, err := kind.Evidence([]byte(bad)); err == nil { + t.Fatalf("accepted %s", bad) + } + } +} + +func TestCapacityProjection(t *testing.T) { + plan := "sha256:plan" + commissionings := map[string]*CommissioningEvidence{"none": nil, "old plan": {PlanDigest: "sha256:old", HealthCurrent: true}, "unhealthy": {PlanDigest: plan}, "current": {PlanDigest: plan, HealthCurrent: true}} + hold := &ops.RecoveryHold{Reason: "x"} + custodies := map[string]*ops.DeviceCustodySpec{ + "missing": nil, + "unverified": {State: ops.CustodyUnverified, Holder: ops.Holder{Type: ops.HolderNone}}, + "held": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderNone}, RecoveryHold: hold}, + "allocated": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderAllocation}}, + "releasing": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderRelease}}, + "service": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderService}}, + "retired": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderRetired}}, + "free": {State: ops.CustodyVerified, Holder: ops.Holder{Type: ops.HolderNone}}, + } + available := 0 + for commissioningName, commissioning := range commissionings { + for custodyName, custody := range custodies { + for _, discovery := range []bool{false, true} { + for _, enabled := range []bool{false, true} { + conditions := ProjectCapacity(CapacityInputs{Generation: 3, Commissioning: commissioning, CurrentPlanDigest: plan, DiscoveryCurrent: discovery, Custody: custody, AllocationPolicyEnabled: enabled}) + prepared := conditions[0].Status == metav1.ConditionTrue + healthy := conditions[1].Status == metav1.ConditionTrue + free := conditions[2].Status == metav1.ConditionTrue + if prepared != (commissioningName == "current" || commissioningName == "unhealthy") { + t.Fatalf("%s: Prepared = %v", commissioningName, prepared) + } + if healthy != (commissioningName != "none" && commissioning.HealthCurrent && discovery) { + t.Fatalf("%s discovery %v: Healthy = %v", commissioningName, discovery, healthy) + } + want := prepared && healthy && custodyName == "free" && enabled + if free != want { + t.Fatalf("%s %s discovery %v enabled %v: Available = %v (%s)", commissioningName, custodyName, discovery, enabled, free, conditions[2].Reason) + } + if free { + available++ + } + for _, condition := range conditions { + if condition.ObservedGeneration != 3 || condition.Reason == "" { + t.Fatalf("condition = %+v", condition) + } + } + } + } + } + } + if available != 1 { + t.Fatalf("%d combinations are Available, want exactly one", available) + } +} + +func TestCRDRules(t *testing.T) { + e := startEnv(t) + ctx := context.Background() + device := e.verified("server-example-600", uid(600), fmt.Sprintf("%064x", 600)) + requireInvalid := func(t *testing.T, err error) { + t.Helper() + if !apierrors.IsInvalid(err) { + t.Fatalf("want Invalid, got %v", err) + } + } + t.Run("operation spec is immutable", func(t *testing.T) { + operation := e.staffOp(device, "a") + operation.Spec.Input = "b" + requireInvalid(t, e.admin.Update(ctx, operation)) + }) + t.Run("authority is exactly one of allocationRef and serviceRequest", func(t *testing.T) { + both := ops.Authority{AllocationRef: &ops.LocalReference{Name: "a"}, ServiceRequest: &ops.ServiceRequest{Reason: "r"}} + requireInvalid(t, e.admin.Create(ctx, &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: "x-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, both), Input: "a"}})) + requireInvalid(t, e.admin.Create(ctx, &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: "x-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, ops.Authority{}), Input: "a"}})) + }) + t.Run("operation phases move forward only and ended phases are final", func(t *testing.T) { + operation := e.staffOp(device, "a") + write := func(phase ops.Phase) error { + if err := e.admin.Get(ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + t.Fatal(err) + } + operation.Status.Phase = phase + return e.admin.Status().Update(ctx, operation) + } + for _, phase := range []ops.Phase{ops.PhasePending, ops.PhaseAdmitted, ops.PhaseVerifying} { + if err := write(phase); err != nil { + t.Fatal(err) + } + } + requireInvalid(t, write(ops.PhaseDispatched)) + requireInvalid(t, write(ops.PhasePending)) + if err := write(ops.PhaseOutcomeUnknown); err != nil { + t.Fatal(err) + } + requireInvalid(t, write(ops.PhaseSucceeded)) + requireInvalid(t, write("Invented")) + }) + t.Run("recovery inputs match the decision", func(t *testing.T) { + base := ops.DeviceRecoverySpec{OperationEnvelope: envelope(device, staffUser, service("r")), Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(time.Now()), Summary: "s"}} + for _, spec := range []func(ops.DeviceRecoverySpec) ops.DeviceRecoverySpec{ + func(s ops.DeviceRecoverySpec) ops.DeviceRecoverySpec { s.Decision = ops.DecisionSettle; return s }, + func(s ops.DeviceRecoverySpec) ops.DeviceRecoverySpec { s.Decision = ops.DecisionResolve; return s }, + func(s ops.DeviceRecoverySpec) ops.DeviceRecoverySpec { + s.Decision, s.Hold, s.DiskDisposal = ops.DecisionSettle, &ops.HeldOperationReference{Kind: "k", Name: "n"}, &ops.DiskDisposal{Method: ops.DisposalDestroyed, Reference: "r"} + return s + }, + } { + requireInvalid(t, e.admin.Create(ctx, &ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: "r-", Namespace: "default"}, Spec: spec(base)})) + } + }) + t.Run("custody fence never decreases, names its Device, and Retired is terminal", func(t *testing.T) { + custody := e.custody(device.Name) + custody.Spec.Fence-- + requireInvalid(t, e.admin.Update(ctx, custody)) + custody = e.custody(device.Name) + custody.Spec.DeviceRef.Name = "another" + requireInvalid(t, e.admin.Update(ctx, custody)) + requireInvalid(t, e.admin.Create(ctx, &ops.DeviceCustody{ObjectMeta: metav1.ObjectMeta{Name: "mismatch", Namespace: "default"}, Spec: ops.DeviceCustodySpec{DeviceRef: ops.DeviceReference{Name: "other", UID: "u"}, State: ops.CustodyUnverified, Holder: ops.Holder{Type: ops.HolderNone}}})) + custody = e.custody(device.Name) + custody.Spec.Holder = ops.Holder{Type: ops.HolderAllocation} + requireInvalid(t, e.admin.Update(ctx, custody)) + }) +} + +func typesUID(value string) types.UID { return types.UID(value) } diff --git a/internal/custody/testdata/crds/test-kinds.yaml b/internal/custody/testdata/crds/test-kinds.yaml new file mode 100644 index 00000000..ff3f95ed --- /dev/null +++ b/internal/custody/testdata/crds/test-kinds.yaml @@ -0,0 +1,353 @@ +# Test-only operation kinds. They prove the registry seams and are never +# shipped in a CRD root, a role or a deployment. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: deviceteststaffoperations.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceTestStaffOperation + listKind: DeviceTestStaffOperationList + plural: deviceteststaffoperations + singular: deviceteststaffoperation + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + - uid + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + required: + - name + - uid + 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 + input: + type: string + minLength: 1 + maxLength: 63 + required: + - creator + - deviceRef + - authority + - input + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + status: + type: object + properties: + 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 + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled''], ''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: devicetestprovideroperations.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceTestProviderOperation + listKind: DeviceTestProviderOperationList + plural: devicetestprovideroperations + singular: devicetestprovideroperation + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + - uid + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + required: + - name + - uid + 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 + input: + type: string + minLength: 1 + maxLength: 63 + required: + - creator + - deviceRef + - authority + - input + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + status: + type: object + properties: + 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 + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled''], ''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 diff --git a/internal/custody/testkinds_test.go b/internal/custody/testkinds_test.go new file mode 100644 index 00000000..5b8b29eb --- /dev/null +++ b/internal/custody/testkinds_test.go @@ -0,0 +1,171 @@ +package custody + +import ( + "context" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// The test-only kinds prove the four seams without editing the core. They +// are registered only here, and their CRDs live in testdata. + +// testSpec is the spec of both test kinds. +type testSpec struct { + ops.OperationEnvelope `json:",inline"` + Input string `json:"input"` +} + +// DeviceTestStaffOperation is a staff kind that acts from holder None. +type DeviceTestStaffOperation struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec testSpec `json:"spec"` + Status ops.OperationStatus `json:"status,omitempty"` +} + +type DeviceTestStaffOperationList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceTestStaffOperation `json:"items"` +} + +// DeviceTestProviderOperation is a provider kind that queues and supersedes, +// as power will. +type DeviceTestProviderOperation struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec testSpec `json:"spec"` + Status ops.OperationStatus `json:"status,omitempty"` +} + +type DeviceTestProviderOperationList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceTestProviderOperation `json:"items"` +} + +func (in *DeviceTestStaffOperation) Envelope() *ops.OperationEnvelope { + return &in.Spec.OperationEnvelope +} +func (in *DeviceTestStaffOperation) OperationStatus() *ops.OperationStatus { return &in.Status } +func (in *DeviceTestProviderOperation) Envelope() *ops.OperationEnvelope { + return &in.Spec.OperationEnvelope +} +func (in *DeviceTestProviderOperation) OperationStatus() *ops.OperationStatus { return &in.Status } +func (in *DeviceTestStaffOperation) DeepCopyObject() runtime.Object { return copyOf(in) } +func (in *DeviceTestStaffOperationList) DeepCopyObject() runtime.Object { return copyOf(in) } +func (in *DeviceTestProviderOperation) DeepCopyObject() runtime.Object { return copyOf(in) } +func (in *DeviceTestProviderOperationList) DeepCopyObject() runtime.Object { return copyOf(in) } + +func addTestKinds(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(ops.GroupVersion, &DeviceTestStaffOperation{}, &DeviceTestStaffOperationList{}, &DeviceTestProviderOperation{}, &DeviceTestProviderOperationList{}) + return nil +} + +const ( + testStaffKind = "DeviceTestStaffOperation" + testProviderKind = "DeviceTestProviderOperation" + reasonTestRefuse = "TestRefused" + testDeadline = 10 * time.Minute +) + +// testEvidence is the test kinds' typed result evidence. +type testEvidence struct { + Before string `json:"before,omitempty"` + After string `json:"after,omitempty"` +} + +func testKinds() []Kind { + check := func(_ context.Context, admission *Admission) *Refusal { + if admission.Operation.(interface{ input() string }).input() == "refuse" { + return refuse(reasonTestRefuse, "the test kind refuses this input") + } + return nil + } + evidence := StrictEvidence(256, func(*testEvidence) error { return nil }) + staff := Kind{ + GVK: ops.GroupVersion.WithKind(testStaffKind), + New: func() ops.Operation { return &DeviceTestStaffOperation{} }, + NewList: func() client.ObjectList { return &DeviceTestStaffOperationList{} }, + Items: func(list client.ObjectList) []ops.Operation { return items(list.(*DeviceTestStaffOperationList).Items) }, + Digest: func(operation ops.Operation) (string, error) { + return SpecDigest(operation.(*DeviceTestStaffOperation).Spec) + }, + Naming: GeneratedName, + Deadline: testDeadline, + Effectful: true, + Check: check, + Settles: []SettleRule{{Held: testStaffKind}}, + Evidence: evidence, + // Seam 4: a hold of this kind settles with recovery evidence observed + // after the operation ended, as power's discovery read will. + RecoverySettle: func(_ context.Context, settle *RecoverySettleContext) *Refusal { + if !settle.Recovery.Spec.Evidence.ObservedAt.After(settle.Hold.Since.Time) || settle.Recovery.Spec.Evidence.Data["state"] == "" { + return refuse("EvidenceNotCurrent", "the evidence must be a state observed after the operation ended") + } + return nil + }, + } + provider := Kind{ + GVK: ops.GroupVersion.WithKind(testProviderKind), + New: func() ops.Operation { return &DeviceTestProviderOperation{} }, + NewList: func() client.ObjectList { return &DeviceTestProviderOperationList{} }, + Items: func(list client.ObjectList) []ops.Operation { + return items(list.(*DeviceTestProviderOperationList).Items) + }, + Digest: func(operation ops.Operation) (string, error) { + return SpecDigest(operation.(*DeviceTestProviderOperation).Spec) + }, + Naming: DeterministicName, + Name: func(operation ops.Operation) string { + return allocationName(operation) + "-test-" + operation.(*DeviceTestProviderOperation).Spec.Input + }, + Deadline: testDeadline, + Effectful: true, + Supersedes: true, + Check: check, + Settles: []SettleRule{{Held: testProviderKind}}, + Evidence: evidence, + } + return []Kind{staff, provider} +} + +func (in *DeviceTestStaffOperation) input() string { return in.Spec.Input } +func (in *DeviceTestProviderOperation) input() string { return in.Spec.Input } + +func testRules() []Rule { + return []Rule{ + {Kind: testStaffKind, Creator: CreatorStaff, Authority: AuthorityService, Holders: []ops.HolderType{ops.HolderNone}}, + {Kind: testProviderKind, Creator: CreatorMetalProvider, Authority: AuthorityAllocation, Holders: []ops.HolderType{ops.HolderAllocation}, Queue: true}, + } +} + +// testRegistry is the default registry plus the test kinds and their rows. +func testRegistry(t interface{ Fatal(...any) }) *Registry { + registry, err := DefaultRegistry() + if err != nil { + t.Fatal(err) + } + for _, kind := range testKinds() { + if err := registry.Register(kind); err != nil { + t.Fatal(err) + } + } + for _, rule := range testRules() { + if err := registry.AddRule(rule); err != nil { + t.Fatal(err) + } + } + return registry +} + +func copyOf[T any](in *T) *T { + out := new(T) + data, _ := jsonMarshal(in) + _ = jsonUnmarshal(data, out) + return out +} From b0222a096c920b70850f613c633f9e35ae13118f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 18:09:36 -0600 Subject: [PATCH 03/19] feat(custody): Record who created each operation Add the validating webhook that Milo's root API server calls. It admits a create only when spec.creator is the authenticated caller, and an update only when the creator is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../custody/creatorwebhook/envtest_test.go | 143 ++++++++++++++++++ internal/custody/creatorwebhook/handler.go | 100 ++++++++++++ .../custody/creatorwebhook/handler_test.go | 87 +++++++++++ 3 files changed, 330 insertions(+) create mode 100644 internal/custody/creatorwebhook/envtest_test.go create mode 100644 internal/custody/creatorwebhook/handler.go create mode 100644 internal/custody/creatorwebhook/handler_test.go diff --git a/internal/custody/creatorwebhook/envtest_test.go b/internal/custody/creatorwebhook/envtest_test.go new file mode 100644 index 00000000..4dac53a5 --- /dev/null +++ b/internal/custody/creatorwebhook/envtest_test.go @@ -0,0 +1,143 @@ +package creatorwebhook + +import ( + "context" + "encoding/pem" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/go-logr/logr" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + ctrllog "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "sigs.k8s.io/yaml" +) + +// TestCreatorAgainstAPIServer serves the handler behind the packaged webhook +// configuration. The API server passes the original caller to the webhook, +// as Milo's root API server does, so the stored creator is the caller's. +func TestCreatorAgainstAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctrllog.SetLogger(logr.Discard()) + root := filepath.Join("..", "..", "..") + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(root, "config", "components", "device-operations", "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = environment.Stop() }) + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{ops.AddToScheme, admissionregistrationv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + admin, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + server := httptest.NewTLSServer(&admission.Webhook{Handler: &Handler{Projects: []string{"provider-example"}, Resources: resources}}) + t.Cleanup(server.Close) + data, err := os.ReadFile(filepath.Join(root, "config", "components", "device-operations", "webhook.yaml")) + if err != nil { + t.Fatal(err) + } + webhooks := &admissionregistrationv1.ValidatingWebhookConfiguration{} + if err := yaml.UnmarshalStrict(data, webhooks); err != nil { + t.Fatal(err) + } + if len(webhooks.Webhooks) != 1 || !strings.HasSuffix(*webhooks.Webhooks[0].ClientConfig.URL, Path) { + t.Fatalf("the packaged webhook must call %s", Path) + } + url := server.URL + Path + for index := range webhooks.Webhooks { + webhooks.Webhooks[index].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw})} + } + if err := admin.Create(context.Background(), webhooks); err != nil { + t.Fatal(err) + } + actor := func(name, project string) client.Client { + cfg := rest.CopyConfig(config) + cfg.Impersonate = rest.ImpersonationConfig{UserName: name, UID: name + "-uid", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {project}}} + api, err := client.New(cfg, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + return api + } + recovery := func(creator ops.Creator) *ops.DeviceRecovery { + return &ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: "recovery-", Namespace: "default"}, Spec: ops.DeviceRecoverySpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: creator, DeviceRef: ops.DeviceReference{Name: "server-example-001", UID: "00000000-0000-4000-8000-000000000001"}, Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "settle"}}}, + Decision: ops.DecisionSettle, Hold: &ops.HeldOperationReference{Kind: "DeviceWipe", Name: "alloc-example-wipe-1", Fence: 3}, + Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(time.Now()), Summary: "observed"}, + }} + } + staff := actor("staff-example", "provider-example") + ctx := context.Background() + // The webhook may take a moment to engage. + deadline := time.Now().Add(15 * time.Second) + for !apierrors.IsForbidden(staff.Create(ctx, recovery(ops.Creator{Username: "probe", UID: "probe"}), client.DryRunAll)) { + if time.Now().After(deadline) { + t.Fatal("creator webhook did not engage") + } + time.Sleep(50 * time.Millisecond) + } + + t.Run("the stored creator is the original caller", func(t *testing.T) { + created := recovery(ops.Creator{Username: "staff-example", UID: "staff-example-uid"}) + if err := staff.Create(ctx, created); err != nil { + t.Fatal(err) + } + stored := &ops.DeviceRecovery{} + if err := admin.Get(ctx, client.ObjectKeyFromObject(created), stored); err != nil { + t.Fatal(err) + } + if stored.Spec.Creator != (ops.Creator{Username: "staff-example", UID: "staff-example-uid"}) { + t.Fatalf("creator = %+v", stored.Spec.Creator) + } + // The coordinator writes status; the webhook does not govern it. + stored.Status = ops.OperationStatus{Phase: ops.PhaseFailed, Reason: "Test"} + if err := admin.Status().Update(ctx, stored); err != nil { + t.Fatalf("status write: %v", err) + } + // Spec, creator included, is immutable. + stored.Spec.Creator.Username = "someone-else" + if err := staff.Update(ctx, stored); !apierrors.IsForbidden(err) && !apierrors.IsInvalid(err) { + t.Fatalf("creator changed: %v", err) + } + }) + t.Run("a client-supplied creator other than the caller is refused", func(t *testing.T) { + for _, creator := range []ops.Creator{{Username: "other-staff", UID: "other-staff-uid"}, {Username: "staff-example", UID: "forged"}} { + if err := staff.Create(ctx, recovery(creator)); !apierrors.IsForbidden(err) { + t.Fatalf("creator %+v: %v", creator, err) + } + } + // Another caller cannot claim this caller's identity either. + if err := actor("other-staff", "provider-example").Create(ctx, recovery(ops.Creator{Username: "staff-example", UID: "staff-example-uid"})); !apierrors.IsForbidden(err) { + t.Fatalf("impersonated creator: %v", err) + } + }) + t.Run("a caller outside the provider projects is refused", func(t *testing.T) { + if err := actor("staff-example", "consumer-example").Create(ctx, recovery(ops.Creator{Username: "staff-example", UID: "staff-example-uid"})); !apierrors.IsForbidden(err) { + t.Fatalf("consumer project: %v", err) + } + // The API server's own identity carries no project and is refused. + if err := admin.Create(ctx, recovery(ops.Creator{Username: "admin", UID: "admin"})); !apierrors.IsForbidden(err) { + t.Fatalf("root identity: %v", err) + } + }) +} diff --git a/internal/custody/creatorwebhook/handler.go b/internal/custody/creatorwebhook/handler.go new file mode 100644 index 00000000..28c8bee3 --- /dev/null +++ b/internal/custody/creatorwebhook/handler.go @@ -0,0 +1,100 @@ +// Package creatorwebhook is the validating webhook that keeps a Device +// operation's spec.creator equal to the authenticated caller who created it. +// +// Milo's root API server calls it, because Milo does not evaluate admission +// policies stored in a project. The request's UserInfo is the original +// caller, as Milo's routing establishes it, with the project in its extras; +// the webhook compares spec.creator with that identity and never substitutes +// its own. It reads nothing, keeps no state and holds no credentials: the API +// server has already authorized the caller to create the kind, and IAM +// decides which caller may create which kind. +package creatorwebhook + +import ( + "context" + "encoding/json" + "errors" + "slices" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// Path is where the handler is served. +const Path = "/validate-operation-creator" + +// Handler admits creates whose creator is the caller and updates that leave +// the creator unchanged. +type Handler struct { + // Projects is the provider scope. Device operations exist only there. + Projects []string + // Resources are the operation plurals the handler governs. + Resources []string +} + +type envelope struct { + Spec struct { + Creator *ops.Creator `json:"creator"` + } `json:"spec"` +} + +func creatorOf(raw []byte) (*ops.Creator, error) { + var object envelope + if err := json.Unmarshal(raw, &object); err != nil { + return nil, err + } + return object.Spec.Creator, nil +} + +// project returns the caller's Milo project. Milo sets these extras when it +// routes a request through a project control plane. +func project(actor authenticationv1.UserInfo) (string, error) { + for key, expected := range map[string]string{iam.ParentKindExtraKey: "Project", iam.ParentAPIGroupExtraKey: "resourcemanager.miloapis.com"} { + if values := actor.Extra[key]; len(values) != 1 || values[0] != expected { + return "", errors.New("an authenticated Milo project context is required") + } + } + values := actor.Extra[iam.ParentNameExtraKey] + if len(values) != 1 || values[0] == "" || actor.Username == "" || actor.UID == "" { + return "", errors.New("an authenticated caller and project are required") + } + return values[0], nil +} + +func (h *Handler) Handle(_ context.Context, request admission.Request) admission.Response { + if request.Resource.Group != ops.GroupVersion.Group || !slices.Contains(h.Resources, request.Resource.Resource) || request.SubResource != "" { + return admission.Denied("unsupported operation creator admission request") + } + name, err := project(request.UserInfo) + if err != nil { + return admission.Denied(err.Error()) + } + if !slices.Contains(h.Projects, name) { + return admission.Denied("Device operations exist only in the provider projects") + } + switch request.Operation { + case admissionv1.Create: + creator, err := creatorOf(request.Object.Raw) + if err != nil { + return admission.Denied("the operation could not be decoded") + } + if creator == nil || creator.Username != request.UserInfo.Username || creator.UID != request.UserInfo.UID { + return admission.Denied("spec.creator must be the authenticated caller's username and UID") + } + return admission.Allowed("the creator is the caller") + case admissionv1.Update: + creator, err := creatorOf(request.Object.Raw) + if err != nil { + return admission.Denied("the operation could not be decoded") + } + previous, err := creatorOf(request.OldObject.Raw) + if err != nil || previous == nil || creator == nil || *creator != *previous { + return admission.Denied("spec.creator cannot change") + } + return admission.Allowed("the creator is unchanged") + } + return admission.Denied("unsupported operation creator admission request") +} diff --git a/internal/custody/creatorwebhook/handler_test.go b/internal/custody/creatorwebhook/handler_test.go new file mode 100644 index 00000000..a064d5ad --- /dev/null +++ b/internal/custody/creatorwebhook/handler_test.go @@ -0,0 +1,87 @@ +package creatorwebhook + +import ( + "context" + "encoding/json" + "testing" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +var resources = []string{"deviceinstallations", "devicewipes", "devicerecoveries"} + +func caller(name, project string) authenticationv1.UserInfo { + return authenticationv1.UserInfo{Username: name, UID: name + "-uid", Extra: map[string]authenticationv1.ExtraValue{ + iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {project}, + }} +} + +func object(t *testing.T, creator *ops.Creator) runtime.RawExtension { + t.Helper() + recovery := ops.DeviceRecovery{Spec: ops.DeviceRecoverySpec{Decision: ops.DecisionSettle}} + if creator != nil { + recovery.Spec.Creator = *creator + } + data, err := json.Marshal(recovery) + if err != nil { + t.Fatal(err) + } + if creator == nil { + var raw map[string]any + _ = json.Unmarshal(data, &raw) + delete(raw["spec"].(map[string]any), "creator") + data, _ = json.Marshal(raw) + } + return runtime.RawExtension{Raw: data} +} + +func request(operation admissionv1.Operation, user authenticationv1.UserInfo, newObject, oldObject runtime.RawExtension) admission.Request { + return admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{ + Operation: operation, UserInfo: user, Object: newObject, OldObject: oldObject, + Resource: metav1.GroupVersionResource{Group: ops.GroupVersion.Group, Version: "v1alpha1", Resource: "devicerecoveries"}, + }} +} + +func TestHandler(t *testing.T) { + handler := &Handler{Projects: []string{"provider-example"}, Resources: resources} + staff := caller("staff-example", "provider-example") + self := &ops.Creator{Username: "staff-example", UID: "staff-example-uid"} + cases := map[string]struct { + request admission.Request + allowed bool + }{ + "a create naming the caller": {request(admissionv1.Create, staff, object(t, self), runtime.RawExtension{}), true}, + "a create naming someone else": {request(admissionv1.Create, staff, object(t, &ops.Creator{Username: "other", UID: "other-uid"}), runtime.RawExtension{}), false}, + "a create with the caller's name only": {request(admissionv1.Create, staff, object(t, &ops.Creator{Username: "staff-example", UID: "forged"}), runtime.RawExtension{}), false}, + "a create without a creator": {request(admissionv1.Create, staff, object(t, nil), runtime.RawExtension{}), false}, + "a caller outside a project": {request(admissionv1.Create, authenticationv1.UserInfo{Username: "staff-example", UID: "staff-example-uid"}, object(t, self), runtime.RawExtension{}), false}, + "a caller in another project": {request(admissionv1.Create, caller("staff-example", "consumer-example"), object(t, self), runtime.RawExtension{}), false}, + "an update keeping the creator": {request(admissionv1.Update, caller("coordinator", "provider-example"), object(t, self), object(t, self)), true}, + "an update changing the creator": {request(admissionv1.Update, staff, object(t, &ops.Creator{Username: "x", UID: "y"}), object(t, self)), false}, + "a delete": {request(admissionv1.Delete, staff, runtime.RawExtension{}, object(t, self)), false}, + } + for name, test := range cases { + t.Run(name, func(t *testing.T) { + if response := handler.Handle(context.Background(), test.request); response.Allowed != test.allowed { + t.Fatalf("allowed = %v (%v)", response.Allowed, response.Result) + } + }) + } + t.Run("ungoverned resources and subresources are denied", func(t *testing.T) { + other := request(admissionv1.Create, staff, object(t, self), runtime.RawExtension{}) + other.Resource.Resource = "devicecustodies" + status := request(admissionv1.Update, staff, object(t, self), object(t, self)) + status.SubResource = "status" + for _, request := range []admission.Request{other, status} { + if handler.Handle(context.Background(), request).Allowed { + t.Fatal("allowed") + } + } + }) +} From 59045030c3ead3820cb3c78fa3116258b6712465 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 18:09:36 -0600 Subject: [PATCH 04/19] docs: Record the Device custody foundation Mark Increment A implemented and inert, record its decisions and the points that need a person, and describe how to add an operation kind. Co-Authored-By: Claude Opus 5.5 --- config/README.md | 5 + docs/architecture/design.md | 1 + docs/development/README.md | 8 + docs/development/device-custody.md | 307 +++++++++++++++++++++++++++++ docs/development/roadmap.md | 12 ++ test/acceptance/coverage.md | 24 +++ 6 files changed, 357 insertions(+) create mode 100644 docs/development/device-custody.md diff --git a/config/README.md b/config/README.md index f28af822..77bd2da6 100644 --- a/config/README.md +++ b/config/README.md @@ -61,6 +61,11 @@ live in the provider project. `config/inventory` renders the CRDs alone for a 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. It is implemented and +inert: no root includes it yet. See [device custody](../docs/development/device-custody.md). + `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, unprivileged. It is in no root here; the deploying repository applies it with diff --git a/docs/architecture/design.md b/docs/architecture/design.md index 7ee559f7..0dd8963b 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -11,6 +11,7 @@ replacement for the source proposals or a claim that their APIs exist. | --- | --- | --- | | [infra #5782: Fleet infrastructure management service](https://github.com/datum-cloud/infra/pull/5782) | `51781e2456367be82281e1443ca56d0686311133` | Service architecture, inventory, shared allocation, capacity publication, provisioning, OS configuration, and cluster lifecycle. Open draft at review time. | | [infra #7705: Node services and consumer pool gates](https://github.com/datum-cloud/infra/pull/7705) | `a712d2d3aaddcdc4d81c09d7f4cdd139bef06631` | Node services, consumer-owned pool sizing and gates, procurement guardrails, and regional independence. Open; targets the #5782 proposal branch. | +| [fleet #174: Device custody and operations](https://github.com/datum-cloud/fleet/pull/174) | `3907eec183616cfc6f08580d32447cd2887442a8` | Per-Device custody, one operation envelope, admission by conditional custody update, site fencing, recovery holds and custody rebuild. Open draft; [implementation status](../development/device-custody.md). | Read the [core proposal at its reviewed revision][proposal] and the [extension at its reviewed revision][extension]. The latter includes the core diff --git a/docs/development/README.md b/docs/development/README.md index 33eccf8b..200d034a 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -50,6 +50,14 @@ physical BMC or server, and the production manager does not use it. Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. +[Device custody and operations](device-custody.md) Increment A is implemented +and inert: the `DeviceCustody` and Device operation kinds, the creator webhook, +the kind registry and admission rule table, and the coordinator that admits, +fences, holds, recovers and rebuilds custody. Tests against a real API server +verify it. No deployment root, manager or staging overlay includes it, and the +Secret-backed lifecycle is unchanged. Site execution, the cutover and the +end-to-end failure scenarios are proposed. + ## API group naming The additive [shared hardware catalog](hardware-catalog.md) implements diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md new file mode 100644 index 00000000..6ccfc2a7 --- /dev/null +++ b/docs/development/device-custody.md @@ -0,0 +1,307 @@ +# Device custody and operations + +[Documentation overview](../README.md) · [Implementation status](README.md) + +This page records how Fleet implements the [device custody and operations +proposal](https://github.com/datum-cloud/fleet/pull/174) (#174, pinned at +`3907eec`). The proposal's API names are provisional. Each piece below is +marked **implemented and verified**, **implemented and inert**, or +**proposed**. + +## Status + +| Increment | What it covers | Status | +| --- | --- | --- | +| A: control-plane foundation | API types and CRDs for `DeviceCustody`, `DeviceInstallation`, `DeviceWipe` and `DeviceRecovery`; CEL rules; IAM resources and roles; the creator webhook; the kind registry and admission rule table; the coordinator's custody reconciler, admission, results, recovery, rebuild and retention; the capacity projector | **Implemented and inert.** Verified with unit tests and with tests against a real API server. No deployment root, manager, or staging overlay includes it. The existing Secret-backed lifecycle is unchanged. | +| B: site execution | Per-Device fence store and journal, older-worker stop, deadlines, fenced results, per-Device credentials, pinned TLS, the new handoff payload | **Proposed** | +| C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the projector as the only condition writer, removal of the private Secret records | **Proposed.** Blocked on the decision about where an allocation's private facts live. | +| D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests | **Proposed** | + +## What Increment A adds + +- **Kinds.** `DeviceCustody` and three 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 not included by any root. A test fails if one includes it. +- **Custody.** One `DeviceCustody` per Device, with the same name. Its fields + are in `spec`, like a Lease, and it has no status. The finalizer + `fleet.datumapis.com/custody` stays until the holder is `Retired`. CEL keeps + the fence from decreasing, keeps `Retired` terminal, and requires the active + operation to carry the current fence. +- **Operations.** Every kind starts with one envelope: `creator`, `deviceRef` + (name and UID) and `authority` (exactly one of `allocationRef` and + `serviceRequest`). The spec is immutable after create. Status phases move + forward only, and an ended phase is final. +- **The coordinator** (`internal/custody`) is the only writer of custody and of + operation status. Every custody change is one update that carries the + resourceVersion just read. On a conflict it reads again and decides again. +- **The creator webhook** (`internal/custody/creatorwebhook`) admits a create + only when `spec.creator` is the authenticated caller's username and UID, and + an update only when the creator is unchanged. +- **The capacity projector** is a pure function that derives `Prepared`, + `Healthy` and `Available`. Nothing calls it outside tests. + +Creating or importing a Device creates `Unverified` custody. That sends +nothing to a BMC and makes no capacity `Available`. + +## Implementation decisions + +Each decision lists the open point from the implementation brief it settles. + +### Who created an operation (O14) + +- The client sets `spec.creator` to its own username and UID. The webhook + rejects any other value and any change. That is how #174 at `3907eec` reads, + so "clients cannot set the creator" becomes "clients can set only + themselves". CEL also makes the creator immutable, as part of the spec. +- Milo's root API server calls the webhook, because Milo v0.32.5 does not + evaluate admission policies stored in a project. The webhook reads the + original caller from the admission request, with the project in Milo's + extras, and refuses a caller outside the configured provider projects. It + reads nothing else and keeps no state. +- The webhook will be served by the existing `fleet-registration` server on + its own path, `/validate-operation-creator`, when Increment C wires it. That + server already has the API-server client CA and the Milo root route, and the + new handler needs no project reads. In Increment A the handler exists and is + tested, and the server does not serve it yet. +- The coordinator classifies a creator by configuration. Each service class, + such as the Fleet provider for Metal or the release controller, maps to + configured principals by username and, optionally, UID. Any other creator is + staff. IAM decides which staff may create which kind, and the API server has + already authorized the create. No identity is hard-coded. + +### Admission + +- **The rule table is data.** Each row names a kind, an optional variant (such + as a recovery decision), a creator class, an authority type, the holders and + custody state it admits from, how it treats a recovery hold, and whether it + queues. A kind's rows are matched only against operations of that kind, so + adding a row never changes how another row is evaluated. +- **Queueing.** Provider and release rows queue. They wait in `Pending` while + another operation runs, while custody is `Unverified`, or while discovery is + not current. All three can clear on their own. Staff rows never queue: those + conditions end a staff operation `Failed`. +- **Phases for refusals (O5).** A refusal ends `Failed` with a reason, and + nothing is sent. Expired, superseded and no-longer-matching operations end + `Cancelled`. A `Pending` operation whose holder no longer matches is + `Cancelled`. One that never matched is `Failed`. The shared reasons are + `Unverified`, `NoMatchingRule`, `HolderMismatch`, `OperationActive`, + `IdentityMismatch`, `IdentityNotCurrent`, `SharedPublicKey`, `RecoveryHold`, + `NameMismatch`, `Expired`, `Superseded`, `Withdrawn`, `DeadlineExceeded` and + `SiteNotConfirmed`. Kinds add their own. +- **Current identity (O9).** Identity is current when BMC discovery reports + `IdentityMatched` true for the Device's current generation, its last complete + inventory read is at most two hours old (twice the default discovery + interval), and it recorded the BMC key at the current endpoint. Admission + check 6 compares the observed key digest across Devices that are not + retired. The snapshot carries the observed digest, and the site worker must + check it against the operator-approved pin before sending anything + (Increment B). +- **Checks 5 and 6 apply only to kinds that can reach the server.** The Device + UID must always match. A `DeviceRecovery` sends nothing, and it must still + work when a BMC is unreachable, for example to retire a dead server. This is + listed under [Points for a person](#points-for-a-person). +- **Names.** Deterministic kinds must use their rule, or they end `Failed` + with `NameMismatch`. A `DeviceInstallation` is named from its allocation and + a digest of the Installation UID. A `DeviceWipe` is named from its allocation + and step. Staff kinds must use a generated name. +- **Order.** Pending operations are admitted oldest first. Ties break on kind, + then name, then UID, so every coordinator picks the same one. +- **Racing refusals.** Delivery must wait until operation status shows + `Admitted`. If a racing coordinator ends an operation, or it is deleted, + after custody admitted it but before the status copy, custody withdraws it + (`Cancelled`, `Withdrawn`). Nothing was delivered, and the fence stays + raised. + +### Deadlines and clock skew (O4) + +| Kind | Deadline | +| --- | --- | +| `DeviceInstallation` | 40 minutes, the Redfish executor's install bound | +| `DeviceWipe` | 40 minutes, the Redfish executor's cleanup bound | +| `DeviceRecovery` | 10 minutes to collect the sites' fence reports | + +The worker stops at the deadline exactly (Increment B). The coordinator +declares `OutcomeUnknown` only after the deadline plus a two-minute skew +margin. A staff operation that is not admitted within five minutes expires. +Each value is configurable. + +### Unknown outcomes and recovery (O2, O3, O6, O7) + +- `OutcomeUnknown` moves the operation from `activeOperation` to + `recoveryHold` in the same update, keeping its kind, name, UID and fence. + The holder stays. +- A result whose evidence does not match the kind's schema proves nothing, and + ends `OutcomeUnknown` with `InvalidEvidence`. +- A settling operation records the hold it settles. If it succeeds, the hold + is cleared. If it also ends unknown, its hold replaces the old one. +- A `DeviceRecovery` is admitted like any operation and raises the fence. The + coordinator applies it only after every site serving the Device reports a + stored fence at least that high, so the held worker has stopped. If no site + confirms before its deadline, it ends `Failed` with `SiteNotConfirmed`, and + the hold stays. It does not end `OutcomeUnknown`, because it cannot change + the server. +- `Settle` clears a hold only when the held kind provides a settle check, and + that check accepts the evidence. Installation and wipe holds have no such + check: later operations settle them. +- `Retry` marks the hold so that the held operation's requester can create one + settling operation. Admitting that operation uses up the retry. +- `Retire` needs a hold and a `Service` or `Release` holder. Retiring from + `Release` requires a disk disposal record. +- `Resolve` is the only operation `Unverified` custody admits. It records the + holder (`None`, `Allocation`, `Release` or `Retired`), marks custody + `Verified`, and adopts the current Device UID. A rebuilt hold stays, to be + settled separately. +- Nothing retries an operation automatically. + +### Rebuilding custody (O13, O15, O16) + +- Missing custody is created `Unverified` from the Device's lifecycle and + succeeded `Retire` recoveries, its MachineAllocations that are not + `Released`, and its operations that have not ended. A releasing allocation + rebuilds `Release` with every gate open. +- Every operation that has not ended is held, even if its status says + `Pending`, because custody is written before status. +- Two live allocations, two unfinished operations, holder sources that + disagree, a Device UID that differs from custody, or a missing Device each + keep custody `Unverified` until a `Resolve`. +- Custody becomes `Verified` only after every site configured to serve the + Device reports its stored fence. The new fence is above every fence those + sites and the operations have used. A Device no site serves stays + `Unverified`. Sites are configured explicitly and never inferred from + placement. +- The site's fence store must be durable, beside the journal on its retained + volume, so a site refuses older fences after a restart (Increment B). + +### Release gates (O17) + +The gates are the machine lifecycle's release obligations: `Operations`, +`Access`, `Network`, `Address`, `Cleaning` and `Quota`. The release +controller closes each one with evidence. A gate the coordinator does not know +stays open. The Device returns to `None` only when no gate, hold or operation +remains. + +### Staff access and customer data (O10) + +- The **device operations viewer** reads custody and operations, but not + MachineAllocations, so it does not see which customer holds a server. +- The **device recovery operator** inherits the viewer, creates + `DeviceRecovery`, and reads MachineAllocations, because a `Resolve` must + name an allocation and staff identify the customer through it. +- A `DeviceRecovery` does not need a second person in this increment. The + creator is recorded and the role is narrow. This is listed under [Points for + a person](#points-for-a-person). +- Bootstrap stays refused. A `DeviceInstallation` that names a bootstrap + reference ends `Failed` with `BootstrapUnsupported`. No role can read a + Secret, a sealed store, or a bootstrap payload, and a test checks the role + definitions. + +### Other decisions + +- **Retention.** Finished operations are deleted 30 days after they end, + unless custody still names them as active or as the hold. +- **Rejected results.** A result whose fence or operation does not match the + active operation is refused, and custody counts it and records the last one + for monitoring. It never changes the holder. A retry of a result already + recorded is accepted without a second write. +- **Boot interface (O12).** `bootInterface` resolves by name against the + Device's interfaces, and the snapshot records its MAC. Target disks stay a + site-local enrollment fact that the worker checks (Increment B). +- **Cleaning policy (O11).** `DeviceWipe` requires the digest of the cleaning + policy record pinned at allocation. The private fixture resolver that pins it + arrives in Increment C. +- **Capacity (O1).** The projector stays a pure function. `Prepared` needs a + succeeded commissioning under the current plan, `Healthy` needs current + commissioning and discovery evidence, and `Available` also needs `Verified` + custody, holder `None`, no hold and an enabled allocation policy. Wiring it + as written would make every server unallocatable, because commissioning is + not built. + +## Points for a person + +These need a decision before the increment that depends on them. + +- **O1, before C: the interim source of `Prepared` and `Healthy`.** Until it + is decided, the projector stays unwired. +- **O8, before C: where an allocation's private facts live.** The accepted + requirements, hardware snapshot, network record and inputs, authority and + external hold, and binding have no home once the private Secrets are + deleted. The proposal is immutable MachineAllocation spec fields written at + create, with no consumer secrets. Increment C cannot start until this is + approved. +- **O10: the sealed store for bootstrap payloads.** Bootstrap stays refused in + every increment until a store is chosen. +- **Admission checks 5 and 6 for `DeviceRecovery`.** This implementation skips + the discovery half of check 5, and check 6, for kinds that cannot reach the + server. +- **A `DeviceRecovery` that no site confirms** ends `Failed`, not + `OutcomeUnknown`. +- **A second person for `DeviceRecovery`.** Not required yet. + +## Adding an operation kind + +A new kind, such as `DevicePowerOperation` or `DeviceCommissioning`, plugs into +four seams. It needs no change to the coordinator. The test-only kinds in +`internal/custody/testkinds_test.go` use every seam. Copy them. + +1. **Register the kind.** Add a `custody.Kind` to the registry with: + - its GroupVersionKind, constructors, and an `Items` adapter; + - a digest of its exact inputs (`custody.SpecDigest` covers the whole + spec); + - its naming rule: `DeterministicName` with a `Name` function for provider + and release kinds, or `GeneratedName` for staff kinds; + - its `Deadline`, and `Effectful` if it can reach the server; + - `Supersedes`, if a newer pending operation for the same authority should + cancel an older one, as power needs; + - `Check` for kind-specific admission checks. They run after the shared + preconditions, before the custody update, and return a named refusal, + such as power's `SystemUUIDMismatch` or `DiscoveryNotCurrent`; + - `Settles`, the held kinds a success settles, with `RequiresRetry` when a + `DeviceRecovery` `Retry` must come first. + + Embed `OperationEnvelope` inline in the spec, and use `OperationStatus` as + the status. Add the CRD with the same envelope, the immutable-spec rule and + the phase rule, plus a ProtectedResource and roles. +2. **Add its rows.** Add one `custody.Rule` per row of the #174 operations + table: the creator class, the authority type, the holders it admits from, + its hold behavior, and whether it queues. Staff rows never queue. To admit + a new service principal, add its class to the coordinator's principal + configuration. Never hard-code an identity. +3. **Implement its site worker** (Increment B). The site framework owns the + fence, the journal, credential lookup, the TLS pin and identity checks, the + deadline and result delivery. A kind supplies only its pre-effect checks, + which refuse with a named reason and send nothing, its journaled steps, how + it recovers by observation after a lost response, and its typed result + evidence. The worker contract is proposed and lands in Increment B. +4. **Define its evidence.** Set `Evidence` to `custody.StrictEvidence` over a + typed, bounded Go struct. 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 + evidence. Power, for example, accepts only a power state that discovery + read after the operation ended. + +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. + +## Tests + +Run `task test:envtest`. It runs these tests with the race detector against +a real API server: + +| Area | Tests | +| --- | --- | +| Every admission precondition, names, kind checks, bootstrap refusal, staff expiry | `TestAdmissionPreconditions` | +| Every holder transition, pending order, supersede, cancellation on holder change, stale fences, results, deadlines | `TestLifecycle`, `TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing` | +| Holds and settlement through the test-only kind, install and wipe holds, `Retry`, `Retire`, retention | `TestRecovery` | +| Rebuild from each source, each conflict, `Resolve`, custody deleted and restored | `TestRebuild` | +| Two allocators, allocator against staff, two coordinators, admission against a holder change, two Devices, a lost claim response | `TestConcurrency` | +| A crash between each pair of custody and status writes, with dropped and lost responses | `TestWriteOrderCrashRecovery` | +| CEL rules | `TestCRDRules` | +| Seams, rows, principals, ordering, evidence bounds, capacity for every input | `TestRegistryRejectsIncompleteKindsAndRows`, `TestAddingRowsLeavesExistingRowsAlone`, `TestPrincipals`, `TestCandidatesOrderOldestFirstWithADeterministicTieBreak`, `TestEvidenceIsTypedAndBounded`, `TestCapacityProjection` | +| Creator recording and caller preservation | `TestHandler`, `TestCreatorAgainstAPIServer` | +| CRD contract, roles, and that nothing ships the component or the test-only kinds | `TestCRDContract`, `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`, `TestComponentIsInert` | + +Increment A has no site, so "nothing was sent" means custody admitted nothing +and the fence did not rise. Increment D proves it with the lab BMC audit. diff --git a/docs/development/roadmap.md b/docs/development/roadmap.md index c3d7282b..63849ac8 100644 --- a/docs/development/roadmap.md +++ b/docs/development/roadmap.md @@ -43,6 +43,18 @@ mandatory ongoing guest agent. Two consumer projects share provider inventory without double allocation. Lost responses, stale executors, access revocation, and incomplete cleaning cannot cause duplicate effects or premature reuse. +### Device custody and operations + +The [device custody and operations work](device-custody.md) replaces +per-allocation fencing with one custody record per Device, ahead of real +hardware qualification. Increment A, the inert control-plane foundation, is +implemented. Increments B (site execution), C (cutover) and D (end-to-end +failure scenarios) are proposed. C waits on a decision about where an +allocation's private facts live. + +Acceptance: the #174 acceptance tests pass, in envtest and in fresh local +end-to-end runs, with "nothing sent" proven by the lab BMC audit. + ## 4. Adopt rented capacity and managed clusters Normalize servers.com/NetActuate facts, retain existing identities and diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 705b369f..b4429303 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -28,3 +28,27 @@ integration evidence. Offline validation is not Milo acceptance. No row becomes accepted until the required owning service participates in a protected live run and the sanitized result reports every required phase `Passed`. + +## Device custody and operations + +These are the acceptance tests of [#174 at `3907eec`](https://github.com/datum-cloud/fleet/pull/174). +Increment A covers them against a real API server. End-to-end coverage arrives +in Increments C and D. See [device custody](../../docs/development/device-custody.md#tests). + +| #174 acceptance test | Executable evidence | Current state | +| --- | --- | --- | +| Two allocators race for one server; one wins | `TestConcurrency` | Envtest verified; end to end proposed | +| An allocator retries after a lost response and claims no second server | `TestConcurrency` | Envtest verified for the custody claim; naming from the Machine UID arrives in C | +| A staff operation names a customer allocation and is refused | `TestAdmissionPreconditions`, with the test-only staff kind | Envtest verified; end to end deferred to power | +| A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope; the mechanism is envtest verified | +| A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery` | Envtest verified; end to end proposed | +| A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery` | Envtest verified with a fake site; end to end proposed | +| A delayed worker's step after a newer admission is refused by the journal | None yet | Proposed in B | +| Custody deleted and restored stays unallocatable until rebuilt with a higher fence | `TestRebuild` | Envtest verified with a fake site; end to end proposed | +| A Machine deleted during installation; release waits; a wipe settles the install hold | `TestLifecycle`, `TestRecovery` | Envtest verified; end to end proposed | +| No staff role can read a bootstrap payload | `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets` | Role definitions verified; bootstrap stays refused | + +The emulator lab cannot cover BMC TLS key rotation, vendor Redfish behavior, +UEFI or real PXE firmware, real disks and wipe assurance, real power reset +evidence, clock skew between coordinator and site, more than one site serving +a Device, or a permanently lost site. None of these tests qualifies hardware. From 48b780c819eb484553ebd44ab027d52d17c25b5e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 18:56:05 -0600 Subject: [PATCH 05/19] fix(custody): Skip discovery checks only for Retire and Resolve A DeviceRecovery with Settle or Retry now needs current discovery and a unique BMC key, like any other operation. Settling a power hold needs fresh discovery evidence of the power state. Retire and Resolve still skip both checks, so a server with an unreachable BMC can be retired. The registry refuses the skip for any kind that can reach the server. Co-Authored-By: Claude Opus 5.5 --- internal/custody/coordinator.go | 4 ++-- internal/custody/kinds.go | 6 ++++++ internal/custody/recovery_test.go | 27 +++++++++++++++++++++++++++ internal/custody/registry.go | 13 +++++++++++++ internal/custody/seams_test.go | 5 +++++ 5 files changed, 53 insertions(+), 2 deletions(-) diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index a0710dd8..a06ebecc 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -648,8 +648,8 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } return fail(ReasonOperationActive, "another operation is running, and staff operations never wait") } - // Preconditions 5 and 6 concern what can reach the BMC. - if kind.Effectful { + // Preconditions 5 and 6: current discovery and a unique BMC key. + if kind.checksDiscovery(operation) { if refusal := c.identityCurrent(device, now); refusal != nil { if row.Queue { return decision{phase: ops.PhasePending, reason: refusal.Reason, message: refusal.Message} diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 28cbfe04..29181bed 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -160,6 +160,12 @@ func DeviceRecoveryKind() Kind { Naming: GeneratedName, Deadline: RecoveryDeadline, Variant: func(operation ops.Operation) string { return string(operation.(*ops.DeviceRecovery).Spec.Decision) }, + // Retire and Resolve must work on a server whose BMC is + // unreachable. Settle and Retry still need current discovery. + SkipsDiscovery: func(operation ops.Operation) bool { + decision := operation.(*ops.DeviceRecovery).Spec.Decision + return decision == ops.DecisionRetire || decision == ops.DecisionResolve + }, Check: func(ctx context.Context, admission *Admission) *Refusal { return checkRecovery(ctx, admission.Operation.(*ops.DeviceRecovery), admission.Custody, admission.Registry, admission) }, diff --git a/internal/custody/recovery_test.go b/internal/custody/recovery_test.go index 9e59dbe1..27fd37d9 100644 --- a/internal/custody/recovery_test.go +++ b/internal/custody/recovery_test.go @@ -107,6 +107,33 @@ func TestRecovery(t *testing.T) { e.requirePhase(blocked, ops.PhaseFailed, ReasonHolderMismatch) }) + t.Run("only Retire and Resolve skip current discovery and the shared-key check", func(t *testing.T) { + e := e.sub(t) + device := fresh() + hold := e.holdOn(device) + key := fmt.Sprintf("%064x", n) + // The BMC stopped answering: discovery is old, and another live + // Device now records the same key. + e.discover(device, key, e.clock.Now().Add(-DefaultDiscoveryMaxAge-time.Minute)) + fence := e.custody(device.Name).Spec.Fence + settle := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: heldRef(hold), Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(e.clock.Now().Add(time.Minute)), Summary: "s", Data: map[string]string{"state": "On"}}}) + e.settle(device.Name) + e.requirePhase(settle, ops.PhaseFailed, ReasonIdentityNotCurrent) + retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + e.settle(device.Name) + e.requirePhase(retry, ops.PhaseFailed, ReasonIdentityNotCurrent) + e.requireUntouched(device.Name, fence) + e.device(fmt.Sprintf("server-twin-%03d", n), uid(900+n), key) + retire := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(hold)}) + e.settle(device.Name) + e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) + e.settle(device.Name) + e.requirePhase(retire, ops.PhaseSucceeded, "") + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderRetired { + t.Fatalf("holder = %s", holder) + } + }) + t.Run("a recovery whose sites never confirm ends Failed and keeps the hold", func(t *testing.T) { e := e.sub(t) device := fresh() diff --git a/internal/custody/registry.go b/internal/custody/registry.go index b635650d..a44683d8 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -58,6 +58,12 @@ type Kind struct { // DeviceRecovery, that passes its deadline ends Failed: nothing it does // can leave the server in an unknown state. Effectful bool + // SkipsDiscovery, when it returns true, exempts the operation from + // admission checks 5 (current discovery) and 6 (a unique BMC key). + // Only a kind that cannot reach the server may set it. DeviceRecovery + // sets it for Retire and Resolve, which must work when a BMC is + // unreachable. The Device UID is always checked. + SkipsDiscovery func(ops.Operation) bool // Supersedes means a newer pending operation of this kind for the same // authority cancels an older pending one. Supersedes bool @@ -87,6 +93,10 @@ type Kind struct { Retires func(ops.Operation) bool } +func (k *Kind) checksDiscovery(operation ops.Operation) bool { + return k.SkipsDiscovery == nil || !k.SkipsDiscovery(operation) +} + // SettleRule says a success of the owning kind settles a hold of Held. When // RequiresRetry is set, a DeviceRecovery with Retry must first authorize it. type SettleRule struct { @@ -180,6 +190,9 @@ func (r *Registry) Register(kind Kind) error { if !kind.Effectful && kind.Apply == nil { return fmt.Errorf("%s: a non-effectful kind needs Apply", name) } + if kind.Effectful && kind.SkipsDiscovery != nil { + return fmt.Errorf("%s: a kind that can reach the server always checks discovery", name) + } if _, ok := r.kinds[name]; ok { return fmt.Errorf("%s is already registered", name) } diff --git a/internal/custody/seams_test.go b/internal/custody/seams_test.go index 0a7151ab..b10288cd 100644 --- a/internal/custody/seams_test.go +++ b/internal/custody/seams_test.go @@ -40,6 +40,11 @@ func TestRegistryRejectsIncompleteKindsAndRows(t *testing.T) { if err := registry.Register(inert); err == nil { t.Fatal("a non-effectful kind without Apply registered") } + skipping := testKinds()[1] + skipping.SkipsDiscovery = func(ops.Operation) bool { return true } + if err := registry.Register(skipping); err == nil { + t.Fatal("a kind that reaches the server skipped discovery") + } if err := registry.AddRule(Rule{Kind: testStaffKind, Creator: CreatorStaff, Authority: AuthorityService, Queue: true}); err == nil { t.Fatal("a staff row that queues was added") } From d791b6fec7de992f80e4201a7949b1291fe7526e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 18:56:06 -0600 Subject: [PATCH 06/19] docs: Record where an allocation's private facts live The allocation's non-secret facts live on its MachineAllocation, which only Fleet writes. Increment C can start after B. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 49 +++++++++++++++++++----------- docs/development/roadmap.md | 4 +-- 2 files changed, 34 insertions(+), 19 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 6ccfc2a7..2f3d59b6 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -14,7 +14,7 @@ marked **implemented and verified**, **implemented and inert**, or | --- | --- | --- | | A: control-plane foundation | API types and CRDs for `DeviceCustody`, `DeviceInstallation`, `DeviceWipe` and `DeviceRecovery`; CEL rules; IAM resources and roles; the creator webhook; the kind registry and admission rule table; the coordinator's custody reconciler, admission, results, recovery, rebuild and retention; the capacity projector | **Implemented and inert.** Verified with unit tests and with tests against a real API server. No deployment root, manager, or staging overlay includes it. The existing Secret-backed lifecycle is unchanged. | | B: site execution | Per-Device fence store and journal, older-worker stop, deadlines, fenced results, per-Device credentials, pinned TLS, the new handoff payload | **Proposed** | -| C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the projector as the only condition writer, removal of the private Secret records | **Proposed.** Blocked on the decision about where an allocation's private facts live. | +| C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the projector as the only condition writer, removal of the private Secret records | **Proposed.** Starts after B. | | D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests | **Proposed** | ## What Increment A adds @@ -97,10 +97,16 @@ Each decision lists the open point from the implementation brief it settles. retired. The snapshot carries the observed digest, and the site worker must check it against the operator-approved pin before sending anything (Increment B). -- **Checks 5 and 6 apply only to kinds that can reach the server.** The Device - UID must always match. A `DeviceRecovery` sends nothing, and it must still - work when a BMC is unreachable, for example to retire a dead server. This is - listed under [Points for a person](#points-for-a-person). +- **Only `Retire` and `Resolve` skip checks 5 and 6.** A `DeviceRecovery` + with `Retire` or `Resolve` skips current discovery and the shared-key check, + because it must work when a BMC is unreachable, for example to retire a dead + server. The Device UID is always checked. `Settle` still needs current + discovery: settling a power hold needs fresh discovery evidence of the power + state, as the #174 settlement table says. `Retry` needs no evidence of its + own, and it still passes both checks. The settling operation it authorizes + goes through normal admission as well. Only a + kind that cannot reach the server may skip these checks, and the registry + refuses any other. - **Names.** Deterministic kinds must use their rule, or they end `Failed` with `NameMismatch`. A `DeviceInstallation` is named from its allocation and a digest of the Installation UID. A `DeviceWipe` is named from its allocation @@ -173,6 +179,18 @@ Each value is configurable. - The site's fence store must be durable, beside the journal on its retained volume, so a site refuses older fences after a restart (Increment B). +### Where an allocation's private facts live (O8) + +Decided: the allocation's facts live on its MachineAllocation, in the provider +project, and only Fleet writes it. This follows the [MachineAllocation +record](../enhancements/machine-lifecycle/README.md#machineallocation-record) +of the machine lifecycle: identity, the accepted contract, the hardware +snapshot, authority and quota evidence, and lifecycle and release obligations. +Immutable accepted inputs go in spec. Lifecycle goes in status. Each +allocation is named from its Machine UID, per #174. Nothing secret goes on it, +and staff roles may read it. Increment C implements this. It replaces the +private `AssetRecord` and the other Secret records. + ### Release gates (O17) The gates are the machine lifecycle's release obligations: `Operations`, @@ -191,6 +209,8 @@ remains. - A `DeviceRecovery` does not need a second person in this increment. The creator is recorded and the role is narrow. This is listed under [Points for a person](#points-for-a-person). +- Staff roles may read MachineAllocations, because nothing secret is on them. + Only the recovery operator role grants that read today. - Bootstrap stays refused. A `DeviceInstallation` that names a bootstrap reference ends `Failed` with `BootstrapUnsupported`. No role can read a Secret, a sealed store, or a bootstrap payload, and a test checks the role @@ -223,20 +243,15 @@ These need a decision before the increment that depends on them. - **O1, before C: the interim source of `Prepared` and `Healthy`.** Until it is decided, the projector stays unwired. -- **O8, before C: where an allocation's private facts live.** The accepted - requirements, hardware snapshot, network record and inputs, authority and - external hold, and binding have no home once the private Secrets are - deleted. The proposal is immutable MachineAllocation spec fields written at - create, with no consumer secrets. Increment C cannot start until this is - approved. - **O10: the sealed store for bootstrap payloads.** Bootstrap stays refused in every increment until a store is chosen. -- **Admission checks 5 and 6 for `DeviceRecovery`.** This implementation skips - the discovery half of check 5, and check 6, for kinds that cannot reach the - server. -- **A `DeviceRecovery` that no site confirms** ends `Failed`, not - `OutcomeUnknown`. -- **A second person for `DeviceRecovery`.** Not required yet. +- **A second person for `DeviceRecovery`.** Not required yet. A person + accepted this for now, and it stays open for a later decision. + +Already decided by a person: [where an allocation's private facts +live](#where-an-allocations-private-facts-live-o8), that [only `Retire` and +`Resolve` skip checks 5 and 6](#admission), and that a `DeviceRecovery` that +no site confirms ends `Failed`, not `OutcomeUnknown`. ## Adding an operation kind diff --git a/docs/development/roadmap.md b/docs/development/roadmap.md index 63849ac8..10629347 100644 --- a/docs/development/roadmap.md +++ b/docs/development/roadmap.md @@ -49,8 +49,8 @@ The [device custody and operations work](device-custody.md) replaces per-allocation fencing with one custody record per Device, ahead of real hardware qualification. Increment A, the inert control-plane foundation, is implemented. Increments B (site execution), C (cutover) and D (end-to-end -failure scenarios) are proposed. C waits on a decision about where an -allocation's private facts live. +failure scenarios) are proposed. An allocation's private facts will live on +its MachineAllocation, which C implements after B. Acceptance: the #174 acceptance tests pass, in envtest and in fresh local end-to-end runs, with "nothing sent" proven by the lab BMC audit. From efb61a128e1b172fba0162f65156244e5f35ecc8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 19:13:06 -0600 Subject: [PATCH 07/19] fix(custody): Keep unproven outcomes held across a rebuild Rebuild now holds an operation that ended OutcomeUnknown unless a later success settled it, ends a held unfinished operation OutcomeUnknown, and never admits a held operation again. With several, the newest is held and custody stays Unverified for a Resolve. Admission decides only on custody that did not change while it listed operations, raises the fence above every fence a site reports, and confirms a recovery only once the sites report that older workers stopped. Resolve must agree with the live MachineAllocations. Queued operations wait under a hold they cannot settle. Retention keeps a succeeded retirement until inventory retires the Device. The creator webhook reads keys case-sensitively. Co-Authored-By: Claude Opus 5.5 --- .../crds/fleet.datumapis.com.yaml | 6 +- internal/custody/coordinator.go | 82 +++++- internal/custody/creatorwebhook/handler.go | 24 +- .../custody/creatorwebhook/handler_test.go | 7 + internal/custody/harness_test.go | 6 +- internal/custody/holds_test.go | 239 ++++++++++++++++++ internal/custody/kinds.go | 42 ++- internal/custody/rebuild.go | 89 +++++-- internal/custody/recovery_test.go | 51 +++- internal/custody/registry.go | 12 +- internal/custody/retention.go | 15 +- .../custody/testdata/crds/test-kinds.yaml | 4 +- 12 files changed, 509 insertions(+), 68 deletions(-) create mode 100644 internal/custody/holds_test.go diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 58722c49..4f2a7fb1 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -575,7 +575,7 @@ spec: type: object x-kubernetes-preserve-unknown-fields: true x-kubernetes-validations: - - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled''], ''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])' + - 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 @@ -765,7 +765,7 @@ spec: type: object x-kubernetes-preserve-unknown-fields: true x-kubernetes-validations: - - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled''], ''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])' + - 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 @@ -1025,7 +1025,7 @@ spec: type: object x-kubernetes-preserve-unknown-fields: true x-kubernetes-validations: - - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled''], ''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])' + - 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 diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index a06ebecc..67d56fe9 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -23,9 +23,20 @@ type Sites interface { // Serving returns the sites explicitly configured to serve the Device. // The coordinator never infers a site from placement. Serving(device *inventory.Device) []string - // Fence returns the highest fence the site has stored for the Device, - // and false if the site has not reported one. - Fence(ctx context.Context, site string, device *inventory.Device) (int64, bool, error) + // Fence returns the site's fence report for the Device, and false if + // the site has not reported one. + Fence(ctx context.Context, site string, device *inventory.Device) (SiteFence, bool, error) +} + +// SiteFence is one site's fence report for one Device. +type SiteFence struct { + // Seen is the highest fence the site has stored. Admission and rebuild + // set the new fence above it. + Seen int64 + // Stopped is the highest fence for which the site confirmed that every + // older worker stopped. A DeviceRecovery applies only once it reaches + // the recovery's fence. + Stopped int64 } // Config holds the coordinator's tunable values. Zero values take the @@ -268,6 +279,22 @@ func (c *Coordinator) copyStatus(ctx context.Context, custody *ops.DeviceCustody } } } + // A held operation has ended, even if a rebuild found it unfinished. It + // is never admitted again. + if hold := custody.Spec.RecoveryHold; hold != nil { + operation, _, err := c.get(ctx, hold.OperationReference) + if err != nil { + return false, err + } + if operation != nil && !operation.OperationStatus().Phase.Ended() { + status := *operation.OperationStatus() + finished := metav1.NewTime(c.now()) + status.Phase, status.Reason, status.Message, status.FinishedAt = ops.PhaseOutcomeUnknown, hold.Reason, "custody holds this operation because its outcome is unknown", &finished + if changed, err := c.writeStatus(ctx, operation, status); err != nil || changed { + return changed, err + } + } + } active := custody.Spec.ActiveOperation if active == nil { return false, nil @@ -372,7 +399,7 @@ func (c *Coordinator) progressActive(ctx context.Context, custody *ops.DeviceCus c.finishActive(custody, active, ops.PhaseCancelled, ReasonWithdrawn, "the operation was deleted before it was applied", nil) return c.writeCustody(ctx, custody) } - spec, refusal := kind.Apply(ctx, &ApplyContext{Operation: operation, Custody: custody.DeepCopy(), Device: device, Registry: c.Registry, ConfirmedFence: confirmed, HighestFence: highest, Now: now}) + spec, refusal := kind.Apply(ctx, &ApplyContext{Operation: operation, Custody: custody.DeepCopy(), Device: device, Registry: c.Registry, Reader: c.Client, ConfirmedFence: confirmed, HighestFence: highest, Now: now}) if refusal != nil { c.finishActive(custody, active, ops.PhaseFailed, refusal.Reason, refusal.Message, nil) return c.writeCustody(ctx, custody) @@ -404,18 +431,34 @@ func (c *Coordinator) siteFence(ctx context.Context, device *inventory.Device, f return 0, 0, false, nil } for _, site := range sites { - stored, reported, err := c.Sites.Fence(ctx, site, device) + report, reported, err := c.Sites.Fence(ctx, site, device) + stored := report.Stopped if err != nil || !reported || stored < fence { return 0, 0, false, err } if lowest < 0 || stored < lowest { lowest = stored } - highest = max(highest, stored) + highest = max(highest, report.Seen) } return lowest, highest, true, nil } +// siteSeen returns the highest fence any serving site reports having seen. +func (c *Coordinator) siteSeen(ctx context.Context, device *inventory.Device) (int64, error) { + var highest int64 + for _, site := range c.Sites.Serving(device) { + report, reported, err := c.Sites.Fence(ctx, site, device) + if err != nil { + return 0, err + } + if reported { + highest = max(highest, report.Seen, report.Stopped) + } + } + return highest, nil +} + // finishActive ends the active operation without a hold. A staff holder // with nothing left to settle returns to None. func (c *Coordinator) finishActive(custody *ops.DeviceCustody, active ops.ActiveOperation, phase ops.Phase, reason, message string, evidence []byte) { @@ -470,6 +513,9 @@ func (c *Coordinator) candidates(ctx context.Context, custody *ops.DeviceCustody if active := custody.Spec.ActiveOperation; active != nil && active.Kind == kind.GVK.Kind && active.UID == string(operation.GetUID()) { continue } + if hold := custody.Spec.RecoveryHold; hold != nil && hold.Kind == kind.GVK.Kind && hold.UID == string(operation.GetUID()) { + continue + } out = append(out, candidate{operation: operation, kind: kind}) } } @@ -511,6 +557,17 @@ func (c *Coordinator) admit(ctx context.Context, custody *ops.DeviceCustody, dev if err != nil { return Outcome{}, err } + // Decide only on custody that is still current after the list. A holder + // change that landed between the custody read and the list, such as a + // claim followed by its installation's create, is then seen before any + // refusal is written. + fresh := &ops.DeviceCustody{} + if err := c.Client.Get(ctx, client.ObjectKeyFromObject(custody), fresh); err != nil { + return Outcome{}, err + } + if fresh.ResourceVersion != custody.ResourceVersion { + return Outcome{Changed: true}, nil + } superseded := c.superseded(candidates) queued := false changed := false @@ -636,6 +693,9 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper case row.Hold == HoldRequired: case hold != nil: if !c.settlesHold(kind, *hold) { + if row.Queue { + return decision{phase: ops.PhasePending, reason: ReasonRecoveryHold, message: "waiting: " + hold.Kind + " " + hold.Name + " is held, and only its settling operations are admitted"} + } return fail(ReasonRecoveryHold, "%s %s is held; only its settling operations are admitted", hold.Kind, hold.Name) } reference := hold.OperationReference @@ -661,7 +721,7 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } } if kind.Check != nil { - if refusal := kind.Check(ctx, &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Now: now}); refusal != nil { + if refusal := kind.Check(ctx, &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Now: now}); refusal != nil { return fail(refusal.Reason, "%s", refusal.Message) } } @@ -737,7 +797,13 @@ func (c *Coordinator) admitOne(ctx context.Context, custody *ops.DeviceCustody, } now := c.now() spec := &custody.Spec - spec.Fence++ + // The fence rises above every fence a site has seen, so a site report at + // or above it proves the site received this admission. + seen, err := c.siteSeen(ctx, device) + if err != nil { + return Outcome{}, err + } + spec.Fence = max(spec.Fence, seen) + 1 active := &ops.ActiveOperation{ OperationReference: ops.OperationReference{Kind: kind.GVK.Kind, Name: operation.GetName(), UID: string(operation.GetUID())}, Fence: spec.Fence, diff --git a/internal/custody/creatorwebhook/handler.go b/internal/custody/creatorwebhook/handler.go index 28c8bee3..495887dd 100644 --- a/internal/custody/creatorwebhook/handler.go +++ b/internal/custody/creatorwebhook/handler.go @@ -35,18 +35,26 @@ type Handler struct { Resources []string } -type envelope struct { - Spec struct { - Creator *ops.Creator `json:"creator"` - } `json:"spec"` -} - +// creatorOf reads spec.creator with exact, case-sensitive keys, as the API +// server does. encoding/json into a struct would match keys without regard +// to case and let a later duplicate win. func creatorOf(raw []byte) (*ops.Creator, error) { - var object envelope + var object map[string]any if err := json.Unmarshal(raw, &object); err != nil { return nil, err } - return object.Spec.Creator, nil + spec, _ := object["spec"].(map[string]any) + value, ok := spec["creator"] + if !ok { + return nil, nil + } + fields, ok := value.(map[string]any) + if !ok { + return nil, errors.New("spec.creator is not an object") + } + username, _ := fields["username"].(string) + uid, _ := fields["uid"].(string) + return &ops.Creator{Username: username, UID: uid}, nil } // project returns the caller's Milo project. Milo sets these extras when it diff --git a/internal/custody/creatorwebhook/handler_test.go b/internal/custody/creatorwebhook/handler_test.go index a064d5ad..b61ef060 100644 --- a/internal/custody/creatorwebhook/handler_test.go +++ b/internal/custody/creatorwebhook/handler_test.go @@ -73,6 +73,13 @@ func TestHandler(t *testing.T) { } }) } + t.Run("creator keys are read case-sensitively", func(t *testing.T) { + // encoding/json into a struct would let the later "Creator" win. + raw := runtime.RawExtension{Raw: []byte(`{"spec":{"creator":{"username":"other","uid":"other-uid"},"Creator":{"username":"staff-example","uid":"staff-example-uid"}}}`)} + if handler.Handle(context.Background(), request(admissionv1.Create, staff, raw, runtime.RawExtension{})).Allowed { + t.Fatal("a differently cased duplicate key decided the creator") + } + }) t.Run("ungoverned resources and subresources are denied", func(t *testing.T) { other := request(admissionv1.Create, staff, object(t, self), runtime.RawExtension{}) other.Resource.Resource = "devicecustodies" diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index a7b72647..f7bbe385 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -80,11 +80,13 @@ func (s *fakeSites) Serving(device *inventory.Device) []string { return []string{testSite} } -func (s *fakeSites) Fence(_ context.Context, site string, device *inventory.Device) (int64, bool, error) { +// Fence reports one fence as both seen and stopped: the fake site's workers +// stop as soon as a newer fence arrives. +func (s *fakeSites) Fence(_ context.Context, site string, device *inventory.Device) (SiteFence, bool, error) { s.mu.Lock() defer s.mu.Unlock() fence, ok := s.fences[site+"/"+device.Name] - return fence, ok, nil + return SiteFence{Seen: fence, Stopped: fence}, ok, nil } // report stores the fence a site reports for a Device. diff --git a/internal/custody/holds_test.go b/internal/custody/holds_test.go new file mode 100644 index 00000000..cee3c7fe --- /dev/null +++ b/internal/custody/holds_test.go @@ -0,0 +1,239 @@ +package custody + +import ( + "context" + "fmt" + "slices" + "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" +) + +// dropCustody removes the finalizer as the harness admin and deletes +// custody, as a restore that lost it would. +func (e *env) dropCustody(name string) { + e.t.Helper() + custody := e.custody(name) + custody.Finalizers = nil + if err := e.admin.Update(e.ctx, custody); err != nil { + e.t.Fatal(err) + } + if err := e.admin.Delete(e.ctx, custody); err != nil { + e.t.Fatal(err) + } +} + +// TestRebuildKeepsUnprovenOutcomes covers rebuild with the built-in +// provider and release kinds: an unproven outcome stays held and its +// operation is never admitted again. +func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { + e := startEnv(t) + n := 700 + next := func() *inventory.Device { + n++ + return e.device(fmt.Sprintf("server-example-%03d", n), uid(n), fmt.Sprintf("%064x", n)) + } + verify := func(e *env, device *inventory.Device, fence int64) *ops.DeviceCustody { + e.t.Helper() + e.sites.report(device.Name, fence) + e.settle(device.Name) + return e.custody(device.Name) + } + + t.Run("an installation that ended OutcomeUnknown is held again after custody is lost", func(t *testing.T) { + e := e.sub(t) + device := next() + e.allocation(device, "alloc-u-"+device.Name, "Active") + verify(e, device, 0) + install := e.installation(device, "alloc-u-"+device.Name, "request-1") + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + fence := e.custody(device.Name).Spec.Fence + e.dropCustody(device.Name) + custody := verify(e, device, fence) + if custody.Spec.State != ops.CustodyVerified || custody.Spec.Holder.Type != ops.HolderAllocation || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.UID != string(install.UID) || custody.Spec.ActiveOperation != nil { + t.Fatalf("rebuilt = %+v", custody.Spec) + } + if err := e.coord.Claim(e.ctx, device.Name, "alloc-other"); err == nil { + t.Fatal("a held server was claimed") + } + }) + + t.Run("an unfinished installation is held, ended unknown, and never admitted again", func(t *testing.T) { + e := e.sub(t) + device := next() + e.allocation(device, "alloc-p-"+device.Name, "Active") + install := e.installation(device, "alloc-p-"+device.Name, "request-1") + // It may have run before custody was lost: its status says Admitted. + install.Status = ops.OperationStatus{Phase: ops.PhaseAdmitted, Fence: 4} + if err := e.admin.Status().Update(e.ctx, install); err != nil { + t.Fatal(err) + } + custody := verify(e, device, 4) + e.settle(device.Name) + custody = e.custody(device.Name) + if hold := custody.Spec.RecoveryHold; hold == nil || hold.UID != string(install.UID) || custody.Spec.ActiveOperation != nil || custody.Spec.Fence <= 4 { + t.Fatalf("rebuilt = %+v", custody.Spec) + } + e.requirePhase(install, ops.PhaseOutcomeUnknown, ReasonRebuilt) + }) + + t.Run("a pending wipe found during a releasing rebuild is held, not run", func(t *testing.T) { + e := e.sub(t) + device := next() + e.allocation(device, "alloc-r-"+device.Name, "Releasing") + wipe := e.wipe(device, "alloc-r-"+device.Name, 1) + wipe.Status = ops.OperationStatus{Phase: ops.PhasePending, Reason: ReasonOperationActive} + if err := e.admin.Status().Update(e.ctx, wipe); err != nil { + t.Fatal(err) + } + custody := verify(e, device, 0) + if custody.Spec.Holder.Type != ops.HolderRelease || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.UID != string(wipe.UID) || custody.Spec.ActiveOperation != nil { + t.Fatalf("rebuilt = %+v", custody.Spec) + } + e.requirePhase(wipe, ops.PhaseOutcomeUnknown, ReasonRebuilt) + }) + + t.Run("a settled unknown outcome is not held again", func(t *testing.T) { + e := e.sub(t) + device := next() + allocation := "alloc-s-" + device.Name + e.allocation(device, allocation, "Releasing") + verify(e, device, 0) + install := e.installation(device, allocation, "request-1") + install.Status = ops.OperationStatus{Phase: ops.PhaseOutcomeUnknown, Fence: 1, FinishedAt: ptrTime(e.clock.Now())} + if err := e.admin.Status().Update(e.ctx, install); err != nil { + t.Fatal(err) + } + wipe := e.wipe(device, allocation, 1) + wipe.Status = ops.OperationStatus{Phase: ops.PhaseSucceeded, Fence: 2, FinishedAt: ptrTime(e.clock.Now())} + if err := e.admin.Status().Update(e.ctx, wipe); err != nil { + t.Fatal(err) + } + e.dropCustody(device.Name) + custody := verify(e, device, 2) + if custody.Spec.RecoveryHold != nil || len(custody.Spec.Conflicts) != 0 || custody.Spec.Fence != 3 { + t.Fatalf("rebuilt = %+v", custody.Spec) + } + }) + + t.Run("several unproven outcomes keep the newest held and need a Resolve", func(t *testing.T) { + e := e.sub(t) + device := next() + allocation := "alloc-m-" + device.Name + e.allocation(device, allocation, "Active") + var newest *ops.DeviceInstallation + for index, fence := range []int64{2, 5} { + install := e.installation(device, allocation, fmt.Sprintf("request-%d", index)) + install.Status = ops.OperationStatus{Phase: ops.PhaseOutcomeUnknown, Fence: fence, FinishedAt: ptrTime(e.clock.Now())} + if err := e.admin.Status().Update(e.ctx, install); err != nil { + t.Fatal(err) + } + newest = install + } + custody := verify(e, device, 5) + if custody.Spec.State != ops.CustodyUnverified || !slices.Contains(custody.Spec.Conflicts, ConflictMultipleUnfinished) || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.UID != string(newest.UID) { + t.Fatalf("rebuilt = %+v", custody.Spec) + } + // Resolve must agree with the live allocation, and keeps the hold. + wrong := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionResolve, Resolve: &ops.ResolveInput{Holder: ops.HolderNone}}) + e.settle(device.Name) + e.requirePhase(wrong, ops.PhaseFailed, ReasonInvalidResolve) + other := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionResolve, Resolve: &ops.ResolveInput{Holder: ops.HolderAllocation, AllocationRef: &ops.LocalReference{Name: "alloc-invented"}}}) + e.settle(device.Name) + e.requirePhase(other, ops.PhaseFailed, ReasonInvalidResolve) + resolve := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionResolve, Resolve: &ops.ResolveInput{Holder: ops.HolderAllocation, AllocationRef: &ops.LocalReference{Name: allocation}}}) + e.settle(device.Name) + admitted := e.custody(device.Name).Spec.ActiveOperation + if admitted == nil || admitted.Fence <= 5 { + t.Fatalf("Resolve admitted at %+v, at or below the site's fence 5", admitted) + } + // A report of the site's old fence does not confirm the Resolve. + e.settle(device.Name) + e.requirePhase(resolve, ops.PhaseAdmitted, "") + e.sites.report(device.Name, admitted.Fence) + e.settle(device.Name) + e.requirePhase(resolve, ops.PhaseSucceeded, "") + custody = e.custody(device.Name) + if custody.Spec.State != ops.CustodyVerified || custody.Spec.Holder.Type != ops.HolderAllocation || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.UID != string(newest.UID) { + t.Fatalf("after Resolve: %+v", custody.Spec) + } + }) + + t.Run("a succeeded Retire is kept past 30 days until inventory retires the Device", func(t *testing.T) { + e := e.sub(t) + device := next() + verify(e, device, 0) + e.staffOp(device, "ok") + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + hold := *e.custody(device.Name).Spec.RecoveryHold + retire := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(hold)}) + e.settle(device.Name) + e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) + e.settle(device.Name) + e.requirePhase(retire, ops.PhaseSucceeded, "") + e.clock.Advance(DefaultRetention + time.Hour) + if _, err := e.coord.SweepRetention(e.ctx); err != nil { + t.Fatal(err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(retire), retire); err != nil { + t.Fatalf("the only record of the retirement was deleted: %v", err) + } + fence := e.custody(device.Name).Spec.Fence + e.dropCustody(device.Name) + if custody := verify(e, device, fence); custody.Spec.Holder.Type != ops.HolderRetired { + t.Fatalf("rebuilt holder = %s", custody.Spec.Holder.Type) + } + }) +} + +func ptrTime(at time.Time) *metav1.Time { + value := metav1.NewTime(at) + return &value +} + +// claimingClient claims custody and creates the installation the first time +// the coordinator lists installations, after it has read custody. +type claimingClient struct { + client.Client + once sync.Once + before func() +} + +func (c *claimingClient) List(ctx context.Context, list client.ObjectList, options ...client.ListOption) error { + if _, ok := list.(*ops.DeviceInstallationList); ok { + c.once.Do(c.before) + } + return c.Client.List(ctx, list, options...) +} + +func TestARefusalNeverUsesCustodyReadBeforeAHolderChange(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-800", uid(800), fmt.Sprintf("%064x", 800)) + var install *ops.DeviceInstallation + racing := &claimingClient{Client: e.client(), before: func() { + if err := e.coord.Claim(e.ctx, device.Name, "alloc-late"); err != nil { + t.Error(err) + } + install = e.installation(device, "alloc-late", "request-1") + }} + coordinator := e.coordinator(racing) + settleWith(t, e.ctx, coordinator, device.Name) + e.requirePhase(install, ops.PhaseAdmitted, "") + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(install), install); apierrors.IsNotFound(err) { + t.Fatal("installation missing") + } +} diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 29181bed..c06d8346 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -170,6 +170,13 @@ func DeviceRecoveryKind() Kind { return checkRecovery(ctx, admission.Operation.(*ops.DeviceRecovery), admission.Custody, admission.Registry, admission) }, Apply: applyRecovery, + Clears: func(operation ops.Operation) *ops.HeldOperationReference { + spec := operation.(*ops.DeviceRecovery).Spec + if spec.Decision == ops.DecisionSettle || spec.Decision == ops.DecisionRetire { + return spec.Hold + } + return nil + }, Retires: func(operation ops.Operation) bool { spec := operation.(*ops.DeviceRecovery).Spec return spec.Decision == ops.DecisionRetire || (spec.Decision == ops.DecisionResolve && spec.Resolve != nil && spec.Resolve.Holder == ops.HolderRetired) @@ -195,7 +202,7 @@ func checkRecovery(ctx context.Context, recovery *ops.DeviceRecovery, custody *o default: return refuse(ReasonInvalidResolve, "Resolve cannot record holder %s", resolve.Holder) } - return nil + return resolveMatchesAllocations(ctx, admission, resolve) } hold := custody.Spec.RecoveryHold if hold == nil || spec.Hold == nil || spec.Hold.Kind != hold.Kind || spec.Hold.Name != hold.Name || spec.Hold.Fence != hold.Fence { @@ -229,12 +236,43 @@ func checkRecovery(ctx context.Context, recovery *ops.DeviceRecovery, custody *o return refuse(ReasonNoMatchingRule, "unknown decision %q", spec.Decision) } +// resolveMatchesAllocations requires the holder a Resolve records to agree +// with the Device's live MachineAllocations: none for None or Retired, and +// exactly the one named, Releasing for Release, for Allocation and Release. +func resolveMatchesAllocations(ctx context.Context, admission *Admission, resolve *ops.ResolveInput) *Refusal { + if admission.Reader == nil { + return refuse(ReasonInvalidResolve, "the live allocations could not be read") + } + allocations, err := LiveAllocations(ctx, admission.Reader, admission.Device) + if err != nil { + return refuse(ReasonInvalidResolve, "the live allocations could not be read") + } + switch { + case len(allocations) > 1: + return refuse(ReasonInvalidResolve, "%d live allocations name the Device; end all but one first", len(allocations)) + case len(allocations) == 0: + if resolve.Holder != ops.HolderNone && resolve.Holder != ops.HolderRetired { + return refuse(ReasonInvalidResolve, "no live allocation names the Device, so the holder is None or Retired") + } + default: + allocation := allocations[0] + want := ops.HolderAllocation + if allocation.Status.Phase == "Releasing" { + want = ops.HolderRelease + } + if resolve.Holder != want || resolve.AllocationRef == nil || resolve.AllocationRef.Name != allocation.Name { + return refuse(ReasonInvalidResolve, "allocation %s names the Device, so the holder is %s with that allocation", allocation.Name, want) + } + } + return nil +} + // applyRecovery applies a confirmed recovery. It re-checks against the // custody read now, because custody may have changed since admission. func applyRecovery(ctx context.Context, apply *ApplyContext) (*ops.DeviceCustodySpec, *Refusal) { recovery := apply.Operation.(*ops.DeviceRecovery) custody := apply.Custody - if refusal := checkRecovery(ctx, recovery, custody, apply.Registry, &Admission{Operation: recovery, Custody: custody, Device: apply.Device, Registry: apply.Registry, Now: apply.Now}); refusal != nil { + if refusal := checkRecovery(ctx, recovery, custody, apply.Registry, &Admission{Operation: recovery, Custody: custody, Device: apply.Device, Registry: apply.Registry, Reader: apply.Reader, Now: apply.Now}); refusal != nil { return nil, refusal } spec := custody.Spec diff --git a/internal/custody/rebuild.go b/internal/custody/rebuild.go index d6d3ee59..378c9190 100644 --- a/internal/custody/rebuild.go +++ b/internal/custody/rebuild.go @@ -1,6 +1,7 @@ package custody import ( + "cmp" "context" "encoding/json" "slices" @@ -49,7 +50,7 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) if inventory.LifecycleOf(device) == inventory.DeviceRetired { holders[ops.HolderRetired] = true } - allocations, err := c.liveAllocations(ctx, device) + allocations, err := LiveAllocations(ctx, c.Client, device) if err != nil { return spec, err } @@ -65,8 +66,11 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) spec.Holder = ops.Holder{Type: ops.HolderAllocation, AllocationRef: &ops.LocalReference{Name: allocation.Name}} } } - var unfinished []ops.Operation - var unfinishedKinds []string + type found struct { + operation ops.Operation + kind *Kind + } + var all []found for _, kind := range c.Registry.Kinds() { list := kind.NewList() if err := c.Client.List(ctx, list, client.InNamespace(device.Namespace)); err != nil { @@ -82,30 +86,61 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) if kind.Retires != nil && status.Phase == ops.PhaseSucceeded && kind.Retires(operation) { holders[ops.HolderRetired] = true } - if status.Phase.Ended() { + all = append(all, found{operation: operation, kind: kind}) + } + } + // settled reports whether a later success settled an unknown outcome: + // an operation whose kind settles the held kind, or a recovery that + // cleared that exact hold. + settled := func(held found) bool { + fence := held.operation.OperationStatus().Fence + for _, other := range all { + status := other.operation.OperationStatus() + if status.Phase != ops.PhaseSucceeded { continue } - unfinished = append(unfinished, operation) - unfinishedKinds = append(unfinishedKinds, kind.GVK.Kind) - switch { - case envelope.Authority.ServiceRequest != nil && kind.Effectful: - holders[ops.HolderService] = true - case envelope.Authority.AllocationRef != nil: - if spec.Holder.AllocationRef == nil || spec.Holder.AllocationRef.Name != envelope.Authority.AllocationRef.Name { - spec.Conflicts = appendOnce(spec.Conflicts, ConflictHolderSources) + if other.kind.Clears != nil { + if cleared := other.kind.Clears(other.operation); cleared != nil && cleared.Kind == held.kind.GVK.Kind && cleared.Name == held.operation.GetName() && cleared.Fence == fence { + return true } } + if status.Fence > fence && slices.ContainsFunc(other.kind.Settles, func(rule SettleRule) bool { return rule.Held == held.kind.GVK.Kind }) { + return true + } + } + return false + } + // Every operation that has not ended may already have been admitted and + // executed, even if its status says Pending, because custody is written + // before status. An unknown outcome nothing later settled is held too. + var held []found + for _, candidate := range all { + phase := candidate.operation.OperationStatus().Phase + if phase.Ended() && (phase != ops.PhaseOutcomeUnknown || settled(candidate)) { + continue + } + held = append(held, candidate) + envelope := candidate.operation.Envelope() + switch { + case envelope.Authority.ServiceRequest != nil && candidate.kind.Effectful: + holders[ops.HolderService] = true + case envelope.Authority.AllocationRef != nil: + if spec.Holder.AllocationRef == nil || spec.Holder.AllocationRef.Name != envelope.Authority.AllocationRef.Name { + spec.Conflicts = appendOnce(spec.Conflicts, ConflictHolderSources) + } } } - // Every unfinished operation, even one whose status says Pending, may - // already have been admitted and executed, so it is held. - switch len(unfinished) { - case 0: - case 1: - operation := unfinished[0] - spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: unfinishedKinds[0], Name: operation.GetName(), UID: string(operation.GetUID())}, Fence: operation.OperationStatus().Fence, Since: metav1.NewTime(c.now()), Reason: ReasonRebuilt} - default: - spec.Conflicts = appendOnce(spec.Conflicts, ConflictMultipleUnfinished) + if len(held) > 0 { + // With several, the newest is held and a Resolve must decide, so the + // hold is never dropped. + slices.SortStableFunc(held, func(a, b found) int { + return cmp.Compare(b.operation.OperationStatus().Fence, a.operation.OperationStatus().Fence) + }) + newest := held[0] + spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: newest.kind.GVK.Kind, Name: newest.operation.GetName(), UID: string(newest.operation.GetUID())}, Fence: newest.operation.OperationStatus().Fence, Since: metav1.NewTime(c.now()), Reason: ReasonRebuilt} + if len(held) > 1 { + spec.Conflicts = appendOnce(spec.Conflicts, ConflictMultipleUnfinished) + } } if len(holders) > 1 { spec.Conflicts = appendOnce(spec.Conflicts, ConflictHolderSources) @@ -126,11 +161,11 @@ func appendOnce(list []string, value string) []string { return append(list, value) } -// liveAllocations returns the MachineAllocations that are not Released and +// LiveAllocations returns the MachineAllocations that are not Released and // whose MachineCapacity is backed by the Device. -func (c *Coordinator) liveAllocations(ctx context.Context, device *inventory.Device) ([]metal.MachineAllocation, error) { +func LiveAllocations(ctx context.Context, reader client.Reader, device *inventory.Device) ([]metal.MachineAllocation, error) { var allocations metal.MachineAllocationList - if err := c.Client.List(ctx, &allocations); err != nil { + if err := reader.List(ctx, &allocations); err != nil { return nil, err } var out []metal.MachineAllocation @@ -140,7 +175,7 @@ func (c *Coordinator) liveAllocations(ctx context.Context, device *inventory.Dev } capacity := &metal.MachineCapacity{} reference := allocation.Spec.MachineCapacityRef - if err := c.Client.Get(ctx, client.ObjectKey{Namespace: reference.Namespace, Name: reference.Name}, capacity); apierrors.IsNotFound(err) { + if err := reader.Get(ctx, client.ObjectKey{Namespace: reference.Namespace, Name: reference.Name}, capacity); apierrors.IsNotFound(err) { continue } else if err != nil { return nil, err @@ -164,14 +199,14 @@ func (c *Coordinator) verify(ctx context.Context, custody *ops.DeviceCustody, de return Outcome{RequeueAfter: verifyPoll}, nil } for _, site := range sites { - stored, reported, err := c.Sites.Fence(ctx, site, device) + report, reported, err := c.Sites.Fence(ctx, site, device) if err != nil { return Outcome{}, err } if !reported { return Outcome{RequeueAfter: verifyPoll}, nil } - highest = max(highest, stored) + highest = max(highest, report.Seen, report.Stopped) } custody.Spec.State = ops.CustodyVerified custody.Spec.Fence = highest + 1 diff --git a/internal/custody/recovery_test.go b/internal/custody/recovery_test.go index 27fd37d9..561c08d0 100644 --- a/internal/custody/recovery_test.go +++ b/internal/custody/recovery_test.go @@ -216,9 +216,11 @@ func TestRecovery(t *testing.T) { e.settle(device.Name) e.requirePhase(first, ops.PhaseOutcomeUnknown, "") hold := *e.custody(device.Name).Spec.RecoveryHold - blocked := e.wipe(device, "alloc-w", 2) + // A wipe that cannot settle the hold yet waits; its name is + // deterministic, so it could not be created again. + next := e.wipe(device, "alloc-w", 2) e.settle(device.Name) - e.requirePhase(blocked, ops.PhaseFailed, ReasonRecoveryHold) + e.requirePhase(next, ops.PhasePending, ReasonRecoveryHold) // Settle is not how a wipe hold ends. settle := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: heldRef(hold)}) e.settle(device.Name) @@ -228,17 +230,11 @@ func TestRecovery(t *testing.T) { e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) e.settle(device.Name) e.requirePhase(retry, ops.PhaseSucceeded, "") - if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy == nil || got.RetryAuthorizedBy.UID != string(retry.UID) { - t.Fatalf("retry not recorded: %+v", got) - } - second := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) - e.settle(device.Name) - e.requirePhase(second, ops.PhaseFailed, ReasonRetryAuthorized) - third := e.wipe(device, "alloc-w", 3) - e.settle(device.Name) - e.requirePhase(third, ops.PhaseAdmitted, "") - if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy != nil { - t.Fatalf("the retry was not consumed: %+v", got) + // The waiting wipe is the one settling operation the Retry allows. + e.requirePhase(next, ops.PhaseAdmitted, "") + custody := e.custody(device.Name) + if got := custody.Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy != nil || custody.Spec.ActiveOperation.Settles == nil || custody.Spec.ActiveOperation.Settles.UID != hold.UID { + t.Fatalf("the retry was not used by the waiting wipe: %+v", custody.Spec) } if err := e.result(device.Name, ops.PhaseSucceeded, ""); err != nil { t.Fatal(err) @@ -249,6 +245,35 @@ func TestRecovery(t *testing.T) { } }) + t.Run("a second Retry for the same hold is refused", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-rr"); err != nil { + t.Fatal(err) + } + if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-rr"); err != nil { + t.Fatal(err) + } + e.wipe(device, "alloc-rr", 1) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + hold := *e.custody(device.Name).Spec.RecoveryHold + retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + e.settle(device.Name) + e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) + e.settle(device.Name) + e.requirePhase(retry, ops.PhaseSucceeded, "") + if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy == nil || got.RetryAuthorizedBy.UID != string(retry.UID) { + t.Fatalf("retry not recorded: %+v", got) + } + second := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + e.settle(device.Name) + e.requirePhase(second, ops.PhaseFailed, ReasonRetryAuthorized) + }) + t.Run("retiring from Release records disk disposal", func(t *testing.T) { e := e.sub(t) device := fresh() diff --git a/internal/custody/registry.go b/internal/custody/registry.go index a44683d8..897d5fef 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -89,8 +89,12 @@ type Kind struct { // confirmed by its site fence. It returns the custody to write. Apply func(context.Context, *ApplyContext) (*ops.DeviceCustodySpec, *Refusal) // Retires reports whether a succeeded operation of this kind retired the - // Device. Rebuild reads it. + // Device. Rebuild and retention read it. Retires func(ops.Operation) bool + // Clears returns the hold a succeeded operation of this kind cleared, if + // any. Rebuild reads it to tell a settled unknown outcome from one that + // is still held. + Clears func(ops.Operation) *ops.HeldOperationReference } func (k *Kind) checksDiscovery(operation ops.Operation) bool { @@ -111,7 +115,9 @@ type Admission struct { Device *inventory.Device Row Rule Registry *Registry - Now time.Time + // Reader reads the provider project. A check must not write. + Reader client.Reader + Now time.Time } // RecoverySettleContext is what a held kind's settle hook sees. @@ -129,6 +135,8 @@ type ApplyContext struct { Custody *ops.DeviceCustody Device *inventory.Device Registry *Registry + // Reader reads the provider project. Apply must not write. + Reader client.Reader // ConfirmedFence is the lowest fence the serving sites report, and // HighestFence the highest. Both are at least the operation's fence. ConfirmedFence int64 diff --git a/internal/custody/retention.go b/internal/custody/retention.go index 7abf3e4c..805a7c72 100644 --- a/internal/custody/retention.go +++ b/internal/custody/retention.go @@ -3,6 +3,7 @@ package custody import ( "context" + 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" "k8s.io/apimachinery/pkg/types" @@ -11,7 +12,8 @@ import ( // SweepRetention deletes operations that finished more than // Config.Retention ago. An operation custody still names, as active or as -// its recovery hold, is kept. Platform audit records keep the history after +// its recovery hold, is kept, and so is a succeeded retirement until +// inventory retires the Device. Platform audit records keep the history after // that. func (c *Coordinator) SweepRetention(ctx context.Context) (int, error) { cfg := c.config() @@ -40,6 +42,17 @@ func (c *Coordinator) SweepRetention(ctx context.Context) (int, error) { if !status.Phase.Ended() || status.FinishedAt == nil || !status.FinishedAt.Time.Before(cutoff) || referenced[operation.GetUID()] { continue } + // A succeeded retirement is the only record of it until + // inventory retires the Device, and rebuild reads it. + if kind.Retires != nil && status.Phase == ops.PhaseSucceeded && kind.Retires(operation) { + device, err := c.device(ctx, operation.Envelope().DeviceRef.Name) + if err != nil { + return deleted, err + } + if device != nil && inventory.LifecycleOf(device) != inventory.DeviceRetired { + continue + } + } uid := operation.GetUID() if err := c.Client.Delete(ctx, operation, client.Preconditions{UID: &uid}); err != nil && !apierrors.IsNotFound(err) { return deleted, err diff --git a/internal/custody/testdata/crds/test-kinds.yaml b/internal/custody/testdata/crds/test-kinds.yaml index ff3f95ed..67985f52 100644 --- a/internal/custody/testdata/crds/test-kinds.yaml +++ b/internal/custody/testdata/crds/test-kinds.yaml @@ -171,7 +171,7 @@ spec: type: object x-kubernetes-preserve-unknown-fields: true x-kubernetes-validations: - - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled''], ''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])' + - 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 @@ -347,7 +347,7 @@ spec: type: object x-kubernetes-preserve-unknown-fields: true x-kubernetes-validations: - - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled''], ''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])' + - 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 From 5a8d255dc106c48b90d13f6c222a27f5d267bc07 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 19:13:07 -0600 Subject: [PATCH 08/19] docs: Record how rebuild keeps unproven outcomes held Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 58 ++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 15 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 2f3d59b6..c331cbfa 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -31,7 +31,9 @@ marked **implemented and verified**, **implemented and inert**, or - **Operations.** Every kind starts with one envelope: `creator`, `deviceRef` (name and UID) and `authority` (exactly one of `allocationRef` and `serviceRequest`). The spec is immutable after create. Status phases move - forward only, and an ended phase is final. + forward only, and an ended phase is final. `Pending` may end + `OutcomeUnknown`, because rebuild holds an operation whose status still + says `Pending`. - **The coordinator** (`internal/custody`) is the only writer of custody and of operation status. Every custody change is one update that carries the resourceVersion just read. On a conflict it reads again and decides again. @@ -78,9 +80,11 @@ Each decision lists the open point from the implementation brief it settles. queues. A kind's rows are matched only against operations of that kind, so adding a row never changes how another row is evaluated. - **Queueing.** Provider and release rows queue. They wait in `Pending` while - another operation runs, while custody is `Unverified`, or while discovery is - not current. All three can clear on their own. Staff rows never queue: those - conditions end a staff operation `Failed`. + another operation runs, while custody is `Unverified`, while discovery is + not current, or while a recovery hold that they cannot settle exists. Each + of these can clear, and a queued operation's name is deterministic, so it + could not be created again. Staff rows never queue: those conditions end a + staff operation `Failed`. - **Phases for refusals (O5).** A refusal ends `Failed` with a reason, and nothing is sent. Expired, superseded and no-longer-matching operations end `Cancelled`. A `Pending` operation whose holder no longer matches is @@ -113,11 +117,20 @@ Each decision lists the open point from the implementation brief it settles. and step. Staff kinds must use a generated name. - **Order.** Pending operations are admitted oldest first. Ties break on kind, then name, then UID, so every coordinator picks the same one. +- **Refusals use current custody.** The coordinator reads custody, lists the + operations, and reads custody again. It decides only if custody did not + change in between. A claim followed by its installation's create is + therefore seen before the installation could be refused. - **Racing refusals.** Delivery must wait until operation status shows `Admitted`. If a racing coordinator ends an operation, or it is deleted, after custody admitted it but before the status copy, custody withdraws it (`Cancelled`, `Withdrawn`). Nothing was delivered, and the fence stays raised. +- **Fences.** Admission raises the fence above both custody's fence and every + fence a serving site reports having seen. Each site reports two fences: the + highest it has seen, and the highest for which it confirmed that older + workers stopped. A site report at or above an admission's fence therefore + proves the site received that admission. ### Deadlines and clock skew (O4) @@ -142,8 +155,8 @@ Each value is configurable. - A settling operation records the hold it settles. If it succeeds, the hold is cleared. If it also ends unknown, its hold replaces the old one. - A `DeviceRecovery` is admitted like any operation and raises the fence. The - coordinator applies it only after every site serving the Device reports a - stored fence at least that high, so the held worker has stopped. If no site + coordinator applies it only after every site serving the Device confirms + that every worker below that fence stopped. If no site confirms before its deadline, it ends `Failed` with `SiteNotConfirmed`, and the hold stays. It does not end `OutcomeUnknown`, because it cannot change the server. @@ -156,21 +169,32 @@ Each value is configurable. `Release` requires a disk disposal record. - `Resolve` is the only operation `Unverified` custody admits. It records the holder (`None`, `Allocation`, `Release` or `Retired`), marks custody - `Verified`, and adopts the current Device UID. A rebuilt hold stays, to be - settled separately. + `Verified`, and adopts the current Device UID. The holder must agree with + the Device's live MachineAllocations, both at admission and when it is + applied: `None` or `Retired` when none names the Device, and `Allocation` + or `Release` with the one that does. A rebuilt hold stays, to be settled + separately. - Nothing retries an operation automatically. ### Rebuilding custody (O13, O15, O16) - Missing custody is created `Unverified` from the Device's lifecycle and succeeded `Retire` recoveries, its MachineAllocations that are not - `Released`, and its operations that have not ended. A releasing allocation - rebuilds `Release` with every gate open. + `Released`, and its operations. A releasing allocation rebuilds `Release` + with every gate open. - Every operation that has not ended is held, even if its status says - `Pending`, because custody is written before status. -- Two live allocations, two unfinished operations, holder sources that - disagree, a Device UID that differs from custody, or a missing Device each - keep custody `Unverified` until a `Resolve`. + `Pending`, because custody is written before status. Its status is ended + `OutcomeUnknown` with reason `Rebuilt`, and it is never admitted again. +- An operation that ended `OutcomeUnknown` is held again unless something + later settled it: a succeeded operation with a higher fence whose kind + settles the held kind, or a succeeded recovery that cleared that exact + hold. +- If several operations would be held, the one with the highest fence is + held and custody stays `Unverified`, so a `Resolve` must decide and the hold + is never dropped. +- Two live allocations, holder sources that disagree, a Device UID that + differs from custody, or a missing Device also keep custody `Unverified` + until a `Resolve`. - Custody becomes `Verified` only after every site configured to serve the Device reports its stored fence. The new fence is above every fence those sites and the operations have used. A Device no site serves stays @@ -219,7 +243,9 @@ remains. ### Other decisions - **Retention.** Finished operations are deleted 30 days after they end, - unless custody still names them as active or as the hold. + unless custody still names them as active or as the hold. A succeeded + retirement is kept until inventory retires the Device, because until then + it is the only record rebuild can read. - **Rejected results.** A result whose fence or operation does not match the active operation is refused, and custody counts it and records the last one for monitoring. It never changes the holder. A retry of a result already @@ -311,7 +337,9 @@ a real API server: | Every holder transition, pending order, supersede, cancellation on holder change, stale fences, results, deadlines | `TestLifecycle`, `TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing` | | Holds and settlement through the test-only kind, install and wipe holds, `Retry`, `Retire`, retention | `TestRecovery` | | Rebuild from each source, each conflict, `Resolve`, custody deleted and restored | `TestRebuild` | +| Rebuild holds unproven and unfinished installations and wipes without admitting them again, settled outcomes, several unproven outcomes, `Resolve` against live allocations, fences above the site's, retirements kept past retention | `TestRebuildKeepsUnprovenOutcomes` | | Two allocators, allocator against staff, two coordinators, admission against a holder change, two Devices, a lost claim response | `TestConcurrency` | +| A claim and its installation landing between the custody read and the operation list | `TestARefusalNeverUsesCustodyReadBeforeAHolderChange` | | A crash between each pair of custody and status writes, with dropped and lost responses | `TestWriteOrderCrashRecovery` | | CEL rules | `TestCRDRules` | | Seams, rows, principals, ordering, evidence bounds, capacity for every input | `TestRegistryRejectsIncompleteKindsAndRows`, `TestAddingRowsLeavesExistingRowsAlone`, `TestPrincipals`, `TestCandidatesOrderOldestFirstWithADeterministicTieBreak`, `TestEvidenceIsTypedAndBounded`, `TestCapacityProjection` | From d741b9aedb4d5bee2a12049c078a206f20a0f73f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 19:28:21 -0600 Subject: [PATCH 09/19] test(custody): Guard the site fence report and held operations Separate the fence a fake site has seen from the fence for which it confirmed older workers stopped, and test that admission rises above the first while a recovery waits for the second. Test on its own that a held operation is never a candidate for admission. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 1 + internal/custody/harness_test.go | 23 ++++++++++++--- internal/custody/holds_test.go | 47 ++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index c331cbfa..6efb5d20 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -340,6 +340,7 @@ a real API server: | Rebuild holds unproven and unfinished installations and wipes without admitting them again, settled outcomes, several unproven outcomes, `Resolve` against live allocations, fences above the site's, retirements kept past retention | `TestRebuildKeepsUnprovenOutcomes` | | Two allocators, allocator against staff, two coordinators, admission against a holder change, two Devices, a lost claim response | `TestConcurrency` | | A claim and its installation landing between the custody read and the operation list | `TestARefusalNeverUsesCustodyReadBeforeAHolderChange` | +| Admission above the fence a site has seen; a recovery confirmed only by the stopped fence; a held operation never a candidate | `TestFencesFollowTheSiteReport`, `TestAHeldOperationIsNeverACandidate` | | A crash between each pair of custody and status writes, with dropped and lost responses | `TestWriteOrderCrashRecovery` | | CEL rules | `TestCRDRules` | | Seams, rows, principals, ordering, evidence bounds, capacity for every input | `TestRegistryRejectsIncompleteKindsAndRows`, `TestAddingRowsLeavesExistingRowsAlone`, `TestPrincipals`, `TestCandidatesOrderOldestFirstWithADeterministicTieBreak`, `TestEvidenceIsTypedAndBounded`, `TestCapacityProjection` | diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index f7bbe385..1f813c73 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -65,10 +65,14 @@ type fakeSites struct { mu sync.Mutex serving map[string][]string fences map[string]int64 + // seen, when set for a Device, is reported as the site's seen fence in + // place of its stopped fence, as a site whose older worker has not yet + // stopped would report. + seen map[string]int64 } func newFakeSites() *fakeSites { - return &fakeSites{serving: map[string][]string{}, fences: map[string]int64{}} + return &fakeSites{serving: map[string][]string{}, fences: map[string]int64{}, seen: map[string]int64{}} } func (s *fakeSites) Serving(device *inventory.Device) []string { @@ -80,13 +84,24 @@ func (s *fakeSites) Serving(device *inventory.Device) []string { return []string{testSite} } -// Fence reports one fence as both seen and stopped: the fake site's workers -// stop as soon as a newer fence arrives. +// Fence reports the stored fence as both seen and stopped, unless a seen +// fence was set for the Device. func (s *fakeSites) Fence(_ context.Context, site string, device *inventory.Device) (SiteFence, bool, error) { s.mu.Lock() defer s.mu.Unlock() fence, ok := s.fences[site+"/"+device.Name] - return SiteFence{Seen: fence, Stopped: fence}, ok, nil + seen := fence + if value, set := s.seen[device.Name]; set { + seen = value + } + return SiteFence{Seen: seen, Stopped: fence}, ok, nil +} + +// reportSeen makes the site report a seen fence above its stopped fence. +func (s *fakeSites) reportSeen(device string, seen int64) { + s.mu.Lock() + defer s.mu.Unlock() + s.seen[device] = seen } // report stores the fence a site reports for a Device. diff --git a/internal/custody/holds_test.go b/internal/custody/holds_test.go index cee3c7fe..9ee3a946 100644 --- a/internal/custody/holds_test.go +++ b/internal/custody/holds_test.go @@ -237,3 +237,50 @@ func TestARefusalNeverUsesCustodyReadBeforeAHolderChange(t *testing.T) { t.Fatal("installation missing") } } + +// TestFencesFollowTheSiteReport separates the fence a site has seen from the +// fence for which it confirmed older workers stopped. +func TestFencesFollowTheSiteReport(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-810", uid(810), fmt.Sprintf("%064x", 810)) + hold := e.holdOn(device) + // The site has seen fence 20 from an assignment custody never recorded, + // and has confirmed stopped workers only up to the held fence. + e.sites.report(device.Name, hold.Fence) + e.sites.reportSeen(device.Name, 20) + retire := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(hold)}) + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + if active == nil || active.Fence <= 20 { + t.Fatalf("admitted at %+v, at or below the fence the site has seen", active) + } + // Seen alone never confirms a recovery. + e.sites.reportSeen(device.Name, active.Fence) + e.settle(device.Name) + e.requirePhase(retire, ops.PhaseAdmitted, "") + e.sites.report(device.Name, active.Fence) + e.settle(device.Name) + e.requirePhase(retire, ops.PhaseSucceeded, "") +} + +// TestAHeldOperationIsNeverACandidate checks the exclusion on its own, +// without the status copy that also ends a held operation. +func TestAHeldOperationIsNeverACandidate(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-820", uid(820), fmt.Sprintf("%064x", 820)) + if err := e.coord.Claim(e.ctx, device.Name, "alloc-held"); err != nil { + t.Fatal(err) + } + install := e.installation(device, "alloc-held", "request-1") + custody := e.custody(device.Name) + custody.Spec.RecoveryHold = &ops.RecoveryHold{OperationReference: reference("DeviceInstallation", install), Fence: 0, Since: metav1.NewTime(e.clock.Now()), Reason: ReasonRebuilt} + candidates, err := e.coord.candidates(e.ctx, custody) + if err != nil { + t.Fatal(err) + } + for _, candidate := range candidates { + if candidate.operation.GetUID() == install.UID { + t.Fatal("the held operation is a candidate for admission") + } + } +} From 7113916a6af98845810025ed8a01f2e01e9baff8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 20:29:40 -0600 Subject: [PATCH 10/19] feat(custody): Widen the seams a new operation kind plugs into Kind checks now see the Device object the snapshot records, the injected clock and the discovery interval, and the coordinator decides again if the Device changes before the custody update. Kinds can add bounded fields to the snapshot, declare their refusal reasons with where each is raised, and declare whether a Retry applies to their holds. A hold keeps its deadline and admission snapshot for the settle hook. A refusal with an undeclared reason is recorded as UndeclaredReason. Co-Authored-By: Claude Opus 5.5 --- .../crds/fleet.datumapis.com.yaml | 54 ++++++ internal/api/operations/v1alpha1/types.go | 15 +- internal/custody/admission_test.go | 5 +- internal/custody/coordinator.go | 72 ++++++-- internal/custody/extension_test.go | 172 ++++++++++++++++++ internal/custody/kinds.go | 9 +- internal/custody/rebuild.go | 3 +- internal/custody/registry.go | 97 +++++++++- .../custody/testdata/crds/test-kinds.yaml | 12 ++ internal/custody/testkinds_test.go | 36 +++- 10 files changed, 451 insertions(+), 24 deletions(-) create mode 100644 internal/custody/extension_test.go diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 4f2a7fb1..18154ab5 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -161,6 +161,12 @@ spec: discoveryObservedAt: type: string maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 creator: type: object properties: @@ -280,6 +286,36 @@ spec: type: string minLength: 1 maxLength: 128 + deadline: + type: string + format: date-time + 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 retryAuthorizedBy: type: object properties: @@ -571,6 +607,12 @@ spec: discoveryObservedAt: type: string maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 evidence: type: object x-kubernetes-preserve-unknown-fields: true @@ -761,6 +803,12 @@ spec: discoveryObservedAt: type: string maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 evidence: type: object x-kubernetes-preserve-unknown-fields: true @@ -1021,6 +1069,12 @@ spec: discoveryObservedAt: type: string maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 evidence: type: object x-kubernetes-preserve-unknown-fields: true diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 61ed4e33..46fc6052 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -129,6 +129,10 @@ type DeviceSnapshot struct { BMCPublicKeySHA256 string `json:"bmcPublicKeySHA256"` DeviceGeneration int64 `json:"deviceGeneration"` DiscoveryObservedAt string `json:"discoveryObservedAt"` + // Extra holds bounded fields a kind adds at admission, such as the reset + // types discovery offered. The worker and recovery see what admission + // saw. + Extra map[string]string `json:"extra,omitempty"` } // OperationResult is how one operation ended, with its typed evidence. @@ -146,9 +150,14 @@ type OperationResult struct { // operations its kind allows are admitted while it exists. type RecoveryHold struct { OperationReference `json:",inline"` - Fence int64 `json:"fence"` - Since metav1.Time `json:"since"` - Reason string `json:"reason"` + Fence int64 `json:"fence"` + // Since is when the held operation ended with an unknown outcome. + Since metav1.Time `json:"since"` + Reason string `json:"reason"` + // Deadline is the held operation's deadline, when it was known. + Deadline *metav1.Time `json:"deadline,omitempty"` + // Snapshot is the Device snapshot the held operation was admitted with. + Snapshot *DeviceSnapshot `json:"snapshot,omitempty"` // RetryAuthorizedBy names the DeviceRecovery with Retry that lets the // held operation's requester create one settling operation. RetryAuthorizedBy *OperationReference `json:"retryAuthorizedBy,omitempty"` diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 6e9f5db9..84c46819 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -2,6 +2,7 @@ package custody import ( "fmt" + "reflect" "testing" "time" @@ -44,11 +45,11 @@ func TestAdmissionPreconditions(t *testing.T) { t.Fatalf("active = %+v", active) } want := ops.DeviceSnapshot{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: device.Spec.Identity.SystemUUID, BMCPublicKeySHA256: fmt.Sprintf("%064x", n), DeviceGeneration: device.Generation, DiscoveryObservedAt: e.clock.Now().Format(time.RFC3339)} - if active.Snapshot != want { + if !reflect.DeepEqual(active.Snapshot, want) { t.Fatalf("snapshot = %+v, want %+v", active.Snapshot, want) } status := e.requirePhase(operation, ops.PhaseAdmitted, "") - if status.Fence != active.Fence || status.InputDigest != digest || status.Snapshot == nil || *status.Snapshot != want { + if status.Fence != active.Fence || status.InputDigest != digest || status.Snapshot == nil || !reflect.DeepEqual(*status.Snapshot, want) { t.Fatalf("status copy = %+v", status) } }) diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 67d56fe9..26385095 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -2,8 +2,10 @@ package custody import ( "context" + "errors" "fmt" "reflect" + "regexp" "slices" "sort" "time" @@ -52,16 +54,21 @@ type Config struct { SkewMargin time.Duration // Retention is how long finished operations are kept. Retention time.Duration + // DiscoveryInterval is how often BMC discovery reads each BMC. Kind + // checks receive it. + DiscoveryInterval time.Duration // DiscoveryMaxAge is how old the last complete discovery may be for - // identity to count as current. + // identity to count as current. It defaults to twice DiscoveryInterval. DiscoveryMaxAge time.Duration } const ( - DefaultStaffExpiry = 5 * time.Minute - DefaultSkewMargin = 2 * time.Minute - DefaultRetention = 30 * 24 * time.Hour - DefaultDiscoveryMaxAge = 2 * time.Hour + DefaultStaffExpiry = 5 * time.Minute + DefaultSkewMargin = 2 * time.Minute + DefaultRetention = 30 * 24 * time.Hour + // DefaultDiscoveryInterval matches BMC discovery's default interval. + DefaultDiscoveryInterval = time.Hour + DefaultDiscoveryMaxAge = 2 * DefaultDiscoveryInterval ) func (c Config) withDefaults() Config { @@ -77,8 +84,11 @@ func (c Config) withDefaults() Config { if c.Retention == 0 { c.Retention = DefaultRetention } + if c.DiscoveryInterval == 0 { + c.DiscoveryInterval = DefaultDiscoveryInterval + } if c.DiscoveryMaxAge == 0 { - c.DiscoveryMaxAge = DefaultDiscoveryMaxAge + c.DiscoveryMaxAge = 2 * c.DiscoveryInterval } return c } @@ -400,7 +410,7 @@ func (c *Coordinator) progressActive(ctx context.Context, custody *ops.DeviceCus return c.writeCustody(ctx, custody) } spec, refusal := kind.Apply(ctx, &ApplyContext{Operation: operation, Custody: custody.DeepCopy(), Device: device, Registry: c.Registry, Reader: c.Client, ConfirmedFence: confirmed, HighestFence: highest, Now: now}) - if refusal != nil { + if refusal = c.Registry.declaredRefusal(kind.GVK.Kind, heldKind(custody), refusal); refusal != nil { c.finishActive(custody, active, ops.PhaseFailed, refusal.Reason, refusal.Message, nil) return c.writeCustody(ctx, custody) } @@ -480,7 +490,8 @@ func (c *Coordinator) holdUnknown(custody *ops.DeviceCustody, active ops.ActiveO spec := &custody.Spec now := metav1.NewTime(c.now()) spec.ActiveOperation = nil - spec.RecoveryHold = &ops.RecoveryHold{OperationReference: active.OperationReference, Fence: active.Fence, Since: now, Reason: reason} + deadline, snapshot := active.Deadline, active.Snapshot + spec.RecoveryHold = &ops.RecoveryHold{OperationReference: active.OperationReference, Fence: active.Fence, Since: now, Reason: reason, Deadline: &deadline, Snapshot: &snapshot} spec.LastResult = &ops.OperationResult{OperationReference: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseOutcomeUnknown, Reason: reason, Message: message, FinishedAt: now} if evidence != nil { spec.LastResult.Evidence = rawExtension(evidence) @@ -548,6 +559,7 @@ type decision struct { message string row Rule settles *ops.OperationReference + extra map[string]string } // admit evaluates pending candidates and admits at most one with a single @@ -708,6 +720,7 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } return fail(ReasonOperationActive, "another operation is running, and staff operations never wait") } + admission := &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Now: now, DiscoveryInterval: cfg.DiscoveryInterval} // Preconditions 5 and 6: current discovery and a unique BMC key. if kind.checksDiscovery(operation) { if refusal := c.identityCurrent(device, now); refusal != nil { @@ -721,11 +734,20 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } } if kind.Check != nil { - if refusal := kind.Check(ctx, &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Now: now}); refusal != nil { + if refusal := c.Registry.declaredRefusal(kind.GVK.Kind, heldKind(custody), kind.Check(ctx, admission)); refusal != nil { return fail(refusal.Reason, "%s", refusal.Message) } } - return decision{row: row, settles: settles} + // Kind fields for the snapshot come from the same Device and clock the + // checks saw. + var extra map[string]string + if kind.SnapshotExtra != nil { + extra = kind.SnapshotExtra(admission) + if err := validExtra(extra); err != nil { + return fail(ReasonSnapshotInvalid, "%s", err.Error()) + } + } + return decision{row: row, settles: settles, extra: extra} } // wait returns Pending for queue rows and Failed otherwise. @@ -795,6 +817,15 @@ func (c *Coordinator) admitOne(ctx context.Context, custody *ops.DeviceCustody, if err != nil { return Outcome{}, err } + // The Device must not change between the checks and the custody update. + // If it did, discovery may have moved, so decide again. + current := &inventory.Device{} + if err := c.Client.Get(ctx, client.ObjectKeyFromObject(device), current); err != nil { + return Outcome{}, err + } + if current.ResourceVersion != device.ResourceVersion { + return Outcome{Changed: true}, nil + } now := c.now() spec := &custody.Spec // The fence rises above every fence a site has seen, so a site report at @@ -811,7 +842,7 @@ func (c *Coordinator) admitOne(ctx context.Context, custody *ops.DeviceCustody, AdmittedAt: metav1.NewTime(now), Deadline: metav1.NewTime(now.Add(kind.Deadline)), InputDigest: digest, - Snapshot: snapshot(kind, operation, device), + Snapshot: snapshot(kind, operation, device, d.extra), Creator: operation.Envelope().Creator, Settles: d.settles, } @@ -832,8 +863,8 @@ func (c *Coordinator) admitOne(ctx context.Context, custody *ops.DeviceCustody, return outcome, err } -func snapshot(kind *Kind, operation ops.Operation, device *inventory.Device) ops.DeviceSnapshot { - out := ops.DeviceSnapshot{SystemUUID: device.Spec.Identity.SystemUUID, DeviceGeneration: device.Generation} +func snapshot(kind *Kind, operation ops.Operation, device *inventory.Device, extra map[string]string) ops.DeviceSnapshot { + out := ops.DeviceSnapshot{SystemUUID: device.Spec.Identity.SystemUUID, DeviceGeneration: device.Generation, Extra: extra} if device.Spec.BMC != nil { out.BMCEndpoint = device.Spec.BMC.Endpoint } @@ -855,3 +886,18 @@ func snapshot(kind *Kind, operation ops.Operation, device *inventory.Device) ops } return out } + +var extraKey = regexp.MustCompile(`^[a-z][A-Za-z0-9]{0,62}$`) + +// validExtra bounds the fields a kind adds to the snapshot. +func validExtra(extra map[string]string) error { + if len(extra) > 16 { + return errors.New("a kind adds at most 16 snapshot fields") + } + for key, value := range extra { + if !extraKey.MatchString(key) || len(value) > 256 { + return fmt.Errorf("snapshot field %q is not a camelCase name with a value of at most 256 bytes", key) + } + } + return nil +} diff --git a/internal/custody/extension_test.go b/internal/custody/extension_test.go new file mode 100644 index 00000000..f4a3f20d --- /dev/null +++ b/internal/custody/extension_test.go @@ -0,0 +1,172 @@ +package custody + +import ( + "fmt" + "strings" + "testing" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// TestExtensionSeams covers what a new kind, such as power, relies on. +func TestExtensionSeams(t *testing.T) { + e := startEnv(t) + n := 900 + fresh := func() *inventory.Device { + n++ + return e.verified(fmt.Sprintf("server-example-%03d", n), uid(n), fmt.Sprintf("%064x", n)) + } + + t.Run("checks see the Device the snapshot records; a Device change before the update decides again", func(t *testing.T) { + e := e.sub(t) + device := fresh() + var seen []string + var intervals []time.Duration + touched := false + hook := func(admission *Admission) { + seen = append(seen, admission.Device.ResourceVersion) + intervals = append(intervals, admission.DiscoveryInterval) + if !touched { + // Discovery writes the Device after the check read it. + touched = true + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now().Add(time.Second)) + } + } + checkHook.Store(&hook) + defer checkHook.Store(nil) + e.staffOp(device, "ok") + e.settle(device.Name) + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + if len(seen) != 2 || seen[0] == seen[1] || seen[1] != device.ResourceVersion { + t.Fatalf("checks saw Device versions %v; the current version is %s", seen, device.ResourceVersion) + } + if intervals[0] != DefaultDiscoveryInterval { + t.Fatalf("discovery interval = %s", intervals[0]) + } + if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.Snapshot.DeviceGeneration != device.Generation { + t.Fatalf("active = %+v", active) + } + }) + + t.Run("a newer pending operation replaces only its own kind under the same authority", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-scope"); err != nil { + t.Fatal(err) + } + running := e.installation(device, "alloc-scope", "request-running") + e.settle(device.Name) + e.requirePhase(running, ops.PhaseAdmitted, "") + install := e.installation(device, "alloc-scope", "request-waiting") + time.Sleep(1100 * time.Millisecond) + older := e.providerOp(device, "alloc-scope", "older") + time.Sleep(1100 * time.Millisecond) + newer := e.providerOp(device, "alloc-scope", "newer") + e.settle(device.Name) + e.requirePhase(install, ops.PhasePending, ReasonOperationActive) + e.requirePhase(older, ops.PhaseCancelled, ReasonSuperseded) + e.requirePhase(newer, ops.PhasePending, ReasonOperationActive) + }) + + t.Run("kinds add bounded snapshot fields that the hold and the settle hook keep", func(t *testing.T) { + e := e.sub(t) + device := fresh() + operation := e.staffOp(device, "extra") + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + if active == nil || active.Snapshot.Extra["resetTypes"] != "On,ForceOff" || active.Snapshot.Extra["discoveryInterval"] != DefaultDiscoveryInterval.String() { + t.Fatalf("active snapshot = %+v", active) + } + if status := e.status(operation); status.Snapshot == nil || status.Snapshot.Extra["resetTypes"] != "On,ForceOff" { + t.Fatalf("status snapshot = %+v", status.Snapshot) + } + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + hold := *e.custody(device.Name).Spec.RecoveryHold + if hold.Snapshot == nil || hold.Snapshot.Extra["resetTypes"] != "On,ForceOff" || hold.Deadline == nil || !hold.Deadline.Equal(&active.Deadline) { + t.Fatalf("hold = %+v", hold) + } + // The settle hook requires the hold's deadline and snapshot. + e.clock.Advance(time.Minute) + settle := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: heldRef(hold), Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(e.clock.Now()), Summary: "s", Data: map[string]string{"state": "On"}}}) + e.settle(device.Name) + e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) + e.settle(device.Name) + e.requirePhase(settle, ops.PhaseSucceeded, "") + + bounded := fresh() + tooMuch := e.staffOp(bounded, "too-much") + e.settle(bounded.Name) + e.requirePhase(tooMuch, ops.PhaseFailed, ReasonSnapshotInvalid) + }) + + t.Run("a refusal with a reason the kind never declared is recorded as UndeclaredReason", func(t *testing.T) { + e := e.sub(t) + device := fresh() + operation := e.staffOp(device, "undeclared") + e.settle(device.Name) + status := e.requirePhase(operation, ops.PhaseFailed, ReasonUndeclared) + if !strings.Contains(status.Message, "Unlisted") { + t.Fatalf("message = %s", status.Message) + } + }) + + t.Run("Retry applies only to a kind that declares it", func(t *testing.T) { + e := e.sub(t) + device := fresh() + hold := e.holdOn(device) + retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + e.settle(device.Name) + e.requirePhase(retry, ops.PhaseFailed, ReasonNotRetryable) + }) + + t.Run("a worker refusal with nothing sent ends Failed and returns a Service holder to None", func(t *testing.T) { + e := e.sub(t) + device := fresh() + operation := e.staffOp(device, "ok") + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + if err := e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseFailed, Reason: "PublicKeyMismatch"}); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, "PublicKeyMismatch") + if custody := e.custody(device.Name); custody.Spec.Holder.Type != ops.HolderNone || custody.Spec.RecoveryHold != nil || custody.Spec.Fence != active.Fence { + t.Fatalf("custody = %+v", custody.Spec) + } + }) +} + +func TestRegistryValidatesDeclaredReasons(t *testing.T) { + for name, reasons := range map[string][]Reason{ + "not CamelCase": {{Name: "not-camel", RaisedBy: RaisedByCoordinator}}, + "shared": {{Name: ReasonHolderMismatch, RaisedBy: RaisedByCoordinator}}, + "twice": {{Name: "Twice", RaisedBy: RaisedByCoordinator}, {Name: "Twice", RaisedBy: RaisedByWorker}}, + "no source": {{Name: "NoSource"}}, + } { + kind := testKinds()[0] + kind.Reasons = reasons + if err := NewRegistry().Register(kind); err == nil { + t.Fatalf("%s: registered", name) + } + } + registry := testRegistry(t) + if !registry.Declared("DeviceInstallation", ReasonBootstrapUnsupported, RaisedByWorker) || !registry.Declared("DeviceInstallation", ReasonBootInterfaceUnknown, RaisedByCoordinator) || registry.Declared("DeviceInstallation", ReasonBootInterfaceUnknown, RaisedByWorker) { + t.Fatal("declared sources are not kept") + } + // A kind may settle no hold itself. + none := testKinds()[1] + none.GVK.Kind, none.Settles = "DeviceTestUnsettled", nil + c := &Coordinator{Registry: registry} + if c.settlesHold(&none, ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceTestUnsettled"}}) { + t.Fatal("a kind with no settle rules settled a hold") + } +} diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index c06d8346..de75ad2f 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -106,6 +106,7 @@ func DeviceInstallationKind() Kind { return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", installation.Spec.BootInterface) }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, + Reasons: []Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}}, Evidence: StrictEvidence(evidenceLimit, func(evidence *ops.InstallationEvidence) error { return validateSteps(evidence.Steps) }), @@ -132,7 +133,8 @@ func DeviceWipeKind() Kind { Effectful: true, // A wipe after release settles an installation hold. A held wipe is // settled by a later wipe only after a DeviceRecovery with Retry. - Settles: []SettleRule{{Held: "DeviceInstallation"}, {Held: "DeviceWipe", RequiresRetry: true}}, + Settles: []SettleRule{{Held: "DeviceInstallation"}, {Held: "DeviceWipe", RequiresRetry: true}}, + Retryable: true, Evidence: StrictEvidence(evidenceLimit, func(evidence *ops.WipeEvidence) error { if len(evidence.WipedDisks) > 16 { return errors.New("evidence records at most 16 disks") @@ -160,6 +162,8 @@ func DeviceRecoveryKind() Kind { Naming: GeneratedName, Deadline: RecoveryDeadline, Variant: func(operation ops.Operation) string { return string(operation.(*ops.DeviceRecovery).Spec.Decision) }, + Reasons: []Reason{{Name: ReasonHoldMismatch, RaisedBy: RaisedByCoordinator}, {Name: ReasonNotSettleable, RaisedBy: RaisedByCoordinator}, {Name: ReasonNotRetryable, RaisedBy: RaisedByCoordinator}, + {Name: ReasonRetryAuthorized, RaisedBy: RaisedByCoordinator}, {Name: ReasonDisposalRequired, RaisedBy: RaisedByCoordinator}, {Name: ReasonInvalidResolve, RaisedBy: RaisedByCoordinator}}, // Retire and Resolve must work on a server whose BMC is // unreachable. Settle and Retry still need current discovery. SkipsDiscovery: func(operation ops.Operation) bool { @@ -219,6 +223,9 @@ func checkRecovery(ctx context.Context, recovery *ops.DeviceRecovery, custody *o if hold.RetryAuthorizedBy != nil { return refuse(ReasonRetryAuthorized, "a retry is already authorized for this hold") } + if held := registry.Kind(hold.Kind); held == nil || !held.Retryable { + return refuse(ReasonNotRetryable, "a DeviceRecovery with Retry does not apply to a %s hold", hold.Kind) + } for _, kind := range registry.Kinds() { for _, rule := range kind.Settles { if rule.Held == hold.Kind && rule.RequiresRetry { diff --git a/internal/custody/rebuild.go b/internal/custody/rebuild.go index 378c9190..5e2ea25e 100644 --- a/internal/custody/rebuild.go +++ b/internal/custody/rebuild.go @@ -137,7 +137,8 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) return cmp.Compare(b.operation.OperationStatus().Fence, a.operation.OperationStatus().Fence) }) newest := held[0] - spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: newest.kind.GVK.Kind, Name: newest.operation.GetName(), UID: string(newest.operation.GetUID())}, Fence: newest.operation.OperationStatus().Fence, Since: metav1.NewTime(c.now()), Reason: ReasonRebuilt} + status := newest.operation.OperationStatus() + spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: newest.kind.GVK.Kind, Name: newest.operation.GetName(), UID: string(newest.operation.GetUID())}, Fence: status.Fence, Since: metav1.NewTime(c.now()), Reason: ReasonRebuilt, Deadline: status.Deadline, Snapshot: status.Snapshot} if len(held) > 1 { spec.Conflicts = appendOnce(spec.Conflicts, ConflictMultipleUnfinished) } diff --git a/internal/custody/registry.go b/internal/custody/registry.go index 897d5fef..a976c6b4 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -17,6 +17,8 @@ import ( "encoding/json" "errors" "fmt" + "regexp" + "slices" "sort" "time" @@ -77,8 +79,21 @@ type Kind struct { // preconditions pass and before the custody update. A non-nil refusal // ends the operation Failed with that reason, and nothing is sent. Check func(context.Context, *Admission) *Refusal - // Settles lists the held kinds a success of this kind settles. + // 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, + // settles no hold itself. Settles []SettleRule + // Retryable means a DeviceRecovery with Retry applies to this kind's + // holds: it lets the held operation's requester create one settling + // operation. + Retryable bool + // Reasons are the kind's own refusal reasons. A refusal with a reason + // that is neither shared nor declared here ends the operation Failed with + // UndeclaredReason. + Reasons []Reason + // SnapshotExtra adds bounded fields to the Device snapshot at admission. + // It sees the same Device the checks saw. + SnapshotExtra func(*Admission) map[string]string // Evidence validates the kind's typed, bounded result evidence and // returns it in canonical form. Nil means the kind's results carry none. Evidence func([]byte) ([]byte, error) @@ -101,6 +116,21 @@ func (k *Kind) checksDiscovery(operation ops.Operation) bool { return k.SkipsDiscovery == nil || !k.SkipsDiscovery(operation) } +// ReasonSource is where a refusal reason is raised. +type ReasonSource string + +const ( + RaisedByCoordinator ReasonSource = "Coordinator" + RaisedByWorker ReasonSource = "Worker" + RaisedByBoth ReasonSource = "Both" +) + +// Reason is one refusal reason a kind declares. +type Reason struct { + Name string + RaisedBy ReasonSource +} + // SettleRule says a success of the owning kind settles a hold of Held. When // RequiresRetry is set, a DeviceRecovery with Retry must first authorize it. type SettleRule struct { @@ -117,10 +147,16 @@ type Admission struct { Registry *Registry // Reader reads the provider project. A check must not write. Reader client.Reader - Now time.Time + // Now is the coordinator's injected clock, read once per decision. + Now time.Time + // DiscoveryInterval is how often BMC discovery reads each BMC. + DiscoveryInterval time.Duration } -// RecoverySettleContext is what a held kind's settle hook sees. +// RecoverySettleContext is what a held kind's settle hook sees. Hold carries +// when the held operation ended (Since), its deadline and its admission +// snapshot. Device is read when the hook runs, at admission of the recovery +// and again when it is applied. type RecoverySettleContext struct { Hold ops.RecoveryHold Recovery *ops.DeviceRecovery @@ -175,8 +211,17 @@ const ( ReasonSiteNotConfirmed = "SiteNotConfirmed" ReasonSiteUnknown = "SiteCouldNotProve" ReasonInvalidEvidence = "InvalidEvidence" + ReasonUndeclared = "UndeclaredReason" + ReasonSnapshotInvalid = "SnapshotInvalid" ) +// sharedReasons are the reasons every kind may raise. +var sharedReasons = []string{ReasonUnverified, ReasonNoMatchingRule, ReasonHolderMismatch, ReasonOperationActive, ReasonIdentityMismatch, ReasonIdentityNotCurrent, + ReasonSharedPublicKey, ReasonRecoveryHold, ReasonNameMismatch, ReasonExpired, ReasonSuperseded, ReasonWithdrawn, ReasonDeadlineExceeded, + ReasonSiteNotConfirmed, ReasonSiteUnknown, ReasonInvalidEvidence, ReasonUndeclared, ReasonSnapshotInvalid} + +var reasonPattern = regexp.MustCompile(`^[A-Z][A-Za-z0-9]{0,62}$`) + // Registry holds the operation kinds and the admission rules. type Registry struct { kinds map[string]*Kind @@ -204,6 +249,20 @@ func (r *Registry) Register(kind Kind) error { if _, ok := r.kinds[name]; ok { return fmt.Errorf("%s is already registered", name) } + seen := map[string]bool{} + for _, reason := range kind.Reasons { + switch { + case !reasonPattern.MatchString(reason.Name): + return fmt.Errorf("%s: reason %q is not a CamelCase name", name, reason.Name) + case slices.Contains(sharedReasons, reason.Name): + return fmt.Errorf("%s: reason %s is shared and needs no declaration", name, reason.Name) + case seen[reason.Name]: + return fmt.Errorf("%s: reason %s is declared twice", name, reason.Name) + case reason.RaisedBy != RaisedByCoordinator && reason.RaisedBy != RaisedByWorker && reason.RaisedBy != RaisedByBoth: + return fmt.Errorf("%s: reason %s needs a source", name, reason.Name) + } + seen[reason.Name] = true + } r.kinds[name] = &kind r.order = append(r.order, name) sort.Strings(r.order) @@ -228,6 +287,38 @@ func (r *Registry) AddRule(rule Rule) error { func (r *Registry) Kind(name string) *Kind { return r.kinds[name] } +// Declared reports whether a reason is shared or declared by the kind for +// the given source. +func (r *Registry) Declared(kind, reason string, source ReasonSource) bool { + if slices.Contains(sharedReasons, reason) { + return true + } + entry := r.kinds[kind] + if entry == nil { + return false + } + return slices.ContainsFunc(entry.Reasons, func(declared Reason) bool { + return declared.Name == reason && (declared.RaisedBy == source || declared.RaisedBy == RaisedByBoth) + }) +} + +// declaredRefusal returns the refusal unchanged when the kind, or the held +// kind whose settle hook it came through, declared its reason, and +// UndeclaredReason otherwise. Every recorded reason is one a kind registered. +func (r *Registry) declaredRefusal(kind, held string, refusal *Refusal) *Refusal { + if refusal == nil || r.Declared(kind, refusal.Reason, RaisedByCoordinator) || (held != "" && r.Declared(held, refusal.Reason, RaisedByCoordinator)) { + return refusal + } + return refuse(ReasonUndeclared, "%s refused with %s, which it does not declare", kind, refusal.Reason) +} + +func heldKind(custody *ops.DeviceCustody) string { + if hold := custody.Spec.RecoveryHold; hold != nil { + return hold.Kind + } + return "" +} + // Kinds returns every registered kind, sorted by name. func (r *Registry) Kinds() []*Kind { out := make([]*Kind, 0, len(r.order)) diff --git a/internal/custody/testdata/crds/test-kinds.yaml b/internal/custody/testdata/crds/test-kinds.yaml index 67985f52..ca93d2a8 100644 --- a/internal/custody/testdata/crds/test-kinds.yaml +++ b/internal/custody/testdata/crds/test-kinds.yaml @@ -167,6 +167,12 @@ spec: discoveryObservedAt: type: string maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 evidence: type: object x-kubernetes-preserve-unknown-fields: true @@ -343,6 +349,12 @@ spec: discoveryObservedAt: type: string maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 evidence: type: object x-kubernetes-preserve-unknown-fields: true diff --git a/internal/custody/testkinds_test.go b/internal/custody/testkinds_test.go index 5b8b29eb..3e388a4a 100644 --- a/internal/custody/testkinds_test.go +++ b/internal/custody/testkinds_test.go @@ -2,6 +2,8 @@ package custody import ( "context" + "fmt" + "sync/atomic" "time" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" @@ -81,8 +83,29 @@ type testEvidence struct { func testKinds() []Kind { check := func(_ context.Context, admission *Admission) *Refusal { - if admission.Operation.(interface{ input() string }).input() == "refuse" { + switch admission.Operation.(interface{ input() string }).input() { + case "refuse": return refuse(reasonTestRefuse, "the test kind refuses this input") + case "undeclared": + return refuse("Unlisted", "the test kind refuses with a reason it never declared") + } + if hook := checkHook.Load(); hook != nil { + (*hook)(admission) + } + return nil + } + // The staff kind adds fields to the snapshot, as power adds the reset + // types discovery offered. + extra := func(admission *Admission) map[string]string { + switch admission.Operation.(interface{ input() string }).input() { + case "extra": + return map[string]string{"resetTypes": "On,ForceOff", "discoveryInterval": admission.DiscoveryInterval.String()} + case "too-much": + out := map[string]string{} + for index := range 17 { + out[fmt.Sprintf("field%d", index)] = "x" + } + return out } return nil } @@ -100,10 +123,17 @@ func testKinds() []Kind { Effectful: true, Check: check, Settles: []SettleRule{{Held: testStaffKind}}, + Reasons: []Reason{{Name: reasonTestRefuse, RaisedBy: RaisedByCoordinator}, {Name: "EvidenceNotCurrent", RaisedBy: RaisedByCoordinator}}, Evidence: evidence, // Seam 4: a hold of this kind settles with recovery evidence observed // after the operation ended, as power's discovery read will. + SnapshotExtra: extra, RecoverySettle: func(_ context.Context, settle *RecoverySettleContext) *Refusal { + // The hook sees when the held operation ended, its deadline and + // its admission snapshot, and the Device as read now. + if settle.Hold.Deadline == nil || settle.Hold.Snapshot == nil || settle.Device == nil { + return refuse("EvidenceNotCurrent", "the hold does not carry its deadline and snapshot") + } if !settle.Recovery.Spec.Evidence.ObservedAt.After(settle.Hold.Since.Time) || settle.Recovery.Spec.Evidence.Data["state"] == "" { return refuse("EvidenceNotCurrent", "the evidence must be a state observed after the operation ended") } @@ -129,11 +159,15 @@ func testKinds() []Kind { Supersedes: true, Check: check, Settles: []SettleRule{{Held: testProviderKind}}, + Reasons: []Reason{{Name: reasonTestRefuse, RaisedBy: RaisedByCoordinator}}, Evidence: evidence, } return []Kind{staff, provider} } +// checkHook, when set, runs inside the test kinds' admission check. +var checkHook atomic.Pointer[func(*Admission)] + func (in *DeviceTestStaffOperation) input() string { return in.Spec.Input } func (in *DeviceTestProviderOperation) input() string { return in.Spec.Input } From c0623ad0aa0168c443705a5008bebc4ce9d96071 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 20:29:41 -0600 Subject: [PATCH 11/19] test(multiplane): Prove Milo enforces the custody CRD rules Both local end-to-end runs now install the custody CRDs into the provider project, require its API to refuse eight writes the CEL rules forbid, and remove the CRDs again. Milo ignores admission policies stored in a project, so the rules need this proof. Record each extension-point decision for the power and commissioning kinds. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 53 +++++++++++-- docs/operations/multiplane.md | 9 +++ hack/multiplane/acceptance-redfish.sh | 1 + hack/multiplane/acceptance.sh | 1 + hack/multiplane/custody_crd_rules.py | 107 ++++++++++++++++++++++++++ hack/multiplane/evidence.py | 7 +- hack/multiplane/test-harness.sh | 13 +++- 7 files changed, 182 insertions(+), 9 deletions(-) create mode 100644 hack/multiplane/custody_crd_rules.py diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 6efb5d20..a112b687 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -263,6 +263,28 @@ remains. as written would make every server unallocatable, because commissioning is not built. +### Extension points for power and commissioning + +The agent rebuilding `DevicePowerOperation` on this foundation asked for +these seams. Each is decided here. + +| # | Seam | Decision | Status | +| --- | --- | --- | --- | +| 1 | Kind checks see the Device the snapshot records, an injected clock and the discovery interval | Checks get the Device object the snapshot is built from, `Admission.Now` and `Admission.DiscoveryInterval`. Before the custody update, the coordinator reads the Device again. If its resourceVersion changed, it decides again, so discovery cannot change between the check and the update unseen. | Implemented and inert | +| 2 | Pending replacement is scoped to the kind and the authority | A newer pending operation replaces only an older one of the same kind under the same authority. A power request never cancels a pending installation. | Implemented and inert | +| 3 | Kinds add bounded snapshot fields | `SnapshotExtra` adds up to 16 camelCase fields of at most 256 bytes each. The snapshot goes to the operation, the active operation, the hold, and the site. | Implemented and inert | +| 4 | The settle hook sees the hold's end time, its deadline and current Device status | The hold records when it ended (`Since`), the operation's deadline and its snapshot. The hook gets the Device as read when the recovery is admitted and again when it is applied. | Implemented and inert | +| 5 | Kinds register their refusal reasons | Each reason is declared with where it is raised. The registry refuses a malformed name, a shared name, a duplicate, or a missing source. A coordinator refusal with an undeclared reason ends `UndeclaredReason`. | Implemented and inert. Worker reasons are checked when results arrive, in B. | +| 6 | A kind may settle no hold, and declares whether `Retry` applies | `Settles` may be empty. `Retryable` marks a kind whose holds a `Retry` may unblock. | Implemented and inert | +| 7 | End-to-end proof that Milo enforces the CRD rules | The `custody-crd-rules` phase of both local end-to-end runs installs only these CRDs into the provider project, requires the project API to refuse eight forbidden writes, and removes them. | Implemented and verified in the local end-to-end runs | +| 8 | Journal steps carry a kind's payload | A step records a bounded payload, such as the send time or the power state before. Observation after a crash reads it. | Proposed for B | +| 9 | Delivery carries the admission time, and kinds declare a start-by window | A worker that starts after the window refuses as `Stale`, with nothing sent. | Proposed for B | +| 10 | The TLS and identity check is separate from install capabilities | The framework verifies the pin and the System only. Each kind checks the capabilities it uses, such as the Pxe and Hdd boot targets, against a pinned client bound to the verified System. | Proposed for B | +| 11 | A worker refusal with nothing sent ends `Failed` | It ends `Failed` under the operation's fence and returns a `Service` holder to `None`. It never ends `OutcomeUnknown`. | Implemented in the coordinator; the worker side arrives in B | +| 12 | The single writer of `Machine.status.power` | The manager's Machine status projector stays the only writer. It reads the custody of the Machine's allocation: while a recovery hold exists it reports power `Unknown`, and otherwise it reports the power state of the last succeeded power operation's evidence or of discovery, whichever is newer. | Proposed for C | + +None of these conflicts with #174. + ## Points for a person These need a decision before the increment that depends on them. @@ -292,13 +314,24 @@ four seams. It needs no change to the coordinator. The test-only kinds in - its naming rule: `DeterministicName` with a `Name` function for provider and release kinds, or `GeneratedName` for staff kinds; - its `Deadline`, and `Effectful` if it can reach the server; - - `Supersedes`, if a newer pending operation for the same authority should - cancel an older one, as power needs; + - `Supersedes`, if a newer pending operation of the same kind and the + same authority should cancel an older one, as power needs. It never + cancels another kind's operation; - `Check` for kind-specific admission checks. They run after the shared preconditions, before the custody update, and return a named refusal, - such as power's `SystemUUIDMismatch` or `DiscoveryNotCurrent`; + 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`; + - `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`; + - `SnapshotExtra`, for bounded fields the kind adds to the snapshot, such + as the reset types discovery offered. The worker and a recovery see + what admission saw; - `Settles`, the held kinds a success settles, with `RequiresRetry` when a - `DeviceRecovery` `Retry` must come first. + `DeviceRecovery` `Retry` must come first. It may be empty; + - `Retryable`, if a `DeviceRecovery` with `Retry` applies to the kind's + holds. Embed `OperationEnvelope` inline in the spec, and use `OperationStatus` as the status. Add the CRD with the same envelope, the immutable-spec rule and @@ -319,8 +352,10 @@ four seams. It needs no change to the coordinator. The test-only kinds in 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 - evidence. Power, for example, accepts only a power state that discovery - read after the operation ended. + evidence. The hook sees the hold, with when the held operation ended + (`Since`), its deadline and its admission snapshot, and the Device as read + when the hook runs. Power, for example, accepts only a power state that + discovery read after the operation ended. Test the kind with the shared harness in `internal/custody`: register it beside the defaults, and run its refusals, admission, results and holds @@ -341,6 +376,7 @@ a real API server: | Two allocators, allocator against staff, two coordinators, admission against a holder change, two Devices, a lost claim response | `TestConcurrency` | | A claim and its installation landing between the custody read and the operation list | `TestARefusalNeverUsesCustodyReadBeforeAHolderChange` | | Admission above the fence a site has seen; a recovery confirmed only by the stopped fence; a held operation never a candidate | `TestFencesFollowTheSiteReport`, `TestAHeldOperationIsNeverACandidate` | +| The extension points: the Device the checks see, scoped replacement, snapshot fields, the settle hook's hold fields, declared reasons, `Retryable`, a worker refusal returning a staff holder to `None` | `TestExtensionSeams`, `TestRegistryValidatesDeclaredReasons` | | A crash between each pair of custody and status writes, with dropped and lost responses | `TestWriteOrderCrashRecovery` | | CEL rules | `TestCRDRules` | | Seams, rows, principals, ordering, evidence bounds, capacity for every input | `TestRegistryRejectsIncompleteKindsAndRows`, `TestAddingRowsLeavesExistingRowsAlone`, `TestPrincipals`, `TestCandidatesOrderOldestFirstWithADeterministicTieBreak`, `TestEvidenceIsTypedAndBounded`, `TestCapacityProjection` | @@ -349,3 +385,8 @@ a real API server: Increment A has no site, so "nothing was sent" means custody admitted nothing and the fence did not rise. Increment D proves it with the lab BMC audit. + +Both local end-to-end runs include the `custody-crd-rules` phase. It proves +that a Milo project API refuses every write the CRD rules forbid, which +envtest alone cannot show, because Milo ignores admission policies stored in a +project. diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index f521f59a..63b70d23 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -153,6 +153,7 @@ mode-0700 `/tmp/fleet-multiplane.*` state directory (override the parent with | `summary.json` | Pass only: allowlisted scenario evidence, operations, digests, receipt hashes, qualification flags | | `flux-verify.json`, `flux-initial.json`, `flux-rbac-restore.json`, `flux-drift.json`, `flux-graph-lifecycle.json`, `flux-restart.json`, `flux-fail-closed.json`, `flux-retention.json`, `flux-final.json`, `flux-ownership-final.json`, `flux-reconciles.json`, `flux-partition.json`, `flux-reflection-suspension.json`, `gitops-r.SHA256SUMS` | Flux source revisions and digests, Ready/generation/revision of every Kustomization and HelmRelease, inventories and single-writer ownership, and each GitOps scenario ([details](gitops.md#acceptance-coverage)) | | `kro-rbac.json` | kro's allowed and denied verbs and each admission probe's outcome | +| `custody-crd-rules.json` | Each forbidden custody or operation write and whether the provider project API refused it, and that the CRDs were removed | | `kubernetes-execution.json` | kro version, image and RGD/instance state; Flux-owned site Deployments; retained volume identity; every worker Job's UID, conditions, Pods, exit codes and policies; per-operation RBAC | | `interrupt.json`, `lifecycle.json`, `delivery-faults.json`, `wrong-location.json` | Scenario-specific observations, no secrets | | `source-SHA256SUMS`, `binary-SHA256SUMS`, `image-id`, `sysctl.json`, `teardown.json` | Tested inputs and teardown record | @@ -201,6 +202,14 @@ The phases are then: not the harness, then restores the binding. Finally, as kro's own identity, it proves the narrowed grant and the admission policies on kro's writes ([trust model](site-execution.md#ownership-and-trust-model)). + `custody-crd-rules` then installs only the [Device custody](../development/device-custody.md) + CRDs into the provider project. It requires the project API to refuse eight + writes their CEL rules forbid: changing an operation's spec or creator, + moving a phase backward or out of an ended phase, setting both authorities, + lowering a custody fence, leaving `Retired`, and naming custody after + another Device. It then removes the objects and the CRDs. Milo ignores + admission policies stored in a project, so this proves the rules hold + there. It sends nothing to any server. 2. **Contention.** Two consumers request one provider capacity. One binding succeeds; `verify-contention` independently reads Bound for A and Pending/InsufficientCapacity for B. diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index 8dc89273..475f3933 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -14,6 +14,7 @@ rf() { ph "redfish-$1" "$2" python3 hack/multiplane/redfish_steps.py "$1" "$stat flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" +ph custody-crd-rules 600 python3 hack/multiplane/custody_crd_rules.py "$state" rf baseline 300 rf discovery-faults 600 ph allocate 900 "$host" allocate --config "$state/acceptance.json" diff --git a/hack/multiplane/acceptance.sh b/hack/multiplane/acceptance.sh index 54d3c27a..8bfc31c3 100755 --- a/hack/multiplane/acceptance.sh +++ b/hack/multiplane/acceptance.sh @@ -11,6 +11,7 @@ step() { ph "$1" "$2" bash hack/multiplane/steps.sh "$1" "$state"; } flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" +ph custody-crd-rules 600 python3 hack/multiplane/custody_crd_rules.py "$state" ph allocate 900 "$host" allocate --config "$state/acceptance.json" step verify-contention 120 ph admit-install 900 "$host" admit-install --config "$state/acceptance.json" diff --git a/hack/multiplane/custody_crd_rules.py b/hack/multiplane/custody_crd_rules.py new file mode 100644 index 00000000..013133df --- /dev/null +++ b/hack/multiplane/custody_crd_rules.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Prove the provider project's Milo API enforces the Device custody CRD rules. + +Milo v0.32.5 ignores admission policies stored in a project, so the custody +contract rests on the CRD schema and CEL rules the project API server itself +evaluates. This phase installs only the device-operations CRDs into the +provider project, tries each forbidden change against synthetic objects, and +requires the API server to refuse it. It then removes the objects and the +CRDs, so no later phase sees them. It sends nothing to any BMC. +""" +import json, pathlib, subprocess, sys + +state = pathlib.Path(sys.argv[1]).resolve() +config = state / 'provider' / 'bootstrap-project.json' +crds = 'config/components/device-operations/crds/fleet.datumapis.com.yaml' +# The provider namespace the fixture bootstrap creates. The phase creates no +# namespace, because a project API may not run a namespace controller to +# finish deleting one. +namespace = 'fleet-provider' +objects = (('devicerecovery', 'rules-recovery'), ('devicecustody', 'server-example-001')) +names = ('devicecustodies', 'deviceinstallations', 'devicewipes', 'devicerecoveries') + + +def kubectl(*args, stdin=None, check=True): + result = subprocess.run(['kubectl', '--kubeconfig', str(config), '--request-timeout=20s', *args], + input=stdin, text=True, capture_output=True) + if check and result.returncode != 0: + raise SystemExit('custody-crd-rules: kubectl %s failed' % args[0]) + return result + + +def apply(obj): + kubectl('apply', '-f', '-', stdin=json.dumps(obj)) + + +def refused(what, *args, stdin=None): + """The API server must refuse the write as Invalid, naming the rule.""" + result = kubectl(*args, stdin=stdin, check=False) + text = result.stderr + ok = result.returncode != 0 and 'invalid' in text.lower() and what in text + checks.append({'rule': what, 'refused': ok}) + if not ok: + raise SystemExit('custody-crd-rules: the project API accepted a write that breaks: ' + what) + + +def status(kind, name, phase): + return kubectl('-n', namespace, 'patch', kind, name, '--subresource=status', '--type=merge', + '-p', json.dumps({'status': {'phase': phase}}), check=False) + + +checks = [] +removed = False +try: + kubectl('apply', '-f', crds) + for name in names: + kubectl('wait', '--for=condition=Established', 'crd/%s.fleet.datumapis.com' % name, '--timeout=90s') + envelope = {'creator': {'username': 'staff-example', 'uid': 'staff-example-uid'}, + 'deviceRef': {'name': 'server-example-001', 'uid': '00000000-0000-4000-8000-000000000001'}, + 'authority': {'serviceRequest': {'reason': 'synthetic rule check'}}} + recovery = {'apiVersion': 'fleet.datumapis.com/v1alpha1', 'kind': 'DeviceRecovery', + 'metadata': {'name': 'rules-recovery', 'namespace': namespace}, + 'spec': dict(envelope, decision='Settle', hold={'kind': 'DeviceWipe', 'name': 'alloc-example-wipe-1', 'fence': 3}, + evidence={'observedAt': '2026-01-02T03:04:05Z', 'summary': 'synthetic'})} + apply(recovery) + refused('an operation spec is immutable after create', '-n', namespace, 'patch', 'devicerecovery', 'rules-recovery', + '--type=merge', '-p', json.dumps({'spec': {'decision': 'Retry'}})) + refused('an operation spec is immutable after create', '-n', namespace, 'patch', 'devicerecovery', 'rules-recovery', + '--type=merge', '-p', json.dumps({'spec': {'creator': {'username': 'someone-else'}}})) + for phase in ('Pending', 'Admitted', 'Verifying'): + if status('devicerecovery', 'rules-recovery', phase).returncode != 0: + raise SystemExit('custody-crd-rules: a forward phase change was refused') + refused('operation phases move forward only', '-n', namespace, 'patch', 'devicerecovery', 'rules-recovery', '--subresource=status', + '--type=merge', '-p', json.dumps({'status': {'phase': 'Admitted'}})) + if status('devicerecovery', 'rules-recovery', 'OutcomeUnknown').returncode != 0: + raise SystemExit('custody-crd-rules: ending OutcomeUnknown was refused') + refused('an ended phase is final', '-n', namespace, 'patch', 'devicerecovery', 'rules-recovery', '--subresource=status', + '--type=merge', '-p', json.dumps({'status': {'phase': 'Succeeded'}})) + both = json.loads(json.dumps(recovery)) + both['metadata']['name'] = 'rules-both' + both['metadata']['namespace'] = namespace + both['spec']['authority'] = {'serviceRequest': {'reason': 'x'}, 'allocationRef': {'name': 'alloc-example'}} + refused('set exactly one of allocationRef and serviceRequest', 'create', '-f', '-', stdin=json.dumps(both)) + custody = {'apiVersion': 'fleet.datumapis.com/v1alpha1', 'kind': 'DeviceCustody', + 'metadata': {'name': 'server-example-001', 'namespace': namespace}, + 'spec': {'deviceRef': envelope['deviceRef'], 'state': 'Verified', 'holder': {'type': 'Retired'}, 'fence': 5}} + apply(custody) + refused('the fence never decreases', '-n', namespace, 'patch', 'devicecustody', 'server-example-001', + '--type=merge', '-p', json.dumps({'spec': {'fence': 4}})) + refused('Retired is terminal', '-n', namespace, 'patch', 'devicecustody', 'server-example-001', + '--type=merge', '-p', json.dumps({'spec': {'holder': {'type': 'None'}}})) + mismatch = json.loads(json.dumps(custody)) + mismatch['metadata']['name'] = 'server-example-002' + mismatch['metadata']['namespace'] = namespace + refused('custody has the same name as its Device', 'create', '-f', '-', stdin=json.dumps(mismatch)) +finally: + cleared = all(kubectl('-n', namespace, 'delete', kind, name, '--ignore-not-found', '--wait=true', '--timeout=120s', check=False).returncode == 0 + for kind, name in objects) + removed = cleared and kubectl('delete', '-f', crds, '--ignore-not-found', '--wait=true', '--timeout=120s', check=False).returncode == 0 + +if not removed: + raise SystemExit('custody-crd-rules: the rule-check objects or CRDs could not be removed') +evidence = state / 'evidence' +evidence.mkdir(mode=0o700, exist_ok=True) +path = evidence / 'custody-crd-rules.json' +path.write_text(json.dumps({'checks': checks, 'crdsRemoved': removed}, indent=1) + '\n') +path.chmod(0o600) +print('custody-crd-rules: the provider project API refused every forbidden custody and operation write (%d rules); CRDs removed' % len(checks), flush=True) diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 8d18e0b6..80c35ce9 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -69,8 +69,12 @@ def copy_out(source, destination): if len(routing) != 2 or any(x['namespace'] != 'default' or x['watch'] != 'Added exact UID' for x in routing) or routing[0]['namespaceUID'] == routing[1]['namespaceUID'] or routing[0]['projectUID'] == routing[1]['projectUID']: fail('missing independent native project create/watch evidence') +custody_rules = json.loads((ev / 'custody-crd-rules.json').read_text()) +if not custody_rules.get('crdsRemoved') or len(custody_rules.get('checks', [])) != 8 or not all(c.get('refused') for c in custody_rules['checks']): + fail('the provider project API did not refuse every forbidden custody write') + phases = (s / 'phases.log').read_text() -markers = ('Verified forbidden observer/project/hub writes', 'allocate: verified', 'contention: consumer-a Bound', 'delivery: Karmada delivered exactly one', +markers = ('custody-crd-rules: the provider project API refused every forbidden custody and operation write', 'Verified forbidden observer/project/hub writes', 'allocate: verified', 'contention: consumer-a Bound', 'delivery: Karmada delivered exactly one', 'kro created the worker Job and per-operation RBAC', 'worker-rbac: per-operation ServiceAccount', 'interrupt-pod: worker Pod force-deleted', 'interrupt-job: running worker Job deleted mid-install', 'resume: replacement worker completed the exact interrupted operation', 'worker Job is Complete while hub/consumer disconnected; public Ready stayed False', 'install: verified', 'lifecycle: runtime, boot and observer Pods', @@ -347,6 +351,7 @@ def network(block): 'installerStarts': starts, 'reflectionRejections': ['wrong-cell', 'stale', 'duplicate', 'future', 'wrong-intent', 'wrong-digest', 'wrong-operation', 'incomplete', 'missing'], 'wrongLocationDeniedBeforeAllocation': json.loads((ev / 'wrong-location.json').read_text()), + 'custodyCRDRules': custody_rules, 'releasedProjection': {'consumerA': {'machine': 'Released, Bound False, Ready False, no currentInstallationRef, no Fleet finalizer', 'installation': 'Released, Ready False'}, 'consumerB': {'machine': 'Released, Bound False, Ready False, no currentInstallationRef, no Fleet finalizer'}}, 'cleanupAndReuse': {'epochs': epochs, 'cleanups': len(cleanups), 'domainsAfterCleanup': [], 'disksAfterCleanup': 0}, diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 8b1cb2b1..5f486440 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -183,18 +183,27 @@ with tempfile.TemporaryDirectory() as tmp: for name, text in (('steps', steps), ('evidence', evidence), ('harness', harness.read_text())): check('no docker process launch in site execution: ' + name, '-vm' not in text and 'cell.pid' not in text) sequence = (root / 'hack/multiplane/acceptance.sh').read_text() - order = ['allocate', 'verify-contention', 'admit-install', 'await-delivery', 'partition', 'dispatch', 'interrupt-pod', 'interrupt-job', 'resume', + order = ['custody-crd-rules', 'allocate', 'verify-contention', 'admit-install', 'await-delivery', 'partition', 'dispatch', 'interrupt-pod', 'interrupt-job', 'resume', 'worker-rbac', 'partition-readiness', 'heal', 'install', 'install-repeat', 'lifecycle', 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention', 'reflection-faults', 'release', 'release-status-a', 'reuse', 'reuse-status', 'delivery-faults', 'release-b', 'release-status-b', 'wrong-location', 'boot-denials', 'flux-final', 'evidence'] positions = [sequence.find(' ' + name + ' ') for name in order] check('acceptance phase order', all(p >= 0 for p in positions) and positions == sorted(positions), str(list(zip(order, positions)))) for name in order: - if name in ('allocate', 'admit-install', 'install', 'install-repeat', 'release', 'reuse', 'release-b', 'reflection-faults', 'evidence', + if name in ('custody-crd-rules', 'allocate', 'admit-install', 'install', 'install-repeat', 'release', 'reuse', 'release-b', 'reflection-faults', 'evidence', 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention'): continue check('step implemented: ' + name, ' %s)' % name in steps or '|%s)' % name in steps or ' %s|' % name in steps) + # The custody CRD rule phase proves the project API enforces the CEL + # rules, then removes everything it installed, in both modes. + rules = (root / 'hack/multiplane/custody_crd_rules.py').read_text() + redfish_sequence = (root / 'hack/multiplane/acceptance-redfish.sh').read_text() + check('custody CRD rules run in both modes', 'ph custody-crd-rules ' in sequence and 'ph custody-crd-rules ' in redfish_sequence) + check('custody CRD rules install only the component CRDs and remove them', rules.count('config/components/device-operations/crds/fleet.datumapis.com.yaml') == 1 + and "'delete', '-f', crds" in rules and "'delete', kind, name" in rules and "'Namespace'" not in rules) + check('custody CRD rules evidence is checked', "custody-crd-rules.json" in evidence and 'custody-crd-rules: the provider project API refused' in evidence) + # The kro graph and the worker exit-code contract must agree. kro owns only # per-operation workers: the shared services and the durable site volume are # Flux-owned and only referenced by the graph. From b84acb03aac1fe993602ad15be761076db21eedf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 20:46:43 -0600 Subject: [PATCH 12/19] test(custody): Guard supersede scope, Retryable and rebuilt holds Prove that a newer pending operation replaces only its own kind when two superseding kinds share an allocation, that Retry needs the held kind to be Retryable, and that a rebuilt hold keeps the deadline and snapshot its operation's status recorded. A held kind's reasons are accepted only through its settle hook. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 7 ++++--- internal/custody/coordinator.go | 4 ++-- internal/custody/extension_test.go | 32 ++++++++++++++++++++++++++++-- internal/custody/holds_test.go | 14 ++++++++++++- internal/custody/registry.go | 13 ++++++++---- 5 files changed, 58 insertions(+), 12 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index a112b687..a19a4ecc 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -273,8 +273,8 @@ these seams. Each is decided here. | 1 | Kind checks see the Device the snapshot records, an injected clock and the discovery interval | Checks get the Device object the snapshot is built from, `Admission.Now` and `Admission.DiscoveryInterval`. Before the custody update, the coordinator reads the Device again. If its resourceVersion changed, it decides again, so discovery cannot change between the check and the update unseen. | Implemented and inert | | 2 | Pending replacement is scoped to the kind and the authority | A newer pending operation replaces only an older one of the same kind under the same authority. A power request never cancels a pending installation. | Implemented and inert | | 3 | Kinds add bounded snapshot fields | `SnapshotExtra` adds up to 16 camelCase fields of at most 256 bytes each. The snapshot goes to the operation, the active operation, the hold, and the site. | Implemented and inert | -| 4 | The settle hook sees the hold's end time, its deadline and current Device status | The hold records when it ended (`Since`), the operation's deadline and its snapshot. The hook gets the Device as read when the recovery is admitted and again when it is applied. | Implemented and inert | -| 5 | Kinds register their refusal reasons | Each reason is declared with where it is raised. The registry refuses a malformed name, a shared name, a duplicate, or a missing source. A coordinator refusal with an undeclared reason ends `UndeclaredReason`. | Implemented and inert. Worker reasons are checked when results arrive, in B. | +| 4 | The settle hook sees the hold's end time, its deadline and current Device status | The hold records when it ended (`Since`), the operation's deadline and its snapshot. The hook gets the Device as read when the recovery is admitted and again when it is applied. A hold that rebuild created has `Since` set to the rebuild time, and copies the deadline and snapshot from the operation's status, so both are absent for an operation whose status never recorded them. A hook checks for that. | Implemented and inert | +| 5 | Kinds register their refusal reasons | Each reason is declared with where it is raised. The registry refuses a malformed name, a shared name, a duplicate, or a missing source. A coordinator refusal with an undeclared reason ends `UndeclaredReason`. A recovery's refusal may carry the held kind's declared reason only when it comes from that kind's settle hook. | Implemented and inert. Worker reasons are checked when results arrive, in B. | | 6 | A kind may settle no hold, and declares whether `Retry` applies | `Settles` may be empty. `Retryable` marks a kind whose holds a `Retry` may unblock. | Implemented and inert | | 7 | End-to-end proof that Milo enforces the CRD rules | The `custody-crd-rules` phase of both local end-to-end runs installs only these CRDs into the provider project, requires the project API to refuse eight forbidden writes, and removes them. | Implemented and verified in the local end-to-end runs | | 8 | Journal steps carry a kind's payload | A step records a bounded payload, such as the send time or the power state before. Observation after a crash reads it. | Proposed for B | @@ -354,7 +354,8 @@ four seams. It needs no change to the coordinator. The test-only kinds in can settle a hold of the kind, set `RecoverySettle` to validate the staff evidence. The hook sees the hold, with when the held operation ended (`Since`), its deadline and its admission snapshot, and the Device as read - when the hook runs. Power, for example, accepts only a power state that + when the hook runs. A hold that rebuild created may lack the deadline and + snapshot, and its `Since` is the rebuild time. Power, for example, accepts only a power state that discovery read after the operation ended. Test the kind with the shared harness in `internal/custody`: register it diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 26385095..f1066e2c 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -410,7 +410,7 @@ func (c *Coordinator) progressActive(ctx context.Context, custody *ops.DeviceCus return c.writeCustody(ctx, custody) } spec, refusal := kind.Apply(ctx, &ApplyContext{Operation: operation, Custody: custody.DeepCopy(), Device: device, Registry: c.Registry, Reader: c.Client, ConfirmedFence: confirmed, HighestFence: highest, Now: now}) - if refusal = c.Registry.declaredRefusal(kind.GVK.Kind, heldKind(custody), refusal); refusal != nil { + if refusal = c.Registry.declaredRefusal(kind.GVK.Kind, settleHookKind(kind, Rule{Hold: HoldRequired}, custody), refusal); refusal != nil { c.finishActive(custody, active, ops.PhaseFailed, refusal.Reason, refusal.Message, nil) return c.writeCustody(ctx, custody) } @@ -734,7 +734,7 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } } if kind.Check != nil { - if refusal := c.Registry.declaredRefusal(kind.GVK.Kind, heldKind(custody), kind.Check(ctx, admission)); refusal != nil { + if refusal := c.Registry.declaredRefusal(kind.GVK.Kind, settleHookKind(kind, row, custody), kind.Check(ctx, admission)); refusal != nil { return fail(refusal.Reason, "%s", refusal.Message) } } diff --git a/internal/custody/extension_test.go b/internal/custody/extension_test.go index f4a3f20d..cf14b858 100644 --- a/internal/custody/extension_test.go +++ b/internal/custody/extension_test.go @@ -56,6 +56,9 @@ func TestExtensionSeams(t *testing.T) { t.Run("a newer pending operation replaces only its own kind under the same authority", func(t *testing.T) { e := e.sub(t) + // Two kinds that supersede share one allocation, as power and a + // future provider kind would. + e.coord.Registry.Kind("DeviceInstallation").Supersedes = true device := fresh() if err := e.coord.Claim(e.ctx, device.Name, "alloc-scope"); err != nil { t.Fatal(err) @@ -63,13 +66,18 @@ func TestExtensionSeams(t *testing.T) { running := e.installation(device, "alloc-scope", "request-running") e.settle(device.Name) e.requirePhase(running, ops.PhaseAdmitted, "") - install := e.installation(device, "alloc-scope", "request-waiting") + olderInstall := e.installation(device, "alloc-scope", "request-older") time.Sleep(1100 * time.Millisecond) older := e.providerOp(device, "alloc-scope", "older") time.Sleep(1100 * time.Millisecond) + newerInstall := e.installation(device, "alloc-scope", "request-newer") + time.Sleep(1100 * time.Millisecond) newer := e.providerOp(device, "alloc-scope", "newer") e.settle(device.Name) - e.requirePhase(install, ops.PhasePending, ReasonOperationActive) + // Each kind's newest pending operation replaces only that kind's + // older one. + e.requirePhase(olderInstall, ops.PhaseCancelled, ReasonSuperseded) + e.requirePhase(newerInstall, ops.PhasePending, ReasonOperationActive) e.requirePhase(older, ops.PhaseCancelled, ReasonSuperseded) e.requirePhase(newer, ops.PhasePending, ReasonOperationActive) }) @@ -126,6 +134,26 @@ func TestExtensionSeams(t *testing.T) { retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) e.settle(device.Name) e.requirePhase(retry, ops.PhaseFailed, ReasonNotRetryable) + // A kind that another kind settles after a retry still refuses Retry + // unless it declares itself Retryable. + e.coord.Registry.Kind("DeviceWipe").Retryable = false + wiped := fresh() + if err := e.coord.Claim(e.ctx, wiped.Name, "alloc-nr"); err != nil { + t.Fatal(err) + } + if err := e.coord.BeginRelease(e.ctx, wiped.Name, "alloc-nr"); err != nil { + t.Fatal(err) + } + e.wipe(wiped, "alloc-nr", 1) + e.settle(wiped.Name) + if err := e.result(wiped.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(wiped.Name) + wipeHold := *e.custody(wiped.Name).Spec.RecoveryHold + refused := e.recovery(wiped, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(wipeHold)}) + e.settle(wiped.Name) + e.requirePhase(refused, ops.PhaseFailed, ReasonNotRetryable) }) t.Run("a worker refusal with nothing sent ends Failed and returns a Service holder to None", func(t *testing.T) { diff --git a/internal/custody/holds_test.go b/internal/custody/holds_test.go index 9ee3a946..bb2c703a 100644 --- a/internal/custody/holds_test.go +++ b/internal/custody/holds_test.go @@ -3,6 +3,7 @@ package custody import ( "context" "fmt" + "reflect" "slices" "sync" "testing" @@ -74,7 +75,9 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { e.allocation(device, "alloc-p-"+device.Name, "Active") install := e.installation(device, "alloc-p-"+device.Name, "request-1") // It may have run before custody was lost: its status says Admitted. - install.Status = ops.OperationStatus{Phase: ops.PhaseAdmitted, Fence: 4} + deadline := metav1.NewTime(e.clock.Now().Add(InstallationDeadline)) + recorded := ops.DeviceSnapshot{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: device.Spec.Identity.SystemUUID, BMCPublicKeySHA256: fmt.Sprintf("%064x", n), Extra: map[string]string{"resetTypes": "On"}} + install.Status = ops.OperationStatus{Phase: ops.PhaseAdmitted, Fence: 4, Deadline: &deadline, Snapshot: &recorded} if err := e.admin.Status().Update(e.ctx, install); err != nil { t.Fatal(err) } @@ -84,6 +87,10 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { if hold := custody.Spec.RecoveryHold; hold == nil || hold.UID != string(install.UID) || custody.Spec.ActiveOperation != nil || custody.Spec.Fence <= 4 { t.Fatalf("rebuilt = %+v", custody.Spec) } + // The rebuilt hold keeps the deadline and snapshot the status recorded. + if hold := custody.Spec.RecoveryHold; hold.Deadline == nil || !hold.Deadline.Equal(&deadline) || hold.Snapshot == nil || !reflect.DeepEqual(*hold.Snapshot, recorded) { + t.Fatalf("rebuilt hold = %+v", hold) + } e.requirePhase(install, ops.PhaseOutcomeUnknown, ReasonRebuilt) }) @@ -100,6 +107,11 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { if custody.Spec.Holder.Type != ops.HolderRelease || custody.Spec.RecoveryHold == nil || custody.Spec.RecoveryHold.UID != string(wipe.UID) || custody.Spec.ActiveOperation != nil { t.Fatalf("rebuilt = %+v", custody.Spec) } + // A Pending status recorded no deadline or snapshot, so the hold has + // none. + if hold := custody.Spec.RecoveryHold; hold.Deadline != nil || hold.Snapshot != nil { + t.Fatalf("rebuilt hold = %+v", hold) + } e.requirePhase(wipe, ops.PhaseOutcomeUnknown, ReasonRebuilt) }) diff --git a/internal/custody/registry.go b/internal/custody/registry.go index a976c6b4..a0273eb1 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -155,8 +155,10 @@ type Admission struct { // RecoverySettleContext is what a held kind's settle hook sees. Hold carries // when the held operation ended (Since), its deadline and its admission -// snapshot. Device is read when the hook runs, at admission of the recovery -// and again when it is applied. +// snapshot. A hold that rebuild created has Since set to the rebuild time, +// and has no deadline or snapshot if the operation's status never recorded +// them, so a hook must check both for nil. Device is read when the hook runs, +// at admission of the recovery and again when it is applied. type RecoverySettleContext struct { Hold ops.RecoveryHold Recovery *ops.DeviceRecovery @@ -312,8 +314,11 @@ func (r *Registry) declaredRefusal(kind, held string, refusal *Refusal) *Refusal return refuse(ReasonUndeclared, "%s refused with %s, which it does not declare", kind, refusal.Reason) } -func heldKind(custody *ops.DeviceCustody) string { - if hold := custody.Spec.RecoveryHold; hold != nil { +// settleHookKind is the held kind whose settle hook may refuse through this +// operation: only a non-effectful kind admitted to decide a hold, such as a +// DeviceRecovery, calls one. Any other kind's refusals must be its own. +func settleHookKind(kind *Kind, row Rule, custody *ops.DeviceCustody) string { + if hold := custody.Spec.RecoveryHold; hold != nil && !kind.Effectful && row.Hold == HoldRequired { return hold.Kind } return "" From 84375debd7fe5a59c7cf9e918c733f471854a39a Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 20:55:51 -0600 Subject: [PATCH 13/19] feat(custody): Follow the reasons and retries of #174 at abb1f88 Rename the shared admission reasons to the names #174 now gives them: CustodyUnverified, CreatorNotPermitted, OperationInProgress and DeviceIdentityMismatch, which also covers discovery that is not current. A hold now counts the Retry decisions applied to it, so a kind such as power can name its next operation from a retry count. Pin #174 at abb1f88 throughout. Co-Authored-By: Claude Opus 5.5 --- .../crds/fleet.datumapis.com.yaml | 6 ++- .../device-operations/kustomization.yaml | 2 +- docs/architecture/design.md | 2 +- docs/development/device-custody.md | 35 ++++++++++++---- internal/api/operations/v1alpha1/types.go | 6 ++- internal/custody/admission_test.go | 12 +++--- internal/custody/coordinator.go | 18 ++++---- internal/custody/extension_test.go | 4 +- internal/custody/holds_test.go | 2 +- internal/custody/kinds.go | 3 +- internal/custody/lifecycle_test.go | 10 ++--- internal/custody/recovery_test.go | 8 ++-- internal/custody/registry.go | 42 ++++++++++--------- test/acceptance/coverage.md | 2 +- 14 files changed, 90 insertions(+), 62 deletions(-) diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 18154ab5..f29e2ce0 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -1,4 +1,4 @@ -# DeviceCustody and the Device operation kinds proposed in #174 at 3907eec. +# DeviceCustody and the Device operation kinds proposed in #174 at abb1f88. # The coordinator is the only writer of custody and of operation status. apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition @@ -335,6 +335,10 @@ spec: - kind - name - uid + retries: + type: integer + format: int32 + minimum: 0 required: - kind - name diff --git a/config/components/device-operations/kustomization.yaml b/config/components/device-operations/kustomization.yaml index 91954847..e10230ba 100644 --- a/config/components/device-operations/kustomization.yaml +++ b/config/components/device-operations/kustomization.yaml @@ -1,4 +1,4 @@ -# Device custody and operations (#174 at 3907eec). Implemented and inert: no +# Device custody and operations (#174 at abb1f88). Implemented and inert: no # deployment root includes this component yet, so nothing serves these kinds # or calls the webhook. apiVersion: kustomize.config.k8s.io/v1beta1 diff --git a/docs/architecture/design.md b/docs/architecture/design.md index 0dd8963b..ef415ea4 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -11,7 +11,7 @@ replacement for the source proposals or a claim that their APIs exist. | --- | --- | --- | | [infra #5782: Fleet infrastructure management service](https://github.com/datum-cloud/infra/pull/5782) | `51781e2456367be82281e1443ca56d0686311133` | Service architecture, inventory, shared allocation, capacity publication, provisioning, OS configuration, and cluster lifecycle. Open draft at review time. | | [infra #7705: Node services and consumer pool gates](https://github.com/datum-cloud/infra/pull/7705) | `a712d2d3aaddcdc4d81c09d7f4cdd139bef06631` | Node services, consumer-owned pool sizing and gates, procurement guardrails, and regional independence. Open; targets the #5782 proposal branch. | -| [fleet #174: Device custody and operations](https://github.com/datum-cloud/fleet/pull/174) | `3907eec183616cfc6f08580d32447cd2887442a8` | Per-Device custody, one operation envelope, admission by conditional custody update, site fencing, recovery holds and custody rebuild. Open draft; [implementation status](../development/device-custody.md). | +| [fleet #174: Device custody and operations](https://github.com/datum-cloud/fleet/pull/174) | `abb1f880e46660690a405ab15ff627916d103812` | Per-Device custody, one operation envelope, admission by conditional custody update, site fencing, recovery holds and custody rebuild. Open draft; [implementation status](../development/device-custody.md). | Read the [core proposal at its reviewed revision][proposal] and the [extension at its reviewed revision][extension]. The latter includes the core diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index a19a4ecc..40b55f06 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -4,7 +4,7 @@ This page records how Fleet implements the [device custody and operations proposal](https://github.com/datum-cloud/fleet/pull/174) (#174, pinned at -`3907eec`). The proposal's API names are provisional. Each piece below is +`abb1f88`). The proposal's API names are provisional. Each piece below is marked **implemented and verified**, **implemented and inert**, or **proposed**. @@ -53,7 +53,7 @@ Each decision lists the open point from the implementation brief it settles. ### Who created an operation (O14) - The client sets `spec.creator` to its own username and UID. The webhook - rejects any other value and any change. That is how #174 at `3907eec` reads, + rejects any other value and any change. That is how #174 at `abb1f88` reads, so "clients cannot set the creator" becomes "clients can set only themselves". CEL also makes the creator immutable, as part of the spec. - Milo's root API server calls the webhook, because Milo v0.32.5 does not @@ -88,11 +88,26 @@ Each decision lists the open point from the implementation brief it settles. - **Phases for refusals (O5).** A refusal ends `Failed` with a reason, and nothing is sent. Expired, superseded and no-longer-matching operations end `Cancelled`. A `Pending` operation whose holder no longer matches is - `Cancelled`. One that never matched is `Failed`. The shared reasons are - `Unverified`, `NoMatchingRule`, `HolderMismatch`, `OperationActive`, - `IdentityMismatch`, `IdentityNotCurrent`, `SharedPublicKey`, `RecoveryHold`, - `NameMismatch`, `Expired`, `Superseded`, `Withdrawn`, `DeadlineExceeded` and - `SiteNotConfirmed`. Kinds add their own. + `Cancelled`. One that never matched is `Failed`. Kinds add their own + reasons. +- **Shared reasons.** The admission reasons use the names of #174's table: + + | Reason | Admission rule | + | --- | --- | + | `CustodyUnverified` | 1 | + | `CreatorNotPermitted` | 2 | + | `HolderMismatch` | 2 or 3 | + | `OperationInProgress` | 4 | + | `DeviceIdentityMismatch` | 5, both a mismatched identity and discovery that is not current | + | `SharedPublicKey` | 6 | + | `RecoveryHold` | A hold admits only its settling operations | + | `Expired` | Not admitted in time; ends `Cancelled` | + + Rule 7 is a kind's own checks of its inputs, with its own reasons. This + implementation adds `NameMismatch`, for a deterministic kind that is not + named by its rule, and outcome reasons: `Superseded`, `Withdrawn`, + `DeadlineExceeded`, `SiteNotConfirmed`, `SiteCouldNotProve`, + `InvalidEvidence`, `SnapshotInvalid` and `UndeclaredReason`. - **Current identity (O9).** Identity is current when BMC discovery reports `IdentityMatched` true for the Device's current generation, its last complete inventory read is at most two hours old (twice the default discovery @@ -275,7 +290,7 @@ these seams. Each is decided here. | 3 | Kinds add bounded snapshot fields | `SnapshotExtra` adds up to 16 camelCase fields of at most 256 bytes each. The snapshot goes to the operation, the active operation, the hold, and the site. | Implemented and inert | | 4 | The settle hook sees the hold's end time, its deadline and current Device status | The hold records when it ended (`Since`), the operation's deadline and its snapshot. The hook gets the Device as read when the recovery is admitted and again when it is applied. A hold that rebuild created has `Since` set to the rebuild time, and copies the deadline and snapshot from the operation's status, so both are absent for an operation whose status never recorded them. A hook checks for that. | Implemented and inert | | 5 | Kinds register their refusal reasons | Each reason is declared with where it is raised. The registry refuses a malformed name, a shared name, a duplicate, or a missing source. A coordinator refusal with an undeclared reason ends `UndeclaredReason`. A recovery's refusal may carry the held kind's declared reason only when it comes from that kind's settle hook. | Implemented and inert. Worker reasons are checked when results arrive, in B. | -| 6 | A kind may settle no hold, and declares whether `Retry` applies | `Settles` may be empty. `Retryable` marks a kind whose holds a `Retry` may unblock. | Implemented and inert | +| 6 | A kind may settle no hold, and declares whether `Retry` applies | `Settles` may be empty. `Retryable` marks a kind whose holds a `Retry` may unblock: a wipe, and, per #174 at `abb1f88`, power, whose hold settles with `Settle` and fresh discovery evidence or with `Retry` and a later power operation. A hold counts the `Retry` decisions applied to it. A deterministic name may carry that count, as power names an operation from its Machine generation and retry count; the kind's check compares the count with the hold's. | Implemented and inert | | 7 | End-to-end proof that Milo enforces the CRD rules | The `custody-crd-rules` phase of both local end-to-end runs installs only these CRDs into the provider project, requires the project API to refuse eight forbidden writes, and removes them. | Implemented and verified in the local end-to-end runs | | 8 | Journal steps carry a kind's payload | A step records a bounded payload, such as the send time or the power state before. Observation after a crash reads it. | Proposed for B | | 9 | Delivery carries the admission time, and kinds declare a start-by window | A worker that starts after the window refuses as `Stale`, with nothing sent. | Proposed for B | @@ -312,7 +327,9 @@ four seams. It needs no change to the coordinator. The test-only kinds in - a digest of its exact inputs (`custody.SpecDigest` covers the whole spec); - its naming rule: `DeterministicName` with a `Name` function for provider - and release kinds, or `GeneratedName` for staff kinds; + and release kinds, or `GeneratedName` for staff kinds. A name may + include a retry count from the spec; a kind that does checks it against + the hold's `Retries`; - its `Deadline`, and `Effectful` if it can reach the server; - `Supersedes`, if a newer pending operation of the same kind and the same authority should cancel an older one, as power needs. It never diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 46fc6052..eaec015b 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -1,5 +1,5 @@ // Package v1alpha1 holds Device custody and the Device operation kinds in -// fleet.datumapis.com, as proposed in datum-cloud/fleet#174 at 3907eec. +// fleet.datumapis.com, as proposed in datum-cloud/fleet#174 at abb1f88. // // DeviceCustody is a coordination record, like a Lease: its fields live in // spec and the coordinator is their only writer. Every operation kind shares @@ -161,6 +161,10 @@ type RecoveryHold struct { // RetryAuthorizedBy names the DeviceRecovery with Retry that lets the // held operation's requester create one settling operation. RetryAuthorizedBy *OperationReference `json:"retryAuthorizedBy,omitempty"` + // Retries counts the DeviceRecovery Retry decisions applied to this + // hold. A requester whose names carry a retry count, such as power's + // Machine generation and retry count, names its next operation from it. + Retries int32 `json:"retries,omitempty"` } // RejectedResults records site results the coordinator refused because their diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 84c46819..39a07c59 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -65,7 +65,7 @@ func TestAdmissionPreconditions(t *testing.T) { e.sites.forget(device.Name) staff := e.staffOp(device, "ok") e.settle(device.Name) - e.requirePhase(staff, ops.PhaseFailed, ReasonUnverified) + e.requirePhase(staff, ops.PhaseFailed, ReasonCustodyUnverified) e.requireUntouched(device.Name, custody.Spec.Fence) }) @@ -87,7 +87,7 @@ func TestAdmissionPreconditions(t *testing.T) { e.create(wipe) e.settle(device.Name) for _, operation := range []ops.Operation{spoof, service, named, wipe} { - e.requirePhase(operation, ops.PhaseFailed, ReasonNoMatchingRule) + e.requirePhase(operation, ops.PhaseFailed, ReasonCreatorNotPermitted) } e.requireUntouched(device.Name, fence) }) @@ -144,7 +144,7 @@ func TestAdmissionPreconditions(t *testing.T) { e.requirePhase(running, ops.PhaseAdmitted, "") waiting := e.providerOp(queued, "alloc-queue", "b") e.settle(queued.Name) - e.requirePhase(waiting, ops.PhasePending, ReasonOperationActive) + e.requirePhase(waiting, ops.PhasePending, ReasonOperationInProgress) if err := e.result(queued.Name, ops.PhaseSucceeded, ""); err != nil { t.Fatal(err) } @@ -161,7 +161,7 @@ func TestAdmissionPreconditions(t *testing.T) { operation.Spec.DeviceRef.UID = "00000000-0000-4000-8000-ffffffffffff" e.create(operation) e.settle(device.Name) - e.requirePhase(operation, ops.PhaseFailed, ReasonIdentityMismatch) + e.requirePhase(operation, ops.PhaseFailed, ReasonDeviceIdentityMismatch) e.requireUntouched(device.Name, fence) }) @@ -173,7 +173,7 @@ func TestAdmissionPreconditions(t *testing.T) { e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now().Add(-DefaultDiscoveryMaxAge-time.Minute)) old := e.staffOp(device, "ok") e.settle(device.Name) - e.requirePhase(old, ops.PhaseFailed, ReasonIdentityNotCurrent) + e.requirePhase(old, ops.PhaseFailed, ReasonDeviceIdentityMismatch) // Discovery that did not match identity. e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now()) if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { @@ -185,7 +185,7 @@ func TestAdmissionPreconditions(t *testing.T) { } mismatched := e.staffOp(device, "ok") e.settle(device.Name) - e.requirePhase(mismatched, ops.PhaseFailed, ReasonIdentityMismatch) + e.requirePhase(mismatched, ops.PhaseFailed, ReasonDeviceIdentityMismatch) e.requireUntouched(device.Name, fence) }) diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index f1066e2c..b1d6936c 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -665,7 +665,7 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } rows := c.Registry.matchRows(kind, operation, class) if len(rows) == 0 { - return fail(ReasonNoMatchingRule, "no row admits %s from a %s creator with this authority", kind.GVK.Kind, class) + return fail(ReasonCreatorNotPermitted, "no row admits %s from a %s creator with this authority", kind.GVK.Kind, class) } switch kind.Naming { case DeterministicName: @@ -678,12 +678,12 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } } if envelope.DeviceRef.UID != string(device.UID) { - return fail(ReasonIdentityMismatch, "deviceRef.uid does not match the Device") + return fail(ReasonDeviceIdentityMismatch, "deviceRef.uid does not match the Device") } // Precondition 1: custody state. rows = slices.DeleteFunc(rows, func(rule Rule) bool { return rule.custodyState() != custody.Spec.State }) if len(rows) == 0 { - return c.wait(class, ReasonUnverified, "custody is Unverified and admits only a DeviceRecovery with Resolve") + return c.wait(class, ReasonCustodyUnverified, "custody is Unverified and admits only a DeviceRecovery with Resolve") } // Preconditions 2 and 3: holder and allocation. holder := custody.Spec.Holder @@ -716,9 +716,9 @@ 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 { - return decision{phase: ops.PhasePending, reason: ReasonOperationActive, message: "waiting for the running operation"} + return decision{phase: ops.PhasePending, reason: ReasonOperationInProgress, message: "waiting for the running operation"} } - return fail(ReasonOperationActive, "another operation is running, and staff operations never wait") + return fail(ReasonOperationInProgress, "another operation is running, and staff operations never wait") } admission := &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Now: now, DiscoveryInterval: cfg.DiscoveryInterval} // Preconditions 5 and 6: current discovery and a unique BMC key. @@ -773,18 +773,18 @@ func (c *Coordinator) settlesHold(kind *Kind, hold ops.RecoveryHold) bool { // recorded the BMC key at the current endpoint. func (c *Coordinator) identityCurrent(device *inventory.Device, now time.Time) *Refusal { if device.Spec.BMC == nil || device.Spec.Identity.SystemUUID == "" { - return refuse(ReasonIdentityNotCurrent, "the Device records no BMC endpoint or system UUID") + return refuse(ReasonDeviceIdentityMismatch, "the Device records no BMC endpoint or system UUID") } condition := meta.FindStatusCondition(device.Status.Conditions, inventory.ConditionIdentityMatched) if condition == nil || condition.Status != metav1.ConditionTrue || condition.ObservedGeneration != device.Generation { - return refuse(ReasonIdentityMismatch, "discovery has not matched the Device identity at its current generation") + return refuse(ReasonDeviceIdentityMismatch, "discovery has not matched the Device identity at its current generation") } discovery := device.Status.Discovery if discovery == nil || discovery.Inventory == nil || now.Sub(discovery.Inventory.ObservedAt.Time) > c.config().DiscoveryMaxAge { - return refuse(ReasonIdentityNotCurrent, "discovery is older than %s", c.config().DiscoveryMaxAge) + return refuse(ReasonDeviceIdentityMismatch, "discovery is older than %s", c.config().DiscoveryMaxAge) } if discovery.TLS == nil || discovery.TLS.PublicKeySHA256 == "" || discovery.TLS.Endpoint != device.Spec.BMC.Endpoint { - return refuse(ReasonIdentityNotCurrent, "discovery has not recorded the BMC key at the current endpoint") + return refuse(ReasonDeviceIdentityMismatch, "discovery has not recorded the BMC key at the current endpoint") } return nil } diff --git a/internal/custody/extension_test.go b/internal/custody/extension_test.go index cf14b858..5a0d126a 100644 --- a/internal/custody/extension_test.go +++ b/internal/custody/extension_test.go @@ -77,9 +77,9 @@ func TestExtensionSeams(t *testing.T) { // Each kind's newest pending operation replaces only that kind's // older one. e.requirePhase(olderInstall, ops.PhaseCancelled, ReasonSuperseded) - e.requirePhase(newerInstall, ops.PhasePending, ReasonOperationActive) + e.requirePhase(newerInstall, ops.PhasePending, ReasonOperationInProgress) e.requirePhase(older, ops.PhaseCancelled, ReasonSuperseded) - e.requirePhase(newer, ops.PhasePending, ReasonOperationActive) + e.requirePhase(newer, ops.PhasePending, ReasonOperationInProgress) }) t.Run("kinds add bounded snapshot fields that the hold and the settle hook keep", func(t *testing.T) { diff --git a/internal/custody/holds_test.go b/internal/custody/holds_test.go index bb2c703a..0bafc5b6 100644 --- a/internal/custody/holds_test.go +++ b/internal/custody/holds_test.go @@ -99,7 +99,7 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { device := next() e.allocation(device, "alloc-r-"+device.Name, "Releasing") wipe := e.wipe(device, "alloc-r-"+device.Name, 1) - wipe.Status = ops.OperationStatus{Phase: ops.PhasePending, Reason: ReasonOperationActive} + wipe.Status = ops.OperationStatus{Phase: ops.PhasePending, Reason: ReasonOperationInProgress} if err := e.admin.Status().Update(e.ctx, wipe); err != nil { t.Fatal(err) } diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index de75ad2f..ec10e5cc 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -240,7 +240,7 @@ func checkRecovery(ctx context.Context, recovery *ops.DeviceRecovery, custody *o } return nil } - return refuse(ReasonNoMatchingRule, "unknown decision %q", spec.Decision) + return refuse(ReasonCreatorNotPermitted, "unknown decision %q", spec.Decision) } // resolveMatchesAllocations requires the holder a Resolve records to agree @@ -293,6 +293,7 @@ func applyRecovery(ctx context.Context, apply *ApplyContext) (*ops.DeviceCustody case ops.DecisionRetry: hold := *spec.RecoveryHold hold.RetryAuthorizedBy = &reference + hold.Retries++ spec.RecoveryHold = &hold case ops.DecisionRetire: spec.RecoveryHold = nil diff --git a/internal/custody/lifecycle_test.go b/internal/custody/lifecycle_test.go index 5a3851ed..0bc4f300 100644 --- a/internal/custody/lifecycle_test.go +++ b/internal/custody/lifecycle_test.go @@ -190,14 +190,14 @@ func TestLifecycle(t *testing.T) { time.Sleep(1100 * time.Millisecond) third := e.installation(device, "alloc-q", "request-third") e.settle(device.Name) - e.requirePhase(second, ops.PhasePending, ReasonOperationActive) - e.requirePhase(third, ops.PhasePending, ReasonOperationActive) + e.requirePhase(second, ops.PhasePending, ReasonOperationInProgress) + e.requirePhase(third, ops.PhasePending, ReasonOperationInProgress) if err := e.result(device.Name, ops.PhaseSucceeded, ""); err != nil { t.Fatal(err) } e.settle(device.Name) e.requirePhase(second, ops.PhaseAdmitted, "") - e.requirePhase(third, ops.PhasePending, ReasonOperationActive) + e.requirePhase(third, ops.PhasePending, ReasonOperationInProgress) }) t.Run("a newer pending operation supersedes an older one for the same authority", func(t *testing.T) { @@ -214,7 +214,7 @@ func TestLifecycle(t *testing.T) { newer := e.providerOp(device, "alloc-s", "newer") e.settle(device.Name) e.requirePhase(older, ops.PhaseCancelled, ReasonSuperseded) - e.requirePhase(newer, ops.PhasePending, ReasonOperationActive) + e.requirePhase(newer, ops.PhasePending, ReasonOperationInProgress) }) t.Run("a holder change cancels pending operations that no longer match", func(t *testing.T) { @@ -227,7 +227,7 @@ func TestLifecycle(t *testing.T) { e.settle(device.Name) pending := e.installation(device, "alloc-c", "request-b") e.settle(device.Name) - e.requirePhase(pending, ops.PhasePending, ReasonOperationActive) + e.requirePhase(pending, ops.PhasePending, ReasonOperationInProgress) // The Machine is deleted while the installation runs. if err := e.coord.BeginRelease(e.ctx, device.Name, "alloc-c"); err != nil { t.Fatal(err) diff --git a/internal/custody/recovery_test.go b/internal/custody/recovery_test.go index 561c08d0..da3bd11f 100644 --- a/internal/custody/recovery_test.go +++ b/internal/custody/recovery_test.go @@ -118,10 +118,10 @@ func TestRecovery(t *testing.T) { fence := e.custody(device.Name).Spec.Fence settle := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: heldRef(hold), Evidence: ops.RecoveryEvidence{ObservedAt: metav1.NewTime(e.clock.Now().Add(time.Minute)), Summary: "s", Data: map[string]string{"state": "On"}}}) e.settle(device.Name) - e.requirePhase(settle, ops.PhaseFailed, ReasonIdentityNotCurrent) + e.requirePhase(settle, ops.PhaseFailed, ReasonDeviceIdentityMismatch) retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) e.settle(device.Name) - e.requirePhase(retry, ops.PhaseFailed, ReasonIdentityNotCurrent) + e.requirePhase(retry, ops.PhaseFailed, ReasonDeviceIdentityMismatch) e.requireUntouched(device.Name, fence) e.device(fmt.Sprintf("server-twin-%03d", n), uid(900+n), key) retire := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(hold)}) @@ -266,7 +266,7 @@ func TestRecovery(t *testing.T) { e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) e.settle(device.Name) e.requirePhase(retry, ops.PhaseSucceeded, "") - if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy == nil || got.RetryAuthorizedBy.UID != string(retry.UID) { + if got := e.custody(device.Name).Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy == nil || got.RetryAuthorizedBy.UID != string(retry.UID) || got.Retries != 1 { t.Fatalf("retry not recorded: %+v", got) } second := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) @@ -540,7 +540,7 @@ func TestRebuild(t *testing.T) { // Only a Resolve recovery is admitted. staff := e.staffOp(replacement, "ok") e.settle(name) - e.requirePhase(staff, ops.PhaseFailed, ReasonUnverified) + e.requirePhase(staff, ops.PhaseFailed, ReasonCustodyUnverified) resolve := e.recovery(replacement, ops.DeviceRecoverySpec{Decision: ops.DecisionResolve, Resolve: &ops.ResolveInput{Holder: ops.HolderNone}}) e.settle(name) e.sites.report(name, e.custody(name).Spec.Fence) diff --git a/internal/custody/registry.go b/internal/custody/registry.go index a0273eb1..f8e1a1b2 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -1,5 +1,5 @@ // Package custody implements Device custody and coordinator admission, as -// proposed in datum-cloud/fleet#174 at 3907eec. +// proposed in datum-cloud/fleet#174 at abb1f88. // // The Coordinator is the only writer of DeviceCustody and of operation status. // Every custody change is one Update carrying the resourceVersion it read; on @@ -197,28 +197,30 @@ func refuse(reason, format string, args ...any) *Refusal { // Shared refusal and cancellation reasons. Kinds add their own; the set is // open. const ( - ReasonUnverified = "Unverified" - ReasonNoMatchingRule = "NoMatchingRule" - ReasonHolderMismatch = "HolderMismatch" - ReasonOperationActive = "OperationActive" - ReasonIdentityMismatch = "IdentityMismatch" - ReasonIdentityNotCurrent = "IdentityNotCurrent" - ReasonSharedPublicKey = "SharedPublicKey" - ReasonRecoveryHold = "RecoveryHold" - ReasonNameMismatch = "NameMismatch" - ReasonExpired = "Expired" - ReasonSuperseded = "Superseded" - ReasonWithdrawn = "Withdrawn" - ReasonDeadlineExceeded = "DeadlineExceeded" - ReasonSiteNotConfirmed = "SiteNotConfirmed" - ReasonSiteUnknown = "SiteCouldNotProve" - ReasonInvalidEvidence = "InvalidEvidence" - ReasonUndeclared = "UndeclaredReason" - ReasonSnapshotInvalid = "SnapshotInvalid" + // The shared admission reasons of #174, named as it names them, with + // the rule each refuses. NameMismatch and the outcome reasons below are + // this implementation's additions. + ReasonCustodyUnverified = "CustodyUnverified" // rule 1 + ReasonCreatorNotPermitted = "CreatorNotPermitted" // rule 2 + ReasonHolderMismatch = "HolderMismatch" // rule 2 or 3 + ReasonOperationInProgress = "OperationInProgress" // rule 4 + ReasonDeviceIdentityMismatch = "DeviceIdentityMismatch" // rule 5 + ReasonSharedPublicKey = "SharedPublicKey" + ReasonRecoveryHold = "RecoveryHold" + ReasonNameMismatch = "NameMismatch" + ReasonExpired = "Expired" + ReasonSuperseded = "Superseded" + ReasonWithdrawn = "Withdrawn" + ReasonDeadlineExceeded = "DeadlineExceeded" + ReasonSiteNotConfirmed = "SiteNotConfirmed" + ReasonSiteUnknown = "SiteCouldNotProve" + ReasonInvalidEvidence = "InvalidEvidence" + ReasonUndeclared = "UndeclaredReason" + ReasonSnapshotInvalid = "SnapshotInvalid" ) // sharedReasons are the reasons every kind may raise. -var sharedReasons = []string{ReasonUnverified, ReasonNoMatchingRule, ReasonHolderMismatch, ReasonOperationActive, ReasonIdentityMismatch, ReasonIdentityNotCurrent, +var sharedReasons = []string{ReasonCustodyUnverified, ReasonCreatorNotPermitted, ReasonHolderMismatch, ReasonOperationInProgress, ReasonDeviceIdentityMismatch, ReasonSharedPublicKey, ReasonRecoveryHold, ReasonNameMismatch, ReasonExpired, ReasonSuperseded, ReasonWithdrawn, ReasonDeadlineExceeded, ReasonSiteNotConfirmed, ReasonSiteUnknown, ReasonInvalidEvidence, ReasonUndeclared, ReasonSnapshotInvalid} diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index b4429303..71c8018e 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -31,7 +31,7 @@ result reports every required phase `Passed`. ## Device custody and operations -These are the acceptance tests of [#174 at `3907eec`](https://github.com/datum-cloud/fleet/pull/174). +These are the acceptance tests of [#174 at `abb1f88`](https://github.com/datum-cloud/fleet/pull/174). Increment A covers them against a real API server. End-to-end coverage arrives in Increments C and D. See [device custody](../../docs/development/device-custody.md#tests). From 32e654c654c0d2e3071183c2660d2300146c545b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 21:08:30 -0600 Subject: [PATCH 14/19] feat(custody): Name retries from the held operation, per #174 at 23c583f An operation created after a Retry is now named from the held operation: its name, -retry- and the Retry count custody records with the hold. It waits until the Retry is applied, and a retry that itself ends unknown keeps the original name and count. Rebuild reads that lineage back from the names. Pending replacement never cancels an operation that settles a hold, and operations waiting for the hold no longer hold back the one that settles it. A row can admit from a holder only to settle a hold of its kind, as the staff power row needs. Pin #174 at 23c583f. Co-Authored-By: Claude Opus 5.5 --- .../crds/fleet.datumapis.com.yaml | 5 +- .../device-operations/kustomization.yaml | 2 +- docs/architecture/design.md | 2 +- docs/development/device-custody.md | 55 +++++++++----- internal/api/operations/v1alpha1/types.go | 12 ++-- internal/custody/coordinator.go | 71 ++++++++++++++++--- internal/custody/extension_test.go | 28 +++++++- internal/custody/harness_test.go | 10 +++ internal/custody/holds_test.go | 22 ++++++ internal/custody/rebuild.go | 25 +++++++ internal/custody/recovery_test.go | 71 ++++++++++++++++--- internal/custody/registry.go | 2 +- internal/custody/rules.go | 4 ++ test/acceptance/coverage.md | 2 +- 14 files changed, 261 insertions(+), 50 deletions(-) diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index f29e2ce0..c7e4ae15 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -1,4 +1,4 @@ -# DeviceCustody and the Device operation kinds proposed in #174 at abb1f88. +# DeviceCustody and the Device operation kinds proposed in #174 at 23c583f. # The coordinator is the only writer of custody and of operation status. apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition @@ -339,6 +339,9 @@ spec: type: integer format: int32 minimum: 0 + retryName: + type: string + maxLength: 253 required: - kind - name diff --git a/config/components/device-operations/kustomization.yaml b/config/components/device-operations/kustomization.yaml index e10230ba..57c04627 100644 --- a/config/components/device-operations/kustomization.yaml +++ b/config/components/device-operations/kustomization.yaml @@ -1,4 +1,4 @@ -# Device custody and operations (#174 at abb1f88). Implemented and inert: no +# Device custody and operations (#174 at 23c583f). Implemented and inert: no # deployment root includes this component yet, so nothing serves these kinds # or calls the webhook. apiVersion: kustomize.config.k8s.io/v1beta1 diff --git a/docs/architecture/design.md b/docs/architecture/design.md index ef415ea4..b7a4eaf5 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -11,7 +11,7 @@ replacement for the source proposals or a claim that their APIs exist. | --- | --- | --- | | [infra #5782: Fleet infrastructure management service](https://github.com/datum-cloud/infra/pull/5782) | `51781e2456367be82281e1443ca56d0686311133` | Service architecture, inventory, shared allocation, capacity publication, provisioning, OS configuration, and cluster lifecycle. Open draft at review time. | | [infra #7705: Node services and consumer pool gates](https://github.com/datum-cloud/infra/pull/7705) | `a712d2d3aaddcdc4d81c09d7f4cdd139bef06631` | Node services, consumer-owned pool sizing and gates, procurement guardrails, and regional independence. Open; targets the #5782 proposal branch. | -| [fleet #174: Device custody and operations](https://github.com/datum-cloud/fleet/pull/174) | `abb1f880e46660690a405ab15ff627916d103812` | Per-Device custody, one operation envelope, admission by conditional custody update, site fencing, recovery holds and custody rebuild. Open draft; [implementation status](../development/device-custody.md). | +| [fleet #174: Device custody and operations](https://github.com/datum-cloud/fleet/pull/174) | `23c583fb0d542a79f4b0abcfe14c03a7b374e225` | Per-Device custody, one operation envelope, admission by conditional custody update, site fencing, recovery holds and custody rebuild. Open draft; [implementation status](../development/device-custody.md). | Read the [core proposal at its reviewed revision][proposal] and the [extension at its reviewed revision][extension]. The latter includes the core diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 40b55f06..b4599dfa 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -4,7 +4,7 @@ This page records how Fleet implements the [device custody and operations proposal](https://github.com/datum-cloud/fleet/pull/174) (#174, pinned at -`abb1f88`). The proposal's API names are provisional. Each piece below is +`23c583f`). The proposal's API names are provisional. Each piece below is marked **implemented and verified**, **implemented and inert**, or **proposed**. @@ -53,7 +53,7 @@ Each decision lists the open point from the implementation brief it settles. ### Who created an operation (O14) - The client sets `spec.creator` to its own username and UID. The webhook - rejects any other value and any change. That is how #174 at `abb1f88` reads, + rejects any other value and any change. That is how #174 at `23c583f` reads, so "clients cannot set the creator" becomes "clients can set only themselves". CEL also makes the creator immutable, as part of the spec. - Milo's root API server calls the webhook, because Milo v0.32.5 does not @@ -92,22 +92,38 @@ Each decision lists the open point from the implementation brief it settles. reasons. - **Shared reasons.** The admission reasons use the names of #174's table: - | Reason | Admission rule | + | Reason | Refused by | | --- | --- | - | `CustodyUnverified` | 1 | - | `CreatorNotPermitted` | 2 | - | `HolderMismatch` | 2 or 3 | - | `OperationInProgress` | 4 | - | `DeviceIdentityMismatch` | 5, both a mismatched identity and discovery that is not current | - | `SharedPublicKey` | 6 | - | `RecoveryHold` | A hold admits only its settling operations | - | `Expired` | Not admitted in time; ends `Cancelled` | - - Rule 7 is a kind's own checks of its inputs, with its own reasons. This - implementation adds `NameMismatch`, for a deterministic kind that is not + | `CustodyUnverified` | Rule 1 | + | `CreatorNotPermitted` | Rule 2 | + | `HolderMismatch` | Rule 2 or 3 | + | `OperationInProgress` | Rule 4 | + | `DeviceIdentityMismatch` | Rule 5, both a mismatched identity and discovery that is not current | + | `SharedPublicKey` | Rule 6 | + | `RecoveryHold` | A recovery hold | + + Rule 7 is a kind's own checks of its inputs, with its own reasons. 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`, `DeadlineExceeded`, `SiteNotConfirmed`, `SiteCouldNotProve`, `InvalidEvidence`, `SnapshotInvalid` and `UndeclaredReason`. +- **Retries.** An operation created after a `Retry` is named from the held + operation: its name, `-retry-`, and the number of `Retry` decisions for it, + which custody records with the hold. This applies to every kind whose + settlement needs a `Retry`, such as a wipe, and the kind's own naming rule + does not apply to it. Until the `Retry` is applied, the retried operation + waits in `Pending`. The `Retry` is used when that operation is admitted. If + the retried operation also ends unknown, its hold keeps the original name + and count, so the next retry is named `-retry-2`, not `-retry-1-retry-1`. + Rebuild reads that lineage back from the names. +- **Settling operations come first.** Pending replacement never cancels an + operation that settles the hold. Other operations wait in `Pending` until the + hold is settled, and they do not hold back the operation that settles it. +- **Holders under a hold.** A row can admit from a holder only to settle a + hold of its kind. The staff power row, "`None`, or `Service` under a power + hold", is two rows: one from `None`, and one from `Service` that requires a + hold the operation settles. - **Current identity (O9).** Identity is current when BMC discovery reports `IdentityMatched` true for the Device's current generation, its last complete inventory read is at most two hours old (twice the default discovery @@ -290,7 +306,7 @@ these seams. Each is decided here. | 3 | Kinds add bounded snapshot fields | `SnapshotExtra` adds up to 16 camelCase fields of at most 256 bytes each. The snapshot goes to the operation, the active operation, the hold, and the site. | Implemented and inert | | 4 | The settle hook sees the hold's end time, its deadline and current Device status | The hold records when it ended (`Since`), the operation's deadline and its snapshot. The hook gets the Device as read when the recovery is admitted and again when it is applied. A hold that rebuild created has `Since` set to the rebuild time, and copies the deadline and snapshot from the operation's status, so both are absent for an operation whose status never recorded them. A hook checks for that. | Implemented and inert | | 5 | Kinds register their refusal reasons | Each reason is declared with where it is raised. The registry refuses a malformed name, a shared name, a duplicate, or a missing source. A coordinator refusal with an undeclared reason ends `UndeclaredReason`. A recovery's refusal may carry the held kind's declared reason only when it comes from that kind's settle hook. | Implemented and inert. Worker reasons are checked when results arrive, in B. | -| 6 | A kind may settle no hold, and declares whether `Retry` applies | `Settles` may be empty. `Retryable` marks a kind whose holds a `Retry` may unblock: a wipe, and, per #174 at `abb1f88`, power, whose hold settles with `Settle` and fresh discovery evidence or with `Retry` and a later power operation. A hold counts the `Retry` decisions applied to it. A deterministic name may carry that count, as power names an operation from its Machine generation and retry count; the kind's check compares the count with the hold's. | Implemented and inert | +| 6 | A kind may settle no hold, and declares whether `Retry` applies | `Settles` may be empty. `Retryable` marks a kind whose holds a `Retry` may unblock: a wipe, and power, whose hold settles with `Settle` and fresh discovery evidence or with `Retry` and a later power operation. A hold counts the `Retry` decisions applied to it, and the operation created after a `Retry` is named from the held operation and that count, as [Retries](#admission) describes. | Implemented and inert | | 7 | End-to-end proof that Milo enforces the CRD rules | The `custody-crd-rules` phase of both local end-to-end runs installs only these CRDs into the provider project, requires the project API to refuse eight forbidden writes, and removes them. | Implemented and verified in the local end-to-end runs | | 8 | Journal steps carry a kind's payload | A step records a bounded payload, such as the send time or the power state before. Observation after a crash reads it. | Proposed for B | | 9 | Delivery carries the admission time, and kinds declare a start-by window | A worker that starts after the window refuses as `Stale`, with nothing sent. | Proposed for B | @@ -327,9 +343,8 @@ four seams. It needs no change to the coordinator. The test-only kinds in - a digest of its exact inputs (`custody.SpecDigest` covers the whole spec); - its naming rule: `DeterministicName` with a `Name` function for provider - and release kinds, or `GeneratedName` for staff kinds. A name may - include a retry count from the spec; a kind that does checks it against - the hold's `Retries`; + and release kinds, or `GeneratedName` for staff kinds. An operation + created after a `Retry` is named by the coordinator's retry rule instead; - its `Deadline`, and `Effectful` if it can reach the server; - `Supersedes`, if a newer pending operation of the same kind and the same authority should cancel an older one, as power needs. It never @@ -355,7 +370,9 @@ four seams. It needs no change to the coordinator. The test-only kinds in the phase rule, plus a ProtectedResource and roles. 2. **Add its rows.** Add one `custody.Rule` per row of the #174 operations table: the creator class, the authority type, the holders it admits from, - its hold behavior, and whether it queues. Staff rows never queue. To admit + its hold behavior, and whether it queues. A holder admitted only under the + kind's own hold, such as `Service` under a power hold, is a separate row + with `HoldSettlesRequired`. Staff rows never queue. To admit a new service principal, add its class to the coordinator's principal configuration. Never hard-code an identity. 3. **Implement its site worker** (Increment B). The site framework owns the diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index eaec015b..42b08f95 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -1,5 +1,5 @@ // Package v1alpha1 holds Device custody and the Device operation kinds in -// fleet.datumapis.com, as proposed in datum-cloud/fleet#174 at abb1f88. +// fleet.datumapis.com, as proposed in datum-cloud/fleet#174 at 23c583f. // // DeviceCustody is a coordination record, like a Lease: its fields live in // spec and the coordinator is their only writer. Every operation kind shares @@ -161,10 +161,14 @@ type RecoveryHold struct { // RetryAuthorizedBy names the DeviceRecovery with Retry that lets the // held operation's requester create one settling operation. RetryAuthorizedBy *OperationReference `json:"retryAuthorizedBy,omitempty"` - // Retries counts the DeviceRecovery Retry decisions applied to this - // hold. A requester whose names carry a retry count, such as power's - // Machine generation and retry count, names its next operation from it. + // Retries counts the DeviceRecovery Retry decisions for the held + // operation. An operation created after a Retry is named RetryName (the + // held operation's name when empty) plus "-retry-" and this count. Retries int32 `json:"retries,omitempty"` + // RetryName is the name retries are named from. It is set when a retried + // operation itself ends unknown, so its retries keep the original + // operation's name and count on. + RetryName string `json:"retryName,omitempty"` } // RejectedResults records site results the coordinator refused because their diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index b1d6936c..da083c13 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -8,6 +8,7 @@ import ( "regexp" "slices" "sort" + "strconv" "time" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" @@ -491,7 +492,16 @@ func (c *Coordinator) holdUnknown(custody *ops.DeviceCustody, active ops.ActiveO now := metav1.NewTime(c.now()) spec.ActiveOperation = nil deadline, snapshot := active.Deadline, active.Snapshot - spec.RecoveryHold = &ops.RecoveryHold{OperationReference: active.OperationReference, Fence: active.Fence, Since: now, Reason: reason, Deadline: &deadline, Snapshot: &snapshot} + next := &ops.RecoveryHold{OperationReference: active.OperationReference, Fence: active.Fence, Since: now, Reason: reason, Deadline: &deadline, Snapshot: &snapshot} + // A retry that itself ends unknown keeps the original operation's name + // and Retry count, so the next retry is named on from it. + if previous := spec.RecoveryHold; previous != nil && active.Settles != nil && *active.Settles == previous.OperationReference && previous.Retries > 0 && active.Name == RetryName(*previous, previous.Retries) { + next.RetryName, next.Retries = previous.RetryName, previous.Retries + if next.RetryName == "" { + next.RetryName = previous.Name + } + } + spec.RecoveryHold = next spec.LastResult = &ops.OperationResult{OperationReference: active.OperationReference, Fence: active.Fence, Phase: ops.PhaseOutcomeUnknown, Reason: reason, Message: message, FinishedAt: now} if evidence != nil { spec.LastResult.Evidence = rawExtension(evidence) @@ -580,7 +590,7 @@ func (c *Coordinator) admit(ctx context.Context, custody *ops.DeviceCustody, dev if fresh.ResourceVersion != custody.ResourceVersion { return Outcome{Changed: true}, nil } - superseded := c.superseded(candidates) + superseded := c.superseded(candidates, custody.Spec.RecoveryHold) queued := false changed := false for _, candidate := range candidates { @@ -597,7 +607,9 @@ func (c *Coordinator) admit(ctx context.Context, custody *ops.DeviceCustody, dev outcome.Changed = true return outcome, err } - if d.phase == ops.PhasePending { + // An operation waiting for the hold to settle does not hold back + // the queue: the operation that settles it goes first. + if d.phase == ops.PhasePending && d.reason != ReasonRecoveryHold { queued = true } wrote, err := c.mark(ctx, operation, d) @@ -611,12 +623,13 @@ func (c *Coordinator) admit(ctx context.Context, custody *ops.DeviceCustody, dev // superseded returns pending operations replaced by a newer one of the same // superseding kind and authority. -func (c *Coordinator) superseded(candidates []candidate) map[types.UID]bool { +func (c *Coordinator) superseded(candidates []candidate, hold *ops.RecoveryHold) map[types.UID]bool { out := map[types.UID]bool{} newest := map[string]ops.Operation{} for _, candidate := range candidates { operation, kind := candidate.operation, candidate.kind - if !kind.Supersedes { + // An operation that settles the hold is never replaced. + if !kind.Supersedes || (hold != nil && (c.settlesHold(kind, *hold, operation) || isRetry(kind, hold, operation))) { continue } key := kind.GVK.Kind + "/" + authorityKey(operation.Envelope().Authority) @@ -667,12 +680,15 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper if len(rows) == 0 { return fail(ReasonCreatorNotPermitted, "no row admits %s from a %s creator with this authority", kind.GVK.Kind, class) } - switch kind.Naming { - case DeterministicName: + // An operation created after a Retry is named for the Retry, whatever + // the kind's own rule. + switch { + case isRetry(kind, custody.Spec.RecoveryHold, operation): + case kind.Naming == DeterministicName: if want := kind.Name(operation); operation.GetName() != want { return fail(ReasonNameMismatch, "the operation must be named %s", want) } - case GeneratedName: + case kind.Naming == GeneratedName: if operation.GetGenerateName() == "" { return fail(ReasonNameMismatch, "a staff operation must be created with a generated name") } @@ -703,8 +719,10 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper case row.Hold == HoldRequired && hold == nil: return fail(ReasonRecoveryHold, "this operation decides a recovery hold, and there is none") case row.Hold == HoldRequired: + case row.Hold == HoldSettlesRequired && (hold == nil || !c.settlesHold(kind, *hold, operation)): + return fail(ReasonHolderMismatch, "from this holder, the operation is admitted only to settle a hold of its kind") case hold != nil: - if !c.settlesHold(kind, *hold) { + if !c.settlesHold(kind, *hold, operation) { if row.Queue { return decision{phase: ops.PhasePending, reason: ReasonRecoveryHold, message: "waiting: " + hold.Kind + " " + hold.Name + " is held, and only its settling operations are admitted"} } @@ -758,15 +776,46 @@ func (c *Coordinator) wait(class CreatorClass, reason, message string) decision return decision{phase: ops.PhaseFailed, reason: reason, message: message} } -func (c *Coordinator) settlesHold(kind *Kind, hold ops.RecoveryHold) bool { +// settlesHold reports whether the operation settles the hold. A settle rule +// that requires a Retry admits only the operation named for the current +// Retry, after that Retry is applied. +func (c *Coordinator) settlesHold(kind *Kind, hold ops.RecoveryHold, operation ops.Operation) bool { for _, rule := range kind.Settles { - if rule.Held == hold.Kind && (!rule.RequiresRetry || hold.RetryAuthorizedBy != nil) { + if rule.Held != hold.Kind { + continue + } + if !rule.RequiresRetry || (hold.RetryAuthorizedBy != nil && operation.GetName() == RetryName(hold, hold.Retries)) { return true } } return false } +// retries reports whether the kind settles the hold only after a Retry. +func retries(kind *Kind, hold *ops.RecoveryHold) bool { + return hold != nil && slices.ContainsFunc(kind.Settles, func(rule SettleRule) bool { return rule.Held == hold.Kind && rule.RequiresRetry }) +} + +// RetryName is the name of the operation created after the count-th Retry +// of a hold: the held operation's name, "-retry-" and the count. +func RetryName(hold ops.RecoveryHold, count int32) string { + base := hold.RetryName + if base == "" { + base = hold.Name + } + return base + "-retry-" + strconv.Itoa(int(count)) +} + +// isRetry reports whether the operation is named as a retry of the hold, +// for the Retry already applied or the next one. +func isRetry(kind *Kind, hold *ops.RecoveryHold, operation ops.Operation) bool { + if !retries(kind, hold) { + return false + } + name := operation.GetName() + return name == RetryName(*hold, hold.Retries) || name == RetryName(*hold, hold.Retries+1) +} + // identityCurrent is precondition 5's discovery half. Identity is current when // BMC discovery matched the recorded identity against this Device // generation, completed an inventory read within DiscoveryMaxAge, and diff --git a/internal/custody/extension_test.go b/internal/custody/extension_test.go index 5a0d126a..d01b36d3 100644 --- a/internal/custody/extension_test.go +++ b/internal/custody/extension_test.go @@ -116,6 +116,32 @@ func TestExtensionSeams(t *testing.T) { e.requirePhase(tooMuch, ops.PhaseFailed, ReasonSnapshotInvalid) }) + t.Run("a row may admit from Service only under a hold its kind settles", func(t *testing.T) { + e := e.sub(t) + // The staff power row: None, or Service under a power hold. + if err := e.coord.Registry.AddRule(Rule{Kind: testStaffKind, Creator: CreatorStaff, Authority: AuthorityService, Holders: []ops.HolderType{ops.HolderService}, Hold: HoldSettlesRequired}); err != nil { + t.Fatal(err) + } + device := fresh() + hold := e.holdOn(device) + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderService { + t.Fatalf("holder = %s", holder) + } + settling := e.staffOp(device, "ok") + e.settle(device.Name) + e.requirePhase(settling, ops.PhaseAdmitted, "") + if active := e.custody(device.Name).Spec.ActiveOperation; active.Settles == nil || active.Settles.UID != hold.UID { + t.Fatalf("active = %+v", active) + } + if err := e.result(device.Name, ops.PhaseSucceeded, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + if custody := e.custody(device.Name); custody.Spec.RecoveryHold != nil || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("after settling: %+v", custody.Spec) + } + }) + t.Run("a refusal with a reason the kind never declared is recorded as UndeclaredReason", func(t *testing.T) { e := e.sub(t) device := fresh() @@ -194,7 +220,7 @@ func TestRegistryValidatesDeclaredReasons(t *testing.T) { none := testKinds()[1] none.GVK.Kind, none.Settles = "DeviceTestUnsettled", nil c := &Coordinator{Registry: registry} - if c.settlesHold(&none, ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceTestUnsettled"}}) { + if c.settlesHold(&none, ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceTestUnsettled"}}, &DeviceTestProviderOperation{}) { t.Fatal("a kind with no settle rules settled a hold") } } diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index 1f813c73..be0a7e81 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -321,6 +321,16 @@ func (e *env) wipe(device *inventory.Device, allocation string, step int32) *ops return operation } +// namedWipe creates a wipe with an explicit name, such as a retry's. +func (e *env) namedWipe(device *inventory.Device, allocation, name string, step int32) *ops.DeviceWipe { + e.t.Helper() + operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: ops.DeviceWipeSpec{ + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, + }} + e.create(operation) + return operation +} + func (e *env) recovery(device *inventory.Device, spec ops.DeviceRecoverySpec) *ops.DeviceRecovery { e.t.Helper() spec.OperationEnvelope = envelope(device, staffUser, service("recovery")) diff --git a/internal/custody/holds_test.go b/internal/custody/holds_test.go index 0bafc5b6..4dd2757a 100644 --- a/internal/custody/holds_test.go +++ b/internal/custody/holds_test.go @@ -138,6 +138,28 @@ func TestRebuildKeepsUnprovenOutcomes(t *testing.T) { } }) + t.Run("a rebuilt hold on a retry keeps the retry lineage", func(t *testing.T) { + e := e.sub(t) + device := next() + allocation := "alloc-l-" + device.Name + e.allocation(device, allocation, "Releasing") + original := e.wipe(device, allocation, 1) + original.Status = ops.OperationStatus{Phase: ops.PhaseOutcomeUnknown, Fence: 1, FinishedAt: ptrTime(e.clock.Now())} + if err := e.admin.Status().Update(e.ctx, original); err != nil { + t.Fatal(err) + } + retried := e.namedWipe(device, allocation, original.Name+"-retry-2", 1) + retried.Status = ops.OperationStatus{Phase: ops.PhaseOutcomeUnknown, Fence: 3, FinishedAt: ptrTime(e.clock.Now())} + if err := e.admin.Status().Update(e.ctx, retried); err != nil { + t.Fatal(err) + } + custody := verify(e, device, 3) + hold := custody.Spec.RecoveryHold + if hold == nil || hold.UID != string(retried.UID) || hold.RetryName != original.Name || hold.Retries != 2 || RetryName(*hold, 3) != original.Name+"-retry-3" || len(custody.Spec.Conflicts) != 0 { + t.Fatalf("rebuilt hold = %+v", hold) + } + }) + t.Run("several unproven outcomes keep the newest held and need a Resolve", func(t *testing.T) { e := e.sub(t) device := next() diff --git a/internal/custody/rebuild.go b/internal/custody/rebuild.go index 5e2ea25e..3bdd2bc0 100644 --- a/internal/custody/rebuild.go +++ b/internal/custody/rebuild.go @@ -4,7 +4,9 @@ import ( "cmp" "context" "encoding/json" + "regexp" "slices" + "strconv" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" @@ -25,6 +27,16 @@ const ( ConflictMultipleUnfinished = "MultipleUnfinishedOperations" ) +var retrySuffix = regexp.MustCompile(`^(.+)-retry-([1-9][0-9]{0,8})$`) + +// retryBase is the name of the operation a retry was named from. +func retryBase(name string) string { + if match := retrySuffix.FindStringSubmatch(name); match != nil { + return match[1] + } + return name +} + // ReasonRebuilt is the hold reason for an operation found unfinished when // custody was rebuilt. const ReasonRebuilt = "Rebuilt" @@ -95,6 +107,10 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) settled := func(held found) bool { fence := held.operation.OperationStatus().Fence for _, other := range all { + // A later retry of the same operation continues its hold. + if other.kind == held.kind && retryBase(other.operation.GetName()) == retryBase(held.operation.GetName()) && other.operation.GetName() != held.operation.GetName() && other.operation.OperationStatus().Fence > fence { + return true + } status := other.operation.OperationStatus() if status.Phase != ops.PhaseSucceeded { continue @@ -139,6 +155,15 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) newest := held[0] status := newest.operation.OperationStatus() spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: newest.kind.GVK.Kind, Name: newest.operation.GetName(), UID: string(newest.operation.GetUID())}, Fence: status.Fence, Since: metav1.NewTime(c.now()), Reason: ReasonRebuilt, Deadline: status.Deadline, Snapshot: status.Snapshot} + // A held retry keeps its lineage: its name is the original + // operation's name, "-retry-" and the Retry count. + if match := retrySuffix.FindStringSubmatch(newest.operation.GetName()); match != nil && slices.ContainsFunc(all, func(other found) bool { + return other.kind == newest.kind && other.operation.GetName() == match[1] + }) { + if count, err := strconv.Atoi(match[2]); err == nil { + spec.RecoveryHold.RetryName, spec.RecoveryHold.Retries = match[1], int32(count) + } + } if len(held) > 1 { spec.Conflicts = appendOnce(spec.Conflicts, ConflictMultipleUnfinished) } diff --git a/internal/custody/recovery_test.go b/internal/custody/recovery_test.go index da3bd11f..1268fac1 100644 --- a/internal/custody/recovery_test.go +++ b/internal/custody/recovery_test.go @@ -199,7 +199,7 @@ func TestRecovery(t *testing.T) { } }) - t.Run("a held wipe settles only after a Retry, which authorizes one wipe", func(t *testing.T) { + t.Run("a held wipe settles only with a wipe named for the Retry, and retries count on", func(t *testing.T) { e := e.sub(t) device := fresh() if err := e.coord.Claim(e.ctx, device.Name, "alloc-w"); err != nil { @@ -210,17 +210,21 @@ func TestRecovery(t *testing.T) { } first := e.wipe(device, "alloc-w", 1) e.settle(device.Name) - if err := e.result(device.Name, ops.PhaseOutcomeUnknown, "BMCResponseLost"); err != nil { + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { t.Fatal(err) } e.settle(device.Name) e.requirePhase(first, ops.PhaseOutcomeUnknown, "") hold := *e.custody(device.Name).Spec.RecoveryHold - // A wipe that cannot settle the hold yet waits; its name is - // deterministic, so it could not be created again. - next := e.wipe(device, "alloc-w", 2) + // Other operations wait until the hold is settled; their names are + // deterministic, so they could not be created again. + later := e.wipe(device, "alloc-w", 2) + e.settle(device.Name) + e.requirePhase(later, ops.PhasePending, ReasonRecoveryHold) + // The retried wipe takes the held wipe's name, and waits for the Retry. + retried := e.namedWipe(device, "alloc-w", RetryName(hold, 1), 1) e.settle(device.Name) - e.requirePhase(next, ops.PhasePending, ReasonRecoveryHold) + e.requirePhase(retried, ops.PhasePending, ReasonRecoveryHold) // Settle is not how a wipe hold ends. settle := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionSettle, Hold: heldRef(hold)}) e.settle(device.Name) @@ -230,19 +234,66 @@ func TestRecovery(t *testing.T) { e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) e.settle(device.Name) e.requirePhase(retry, ops.PhaseSucceeded, "") - // The waiting wipe is the one settling operation the Retry allows. - e.requirePhase(next, ops.PhaseAdmitted, "") + // The retried wipe goes first, ahead of the older waiting one, and + // uses the Retry. + e.requirePhase(retried, ops.PhaseAdmitted, "") + e.requirePhase(later, ops.PhasePending, ReasonRecoveryHold) custody := e.custody(device.Name) - if got := custody.Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy != nil || custody.Spec.ActiveOperation.Settles == nil || custody.Spec.ActiveOperation.Settles.UID != hold.UID { - t.Fatalf("the retry was not used by the waiting wipe: %+v", custody.Spec) + if got := custody.Spec.RecoveryHold; got == nil || got.RetryAuthorizedBy != nil || got.Retries != 1 || custody.Spec.ActiveOperation.Settles == nil || custody.Spec.ActiveOperation.Settles.UID != hold.UID { + t.Fatalf("the retry was not used by the retried wipe: %+v", custody.Spec) + } + // The retried wipe ends unknown too: the next retry keeps the + // original name and counts on. + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + second := *e.custody(device.Name).Spec.RecoveryHold + if second.UID != string(retried.UID) || second.RetryName != hold.Name || second.Retries != 1 { + t.Fatalf("second hold = %+v", second) + } + again := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(second)}) + e.settle(device.Name) + e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) + e.settle(device.Name) + e.requirePhase(again, ops.PhaseSucceeded, "") + if name := RetryName(*e.custody(device.Name).Spec.RecoveryHold, 2); name != hold.Name+"-retry-2" { + t.Fatalf("next retry name = %s", name) } + retriedAgain := e.namedWipe(device, "alloc-w", hold.Name+"-retry-2", 1) + e.settle(device.Name) + e.requirePhase(retriedAgain, ops.PhaseAdmitted, "") if err := e.result(device.Name, ops.PhaseSucceeded, ""); err != nil { t.Fatal(err) } e.settle(device.Name) + // The hold is settled, and the waiting wipe runs next. if got := e.custody(device.Name).Spec.RecoveryHold; got != nil { t.Fatalf("hold survived the retried wipe: %+v", got) } + e.requirePhase(later, ops.PhaseAdmitted, "") + }) + + t.Run("pending replacement never cancels an operation that settles a hold", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-ps"); err != nil { + t.Fatal(err) + } + e.providerOp(device, "alloc-ps", "held") + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + // Both settle the held provider operation, and the kind supersedes: + // neither replaces the other while the hold exists. + older := e.providerOp(device, "alloc-ps", "older") + time.Sleep(1100 * time.Millisecond) + newer := e.providerOp(device, "alloc-ps", "newer") + e.settle(device.Name) + e.requirePhase(older, ops.PhaseAdmitted, "") + e.requirePhase(newer, ops.PhasePending, ReasonOperationInProgress) }) t.Run("a second Retry for the same hold is refused", func(t *testing.T) { diff --git a/internal/custody/registry.go b/internal/custody/registry.go index f8e1a1b2..d3055a86 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -1,5 +1,5 @@ // Package custody implements Device custody and coordinator admission, as -// proposed in datum-cloud/fleet#174 at abb1f88. +// proposed in datum-cloud/fleet#174 at 23c583f. // // The Coordinator is the only writer of DeviceCustody and of operation status. // Every custody change is one Update carrying the resourceVersion it read; on diff --git a/internal/custody/rules.go b/internal/custody/rules.go index 4001f8a7..daf23d87 100644 --- a/internal/custody/rules.go +++ b/internal/custody/rules.go @@ -43,6 +43,10 @@ const ( HoldRequired HoldBehavior = "Required" // HoldIgnored admits the operation whether or not a hold exists. HoldIgnored HoldBehavior = "Ignored" + // HoldSettlesRequired admits the operation only under a hold it + // settles, such as a staff power operation from holder Service under a + // power hold. + HoldSettlesRequired HoldBehavior = "SettlesRequired" ) // Rule is one row of the operations table in #174. diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 71c8018e..7901531e 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -31,7 +31,7 @@ result reports every required phase `Passed`. ## Device custody and operations -These are the acceptance tests of [#174 at `abb1f88`](https://github.com/datum-cloud/fleet/pull/174). +These are the acceptance tests of [#174 at `23c583f`](https://github.com/datum-cloud/fleet/pull/174). Increment A covers them against a real API server. End-to-end coverage arrives in Increments C and D. See [device custody](../../docs/development/device-custody.md#tests). From 87241be0642078530cbbdc0228c68945562dab01 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 21:10:28 -0600 Subject: [PATCH 15/19] docs: Pin #174 at d4d17f9 and map its recovery hold fields #174 now says what a recovery hold carries and when a Retry is accepted. The implementation already matches. Record how the hold's retry count and its unused-Retry marker map to that text, and pin the new head. Co-Authored-By: Claude Opus 5.5 --- .../device-operations/crds/fleet.datumapis.com.yaml | 2 +- .../components/device-operations/kustomization.yaml | 2 +- docs/architecture/design.md | 2 +- docs/development/device-custody.md | 12 +++++++++--- internal/api/operations/v1alpha1/types.go | 2 +- internal/custody/registry.go | 2 +- test/acceptance/coverage.md | 2 +- 7 files changed, 15 insertions(+), 9 deletions(-) diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index c7e4ae15..6b60afe9 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -1,4 +1,4 @@ -# DeviceCustody and the Device operation kinds proposed in #174 at 23c583f. +# DeviceCustody and the Device operation kinds proposed in #174 at d4d17f9. # The coordinator is the only writer of custody and of operation status. apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition diff --git a/config/components/device-operations/kustomization.yaml b/config/components/device-operations/kustomization.yaml index 57c04627..093f38a4 100644 --- a/config/components/device-operations/kustomization.yaml +++ b/config/components/device-operations/kustomization.yaml @@ -1,4 +1,4 @@ -# Device custody and operations (#174 at 23c583f). Implemented and inert: no +# Device custody and operations (#174 at d4d17f9). Implemented and inert: no # deployment root includes this component yet, so nothing serves these kinds # or calls the webhook. apiVersion: kustomize.config.k8s.io/v1beta1 diff --git a/docs/architecture/design.md b/docs/architecture/design.md index b7a4eaf5..a046ee4d 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -11,7 +11,7 @@ replacement for the source proposals or a claim that their APIs exist. | --- | --- | --- | | [infra #5782: Fleet infrastructure management service](https://github.com/datum-cloud/infra/pull/5782) | `51781e2456367be82281e1443ca56d0686311133` | Service architecture, inventory, shared allocation, capacity publication, provisioning, OS configuration, and cluster lifecycle. Open draft at review time. | | [infra #7705: Node services and consumer pool gates](https://github.com/datum-cloud/infra/pull/7705) | `a712d2d3aaddcdc4d81c09d7f4cdd139bef06631` | Node services, consumer-owned pool sizing and gates, procurement guardrails, and regional independence. Open; targets the #5782 proposal branch. | -| [fleet #174: Device custody and operations](https://github.com/datum-cloud/fleet/pull/174) | `23c583fb0d542a79f4b0abcfe14c03a7b374e225` | Per-Device custody, one operation envelope, admission by conditional custody update, site fencing, recovery holds and custody rebuild. Open draft; [implementation status](../development/device-custody.md). | +| [fleet #174: Device custody and operations](https://github.com/datum-cloud/fleet/pull/174) | `d4d17f9b4a34307d190efb0cea59dde2f26662ee` | Per-Device custody, one operation envelope, admission by conditional custody update, site fencing, recovery holds and custody rebuild. Open draft; [implementation status](../development/device-custody.md). | Read the [core proposal at its reviewed revision][proposal] and the [extension at its reviewed revision][extension]. The latter includes the core diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index b4599dfa..994350ae 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -4,7 +4,7 @@ This page records how Fleet implements the [device custody and operations proposal](https://github.com/datum-cloud/fleet/pull/174) (#174, pinned at -`23c583f`). The proposal's API names are provisional. Each piece below is +`d4d17f9`). The proposal's API names are provisional. Each piece below is marked **implemented and verified**, **implemented and inert**, or **proposed**. @@ -53,7 +53,7 @@ Each decision lists the open point from the implementation brief it settles. ### Who created an operation (O14) - The client sets `spec.creator` to its own username and UID. The webhook - rejects any other value and any change. That is how #174 at `23c583f` reads, + rejects any other value and any change. That is how #174 at `d4d17f9` reads, so "clients cannot set the creator" becomes "clients can set only themselves". CEL also makes the creator immutable, as part of the spec. - Milo's root API server calls the webhook, because Milo v0.32.5 does not @@ -195,7 +195,13 @@ Each value is configurable. that check accepts the evidence. Installation and wipe holds have no such check: later operations settle them. - `Retry` marks the hold so that the held operation's requester can create one - settling operation. Admitting that operation uses up the retry. + settling operation. The hold carries what #174 asks of it: the held + operation, its `Retry` count (`retries`), and whether a `Retry` is unused + (`retryAuthorizedBy`). Admission accepts a `Retry` only for a hold whose + settlement row requires one, meaning the held kind is `Retryable` and a kind + settles it after a `Retry`, and refuses one while an earlier `Retry` is + unused. Applying a `Retry` raises the count, and admitting the settling + operation uses it. - `Retire` needs a hold and a `Service` or `Release` holder. Retiring from `Release` requires a disk disposal record. - `Resolve` is the only operation `Unverified` custody admits. It records the diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 42b08f95..de825e1c 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -1,5 +1,5 @@ // Package v1alpha1 holds Device custody and the Device operation kinds in -// fleet.datumapis.com, as proposed in datum-cloud/fleet#174 at 23c583f. +// fleet.datumapis.com, as proposed in datum-cloud/fleet#174 at d4d17f9. // // DeviceCustody is a coordination record, like a Lease: its fields live in // spec and the coordinator is their only writer. Every operation kind shares diff --git a/internal/custody/registry.go b/internal/custody/registry.go index d3055a86..bc39f075 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -1,5 +1,5 @@ // Package custody implements Device custody and coordinator admission, as -// proposed in datum-cloud/fleet#174 at 23c583f. +// proposed in datum-cloud/fleet#174 at d4d17f9. // // The Coordinator is the only writer of DeviceCustody and of operation status. // Every custody change is one Update carrying the resourceVersion it read; on diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 7901531e..3e4dd6f4 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -31,7 +31,7 @@ result reports every required phase `Passed`. ## Device custody and operations -These are the acceptance tests of [#174 at `23c583f`](https://github.com/datum-cloud/fleet/pull/174). +These are the acceptance tests of [#174 at `d4d17f9`](https://github.com/datum-cloud/fleet/pull/174). Increment A covers them against a real API server. End-to-end coverage arrives in Increments C and D. See [device custody](../../docs/development/device-custody.md#tests). From eb5395afaf6d1c035d6950b1880d26a1c3394e3c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 21:23:12 -0600 Subject: [PATCH 16/19] test(custody): Refuse Service without a hold the kind settles Cover the refusals of a row that admits from Service only under a hold of its kind: with no hold, and under a hold the kind does not settle. Both end Failed with HolderMismatch. Co-Authored-By: Claude Opus 5.5 --- internal/custody/extension_test.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/internal/custody/extension_test.go b/internal/custody/extension_test.go index d01b36d3..65d70b52 100644 --- a/internal/custody/extension_test.go +++ b/internal/custody/extension_test.go @@ -140,6 +140,27 @@ func TestExtensionSeams(t *testing.T) { if custody := e.custody(device.Name); custody.Spec.RecoveryHold != nil || custody.Spec.Holder.Type != ops.HolderNone { t.Fatalf("after settling: %+v", custody.Spec) } + + // From Service with no hold, the row refuses: the holder is a running + // staff operation, not a hold to settle. + busy := fresh() + e.staffOp(busy, "ok") + e.settle(busy.Name) + noHold := e.staffOp(busy, "ok") + e.settle(busy.Name) + e.requirePhase(noHold, ops.PhaseFailed, ReasonHolderMismatch) + + // From Service under a hold the kind does not settle, it refuses too. + other := fresh() + custody := e.custody(other.Name) + custody.Spec.Holder = ops.Holder{Type: ops.HolderService} + custody.Spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: testProviderKind, Name: "alloc-x-test-a", UID: "00000000-0000-4000-8000-00000000abcd"}, Fence: custody.Spec.Fence, Since: metav1.NewTime(e.clock.Now()), Reason: "Test"} + if err := e.admin.Update(e.ctx, custody); err != nil { + t.Fatal(err) + } + unrelated := e.staffOp(other, "ok") + e.settle(other.Name) + e.requirePhase(unrelated, ops.PhaseFailed, ReasonHolderMismatch) }) t.Run("a refusal with a reason the kind never declared is recorded as UndeclaredReason", func(t *testing.T) { From b8be397dbb01fdd38121d256f2f53032154023ab Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 23:32:14 -0600 Subject: [PATCH 17/19] fix(custody): Close six admission gaps the power kind found The power kind, built on this foundation, found six gaps. Each now has a subtest in TestRowsAndReplacement that fails when its fix is removed. - Only an operation that passes the creator, authority, holder and allocation checks on a queue row can replace another, so a request refused its permission check no longer cancels a customer's pending operation. - Staff rows never queue, so staff requests never replace one another. - A row can set its own naming rule, such as generated names for staff power and generation-based names for provider power. - A kind's own checks run before the shared identity and key checks, so its more specific reason is the one reported. - An operation named for a Retry waits for it, a staff one included, and does not expire while it waits. - The evidence validator receives the operation, and EvidenceRequired makes a success without evidence prove nothing. Co-Authored-By: Claude Opus 5.5 --- internal/custody/coordinator.go | 80 ++++++++++----- internal/custody/kinds.go | 4 +- internal/custody/recovery_test.go | 4 + internal/custody/registry.go | 34 +++++-- internal/custody/results.go | 17 +++- internal/custody/rows_test.go | 152 +++++++++++++++++++++++++++++ internal/custody/rules.go | 9 +- internal/custody/seams_test.go | 4 +- internal/custody/testkinds_test.go | 19 +++- 9 files changed, 283 insertions(+), 40 deletions(-) create mode 100644 internal/custody/rows_test.go diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index da083c13..8542ea6a 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -590,7 +590,7 @@ func (c *Coordinator) admit(ctx context.Context, custody *ops.DeviceCustody, dev if fresh.ResourceVersion != custody.ResourceVersion { return Outcome{Changed: true}, nil } - superseded := c.superseded(candidates, custody.Spec.RecoveryHold) + superseded := c.superseded(candidates, custody) queued := false changed := false for _, candidate := range candidates { @@ -623,13 +623,19 @@ func (c *Coordinator) admit(ctx context.Context, custody *ops.DeviceCustody, dev // superseded returns pending operations replaced by a newer one of the same // superseding kind and authority. -func (c *Coordinator) superseded(candidates []candidate, hold *ops.RecoveryHold) map[types.UID]bool { +func (c *Coordinator) superseded(candidates []candidate, custody *ops.DeviceCustody) map[types.UID]bool { out := map[types.UID]bool{} newest := map[string]ops.Operation{} + hold := custody.Spec.RecoveryHold for _, candidate := range candidates { operation, kind := candidate.operation, candidate.kind - // An operation that settles the hold is never replaced. - if !kind.Supersedes || (hold != nil && (c.settlesHold(kind, *hold, operation) || isRetry(kind, hold, operation))) { + // Only an operation that passes the creator, authority and holder + // checks on a queue row takes part: staff rows never queue, so + // staff requests never replace one another, and a request naming + // another's allocation replaces nothing. An operation that settles + // the hold is never replaced. + row, ok := c.rowFor(kind, operation, custody) + if !kind.Supersedes || !ok || !row.Queue || (hold != nil && (c.settlesHold(kind, *hold, operation) || isRetry(kind, hold, operation))) { continue } key := kind.GVK.Kind + "/" + authorityKey(operation.Envelope().Authority) @@ -641,6 +647,21 @@ func (c *Coordinator) superseded(candidates []candidate, hold *ops.RecoveryHold) return out } +// rowFor returns the row that admits the operation from the current custody +// state and holder, if its creator, authority and allocation match. +func (c *Coordinator) rowFor(kind *Kind, operation ops.Operation, custody *ops.DeviceCustody) (Rule, bool) { + envelope := operation.Envelope() + rows := c.Registry.matchRows(kind, operation, c.config().Principals.Classify(envelope.Creator)) + holder := custody.Spec.Holder + rows = slices.DeleteFunc(rows, func(rule Rule) bool { + return rule.custodyState() != custody.Spec.State || !rule.admitsHolder(holder.Type) + }) + if len(rows) == 0 || (envelope.Authority.AllocationRef != nil && (holder.AllocationRef == nil || holder.AllocationRef.Name != envelope.Authority.AllocationRef.Name)) { + return Rule{}, false + } + return rows[0], true +} + func authorityKey(authority ops.Authority) string { if authority.AllocationRef != nil { return "allocation:" + authority.AllocationRef.Name @@ -673,26 +694,17 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper fail := func(reason, format string, args ...any) decision { return decision{phase: ops.PhaseFailed, reason: reason, message: fmt.Sprintf(format, args...)} } - if class == CreatorStaff && !now.Before(operation.GetCreationTimestamp().Add(cfg.StaffExpiry)) { + // An operation named for a Retry waits for it: a staff retry created + // before its Retry is applied neither fails nor expires, or its name + // would be used up and the hold could not be settled. + retry := isRetry(kind, custody.Spec.RecoveryHold, operation) + if class == CreatorStaff && !retry && !now.Before(operation.GetCreationTimestamp().Add(cfg.StaffExpiry)) { return decision{phase: ops.PhaseCancelled, reason: ReasonExpired, message: "a staff operation must be admitted within " + cfg.StaffExpiry.String()} } rows := c.Registry.matchRows(kind, operation, class) if len(rows) == 0 { return fail(ReasonCreatorNotPermitted, "no row admits %s from a %s creator with this authority", kind.GVK.Kind, class) } - // An operation created after a Retry is named for the Retry, whatever - // the kind's own rule. - switch { - case isRetry(kind, custody.Spec.RecoveryHold, operation): - case kind.Naming == DeterministicName: - if want := kind.Name(operation); operation.GetName() != want { - return fail(ReasonNameMismatch, "the operation must be named %s", want) - } - case kind.Naming == GeneratedName: - if operation.GetGenerateName() == "" { - return fail(ReasonNameMismatch, "a staff operation must be created with a generated name") - } - } if envelope.DeviceRef.UID != string(device.UID) { return fail(ReasonDeviceIdentityMismatch, "deviceRef.uid does not match the Device") } @@ -712,6 +724,23 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper return d } row := rows[0] + // Names follow the row's rule, or the kind's. An operation created after + // a Retry is named for the Retry instead. + naming, name := kind.Naming, kind.Name + if row.Naming != KindNaming { + naming, name = row.Naming, row.Name + } + switch { + case retry: + case naming == DeterministicName: + if want := name(operation); operation.GetName() != want { + return fail(ReasonNameMismatch, "the operation must be named %s", want) + } + case naming == GeneratedName: + if operation.GetGenerateName() == "" { + return fail(ReasonNameMismatch, "this operation must be created with a generated name") + } + } // Recovery holds. var settles *ops.OperationReference switch hold := custody.Spec.RecoveryHold; { @@ -719,6 +748,8 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper case row.Hold == HoldRequired && hold == nil: return fail(ReasonRecoveryHold, "this operation decides a recovery hold, and there is none") case row.Hold == HoldRequired: + case hold != nil && retry && !c.settlesHold(kind, *hold, operation): + return decision{phase: ops.PhasePending, reason: ReasonRecoveryHold, message: "waiting for the Retry this operation is named for"} case row.Hold == HoldSettlesRequired && (hold == nil || !c.settlesHold(kind, *hold, operation)): return fail(ReasonHolderMismatch, "from this holder, the operation is admitted only to settle a hold of its kind") case hold != nil: @@ -739,6 +770,14 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper return fail(ReasonOperationInProgress, "another operation is running, and staff operations never wait") } admission := &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Now: now, DiscoveryInterval: cfg.DiscoveryInterval} + // Rule 7, the kind's own checks, runs before the shared identity and + // key checks, so a kind's more specific reason, such as a system UUID + // 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 { + return fail(refusal.Reason, "%s", refusal.Message) + } + } // Preconditions 5 and 6: current discovery and a unique BMC key. if kind.checksDiscovery(operation) { if refusal := c.identityCurrent(device, now); refusal != nil { @@ -751,11 +790,6 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper return fail(refusal.Reason, "%s", refusal.Message) } } - if kind.Check != nil { - if refusal := c.Registry.declaredRefusal(kind.GVK.Kind, settleHookKind(kind, row, custody), kind.Check(ctx, admission)); refusal != nil { - return fail(refusal.Reason, "%s", refusal.Message) - } - } // Kind fields for the snapshot come from the same Device and clock the // checks saw. var extra map[string]string diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index ec10e5cc..af1af83f 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -107,7 +107,7 @@ func DeviceInstallationKind() Kind { }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, Reasons: []Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}}, - Evidence: StrictEvidence(evidenceLimit, func(evidence *ops.InstallationEvidence) error { + Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.InstallationEvidence) error { return validateSteps(evidence.Steps) }), } @@ -135,7 +135,7 @@ func DeviceWipeKind() Kind { // settled by a later wipe only after a DeviceRecovery with Retry. Settles: []SettleRule{{Held: "DeviceInstallation"}, {Held: "DeviceWipe", RequiresRetry: true}}, Retryable: true, - Evidence: StrictEvidence(evidenceLimit, func(evidence *ops.WipeEvidence) error { + Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.WipeEvidence) error { if len(evidence.WipedDisks) > 16 { return errors.New("evidence records at most 16 disks") } diff --git a/internal/custody/recovery_test.go b/internal/custody/recovery_test.go index 1268fac1..dbac7d14 100644 --- a/internal/custody/recovery_test.go +++ b/internal/custody/recovery_test.go @@ -109,6 +109,10 @@ func TestRecovery(t *testing.T) { t.Run("only Retire and Resolve skip current discovery and the shared-key check", func(t *testing.T) { e := e.sub(t) + // The held kind accepts a Retry, so the kind's own checks pass and + // the discovery check is what refuses it. + staff := e.coord.Registry.Kind(testStaffKind) + staff.Settles, staff.Retryable = []SettleRule{{Held: testStaffKind}, {Held: testStaffKind, RequiresRetry: true}}, true device := fresh() hold := e.holdOn(device) key := fmt.Sprintf("%064x", n) diff --git a/internal/custody/registry.go b/internal/custody/registry.go index bc39f075..13cc2d8c 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -32,9 +32,12 @@ import ( type Naming int const ( + // KindNaming, on a row, means the kind's own naming rule applies. A kind + // must name a rule of its own. + KindNaming Naming = iota // DeterministicName kinds are named from their authority and request, so // a retried create collides instead of making a second operation. - DeterministicName Naming = iota + DeterministicName // GeneratedName kinds are staff requests. Each one is new, so each must // be created with metadata.generateName. GeneratedName @@ -94,9 +97,14 @@ type Kind struct { // SnapshotExtra adds bounded fields to the Device snapshot at admission. // It sees the same Device the checks saw. SnapshotExtra func(*Admission) map[string]string - // Evidence validates the kind's typed, bounded result evidence and - // returns it in canonical form. Nil means the kind's results carry none. - Evidence func([]byte) ([]byte, error) + // 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. + Evidence func(ops.Operation, []byte) ([]byte, error) + // EvidenceRequired means a Succeeded result without evidence proves + // nothing and ends OutcomeUnknown. + EvidenceRequired bool // 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 @@ -241,9 +249,15 @@ func (r *Registry) Register(kind Kind) error { if name == "" || kind.New == nil || kind.NewList == nil || kind.Items == nil || kind.Digest == nil || kind.Deadline <= 0 { return errors.New("a kind needs a GVK, constructors, a digest and a deadline") } + if kind.Naming != DeterministicName && kind.Naming != GeneratedName { + return fmt.Errorf("%s: a kind names a deterministic or a generated naming rule", name) + } if kind.Naming == DeterministicName && kind.Name == nil { return fmt.Errorf("%s: a deterministic name rule is required", name) } + if kind.EvidenceRequired && kind.Evidence == nil { + return fmt.Errorf("%s: required evidence needs a validator", name) + } if !kind.Effectful && kind.Apply == nil { return fmt.Errorf("%s: a non-effectful kind needs Apply", name) } @@ -285,6 +299,9 @@ func (r *Registry) AddRule(rule Rule) error { if rule.Queue && rule.Creator == CreatorStaff { return errors.New("staff operations never queue") } + if rule.Naming == DeterministicName && rule.Name == nil { + return errors.New("a row with a deterministic name rule needs its Name function") + } r.rules = append(r.rules, rule) return nil } @@ -350,9 +367,10 @@ func SpecDigest(spec any) (string, error) { } // StrictEvidence returns an Evidence function that decodes into T, rejecting -// unknown fields and anything over maxBytes, then runs validate. -func StrictEvidence[T any](maxBytes int, validate func(*T) error) func([]byte) ([]byte, error) { - return func(raw []byte) ([]byte, error) { +// unknown fields and anything over maxBytes, then runs validate with the +// operation the evidence is for. +func StrictEvidence[T any](maxBytes int, validate func(ops.Operation, *T) error) func(ops.Operation, []byte) ([]byte, error) { + return func(operation ops.Operation, raw []byte) ([]byte, error) { if len(raw) > maxBytes { return nil, fmt.Errorf("evidence is %d bytes; the limit is %d", len(raw), maxBytes) } @@ -366,7 +384,7 @@ func StrictEvidence[T any](maxBytes int, validate func(*T) error) func([]byte) ( return nil, errors.New("evidence has trailing data") } if validate != nil { - if err := validate(value); err != nil { + if err := validate(operation, value); err != nil { return nil, err } } diff --git a/internal/custody/results.go b/internal/custody/results.go index e77e40ae..3280afb0 100644 --- a/internal/custody/results.go +++ b/internal/custody/results.go @@ -80,8 +80,13 @@ func ignoreNoChange(err error) error { // a rejected fence; ErrStaleFence is returned either way, so the site // deletes its copy. func (c *Coordinator) AcceptResult(ctx context.Context, result SiteResult) error { + // The evidence hook validates against the operation it is for. + operation, _, err := c.get(ctx, result.Operation) + if err != nil { + return err + } stale := false - err := c.update(ctx, result.Device, func(custody *ops.DeviceCustody) error { + err = c.update(ctx, result.Device, func(custody *ops.DeviceCustody) error { stale = false spec := &custody.Spec active := spec.ActiveOperation @@ -112,12 +117,20 @@ func (c *Coordinator) AcceptResult(ctx context.Context, result SiteResult) error return fmt.Errorf("a site cannot report phase %q", result.Phase) } var evidence []byte + if result.Phase == ops.PhaseSucceeded && kind.EvidenceRequired && len(result.Evidence) == 0 { + c.holdUnknown(custody, *active, ReasonInvalidEvidence, "the kind requires evidence, and the site sent none", nil) + return nil + } if len(result.Evidence) != 0 { if kind.Evidence == nil { c.holdUnknown(custody, *active, ReasonInvalidEvidence, "the kind records no evidence, and the site sent some", nil) return nil } - canonical, err := kind.Evidence(result.Evidence) + if operation == nil { + c.holdUnknown(custody, *active, ReasonInvalidEvidence, "the operation is missing, so its evidence cannot be checked", nil) + return nil + } + canonical, err := kind.Evidence(operation, result.Evidence) if err != nil { c.holdUnknown(custody, *active, ReasonInvalidEvidence, err.Error(), nil) return nil diff --git a/internal/custody/rows_test.go b/internal/custody/rows_test.go new file mode 100644 index 00000000..94e2bf9b --- /dev/null +++ b/internal/custody/rows_test.go @@ -0,0 +1,152 @@ +package custody + +import ( + "fmt" + "testing" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// TestRowsAndReplacement covers the seams the power kind found missing. +func TestRowsAndReplacement(t *testing.T) { + e := startEnv(t) + n := 1000 + fresh := func() *inventory.Device { + n++ + return e.verified(fmt.Sprintf("server-example-%04d", n), uid(n), fmt.Sprintf("%064x", n)) + } + + t.Run("a request refused its permission check replaces nothing", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-cust"); err != nil { + t.Fatal(err) + } + e.installation(device, "alloc-cust", "request-running") + e.settle(device.Name) + customer := e.providerOp(device, "alloc-cust", "mine") + e.settle(device.Name) + e.requirePhase(customer, ops.PhasePending, ReasonOperationInProgress) + time.Sleep(1100 * time.Millisecond) + // Staff name the customer's allocation with the superseding kind. + staff := &DeviceTestProviderOperation{ObjectMeta: metav1.ObjectMeta{Name: "alloc-cust-test-theirs", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-cust")), Input: "theirs"}} + e.create(staff) + e.settle(device.Name) + e.requirePhase(staff, ops.PhaseFailed, ReasonCreatorNotPermitted) + e.requirePhase(customer, ops.PhasePending, ReasonOperationInProgress) + }) + + t.Run("staff requests never replace one another", func(t *testing.T) { + e := e.sub(t) + e.coord.Registry.Kind(testStaffKind).Supersedes = true + device := fresh() + older := e.staffOp(device, "ok") + time.Sleep(1100 * time.Millisecond) + newer := e.staffOp(device, "ok") + 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("a row may name its operations differently from the kind", func(t *testing.T) { + e := e.sub(t) + // Provider-created operations of the staff kind are named from their + // allocation, while staff-created ones keep generated names. + if err := e.coord.Registry.AddRule(Rule{Kind: testStaffKind, Creator: CreatorMetalProvider, Authority: AuthorityAllocation, Holders: []ops.HolderType{ops.HolderAllocation}, Queue: true, + Naming: DeterministicName, Name: func(operation ops.Operation) string { + return allocationName(operation) + "-staff-" + operation.(*DeviceTestStaffOperation).Spec.Input + }}); err != nil { + t.Fatal(err) + } + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-row"); err != nil { + t.Fatal(err) + } + named := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{Name: "alloc-row-staff-a", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, providerUser, allocated("alloc-row")), Input: "a"}} + e.create(named) + e.settle(device.Name) + e.requirePhase(named, ops.PhaseAdmitted, "") + // A row with a deterministic rule needs its Name function. + if err := e.coord.Registry.AddRule(Rule{Kind: testStaffKind, Creator: CreatorReleaseController, Authority: AuthorityAllocation, Naming: DeterministicName}); err == nil { + t.Fatal("a deterministic row without a name rule was added") + } + }) + + t.Run("a kind's own refusal comes before the shared identity check", func(t *testing.T) { + e := e.sub(t) + n++ + device := e.device(fmt.Sprintf("server-example-%04d", n), "", fmt.Sprintf("%064x", n)) + e.settle(device.Name) + e.sites.report(device.Name, 0) + e.settle(device.Name) + operation := e.staffOp(device, "needs-uuid") + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, reasonTestUUID) + }) + + t.Run("a staff retry created before its Retry waits for it", func(t *testing.T) { + e := e.sub(t) + // The staff kind settles its own hold only after a Retry, from + // Service under that hold, as staff power does. + staff := e.coord.Registry.Kind(testStaffKind) + staff.Settles, staff.Retryable = []SettleRule{{Held: testStaffKind, RequiresRetry: true}}, true + if err := e.coord.Registry.AddRule(Rule{Kind: testStaffKind, Creator: CreatorStaff, Authority: AuthorityService, Holders: []ops.HolderType{ops.HolderService}, Hold: HoldSettlesRequired}); err != nil { + t.Fatal(err) + } + device := fresh() + hold := e.holdOn(device) + retried := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{Name: RetryName(hold, 1), Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, service("retry")), Input: "ok"}} + e.create(retried) + e.settle(device.Name) + e.requirePhase(retried, ops.PhasePending, ReasonRecoveryHold) + retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + e.settle(device.Name) + // It does not expire while it waits for the Retry to be applied. + e.clock.Advance(DefaultStaffExpiry + time.Minute) + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now()) + e.settle(device.Name) + e.requirePhase(retried, ops.PhasePending, ReasonRecoveryHold) + e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) + e.settle(device.Name) + e.requirePhase(retry, ops.PhaseSucceeded, "") + e.requirePhase(retried, ops.PhaseAdmitted, "") + }) + + t.Run("evidence is checked against its operation and can be required", func(t *testing.T) { + e := e.sub(t) + e.coord.Registry.Kind(testStaffKind).EvidenceRequired = true + bare := fresh() + e.staffOp(bare, "ok") + e.settle(bare.Name) + if err := e.result(bare.Name, ops.PhaseSucceeded, ""); err != nil { + t.Fatal(err) + } + e.settle(bare.Name) + if hold := e.custody(bare.Name).Spec.RecoveryHold; hold == nil || hold.Reason != ReasonInvalidEvidence { + t.Fatalf("a success without required evidence was accepted: %+v", hold) + } + restart := fresh() + e.staffOp(restart, "restart") + e.settle(restart.Name) + if err := e.result(restart.Name, ops.PhaseSucceeded, `{"before":"On"}`); err != nil { + t.Fatal(err) + } + e.settle(restart.Name) + if hold := e.custody(restart.Name).Spec.RecoveryHold; hold == nil || hold.Reason != ReasonInvalidEvidence { + t.Fatalf("a restart without proof of the reset was accepted: %+v", hold) + } + proven := fresh() + operation := e.staffOp(proven, "restart") + e.settle(proven.Name) + if err := e.result(proven.Name, ops.PhaseSucceeded, `{"before":"On","after":"On"}`); err != nil { + t.Fatal(err) + } + e.settle(proven.Name) + e.requirePhase(operation, ops.PhaseSucceeded, "") + }) +} diff --git a/internal/custody/rules.go b/internal/custody/rules.go index daf23d87..8a8bf3ac 100644 --- a/internal/custody/rules.go +++ b/internal/custody/rules.go @@ -62,8 +62,15 @@ type Rule struct { Custody ops.CustodyState Hold HoldBehavior // Queue rows wait in Pending while another operation runs. Staff rows - // never queue: admission refuses what cannot run now. + // never queue: admission refuses what cannot run now. Only an operation + // on a queue row may replace an older pending one of its kind. Queue bool + // Naming overrides the kind's naming rule for this row, such as + // generated names for staff power and deterministic ones for provider + // power. KindNaming, the zero value, keeps the kind's rule. + Naming Naming + // Name is the row's deterministic name rule. + Name func(ops.Operation) string } func (r Rule) custodyState() ops.CustodyState { diff --git a/internal/custody/seams_test.go b/internal/custody/seams_test.go index b10288cd..adcde936 100644 --- a/internal/custody/seams_test.go +++ b/internal/custody/seams_test.go @@ -141,11 +141,11 @@ func TestCandidatesOrderOldestFirstWithADeterministicTieBreak(t *testing.T) { func TestEvidenceIsTypedAndBounded(t *testing.T) { kind := DeviceWipeKind() - if _, err := kind.Evidence([]byte(`{"wipedDisks":["disk-0"]}`)); err != nil { + if _, err := kind.Evidence(&ops.DeviceWipe{}, []byte(`{"wipedDisks":["disk-0"]}`)); err != nil { t.Fatal(err) } for _, bad := range []string{`{"bmcResponse":"raw"}`, `{"wipedDisks":["disk-0"]} {}`, `{"steps":[{"name":""}]}`, fmt.Sprintf(`{"policyDigest":"%0*d"}`, evidenceLimit, 0)} { - if _, err := kind.Evidence([]byte(bad)); err == nil { + if _, err := kind.Evidence(&ops.DeviceWipe{}, []byte(bad)); err == nil { t.Fatalf("accepted %s", bad) } } diff --git a/internal/custody/testkinds_test.go b/internal/custody/testkinds_test.go index 3e388a4a..17fbd37e 100644 --- a/internal/custody/testkinds_test.go +++ b/internal/custody/testkinds_test.go @@ -2,6 +2,7 @@ package custody import ( "context" + "errors" "fmt" "sync/atomic" "time" @@ -72,6 +73,7 @@ const ( testStaffKind = "DeviceTestStaffOperation" testProviderKind = "DeviceTestProviderOperation" reasonTestRefuse = "TestRefused" + reasonTestUUID = "TestSystemUUIDNotRecorded" testDeadline = 10 * time.Minute ) @@ -88,6 +90,12 @@ 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 "needs-uuid": + // A kind's own, more specific reason, as power's + // SystemUUIDNotRecorded. + if admission.Device.Spec.Identity.SystemUUID == "" { + return refuse(reasonTestUUID, "the Device records no system UUID") + } } if hook := checkHook.Load(); hook != nil { (*hook)(admission) @@ -109,7 +117,14 @@ func testKinds() []Kind { } return nil } - evidence := StrictEvidence(256, func(*testEvidence) error { return nil }) + // The test kinds' evidence must agree with the operation: an input of + // "restart" requires proof of the reset. + evidence := StrictEvidence(256, func(operation ops.Operation, evidence *testEvidence) error { + if operation.(interface{ input() string }).input() == "restart" && evidence.After == "" { + return errors.New("a restart needs the power state after it") + } + return nil + }) staff := Kind{ GVK: ops.GroupVersion.WithKind(testStaffKind), New: func() ops.Operation { return &DeviceTestStaffOperation{} }, @@ -123,7 +138,7 @@ func testKinds() []Kind { Effectful: true, Check: check, Settles: []SettleRule{{Held: testStaffKind}}, - Reasons: []Reason{{Name: reasonTestRefuse, RaisedBy: RaisedByCoordinator}, {Name: "EvidenceNotCurrent", RaisedBy: RaisedByCoordinator}}, + Reasons: []Reason{{Name: reasonTestRefuse, RaisedBy: RaisedByCoordinator}, {Name: "EvidenceNotCurrent", RaisedBy: RaisedByCoordinator}, {Name: reasonTestUUID, RaisedBy: RaisedByCoordinator}}, Evidence: evidence, // Seam 4: a hold of this kind settles with recovery evidence observed // after the operation ended, as power's discovery read will. From 36a8278a96783cf3c588be29a60e43ac6db7029c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 23:32:14 -0600 Subject: [PATCH 18/19] docs: Record replacement, naming and evidence for new kinds Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 31 +++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 994350ae..1d6f68c9 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -102,7 +102,11 @@ Each decision lists the open point from the implementation brief it settles. | `SharedPublicKey` | Rule 6 | | `RecoveryHold` | A recovery hold | - Rule 7 is a kind's own checks of its inputs, with its own reasons. A staff + Rule 7 is a kind's own checks of its inputs, with its own reasons. They run + 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 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`, @@ -113,10 +117,16 @@ Each decision lists the open point from the implementation brief it settles. which custody records with the hold. This applies to every kind whose settlement needs a `Retry`, such as a wipe, and the kind's own naming rule does not apply to it. Until the `Retry` is applied, the retried operation - waits in `Pending`. The `Retry` is used when that operation is admitted. If + waits in `Pending`, a staff one included, and does not expire while it + waits. The `Retry` is used when that operation is admitted. If the retried operation also ends unknown, its hold keeps the original name and count, so the next retry is named `-retry-2`, not `-retry-1-retry-1`. Rebuild reads that lineage back from the names. +- **Replacement.** Only an operation that passes the creator, authority, + holder and allocation checks on a row that queues can replace an older + pending one, of the same kind under the same allocation. A request refused + its permission check therefore replaces nothing, and staff requests, whose + rows never queue, never replace one another. - **Settling operations come first.** Pending replacement never cancels an operation that settles the hold. Other operations wait in `Pending` until the hold is settled, and they do not hold back the operation that settles it. @@ -142,8 +152,10 @@ Each decision lists the open point from the implementation brief it settles. goes through normal admission as well. Only a kind that cannot reach the server may skip these checks, and the registry refuses any other. -- **Names.** Deterministic kinds must use their rule, or they end `Failed` - with `NameMismatch`. A `DeviceInstallation` is named from its allocation and +- **Names.** A row may set its own naming rule, such as generated names for + staff power and generation-based names for provider power; otherwise the + kind's rule applies. An operation that does not follow its rule ends + `Failed` with `NameMismatch`. A `DeviceInstallation` is named from its allocation and a digest of the Installation UID. A `DeviceWipe` is named from its allocation and step. Staff kinds must use a generated name. - **Order.** Pending operations are admitted oldest first. Ties break on kind, @@ -349,8 +361,9 @@ four seams. It needs no change to the coordinator. The test-only kinds in - a digest of its exact inputs (`custody.SpecDigest` covers the whole spec); - its naming rule: `DeterministicName` with a `Name` function for provider - and release kinds, or `GeneratedName` for staff kinds. An operation - created after a `Retry` is named by the coordinator's retry rule instead; + and release kinds, or `GeneratedName` for staff kinds. A row can override + it with its own `Naming` and `Name`. An operation created after a `Retry` + is named by the coordinator's retry rule instead; - its `Deadline`, and `Effectful` if it can reach the server; - `Supersedes`, if a newer pending operation of the same kind and the same authority should cancel an older one, as power needs. It never @@ -388,7 +401,10 @@ four seams. It needs no change to the coordinator. The test-only kinds in it recovers by observation after a lost response, and its typed result evidence. The worker contract is proposed and lands in Increment B. 4. **Define its evidence.** Set `Evidence` to `custody.StrictEvidence` over a - typed, bounded Go struct. Unknown fields, oversized evidence and trailing + 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 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 @@ -417,6 +433,7 @@ a real API server: | Two allocators, allocator against staff, two coordinators, admission against a holder change, two Devices, a lost claim response | `TestConcurrency` | | A claim and its installation landing between the custody read and the operation list | `TestARefusalNeverUsesCustodyReadBeforeAHolderChange` | | Admission above the fence a site has seen; a recovery confirmed only by the stopped fence; a held operation never a candidate | `TestFencesFollowTheSiteReport`, `TestAHeldOperationIsNeverACandidate` | +| Replacement only after the permission checks, staff never replacing, naming per row, a kind's reason before the shared identity check, a staff retry waiting for its Retry, evidence checked against its operation and required | `TestRowsAndReplacement` | | The extension points: the Device the checks see, scoped replacement, snapshot fields, the settle hook's hold fields, declared reasons, `Retryable`, a worker refusal returning a staff holder to `None` | `TestExtensionSeams`, `TestRegistryValidatesDeclaredReasons` | | A crash between each pair of custody and status writes, with dropped and lost responses | `TestWriteOrderCrashRecovery` | | CEL rules | `TestCRDRules` | From 9cf6d3265f5c6cb101db9df2add35de7edeca720 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 23:44:08 -0600 Subject: [PATCH 19/19] fix(custody): Reject a result for an unregistered kind as stale Reading the operation for its evidence returned a plain error for a result naming an unregistered kind, so the site would retry it forever. Read the operation only when there is evidence to check for a registered kind, and let the stale path reject the rest. Co-Authored-By: Claude Opus 5.5 --- internal/custody/results.go | 15 +++++++++++---- internal/custody/rows_test.go | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/internal/custody/results.go b/internal/custody/results.go index 3280afb0..75ad3cb2 100644 --- a/internal/custody/results.go +++ b/internal/custody/results.go @@ -80,11 +80,18 @@ func ignoreNoChange(err error) error { // a rejected fence; ErrStaleFence is returned either way, so the site // deletes its copy. func (c *Coordinator) AcceptResult(ctx context.Context, result SiteResult) error { - // The evidence hook validates against the operation it is for. - operation, _, err := c.get(ctx, result.Operation) - if err != nil { - return err + // The evidence hook validates against the operation it is for. It is + // read only when there is evidence to check; a result for an + // unregistered kind is rejected as stale below. + var operation ops.Operation + if kind := c.Registry.Kind(result.Operation.Kind); kind != nil && len(result.Evidence) != 0 { + found, _, err := c.get(ctx, result.Operation) + if err != nil { + return err + } + operation = found } + var err error stale := false err = c.update(ctx, result.Device, func(custody *ops.DeviceCustody) error { stale = false diff --git a/internal/custody/rows_test.go b/internal/custody/rows_test.go index 94e2bf9b..00dba5a3 100644 --- a/internal/custody/rows_test.go +++ b/internal/custody/rows_test.go @@ -1,6 +1,7 @@ package custody import ( + "errors" "fmt" "testing" "time" @@ -149,4 +150,19 @@ func TestRowsAndReplacement(t *testing.T) { e.settle(proven.Name) e.requirePhase(operation, ops.PhaseSucceeded, "") }) + + t.Run("a result for an unregistered kind is rejected as stale", func(t *testing.T) { + e := e.sub(t) + device := fresh() + e.staffOp(device, "ok") + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + err := e.coord.AcceptResult(e.ctx, SiteResult{Site: testSite, Device: device.Name, Operation: ops.OperationReference{Kind: "DeviceInvented", Name: active.Name, UID: active.UID}, Fence: active.Fence, Phase: ops.PhaseSucceeded, Evidence: []byte(`{"after":"On"}`)}) + if !errors.Is(err, ErrStaleFence) { + t.Fatalf("result for an unregistered kind: %v", err) + } + if rejected := e.custody(device.Name).Spec.RejectedResults; rejected == nil || rejected.Count != 1 { + t.Fatalf("rejected = %+v", rejected) + } + }) }