diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index 0caa3383..b37d7d77 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -375,7 +375,7 @@ spec: metadata: {type: object} spec: type: object - required: [consumerRef, machineRef, machineCapacityRef, deviceRef, accepted, hardware, authority, cleaningPolicy, bootInterface, targetDisks] + required: [consumerRef, machineRef, machineCapacityRef, deviceRef, accepted, hardware, authority, cleaningPolicy, drives, bootInterface, targetDisks] x-kubernetes-validations: - {rule: 'self == oldSelf', message: MachineAllocation identity and endpoints are immutable} properties: @@ -512,6 +512,23 @@ spec: x-kubernetes-list-type: set items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} alwaysEncrypts: {type: boolean} + drives: + type: array + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name, serialNumber, model, firmware, protocol, mediaType, capacityBytes, rule] + properties: + name: {type: string, pattern: '^disk-[0-9]+$', maxLength: 12} + serialNumber: {type: string, maxLength: 253} + model: {type: string, maxLength: 253} + firmware: {type: string, maxLength: 63} + protocol: {type: string, maxLength: 31} + mediaType: {type: string, maxLength: 31} + capacityBytes: {type: integer, minimum: 0} + rule: {type: string, maxLength: 63} bootInterface: {type: string, minLength: 1, maxLength: 63} targetDisks: type: array diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 739a7e58..881aad4d 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -852,15 +852,40 @@ spec: - name - generation - digest - targetDisks: + assurance: + type: string + enum: [Clear, Purge] + drives: type: array minItems: 1 maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] items: - type: string - minLength: 1 - maxLength: 63 - x-kubernetes-list-type: set + type: object + required: [name, serialNumber, model, firmware, protocol, mediaType, capacityBytes] + properties: + name: {type: string, pattern: '^disk-[0-9]+$', maxLength: 12} + serialNumber: {type: string, maxLength: 253} + model: {type: string, maxLength: 253} + firmware: {type: string, maxLength: 63} + protocol: {type: string, maxLength: 31} + mediaType: {type: string, maxLength: 31} + capacityBytes: {type: integer, minimum: 0} + rule: {type: string, maxLength: 63} + methods: + type: array + maxItems: 6 + x-kubernetes-list-type: set + items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} + verify: + type: object + required: [mode] + properties: + mode: {type: string, enum: [Full, Canary]} + samples: {type: integer, format: int32, minimum: 0, maximum: 1024} + timePerTiB: {type: string, maxLength: 32, pattern: '^([0-9]+(\.[0-9]+)?(ns|us|µs|μs|ms|s|m|h))+$'} + state: {type: string, enum: [Missing, Uncovered]} # Optional in the schema so wipes stored before it existed stay # valid; admission refuses a wipe whose boot interface the # Device does not record with a MAC address. @@ -906,7 +931,8 @@ spec: - authority - step - policy - - targetDisks + - assurance + - drives x-kubernetes-validations: - rule: self == oldSelf message: an operation spec is immutable after create diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 2210da9c..4102258f 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -796,6 +796,7 @@ guarded, and a test fails if its guard is removed: | Consumer project, against quota | Quota resolves the project and requires the incarnation the Machine was admitted in | `TestQuotaServesOnlyTheMachinesProjectIncarnation` | | Device | Custody's `device-uid` label must match the Device, or custody stays `Unverified` until a `Resolve` | `TestARecreatedDeviceLeavesCustodyUnverified` | | Device, against free capacity | Custody for another Device incarnation is never free | `TestCustodyForAnotherDeviceIncarnationIsNotFree` | +| Device, against a release wipe | The release controller plans a wipe only if the Device's UID is the allocation's `device-uid` label | `TestAWipeIsNeverPlannedForARecreatedDevice` | | Device, against a claim | `Claim` takes the Device incarnation the allocation names, and refuses unless both the live Device and custody's label match it | `TestCustodyForAnotherDeviceIncarnationIsNeverClaimed`, `TestARecreatedDeviceIsNeverClaimedUnderItsStaleLabel`, `TestARecreatedDeviceIsNeverClaimedForTheEarlierIncarnation` | | Device, against an operation | An operation's `device-uid` label must match the Device at admission | `TestAdmissionPreconditions` | | Device, against an existing operation | The Metal provider and release controller require an existing same-name operation to carry the same labels | `TestAnOperationForAnotherDeviceIncarnationIsAConflict` | @@ -853,12 +854,38 @@ real API server. The rest of #183 is **proposed**. BMC discovery records each System's drives from Redfish in Device status, and fixture discovery reports one simulated drive per enrolled disk. The Redfish -lab serves a Storage collection for its targets. These are observations only. - -Not implemented yet: drive inventory from commissioning, the media -manifest and pinned drive names, the per-drive plan in `DeviceWipe`, the -in-band methods and their evidence, the evidence check and its reasons, and -`DisposeDrive`. Until then, every site still wipes its one enrolled disk. +lab's targets each have one emulated NVMe drive. + +- **Manifest.** The allocator pins every drive the server reports, named + `disk-0`, `disk-1` and so on by protocol and serial number, with the rule + that covers it. A server whose drives are unknown, back a RAID volume, lack + a serial number, or have no planned method is skipped as uncovered. + Installation target disks must be names in the manifest. +- **Plan.** One shared planner turns the pin and current discovery into one + step per drive. It matches a pinned drive by serial number and requires + the same model, protocol, media type and capacity; firmware may change but + must still be qualified. A drive that shares its serial number with another, + or reports none, is `Uncovered`. The release controller writes the plan into + each `DeviceWipe`, and admission plans again and refuses a wipe whose plan + differs, with reason `PlanMismatch`. Such a refusal does not count toward + the release's three failed steps, but a release stops after 16 steps. A + retried create that finds a wipe with another plan keeps it, because + admission plans it again. +- **Missing and uncovered drives (interim).** While a planned drive is + `Missing` or `Uncovered`, the release controller creates no wipe. It sets + the allocation's `Cleaning` condition to `False` with reason `DriveMissing` + or `DriveUncovered`, and plans again when discovery changes. Admission also + refuses such a wipe. #183 instead ends it `OutcomeUnknown` under a recovery + hold that `DisposeDrive` settles; that comes with `DisposeDrive`. +- **Sites.** Every site cleans only by overwriting each planned drive and + reading it back, and refuses any other plan before sending anything. Sites + match planned drives to their enrolled disks by name, and fixture drives' + serial numbers sort in enrollment order so the names agree. Matching by + serial number on the server comes with the wipe environment. + +Not implemented yet: drive inventory from commissioning, the in-band methods +other than overwrite and their evidence, the evidence check and its reasons, +the plan-derived deadline, and `DisposeDrive`. ### Cutover decisions diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index 256258f1..10f6dd63 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -52,7 +52,7 @@ for crd in installations machineallocations machinecapacities machineclasses mac exit 1 fi done -for crd in devices devicecustodies deviceinstallations devicewipes devicepoweroperations devicerecoveries devicecommissionings devicecommissioningplans devicecommissioningplanapprovals sealedpayloads; do +for crd in devices devicecustodies deviceinstallations devicewipes devicepoweroperations devicerecoveries devicecommissionings devicecommissioningplans devicecommissioningplanapprovals cleaningpolicies sealedpayloads; do if kubectl --context "$context" get crd "$crd.fleet.datumapis.com" >/dev/null 2>&1; then echo "fixed Fleet CRD $crd already exists; use a fresh dedicated kind cluster" >&2 exit 1 diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index ef7ea54d..5140579f 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -482,6 +482,18 @@ func (a *Allocator) newAllocation(ctx context.Context, request Request, capacity if err != nil { return nil, err } + // The manifest pins every drive the server has now. A server with a drive + // the policy cannot clean, or storage discovery has not reported, is not + // covered. + drives, err := cleaning.Manifest(policy.Spec, cleaning.StorageOf(device)) + if err != nil { + return nil, fmt.Errorf("%w: capacity %s: %v", ErrCleaningUncovered, capacity.Name, err) + } + for _, disk := range a.TargetDisks { + if !slices.ContainsFunc(drives, func(d ops.ManifestDrive) bool { return d.Name == disk }) { + return nil, fmt.Errorf("%w: capacity %s has no drive %s to install on", ErrCleaningUncovered, capacity.Name, disk) + } + } classDigest, err := custody.SpecDigest(request.Class.Spec) if err != nil { return nil, err @@ -508,6 +520,7 @@ func (a *Allocator) newAllocation(ctx context.Context, request Request, capacity Hardware: hardware, Authority: request.Authority, CleaningPolicy: policy, + Drives: drives, BootInterface: a.BootInterface, TargetDisks: slices.Clone(a.TargetDisks), }, diff --git a/internal/allocation/cleaning_test.go b/internal/allocation/cleaning_test.go index 4599e351..2fb13fec 100644 --- a/internal/allocation/cleaning_test.go +++ b/internal/allocation/cleaning_test.go @@ -2,12 +2,17 @@ package allocation import ( "errors" + "strings" "testing" apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/custody" ) @@ -58,13 +63,23 @@ func TestAllocationPinsItsCleaningPolicy(t *testing.T) { if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: custody.WipeName(allocation.Name, 1)}, wipe); err != nil { t.Fatal(err) } - if wipe.Spec.Policy != pinned.CleaningPolicyReference { + if wipe.Spec.Policy != pinned.CleaningPolicyReference || wipe.Spec.Assurance != ops.AssuranceClear { t.Fatalf("wipe policy = %+v, want %+v", wipe.Spec.Policy, pinned.CleaningPolicyReference) } + // The manifest pinned the server's one drive, and the wipe plans it with + // the pinned rule's method and check. + if len(allocation.Spec.Drives) != 1 || allocation.Spec.Drives[0].Name != "disk-0" || allocation.Spec.Drives[0].SerialNumber == "" { + t.Fatalf("manifest = %+v", allocation.Spec.Drives) + } + if len(wipe.Spec.Drives) != 1 || wipe.Spec.Drives[0].ManifestDrive != allocation.Spec.Drives[0] || wipe.Spec.Drives[0].State != "" || + wipe.Spec.Drives[0].Verify == nil || wipe.Spec.Drives[0].Verify.Mode != ops.VerifyFull { + t.Fatalf("plan = %+v", wipe.Spec.Drives) + } } // TestCapacityWithoutAUsableCleaningPolicyIsNotAllocated skips capacity -// whose policy is missing or invalid, and claims nothing. +// whose policy is missing or invalid, or whose drives the policy does not +// cover, and claims nothing. func TestCapacityWithoutAUsableCleaningPolicyIsNotAllocated(t *testing.T) { cases := map[string]func(e *env){ "missing policy": func(e *env) { @@ -83,6 +98,20 @@ func TestCapacityWithoutAUsableCleaningPolicyIsNotAllocated(t *testing.T) { e.create(invalid) }, } + cases["drives not reported"] = func(e *env) { + device := e.device("server-example-001") + device.Status.Discovery.Inventory.Systems[0].Storage = nil + if err := e.admin.Status().Update(e.ctx, device); err != nil { + e.t.Fatal(err) + } + } + cases["a drive no rule covers"] = func(e *env) { + device := e.device("server-example-001") + device.Status.Discovery.Inventory.Systems[0].Storage.Drives[0].Protocol = "SAS" + if err := e.admin.Status().Update(e.ctx, device); err != nil { + e.t.Fatal(err) + } + } for name, setup := range cases { t.Run(name, func(t *testing.T) { e := startEnv(t) @@ -145,3 +174,142 @@ func TestARecreatedPolicyChangesNoPin(t *testing.T) { t.Fatalf("the release must wipe under the original pin: %+v, want %+v", wipe.Spec.Policy, original.CleaningPolicyReference) } } + +// TestReleaseWaitsWhileADriveCannotBeCleaned creates no wipe while a pinned +// drive is missing, so a gap in discovery spends no wipe step, and plans +// again when the drive returns. +func TestReleaseWaitsWhileADriveCannotBeCleaned(t *testing.T) { + e := startEnv(t) + device := e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + saved := e.device(device.Name).Status.Discovery.Inventory.Systems[0].Storage.Drives + setDrives := func(drives []inventory.ObservedDrive) { + t.Helper() + current := e.device(device.Name) + current.Status.Discovery.Inventory.Systems[0].Storage.Drives = drives + if err := e.admin.Status().Update(e.ctx, current); err != nil { + t.Fatal(err) + } + } + setDrives(nil) + var blocked error + e.until("release reports the missing drive", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + t.Fatal(err) + } + _, blocked = e.allocator.Release(e.ctx, allocation, machine(1)) + return errors.Is(blocked, ErrCleaningBlocked) + }) + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + t.Fatal(err) + } + condition := apiMeta.FindStatusCondition(allocation.Status.Conditions, ConditionCleaning) + if condition == nil || condition.Status != metav1.ConditionFalse || condition.Reason != custody.ReasonDriveMissing || allocation.Status.Wipe != nil { + t.Fatalf("condition = %+v, wipe = %+v", condition, allocation.Status.Wipe) + } + wipes := &ops.DeviceWipeList{} + if err := e.admin.List(e.ctx, wipes); err != nil || len(wipes.Items) != 0 { + t.Fatalf("no wipe may exist while a drive cannot be cleaned: %d, %v", len(wipes.Items), err) + } + setDrives(saved) + e.release(allocation, machine(1)) + if apiMeta.FindStatusCondition(allocation.Status.Conditions, ConditionCleaning) != nil { + t.Fatal("the Cleaning condition must clear once a wipe is planned") + } +} + +// TestPlanMismatchSpendsNoWipeStep counts only failures that are not plan +// mismatches toward the release's limit. +func TestPlanMismatchSpendsNoWipeStep(t *testing.T) { + e := startEnv(t) + device := e.server(1) + for step, reason := range map[int32]string{1: custody.ReasonPlanMismatch, 2: custody.ReasonPlanMismatch, 3: "TargetDisksUnknown"} { + wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: custody.WipeName("alloc-steps", step), Namespace: namespace}, Spec: ops.DeviceWipeSpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: ops.Creator{Username: releaseUser, UID: uid(802)}, DeviceRef: ops.DeviceReference{Name: device.Name}, + Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: "alloc-steps"}}}, + Step: step, Policy: ops.CleaningPolicyReference{Name: "p", Generation: 1, Digest: "sha256:" + strings.Repeat("a", 64)}, Assurance: ops.AssuranceClear, + Drives: []ops.PlannedDrive{{ManifestDrive: ops.ManifestDrive{Name: "disk-0", SerialNumber: "SN", Model: "M", Firmware: "F", Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD, CapacityBytes: 1}, State: ops.DriveMissing}}}} + e.create(wipe) + wipe.Status = ops.OperationStatus{Phase: ops.PhaseFailed, Reason: reason} + if err := e.admin.Status().Update(e.ctx, wipe); err != nil { + t.Fatal(err) + } + } + failed, err := e.allocator.failedSteps(e.ctx, "alloc-steps", 3) + if err != nil || failed != 1 { + t.Fatalf("failed steps = %d, %v; want 1", failed, err) + } +} + +// TestInstallTargetMustBeAPinnedDrive skips capacity whose drives do not +// include the disk installations target. +func TestInstallTargetMustBeAPinnedDrive(t *testing.T) { + e := startEnv(t) + e.server(1) + e.allocator.TargetDisks = []string{"disk-1"} + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrInsufficientCapacity) || !errors.Is(err, ErrCleaningUncovered) { + t.Fatalf("allocate = %v", err) + } +} + +// TestARetriedWipeAdoptsTheExistingOne keeps a wipe whose create response was +// lost even when discovery changed before the retry: admission plans it again. +func TestARetriedWipeAdoptsTheExistingOne(t *testing.T) { + e := startEnv(t) + e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + reference := fleetv1.WipeReference{Name: custody.WipeName(allocation.Name, 1), Step: 1} + existing := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: reference.Name, Namespace: namespace, Labels: operationLabels(allocation)}, Spec: ops.DeviceWipeSpec{ + OperationEnvelope: e.allocator.envelope(allocation, e.allocator.ReleaseCreator), Step: 1, + Policy: allocation.Spec.CleaningPolicy.CleaningPolicyReference, Assurance: ops.AssuranceClear, BootInterface: allocation.Spec.BootInterface, + Drives: []ops.PlannedDrive{{ManifestDrive: allocation.Spec.Drives[0], State: ops.DriveMissing}}}} + e.create(existing) + if err := e.allocator.wipe(e.ctx, allocation, reference); err != nil { + t.Fatalf("wipe = %v, want the existing wipe adopted", err) + } + got := &ops.DeviceWipe{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(existing), got); err != nil || got.Spec.Drives[0].State != ops.DriveMissing { + t.Fatalf("the existing wipe must stand: %+v, %v", got.Spec.Drives, err) + } +} + +// TestAWipeIsNeverPlannedForARecreatedDevice deletes the allocated Device and +// creates another under its name. The release controller must not plan a +// wipe from the new Device's drives: the allocation's device-uid label names +// the server it pinned. +func TestAWipeIsNeverPlannedForARecreatedDevice(t *testing.T) { + e := startEnv(t) + e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + device := e.device("server-example-001") + if err := e.admin.Delete(e.ctx, device); err != nil { + t.Fatal(err) + } + replacement := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: device.Name, Namespace: namespace}, Spec: device.Spec} + e.until("the Device is recreated", func() bool { return e.admin.Create(e.ctx, replacement) == nil }) + if replacement.UID == device.UID { + t.Fatal("the recreated Device has the old UID") + } + // The new Device reports the same drives, so only the incarnation check + // stands between it and a wipe. + replacement.Status = device.Status + if err := e.admin.Status().Update(e.ctx, replacement); err != nil { + t.Fatal(err) + } + reference := fleetv1.WipeReference{Name: custody.WipeName(allocation.Name, 1), Step: 1} + if err := e.allocator.wipe(e.ctx, allocation, reference); !errors.Is(err, ErrCustodyLost) { + t.Fatalf("wipe = %v, want ErrCustodyLost", err) + } + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: reference.Name}, &ops.DeviceWipe{}); !apierrors.IsNotFound(err) { + t.Fatalf("no wipe may be created for a recreated Device: %v", err) + } +} diff --git a/internal/allocation/flow_test.go b/internal/allocation/flow_test.go index 4b8b3d1b..78c3cafa 100644 --- a/internal/allocation/flow_test.go +++ b/internal/allocation/flow_test.go @@ -180,7 +180,7 @@ func TestAnAllocationThatLostItsDeviceIsReplaced(t *testing.T) { } // A crash left the second Machine's allocation naming the taken Device, // before it claimed custody. - stale, err := e.allocator.newAllocation(context.Background(), e.request(2), e.capacity(taken.Name), taken, fleetv1.Hardware{}, "") + stale, err := e.allocator.newAllocation(context.Background(), e.request(2), e.capacity(taken.Name), e.device(taken.Name), fleetv1.Hardware{}, "") if err != nil { t.Fatal(err) } diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index 8b2db52b..b7443e11 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -212,7 +212,7 @@ func (e *env) server(n int) *inventory.Device { return state != nil && state.Spec.State == ops.CustodyVerified }) e.commission(device, capacity) - return device + return e.device(name) } // commission commissions the server under the fixture plan and waits until @@ -342,3 +342,25 @@ func examplePolicy(namespace string) *ops.CleaningPolicy { Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: ops.VerifySpec{Mode: ops.VerifyFull}, TimePerTiB: metav1.Duration{Duration: time.Hour}}}, }} } + +// device reads the Device as the allocator would. +func (e *env) device(name string) *inventory.Device { + e.t.Helper() + device := &inventory.Device{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: name}, device); err != nil { + e.t.Fatal(err) + } + return device +} + +// addDrive makes discovery report one more simulated drive for the Device. +func (e *env) addDrive(name, disk string) { + e.t.Helper() + device := e.device(name) + storage := device.Status.Discovery.Inventory.Systems[0].Storage + extra := fixture.Drives(namespace+"/"+name, fixture.Target{Disks: []string{disk}}) + storage.Drives = append(storage.Drives, extra.Drives...) + if err := e.admin.Status().Update(e.ctx, device); err != nil { + e.t.Fatal(err) + } +} diff --git a/internal/allocation/release.go b/internal/allocation/release.go index 9cac76c3..0ab0579c 100644 --- a/internal/allocation/release.go +++ b/internal/allocation/release.go @@ -7,6 +7,7 @@ import ( "slices" apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" @@ -14,18 +15,33 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/bootaddress" + "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/custody" ) // maxWipeSteps bounds the wipes one release creates after wipes that ended // Failed, which sent nothing. A wipe whose outcome is unknown is never -// repeated without a DeviceRecovery Retry. -const maxWipeSteps = 3 +// repeated without a DeviceRecovery Retry. A wipe refused because discovery +// changed between planning and admission (PlanMismatch) does not count +// toward it, but every release stops at maxPlanSteps steps in all. +const ( + maxWipeSteps = 3 + maxPlanSteps = 16 +) + +// ConditionCleaning is the MachineAllocation condition the release +// controller sets False while no wipe can be planned, with the reason. +const ConditionCleaning = "Cleaning" // ErrWipeFailed means the release created its last wipe step and it failed. // The Cleaning gate stays open, and the Device stays in Release. var ErrWipeFailed = errors.New("every wipe step of the release failed") +// ErrCleaningBlocked means a drive cannot be cleaned now: discovery does not +// report a pinned drive, or reports one no method covers. No wipe is +// created; the release plans again when discovery changes. +var ErrCleaningBlocked = errors.New("a drive cannot be cleaned") + // Release advances the release of an allocation by one step and reports // whether it is Released. Callers repeat it while the custody coordinator // runs. The holder moves to Release, the release controller closes each @@ -313,7 +329,11 @@ func (a *Allocator) clean(ctx context.Context, state *ops.DeviceCustody, allocat case ops.PhaseSucceeded: return true, nil case ops.PhaseFailed, ops.PhaseCancelled: - if current.Step >= maxWipeSteps { + failed, err := a.failedSteps(ctx, allocation.Name, current.Step) + if err != nil { + return false, err + } + if failed >= maxWipeSteps || current.Step >= maxPlanSteps { return false, fmt.Errorf("%w: %s: %s", ErrWipeFailed, wipe.Status.Reason, wipe.Status.Message) } step := current.Step + 1 @@ -327,9 +347,57 @@ func (a *Allocator) clean(ctx context.Context, state *ops.DeviceCustody, allocat return false, nil } +// failedSteps counts the release's wipes up to step that ended Failed or +// Cancelled for a reason other than PlanMismatch. +func (a *Allocator) failedSteps(ctx context.Context, allocation string, step int32) (int, error) { + failed := 0 + for n := int32(1); n <= step; n++ { + wipe := &ops.DeviceWipe{} + if err := a.Releaser.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: custody.WipeName(allocation, n)}, wipe); apierrors.IsNotFound(err) { + continue + } else if err != nil { + return 0, err + } + if (wipe.Status.Phase == ops.PhaseFailed || wipe.Status.Phase == ops.PhaseCancelled) && wipe.Status.Reason != custody.ReasonPlanMismatch { + failed++ + } + } + return failed, nil +} + // wipe records the wipe in status, then creates it, so a crash between the -// two creates the same wipe again. +// two creates the same wipe again. Its plan comes from the shared planner: +// the allocation's pinned policy and manifest, and the drives discovery +// reports now. Until discovery reports the server's drives, no wipe is +// created. func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocation, reference fleetv1.WipeReference) error { + device := &inventory.Device{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: allocation.Spec.DeviceRef.Name}, device); err != nil { + return err + } + // The allocation's device-uid label records the incarnation it holds; + // a Device recreated under the same name is not that server. + if string(device.UID) != allocation.Labels[fleetv1.LabelDeviceUID] { + return fmt.Errorf("%w: the Device is another incarnation", ErrCustodyLost) + } + pin := allocation.Spec.CleaningPolicy + plan, err := cleaning.Plan(pin.Spec, allocation.Spec.Drives, cleaning.StorageOf(device), nil) + if err != nil { + return fmt.Errorf("plan the wipe: %w", err) + } + if blocked := blockedReason(plan); blocked != nil { + if changed := apiMeta.SetStatusCondition(&allocation.Status.Conditions, *blocked); changed { + if err := a.Provider.Status().Update(ctx, allocation); err != nil { + return err + } + } + return fmt.Errorf("%w: %s", ErrCleaningBlocked, blocked.Message) + } + if apiMeta.RemoveStatusCondition(&allocation.Status.Conditions, ConditionCleaning) { + if err := a.Provider.Status().Update(ctx, allocation); err != nil { + return err + } + } // A wipe network-boots, the only method it has. Where the site offers // no network boot, or has not reported what it offers, nothing claims a // boot address and no wipe is made. @@ -347,8 +415,9 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat Spec: ops.DeviceWipeSpec{ OperationEnvelope: a.envelope(allocation, a.ReleaseCreator), Step: reference.Step, - Policy: allocation.Spec.CleaningPolicy.CleaningPolicyReference, - TargetDisks: slices.Clone(allocation.Spec.TargetDisks), + Policy: pin.CleaningPolicyReference, + Assurance: pin.Spec.Assurance, + Drives: plan, BootInterface: allocation.Spec.BootInterface, }, } @@ -357,6 +426,7 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat existing := &ops.DeviceWipe{} if err := a.Releaser.Get(ctx, client.ObjectKeyFromObject(wipe), existing); err == nil { wipe.Spec.BootNetwork = existing.Spec.BootNetwork + wipe.Spec.Drives = existing.Spec.Drives return matchExisting(wipe, existing) } else if !apierrors.IsNotFound(err) { return err @@ -369,6 +439,25 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat return a.createOnce(ctx, a.Releaser, wipe, &ops.DeviceWipe{}) } +// blockedReason is the Cleaning condition for a plan with a drive that +// cannot be cleaned, or nil. +func blockedReason(plan []ops.PlannedDrive) *metav1.Condition { + for _, d := range plan { + reason := "" + switch d.State { + case ops.DriveMissing: + reason = custody.ReasonDriveMissing + case ops.DriveUncovered: + reason = custody.ReasonDriveUncovered + default: + continue + } + return &metav1.Condition{Type: ConditionCleaning, Status: metav1.ConditionFalse, Reason: reason, + Message: fmt.Sprintf("drive %s (%s) cannot be cleaned", d.Name, d.SerialNumber)} + } + return nil +} + // offersNetworkBoot reports ErrNoWipeMethod unless every site serving the // allocation's Device offers network boot, and ErrDeliveryUnknown while a // serving site has no current declaration. diff --git a/internal/allocation/release_test.go b/internal/allocation/release_test.go index 4cc89e04..5f170f53 100644 --- a/internal/allocation/release_test.go +++ b/internal/allocation/release_test.go @@ -72,7 +72,7 @@ func TestAnAllocationThatNeverHeldItsDeviceIsReleased(t *testing.T) { if _, err := q.Acquire(e.ctx, machine(1)); err != nil { t.Fatal(err) } - orphan, err := e.allocator.newAllocation(context.Background(), e.request(1), e.capacity(device.Name), device, fleetv1.Hardware{}, "fleet-machine-601") + orphan, err := e.allocator.newAllocation(context.Background(), e.request(1), e.capacity(device.Name), e.device(device.Name), fleetv1.Hardware{}, "fleet-machine-601") if err != nil { t.Fatal(err) } @@ -96,13 +96,13 @@ func TestAnAllocationThatNeverHeldItsDeviceIsReleased(t *testing.T) { func TestAFailingWipeGetsNewStepsThenStops(t *testing.T) { e := startEnv(t) device := e.server(1) - // The site enrolls disk-0; a wipe of disk-1 is refused before anything - // is sent. - e.allocator.TargetDisks = []string{"disk-1"} held, err := e.allocator.Allocate(e.ctx, e.request(1)) if err != nil { t.Fatal(err) } + // Discovery now reports a second drive the site does not enroll. Every + // wipe plans it, and the site refuses each one before anything is sent. + e.addDrive(device.Name, "disk-1") deadline := time.Now().Add(45 * time.Second) for { if err := e.loop.Pass(e.ctx); err != nil { diff --git a/internal/api/operations/v1alpha1/cleaning.go b/internal/api/operations/v1alpha1/cleaning.go index 68c1c08b..6954cea4 100644 --- a/internal/api/operations/v1alpha1/cleaning.go +++ b/internal/api/operations/v1alpha1/cleaning.go @@ -137,3 +137,62 @@ type CleaningPolicyList struct { func (in *CleaningPolicy) DeepCopyObject() runtime.Object { return deepCopy(in) } func (in *CleaningPolicyList) DeepCopyObject() runtime.Object { return deepCopy(in) } + +// ManifestDrive is one drive an allocation pinned: its name for the +// allocation, its identity, and the rule that covers it. +type ManifestDrive struct { + Name string `json:"name"` + SerialNumber string `json:"serialNumber"` + Model string `json:"model"` + Firmware string `json:"firmware"` + Protocol DriveProtocol `json:"protocol"` + MediaType MediaType `json:"mediaType"` + CapacityBytes int64 `json:"capacityBytes"` + Rule string `json:"rule"` +} + +// DriveState marks a planned drive the plan cannot clean. +type DriveState string + +const ( + // DriveMissing is a pinned drive that discovery no longer reports. + DriveMissing DriveState = "Missing" + // DriveUncovered is a drive no qualified method of the pinned policy + // can clean. + DriveUncovered DriveState = "Uncovered" +) + +// PlannedDrive is one step of a wipe: a drive as discovery reports it now, +// and the methods and check the pinned policy plans for it. State is set +// only for a drive the plan cannot clean. +type PlannedDrive struct { + ManifestDrive `json:",inline"` + Methods []CleaningMethod `json:"methods,omitempty"` + Verify *VerifySpec `json:"verify,omitempty"` + TimePerTiB *metav1.Duration `json:"timePerTiB,omitempty"` + State DriveState `json:"state,omitempty"` +} + +// OverwriteDrives returns the names of the planned drives when every one can +// be cleaned by Overwrite with Full verification, the only method today's +// sites run. It returns false when a drive is Missing or Uncovered or its +// plan does not allow that method. +func (in *DeviceWipeSpec) OverwriteDrives() ([]string, bool) { + var names []string + for _, d := range in.Drives { + if d.State != "" || d.Verify == nil || d.Verify.Mode != VerifyFull || !containsMethod(d.Methods, MethodOverwrite) { + return nil, false + } + names = append(names, d.Name) + } + return names, len(names) > 0 +} + +func containsMethod(methods []CleaningMethod, m CleaningMethod) bool { + for _, have := range methods { + if have == m { + return true + } + } + return false +} diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 3723578c..181bf6e1 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -487,9 +487,12 @@ type DeviceWipeSpec struct { // Step numbers the wipes of one release, from 1. The name is derived // from it. Step int32 `json:"step"` - // Policy is the cleaning policy pinned at allocation. - Policy CleaningPolicyReference `json:"policy"` - TargetDisks []string `json:"targetDisks"` + // Policy is the cleaning policy pinned at allocation, and Assurance what + // it requires of every drive. + Policy CleaningPolicyReference `json:"policy"` + Assurance Assurance `json:"assurance"` + // Drives is the plan: one step per drive, from the shared planner. + Drives []PlannedDrive `json:"drives"` // BootInterface names the Device interface the wipe network-boots. // Admission requires it; the schema leaves it optional so wipes stored // before it existed stay valid. diff --git a/internal/api/v1alpha1/types.go b/internal/api/v1alpha1/types.go index b111a304..fd9d3ab3 100644 --- a/internal/api/v1alpha1/types.go +++ b/internal/api/v1alpha1/types.go @@ -475,6 +475,10 @@ type MachineAllocationSpec struct { // CleaningPolicy is the copy of the capacity's cleaning policy the // release wipes under. It is pinned at allocation. CleaningPolicy ops.PinnedCleaningPolicy `json:"cleaningPolicy"` + // Drives is the media manifest: every drive the server had when Fleet + // allocated it, named for this allocation and matched to a rule of the + // pinned policy. Release cleans every one of them. + Drives []ops.ManifestDrive `json:"drives"` // BootInterface and TargetDisks are what installations and wipes for // this allocation use. BootInterface string `json:"bootInterface"` diff --git a/internal/cleaning/plan.go b/internal/cleaning/plan.go new file mode 100644 index 00000000..24ea8282 --- /dev/null +++ b/internal/cleaning/plan.go @@ -0,0 +1,191 @@ +package cleaning + +import ( + "errors" + "fmt" + "slices" + "strconv" + "strings" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +var ( + // ErrUncovered means a server has a drive the policy cannot clean, or + // storage Fleet cannot account for. Its capacity is not offered. + ErrUncovered = errors.New("CleaningUncovered") + // ErrStorageUnknown means discovery has not reported the server's drives. + ErrStorageUnknown = errors.New("the server's drives are not known") +) + +// MaxDrives bounds a manifest and a plan. +const MaxDrives = 16 + +func driveOf(d inventory.ObservedDrive) Drive { + return Drive{Protocol: ops.DriveProtocol(d.Protocol), MediaType: ops.MediaType(d.MediaType), Model: d.Model, Firmware: d.Firmware} +} + +// Manifest pins a server's drives under a policy. Every drive must be +// addressed directly by the host, identify itself, and have a planned method; +// otherwise the server is not covered. Drives are named disk-0, disk-1 and so +// on, ordered by protocol and serial number. +func Manifest(spec ops.CleaningPolicySpec, storage *inventory.ObservedStorage) ([]ops.ManifestDrive, error) { + if storage == nil { + return nil, fmt.Errorf("%w: %w", ErrUncovered, ErrStorageUnknown) + } + if len(storage.Drives) == 0 { + return nil, fmt.Errorf("%w: discovery reports no drives", ErrUncovered) + } + if len(storage.Drives) > MaxDrives { + return nil, fmt.Errorf("%w: more than %d drives", ErrUncovered, MaxDrives) + } + drives := slices.Clone(storage.Drives) + slices.SortFunc(drives, func(a, b inventory.ObservedDrive) int { + return strings.Compare(a.Protocol+"\x00"+a.SerialNumber, b.Protocol+"\x00"+b.SerialNumber) + }) + var out []ops.ManifestDrive + seen := map[string]bool{} + for i, d := range drives { + switch { + case d.InVolume: + return nil, fmt.Errorf("%w: drive %s backs a RAID volume", ErrUncovered, d.ID) + case d.SerialNumber == "" || d.CapacityBytes <= 0: + return nil, fmt.Errorf("%w: drive %s reports no serial number or capacity", ErrUncovered, d.ID) + case seen[d.SerialNumber]: + return nil, fmt.Errorf("%w: two drives report serial number %s", ErrUncovered, d.SerialNumber) + } + seen[d.SerialNumber] = true + rule := Match(spec, driveOf(d)) + if rule == nil || len(Methods(spec, *rule, driveOf(d))) == 0 { + return nil, fmt.Errorf("%w: no qualified method cleans drive %s (%s %s %s)", ErrUncovered, d.SerialNumber, d.Protocol, d.MediaType, d.Model) + } + out = append(out, ops.ManifestDrive{Name: "disk-" + strconv.Itoa(i), SerialNumber: d.SerialNumber, Model: d.Model, Firmware: d.Firmware, + Protocol: ops.DriveProtocol(d.Protocol), MediaType: ops.MediaType(d.MediaType), CapacityBytes: d.CapacityBytes, Rule: rule.Name}) + } + return out, nil +} + +// Plan is the one shared planner. The release controller uses it to create a +// wipe, and admission uses it to check one. Every pinned drive that was not +// disposed of gets a step, and so does every drive discovery reports now that +// the manifest lacks. Methods come from the pinned policy and the drive as +// discovery reports it now, so changed firmware must still be qualified. A +// pinned drive discovery no longer reports is Missing. A drive with no +// planned method is Uncovered, and so is every drive that shares its serial +// number with another, a pinned drive whose model, protocol, media type or +// capacity changed, and a drive that reports no serial number: none of them +// can be matched to one physical drive. +func Plan(policy ops.CleaningPolicySpec, manifest []ops.ManifestDrive, storage *inventory.ObservedStorage, disposed []string) ([]ops.PlannedDrive, error) { + if storage == nil { + return nil, ErrStorageUnknown + } + current := map[string]inventory.ObservedDrive{} + count := map[string]int{} + for _, d := range storage.Drives { + count[d.SerialNumber]++ + if d.SerialNumber != "" { + current[d.SerialNumber] = d + } + } + unmatchable := func(d inventory.ObservedDrive) bool { return d.SerialNumber == "" || count[d.SerialNumber] > 1 } + uncovered := func(p ops.PlannedDrive) ops.PlannedDrive { + p.State, p.Methods, p.Verify, p.TimePerTiB, p.Rule = ops.DriveUncovered, nil, nil, nil, "" + return p + } + step := func(name string, d inventory.ObservedDrive) ops.PlannedDrive { + planned := ops.PlannedDrive{ManifestDrive: ops.ManifestDrive{Name: name, SerialNumber: d.SerialNumber, Model: d.Model, Firmware: d.Firmware, + Protocol: ops.DriveProtocol(d.Protocol), MediaType: ops.MediaType(d.MediaType), CapacityBytes: d.CapacityBytes}} + rule := Match(policy, driveOf(d)) + var methods []ops.CleaningMethod + if rule != nil && !d.InVolume { + methods = Methods(policy, *rule, driveOf(d)) + } + if len(methods) == 0 { + planned.State = ops.DriveUncovered + return planned + } + verify, bound := rule.Verify, rule.TimePerTiB + planned.Rule, planned.Methods, planned.Verify, planned.TimePerTiB = rule.Name, methods, &verify, &bound + return planned + } + var out []ops.PlannedDrive + pinned := map[string]bool{} + used := map[string]bool{} + for _, m := range manifest { + pinned[m.SerialNumber] = true + used[m.Name] = true + if slices.Contains(disposed, m.Name) { + continue + } + d, ok := current[m.SerialNumber] + switch { + case !ok: + out = append(out, ops.PlannedDrive{ManifestDrive: m, State: ops.DriveMissing}) + case unmatchable(d) || d.Model != m.Model || ops.DriveProtocol(d.Protocol) != m.Protocol || ops.MediaType(d.MediaType) != m.MediaType || d.CapacityBytes != m.CapacityBytes: + out = append(out, uncovered(ops.PlannedDrive{ManifestDrive: m})) + default: + out = append(out, step(m.Name, d)) + } + } + // Every drive not planned above gets a step: a new drive, a drive with + // no serial number, and every extra drive sharing a serial number. + var added []inventory.ObservedDrive + planned := map[string]bool{} + for _, d := range storage.Drives { + if pinned[d.SerialNumber] && !planned[d.SerialNumber] { + planned[d.SerialNumber] = true + continue + } + added = append(added, d) + } + slices.SortFunc(added, func(a, b inventory.ObservedDrive) int { + return strings.Compare(a.Protocol+"\x00"+a.SerialNumber+"\x00"+a.ID, b.Protocol+"\x00"+b.SerialNumber+"\x00"+b.ID) + }) + next := 0 + for _, d := range added { + for used["disk-"+strconv.Itoa(next)] { + next++ + } + name := "disk-" + strconv.Itoa(next) + used[name] = true + step := step(name, d) + if unmatchable(d) { + step = uncovered(step) + } + out = append(out, step) + } + if len(out) > MaxDrives { + return nil, fmt.Errorf("a plan has at most %d drives", MaxDrives) + } + return out, nil +} + +// Cleanable reports whether every planned drive can be cleaned. +func Cleanable(plan []ops.PlannedDrive) bool { + return !slices.ContainsFunc(plan, func(d ops.PlannedDrive) bool { return d.State != "" }) +} + +// StorageOf returns the drives discovery last observed for the Device's +// system: the System whose UUID is the Device's, or the only System when the +// Device records no UUID. It is nil when discovery has not reported storage. +func StorageOf(device *inventory.Device) *inventory.ObservedStorage { + if device == nil || device.Status.Discovery == nil || device.Status.Discovery.Inventory == nil { + return nil + } + systems := device.Status.Discovery.Inventory.Systems + want := strings.ToLower(device.Spec.Identity.SystemUUID) + var found *inventory.ObservedSystem + for i := range systems { + if want == "" && len(systems) == 1 || want != "" && strings.ToLower(systems[i].UUID) == want { + if found != nil { + return nil + } + found = &systems[i] + } + } + if found == nil { + return nil + } + return found.Storage +} diff --git a/internal/cleaning/plan_test.go b/internal/cleaning/plan_test.go new file mode 100644 index 00000000..3cde661f --- /dev/null +++ b/internal/cleaning/plan_test.go @@ -0,0 +1,142 @@ +package cleaning + +import ( + "errors" + "slices" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +func nvme(serial, firmware string) inventory.ObservedDrive { + return inventory.ObservedDrive{ID: serial, SerialNumber: serial, Model: "EXAMPLE-NVME-3840", Firmware: firmware, Protocol: "NVMe", MediaType: "SSD", CapacityBytes: 3840755982336} +} + +func storage(drives ...inventory.ObservedDrive) *inventory.ObservedStorage { + return &inventory.ObservedStorage{Drives: drives} +} + +func TestManifestNamesCoveredDrivesInOrder(t *testing.T) { + manifest, err := Manifest(purgePolicy(), storage(nvme("SN-B", "EX1.3"), nvme("SN-A", "EX1.2"))) + if err != nil { + t.Fatal(err) + } + if len(manifest) != 2 || manifest[0].Name != "disk-0" || manifest[0].SerialNumber != "SN-A" || manifest[1].SerialNumber != "SN-B" || manifest[0].Rule != "nvme-qualified" { + t.Fatalf("manifest = %+v", manifest) + } +} + +func TestManifestRefusesUncoveredServers(t *testing.T) { + raid := nvme("SN-R", "EX1.3") + raid.InVolume = true + anonymous := nvme("", "EX1.3") + cases := map[string]*inventory.ObservedStorage{ + "unknown storage": nil, + "no drives": storage(), + "unqualified drive": storage(nvme("SN-A", "EX0.9")), + "RAID member": storage(raid), + "no serial number": storage(anonymous), + "duplicate serial": storage(nvme("SN-A", "EX1.3"), nvme("SN-A", "EX1.3")), + "no rule for the bus": storage(inventory.ObservedDrive{ID: "x", SerialNumber: "SN-X", Protocol: "SAS", MediaType: "HDD", CapacityBytes: 1}), + } + for name, s := range cases { + if _, err := Manifest(purgePolicy(), s); !errors.Is(err, ErrUncovered) { + t.Errorf("%s: err = %v, want ErrUncovered", name, err) + } + } +} + +func TestPlan(t *testing.T) { + policy := purgePolicy() + manifest, err := Manifest(policy, storage(nvme("SN-A", "EX1.3"), nvme("SN-B", "EX1.3"))) + if err != nil { + t.Fatal(err) + } + states := func(plan []ops.PlannedDrive) []string { + var out []string + for _, d := range plan { + out = append(out, d.Name+"="+d.SerialNumber+":"+string(d.State)) + } + return out + } + raid := nvme("SN-A", "EX1.3") + raid.InVolume = true + cases := []struct { + name string + current *inventory.ObservedStorage + disposed []string + want []string + }{ + {"unchanged", storage(nvme("SN-A", "EX1.3"), nvme("SN-B", "EX1.3")), nil, []string{"disk-0=SN-A:", "disk-1=SN-B:"}}, + {"pinned drive joined a volume", storage(raid, nvme("SN-B", "EX1.3")), nil, []string{"disk-0=SN-A:Uncovered", "disk-1=SN-B:"}}, + {"missing", storage(nvme("SN-A", "EX1.3")), nil, []string{"disk-0=SN-A:", "disk-1=SN-B:Missing"}}, + {"disposed", storage(nvme("SN-A", "EX1.3")), []string{"disk-1"}, []string{"disk-0=SN-A:"}}, + {"unqualified firmware flashed during the allocation", storage(nvme("SN-A", "EX9.9"), nvme("SN-B", "EX1.3")), nil, []string{"disk-0=SN-A:Uncovered", "disk-1=SN-B:"}}, + {"added drive", storage(nvme("SN-A", "EX1.3"), nvme("SN-B", "EX1.3"), nvme("SN-C", "EX1.2")), nil, []string{"disk-0=SN-A:", "disk-1=SN-B:", "disk-2=SN-C:"}}, + {"added drive after a disposal keeps names unique", storage(nvme("SN-A", "EX1.3"), nvme("SN-C", "EX1.2")), []string{"disk-1"}, []string{"disk-0=SN-A:", "disk-2=SN-C:"}}, + {"added anonymous drive", storage(nvme("SN-A", "EX1.3"), nvme("SN-B", "EX1.3"), nvme("", "EX1.3")), nil, []string{"disk-0=SN-A:", "disk-1=SN-B:", "disk-2=:Uncovered"}}, + {"a pinned serial reported twice", storage(nvme("SN-A", "EX1.3"), nvme("SN-B", "EX1.3"), withID(nvme("SN-A", "EX1.3"), "clone")), nil, []string{"disk-0=SN-A:Uncovered", "disk-1=SN-B:", "disk-2=SN-A:Uncovered"}}, + {"two new drives share a serial", storage(nvme("SN-A", "EX1.3"), nvme("SN-B", "EX1.3"), withID(nvme("SN-C", "EX1.3"), "c1"), withID(nvme("SN-C", "EX1.3"), "c2")), nil, []string{"disk-0=SN-A:", "disk-1=SN-B:", "disk-2=SN-C:Uncovered", "disk-3=SN-C:Uncovered"}}, + {"a pinned serial on another model", storage(withModel(nvme("SN-A", "EX1.3"), "OTHER-MODEL"), nvme("SN-B", "EX1.3")), nil, []string{"disk-0=SN-A:Uncovered", "disk-1=SN-B:"}}, + {"a pinned serial with another capacity", storage(withCapacity(nvme("SN-A", "EX1.3"), 1<<30), nvme("SN-B", "EX1.3")), nil, []string{"disk-0=SN-A:Uncovered", "disk-1=SN-B:"}}, + } + for _, tc := range cases { + plan, err := Plan(policy, manifest, tc.current, tc.disposed) + if err != nil { + t.Fatalf("%s: %v", tc.name, err) + } + if got := states(plan); !slices.Equal(got, tc.want) { + t.Errorf("%s: plan = %v, want %v", tc.name, got, tc.want) + } + if Cleanable(plan) != !slices.ContainsFunc(tc.want, func(s string) bool { return s[len(s)-1] != ':' }) { + t.Errorf("%s: Cleanable disagrees with the states", tc.name) + } + } + plan, _ := Plan(policy, manifest, storage(nvme("SN-A", "EX1.3"), nvme("SN-B", "EX1.3")), nil) + if !slices.Equal(plan[0].Methods, []ops.CleaningMethod{ops.MethodCryptographicErase, ops.MethodBlockErase}) || plan[0].Verify.Mode != ops.VerifyCanary || plan[0].TimePerTiB == nil { + t.Fatalf("a covered step carries its methods, check and time bound: %+v", plan[0]) + } + if _, err := Plan(policy, manifest, nil, nil); !errors.Is(err, ErrStorageUnknown) { + t.Fatalf("unknown storage = %v", err) + } +} + +func TestStorageOfFindsTheDevicesSystem(t *testing.T) { + mine, other := storage(nvme("SN-MINE", "EX1.3")), storage(nvme("SN-OTHER", "EX1.3")) + device := func(uuid string, systems ...inventory.ObservedSystem) *inventory.Device { + d := &inventory.Device{} + d.Spec.Identity.SystemUUID = uuid + d.Status.Discovery = &inventory.DeviceDiscovery{Inventory: &inventory.ObservedInventory{Systems: systems}} + return d + } + const uuid = "00000000-0000-4000-8000-000000000001" + cases := []struct { + name string + device *inventory.Device + want *inventory.ObservedStorage + }{ + {"matched by UUID", device(uuid, inventory.ObservedSystem{ID: "2", UUID: "00000000-0000-4000-8000-000000000002", Storage: other}, inventory.ObservedSystem{ID: "1", UUID: uuid, Storage: mine}), mine}, + {"UUID case differs", device(uuid, inventory.ObservedSystem{ID: "1", UUID: "00000000-0000-4000-8000-000000000001", Storage: mine}), mine}, + {"only System, no UUID recorded", device("", inventory.ObservedSystem{ID: "1", Storage: mine}), mine}, + {"no System with the UUID", device(uuid, inventory.ObservedSystem{ID: "2", UUID: "00000000-0000-4000-8000-000000000002", Storage: other}), nil}, + {"two Systems and no UUID", device("", inventory.ObservedSystem{ID: "1", Storage: mine}, inventory.ObservedSystem{ID: "2", Storage: other}), nil}, + {"two Systems claim the UUID", device(uuid, inventory.ObservedSystem{ID: "1", UUID: uuid, Storage: mine}, inventory.ObservedSystem{ID: "2", UUID: uuid, Storage: other}), nil}, + {"no discovery", &inventory.Device{}, nil}, + } + for _, tc := range cases { + if got := StorageOf(tc.device); got != tc.want { + t.Errorf("%s: got %v, want %v", tc.name, got, tc.want) + } + } +} + +func withID(d inventory.ObservedDrive, id string) inventory.ObservedDrive { d.ID = id; return d } +func withModel(d inventory.ObservedDrive, model string) inventory.ObservedDrive { + d.Model = model + return d +} +func withCapacity(d inventory.ObservedDrive, bytes int64) inventory.ObservedDrive { + d.CapacityBytes = bytes + return d +} diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go index d1778153..2864b6bc 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -156,7 +156,7 @@ func newFixture(t *testing.T) *rig { func (f *rig) wipe(fence int64, uid string) site.Assignment { spec := ops.DeviceWipeSpec{OperationEnvelope: ops.OperationEnvelope{Creator: ops.Creator{Username: "release", UID: "u"}, DeviceRef: ops.DeviceReference{Name: "server-example-001"}, Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: "alloc-example"}}}, - Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + keyDigest}, TargetDisks: []string{"disk-0"}} + Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + keyDigest}, Assurance: ops.AssuranceClear, Drives: []ops.PlannedDrive{overwriteDrive("disk-0")}} inputs, _ := json.Marshal(spec) digest, _ := custody.SpecDigest(spec) now := time.Now().UTC() @@ -334,6 +334,13 @@ func TestTheCellRunsOnlyItsOwnAssignments(t *testing.T) { } } +// overwriteDrive is one planned drive the site cleans by overwriting it and +// reading it back. +func overwriteDrive(name string) ops.PlannedDrive { + return ops.PlannedDrive{ManifestDrive: ops.ManifestDrive{Name: name, SerialNumber: "EXAMPLE-SN-0001", Model: "EXAMPLE-NVME", Firmware: "EX1", Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD, CapacityBytes: 2 << 30, Rule: "nvme-ssd"}, + Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: &ops.VerifySpec{Mode: ops.VerifyFull}} +} + // sealedWipe is a wipe assignment whose admitted inputs name a sealed // payload, and the payload. func (f *rig) sealedWipe(fence int64, uid string) (site.Assignment, site.Payload) { diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index caeedda9..afc78ac1 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -100,7 +100,7 @@ func TestAdmissionPreconditions(t *testing.T) { 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, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"}} + 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, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, BootInterface: "primary", Assurance: ops.AssuranceClear, Drives: e.wipePlan(device, "alloc-x")}} e.create(wipe) e.settle(device.Name) for _, operation := range []ops.Operation{spoof, service, named, wipe} { @@ -410,7 +410,7 @@ func TestAdmissionPreconditions(t *testing.T) { } wipeFence := e.custody(releasing.Name).Spec.Fence wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName("alloc-net-wipe", 1), Namespace: "default"}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: envelope(releasing, releaseUser, allocated("alloc-net-wipe")), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, TargetDisks: []string{"disk-0"}, BootInterface: "absent", + OperationEnvelope: envelope(releasing, releaseUser, allocated("alloc-net-wipe")), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, Assurance: ops.AssuranceClear, Drives: e.wipePlan(releasing, "alloc-net-wipe"), BootInterface: "absent", }} e.create(wipe) e.settle(releasing.Name) diff --git a/internal/custody/cleaning_test.go b/internal/custody/cleaning_test.go new file mode 100644 index 00000000..02f7c3fd --- /dev/null +++ b/internal/custody/cleaning_test.go @@ -0,0 +1,104 @@ +package custody + +import ( + "fmt" + "testing" + + "sigs.k8s.io/controller-runtime/pkg/client" + + 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" + "go.datum.net/fleet/internal/cleaning" +) + +// TestWipeAdmissionChecksThePlan admits a wipe only with the plan the shared +// planner makes now, and refuses one whose pinned drive is gone. +func TestWipeAdmissionChecksThePlan(t *testing.T) { + e := startEnv(t) + release := func(n int, allocation string) { + name := fmt.Sprintf("server-example-%d", n) + t.Helper() + device := e.verified(name, uid(n), fmt.Sprintf("%064x", n)) + e.allocation(device, allocation, "Releasing") + if err := e.coord.Claim(e.ctx, device.Name, device.UID, allocation); err != nil { + t.Fatal(err) + } + if err := e.coord.BeginRelease(e.ctx, device.Name, allocation); err != nil { + t.Fatal(err) + } + } + + t.Run("a plan that differs from the planner's is refused before anything is sent", func(t *testing.T) { + release(781, "alloc-pm") + device := e.read("server-example-781") + wipe := &ops.DeviceWipe{} + wipe.Name, wipe.Namespace = WipeName("alloc-pm", 1), "default" + wipe.Spec = ops.DeviceWipeSpec{OperationEnvelope: envelope(device, releaseUser, allocated("alloc-pm")), Step: 1, + Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, BootInterface: "primary", Assurance: ops.AssuranceClear, Drives: e.wipePlan(device, "alloc-pm")} + // Drop the check the pinned rule requires. + wipe.Spec.Drives[0].Verify = nil + e.create(wipe) + fence := e.custody(device.Name).Spec.Fence + e.settle(device.Name) + e.requirePhase(wipe, ops.PhaseFailed, ReasonPlanMismatch) + e.requireUntouched(device.Name, fence) + }) + + t.Run("a pinned drive discovery no longer reports is refused", func(t *testing.T) { + release(782, "alloc-dm") + device := e.read("server-example-782") + device.Status.Discovery.Inventory.Systems[0].Storage.Drives = nil + if err := e.admin.Status().Update(e.ctx, device); err != nil { + t.Fatal(err) + } + plan := e.planWith(device, "alloc-dm") + if len(plan) != 1 || plan[0].State != ops.DriveMissing { + t.Fatalf("plan = %+v", plan) + } + wipe := &ops.DeviceWipe{} + wipe.Name, wipe.Namespace = WipeName("alloc-dm", 1), "default" + wipe.Spec = ops.DeviceWipeSpec{OperationEnvelope: envelope(device, releaseUser, allocated("alloc-dm")), Step: 1, + Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, BootInterface: "primary", Assurance: ops.AssuranceClear, Drives: plan} + e.create(wipe) + fence := e.custody(device.Name).Spec.Fence + e.settle(device.Name) + e.requirePhase(wipe, ops.PhaseFailed, ReasonDriveMissing) + e.requireUntouched(device.Name, fence) + }) + + t.Run("the planner's plan is admitted", func(t *testing.T) { + release(783, "alloc-ok") + device := e.read("server-example-783") + wipe := e.wipe(device, "alloc-ok", 1) + e.settle(device.Name) + if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.Name != wipe.Name { + t.Fatalf("active = %+v, want the wipe admitted", active) + } + }) +} + +// read returns the Device as stored now. +func (e *env) read(name string) *inventory.Device { + e.t.Helper() + device := &inventory.Device{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: "default", Name: name}, device); err != nil { + e.t.Fatal(err) + } + return device +} + +// planWith plans the allocation's wipe from the Device's discovery as stored +// now, as admission does. +func (e *env) planWith(device *inventory.Device, allocation string) []ops.PlannedDrive { + e.t.Helper() + pinned := &metal.MachineAllocation{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: "default", Name: allocation}, pinned); err != nil { + e.t.Fatal(err) + } + plan, err := cleaning.Plan(pinned.Spec.CleaningPolicy.Spec, pinned.Spec.Drives, cleaning.StorageOf(device), nil) + if err != nil { + e.t.Fatal(err) + } + return plan +} diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index d01370a0..43ad8855 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -15,6 +15,7 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" metal "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/bootaddress" + "go.datum.net/fleet/internal/cleaning" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -247,8 +248,10 @@ func (e *env) discover(device *inventory.Device, key string, at time.Time) { } 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}, + TLS: &inventory.ObservedTLS{ObservedAt: observed, Endpoint: device.Spec.BMC.Endpoint, PublicKeySHA256: key}, + Inventory: &inventory.ObservedInventory{ObservedAt: observed, Endpoint: device.Spec.BMC.Endpoint, Systems: []inventory.ObservedSystem{{ + ID: "System-1", UUID: device.Spec.Identity.SystemUUID, Storage: harnessStorage(device), + }}}, } 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 { @@ -377,8 +380,10 @@ func (e *env) installation(device *inventory.Device, allocation, request string) func (e *env) wipe(device *inventory.Device, allocation string, step int32) *ops.DeviceWipe { e.t.Helper() + e.ensureAllocation(device, allocation) operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName(allocation, step), Namespace: "default"}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, TargetDisks: []string{"disk-0"}, BootInterface: "primary", + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, + BootInterface: "primary", Assurance: ops.AssuranceClear, Drives: e.wipePlan(device, allocation), }} e.create(operation) return operation @@ -407,8 +412,10 @@ func (e *env) ipClaim(name, operation, kind, phase, address string) *unstructure // 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() + e.ensureAllocation(device, allocation) operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, TargetDisks: []string{"disk-0"}, BootInterface: "primary", + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, + BootInterface: "primary", Assurance: ops.AssuranceClear, Drives: e.wipePlan(device, allocation), }} e.create(operation) return operation @@ -487,6 +494,11 @@ func (e *env) allocation(device *inventory.Device, name, phase string) *metal.Ma BootInterface: "primary", TargetDisks: []string{"disk-0"}, }} + drives, err := cleaning.Manifest(allocation.Spec.CleaningPolicy.Spec, harnessStorage(device)) + if err != nil { + e.t.Fatal(err) + } + allocation.Spec.Drives = drives e.create(allocation) if phase != "" { allocation.Status.Phase = phase @@ -509,3 +521,41 @@ func (e *env) deviceUID(name string) types.UID { } return device.UID } + +// harnessStorage is the one drive fixture discovery reports for a Device. +func harnessStorage(device *inventory.Device) *inventory.ObservedStorage { + return &inventory.ObservedStorage{Drives: []inventory.ObservedDrive{{ID: "Storage/1/Drives/0", SerialNumber: "EXAMPLE-SN-" + device.Name, Model: "EXAMPLE-NVME", + Firmware: "EX1", Protocol: "NVMe", MediaType: "SSD", CapacityBytes: 2 << 30}}} +} + +// plan is what the shared planner makes for a wipe of the allocation now. +func (e *env) wipePlan(device *inventory.Device, allocation string) []ops.PlannedDrive { + e.t.Helper() + pinned := &metal.MachineAllocation{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: "default", Name: allocation}, pinned); err != nil { + // A wipe for an allocation the test never created: plan the one + // harness drive under the harness policy. + pinned.Spec.CleaningPolicy.Spec = ops.CleaningPolicySpec{Assurance: ops.AssuranceClear, Rules: []ops.CleaningRule{{Name: "nvme-ssd", Match: ops.DriveMatch{Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD}, + Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: ops.VerifySpec{Mode: ops.VerifyFull}, TimePerTiB: metav1.Duration{Duration: time.Hour}}}} + pinned.Spec.Drives, _ = cleaning.Manifest(pinned.Spec.CleaningPolicy.Spec, harnessStorage(device)) + } + plan, err := cleaning.Plan(pinned.Spec.CleaningPolicy.Spec, pinned.Spec.Drives, harnessStorage(device), nil) + if err != nil { + e.t.Fatal(err) + } + return plan +} + +// ensureAllocation creates the releasing allocation a wipe names, when the +// test has not, because wipe admission plans from it. +func (e *env) ensureAllocation(device *inventory.Device, name string) { + e.t.Helper() + err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: "default", Name: name}, &metal.MachineAllocation{}) + if apierrors.IsNotFound(err) { + e.allocation(device, name, "Releasing") + return + } + if err != nil { + e.t.Fatal(err) + } +} diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index a0737ed8..a4347ccd 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -9,7 +9,10 @@ import ( "strconv" "time" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/sealed" + "k8s.io/apimachinery/pkg/api/equality" "sigs.k8s.io/controller-runtime/pkg/client" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" @@ -44,6 +47,10 @@ const ( ReasonRetryAuthorized = "RetryAlreadyAuthorized" ReasonDisposalRequired = "DisposalRequired" ReasonInvalidResolve = "InvalidResolve" + // A wipe plans a drive it cannot clean. These refuse the wipe until the + // recovery hold that #183 specifies replaces the refusal. + ReasonDriveMissing = "DriveMissing" + ReasonDriveUncovered = "DriveUncovered" // ReasonBootAddress means the boot address claim's source could not be // read. The operation waits and is checked again. ReasonBootAddress = "BootAddressUnavailable" @@ -259,13 +266,16 @@ func DeviceWipeKind() Kind { if refusal := checkWipeDelivery(admission); refusal != nil { return refusal } - return checkNetworkBoot(ctx, admission, "DeviceWipe", wipe.Spec.BootInterface, wipe.Spec.BootNetwork) + if refusal := checkNetworkBoot(ctx, admission, "DeviceWipe", wipe.Spec.BootInterface, wipe.Spec.BootNetwork); refusal != nil { + return refusal + } + return checkWipePlan(ctx, admission) }, // 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}}, Retryable: true, - Reasons: append(append([]Reason{{Name: ReasonDeliveryMismatch, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryNotOffered, RaisedBy: RaisedByCoordinator}}, networkBootReasons...), workerReasons...), + Reasons: append(append([]Reason{{Name: ReasonPlanMismatch, RaisedBy: RaisedByCoordinator}, {Name: ReasonDriveMissing, RaisedBy: RaisedByCoordinator}, {Name: ReasonDriveUncovered, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryMismatch, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryNotOffered, RaisedBy: RaisedByCoordinator}}, networkBootReasons...), workerReasons...), Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.WipeEvidence) error { if len(evidence.WipedDisks) > 16 { return errors.New("evidence records at most 16 disks") @@ -275,6 +285,39 @@ func DeviceWipeKind() Kind { } } +// checkWipePlan admits a wipe only if its plan is exactly what the shared +// planner makes from its allocation's pinned policy and manifest and the +// drives discovery reports now, and only if every planned drive can be +// cleaned. +func checkWipePlan(ctx context.Context, admission *Admission) *Refusal { + wipe := admission.Operation.(*ops.DeviceWipe) + reference := wipe.Spec.Authority.AllocationRef + if reference == nil { + return refuse(ReasonPlanMismatch, "a wipe names no allocation") + } + allocation := &metal.MachineAllocation{} + if err := admission.Reader.Get(ctx, client.ObjectKey{Namespace: wipe.Namespace, Name: reference.Name}, allocation); err != nil { + return refuse(ReasonPlanMismatch, "the wipe's allocation cannot be read: %v", err) + } + pin := allocation.Spec.CleaningPolicy + plan, err := cleaning.Plan(pin.Spec, allocation.Spec.Drives, cleaning.StorageOf(admission.Device), nil) + if err != nil { + return refuse(ReasonPlanMismatch, "the wipe cannot be planned: %v", err) + } + if wipe.Spec.Policy != pin.CleaningPolicyReference || wipe.Spec.Assurance != pin.Spec.Assurance || !equality.Semantic.DeepEqual(wipe.Spec.Drives, plan) { + return refuse(ReasonPlanMismatch, "the wipe's plan differs from the plan its allocation and current discovery give") + } + for _, d := range plan { + switch d.State { + case ops.DriveMissing: + return refuse(ReasonDriveMissing, "drive %s (%s) is pinned but discovery no longer reports it", d.Name, d.SerialNumber) + case ops.DriveUncovered: + return refuse(ReasonDriveUncovered, "no qualified method of the pinned policy cleans drive %s (%s)", d.Name, d.SerialNumber) + } + } + return nil +} + // 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 diff --git a/internal/registration/stage2_envtest_test.go b/internal/registration/stage2_envtest_test.go index 518b4d73..f807057d 100644 --- a/internal/registration/stage2_envtest_test.go +++ b/internal/registration/stage2_envtest_test.go @@ -137,6 +137,7 @@ func TestStageTwoEnablesRegisteredCapacity(t *testing.T) { CPU: metal.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: metal.MemoryRequirement{Capacity: "2Gi"}}, Authority: metal.AllocationAuthority{Principal: "fixture", Decision: "fixture"}, CleaningPolicy: ops.PinnedCleaningPolicy{CleaningPolicyReference: ops.CleaningPolicyReference{Name: policy.Name, Generation: policy.Generation, Digest: digest}, Spec: policy.Spec}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + Drives: []ops.ManifestDrive{{Name: "disk-0", SerialNumber: "fixture-orphan", Model: "fixture", Firmware: "v1", Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD, CapacityBytes: 1}}, }} if err := api.admin.Create(ctx, allocation); err != nil { t.Fatal(err) diff --git a/internal/site/fixture/discovery.go b/internal/site/fixture/discovery.go index ed8a20af..4b3d1a10 100644 --- a/internal/site/fixture/discovery.go +++ b/internal/site/fixture/discovery.go @@ -5,6 +5,7 @@ import ( "crypto/sha256" "encoding/hex" "errors" + "fmt" "strings" "time" @@ -103,12 +104,13 @@ const SimulatedDriveBytes = 2 << 30 // Drives is what fixture discovery reports for an enrolled Device: one // simulated NVMe drive per enrolled disk, in order, with a serial number -// derived from the Device and the disk. +// derived from the Device and the disk. Serial numbers sort in enrollment +// order, so the manifest names each drive as the site enrolls it. func Drives(device string, target Target) *inventory.ObservedStorage { out := &inventory.ObservedStorage{} - for _, disk := range target.Disks { + for i, disk := range target.Disks { sum := sha256.Sum256([]byte(device + "/" + disk)) - out.Drives = append(out.Drives, inventory.ObservedDrive{ID: disk, SerialNumber: "SIM-" + strings.ToUpper(hex.EncodeToString(sum[:6])), Model: SimulatedModel, + out.Drives = append(out.Drives, inventory.ObservedDrive{ID: disk, SerialNumber: fmt.Sprintf("SIM-%02d-%s", i, strings.ToUpper(hex.EncodeToString(sum[:6]))), Model: SimulatedModel, Firmware: "sim", Protocol: "NVMe", MediaType: "SSD", CapacityBytes: SimulatedDriveBytes}) } return out diff --git a/internal/site/fixture/discovery_test.go b/internal/site/fixture/discovery_test.go index 958ea3ed..0dcc4743 100644 --- a/internal/site/fixture/discovery_test.go +++ b/internal/site/fixture/discovery_test.go @@ -66,6 +66,12 @@ func TestSimulatedDrivesAreStableAndDistinct(t *testing.T) { if d := a.Drives[0]; d.Model != SimulatedModel || d.Protocol != "NVMe" || d.MediaType != "SSD" || d.CapacityBytes != SimulatedDriveBytes { t.Fatalf("drive = %+v", d) } + many := Drives("default/server-a", Target{Disks: []string{"disk-0", "disk-1", "disk-2", "disk-3", "disk-4", "disk-5", "disk-6", "disk-7", "disk-8", "disk-9", "disk-10"}}) + for i := 1; i < len(many.Drives); i++ { + if many.Drives[i-1].SerialNumber >= many.Drives[i].SerialNumber { + t.Fatalf("serials must sort in enrollment order: %s >= %s", many.Drives[i-1].SerialNumber, many.Drives[i].SerialNumber) + } + } if empty := Drives("default/server-c", Target{}); empty == nil || len(empty.Drives) != 0 { t.Fatal("a target with no disks reports a verified empty list") } diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index 3b03ec05..42bb5696 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -139,7 +139,7 @@ func TestAStaticSiteStoresNoReservation(t *testing.T) { if result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-static-install", 1, installSpec())); err != nil || result.Phase != ops.PhaseSucceeded { t.Fatalf("install: %+v, %v", result, err) } - wipe := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + wipe := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, Assurance: ops.AssuranceClear, Drives: []ops.PlannedDrive{overwriteDrive("disk-0")}, BootInterface: "primary"} if result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-static-wipe", 2, wipe)); err != nil || result.Phase != ops.PhaseSucceeded { t.Fatalf("wipe: %+v, %v", result, err) } @@ -170,7 +170,7 @@ func TestABootAddressMustFitTheSiteDHCP(t *testing.T) { m := newLab(t) s := runner(t, m) synced(s) - wipe := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + wipe := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, Assurance: ops.AssuranceClear, Drives: []ops.PlannedDrive{overwriteDrive("disk-0")}, BootInterface: "primary"} result, _ = s.Run(context.Background(), assignment(m, "DeviceWipe", "op-no-address", 1, wipe)) if result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonBootNetworkRequired || m.onCount() != 0 { t.Fatalf("synced site without an address: %+v", result) diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index c53bf9a3..537981d4 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -240,7 +240,11 @@ func (k Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { if refusal := k.checkBootNetwork(work, spec.BootNetwork); refusal != nil { return refusal } - return checkTarget(work, spec.TargetDisks, wipePhases) + names, ok := spec.OverwriteDrives() + if !ok { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "this site cleans only by overwriting every planned drive and reading it back"} + } + return checkTarget(work, names, wipePhases) } // checkBootNetwork requires a boot address exactly at a synchronized site, diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 6fb0e5ee..3cd07857 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -430,7 +430,7 @@ func TestNetworkBootNeedsNoWorkerIdentity(t *testing.T) { if result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-nb-identity", 1, installSpec())); err != nil || result.Phase != ops.PhaseSucceeded { t.Fatalf("install = %+v, %v", result, err) } - spec := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + spec := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, Assurance: ops.AssuranceClear, Drives: []ops.PlannedDrive{overwriteDrive("disk-0")}, BootInterface: "primary"} if result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-wipe-identity", 2, spec)); err != nil || result.Phase != ops.PhaseSucceeded { t.Fatalf("wipe = %+v, %v", result, err) } @@ -439,7 +439,7 @@ func TestNetworkBootNeedsNoWorkerIdentity(t *testing.T) { func TestWipeChecksTheEnrolledDisk(t *testing.T) { l := newLab(t) r := runner(t, l) - spec := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + spec := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, BootInterface: "primary", Assurance: ops.AssuranceClear, Drives: []ops.PlannedDrive{overwriteDrive("disk-0")}} result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-wipe", 1, spec)) if err != nil { t.Fatal(err) @@ -450,7 +450,7 @@ func TestWipeChecksTheEnrolledDisk(t *testing.T) { // A disk the site does not enroll is refused before anything is sent. m := newLab(t) s := runner(t, m) - spec.TargetDisks = []string{"disk-1"} + spec.Drives = []ops.PlannedDrive{overwriteDrive("disk-1")} result, _ = s.Run(context.Background(), assignment(m, "DeviceWipe", "op-wipe-other", 1, spec)) if result.Phase != ops.PhaseFailed || result.Reason != ReasonTargetDisks || m.onCount() != 0 { t.Fatalf("result = %+v", result) @@ -589,6 +589,13 @@ func TestAServerThatNeverPowersOffEndsTheStep(t *testing.T) { } } +// overwriteDrive is one planned drive the site cleans by overwriting it and +// reading it back. +func overwriteDrive(name string) ops.PlannedDrive { + return ops.PlannedDrive{ManifestDrive: ops.ManifestDrive{Name: name, SerialNumber: "EXAMPLE-SN-0001", Model: "EXAMPLE-NVME", Firmware: "EX1", Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD, CapacityBytes: 2 << 30, Rule: "nvme-ssd"}, + Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: &ops.VerifySpec{Mode: ops.VerifyFull}} +} + // TestTheInstallerVerifiesBootstrapDataOverRedfish: the network boot loads // the seed, and the install succeeds only if the installer reports the // admitted data's salted digest after reading it back from the disk. A diff --git a/internal/site/simwork/kinds.go b/internal/site/simwork/kinds.go index e7963523..48e3fc0f 100644 --- a/internal/site/simwork/kinds.go +++ b/internal/site/simwork/kinds.go @@ -201,7 +201,11 @@ func (Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { if refusal := custody.NoBootNetwork(spec.BootNetwork); refusal != nil { return refusal } - return checkDisks(work, spec.TargetDisks) + names, ok := spec.OverwriteDrives() + if !ok { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "this site cleans only by overwriting every planned drive and reading it back"} + } + return checkDisks(work, names) } func (Wipe) Run(ctx context.Context, work *site.Work) (any, error) { @@ -225,7 +229,12 @@ func (Wipe) Run(ctx context.Context, work *site.Work) (any, error) { at, _ := work.JournaledAt(step.Name) return ops.WipeEvidence{ Steps: []ops.StepEvidence{{Name: step.Name, CompletedAt: metav1.NewTime(at.UTC())}}, - WipedDisks: slices.Clone(spec.TargetDisks), + WipedDisks: driveNames(spec), PolicyDigest: spec.Policy.Digest, }, nil } + +func driveNames(spec ops.DeviceWipeSpec) []string { + names, _ := spec.OverwriteDrives() + return names +} diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 7609ef72..c77fc212 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -519,7 +519,11 @@ func (k Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { if refusal := custody.NoBootNetwork(spec.BootNetwork); refusal != nil { return refusal } - return enrolled(work, spec.TargetDisks) + names, ok := spec.OverwriteDrives() + if !ok { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "this site cleans only by overwriting every planned drive and reading it back"} + } + return enrolled(work, names) } // Run deletes every installation disk of the Device. A disk whose domain @@ -609,5 +613,10 @@ func (k Wipe) Run(ctx context.Context, work *site.Work) (any, error) { return nil, &custody.Refusal{Reason: site.ReasonStep, Message: "a disk remained after the wipe"} } at, _ := work.JournaledAt(step.Name) - return ops.WipeEvidence{Steps: []ops.StepEvidence{{Name: step.Name, CompletedAt: metav1.NewTime(at.UTC())}}, WipedDisks: spec.TargetDisks, PolicyDigest: spec.Policy.Digest}, nil + return ops.WipeEvidence{Steps: []ops.StepEvidence{{Name: step.Name, CompletedAt: metav1.NewTime(at.UTC())}}, WipedDisks: wipedDrives(spec), PolicyDigest: spec.Policy.Digest}, nil +} + +func wipedDrives(spec ops.DeviceWipeSpec) []string { + names, _ := spec.OverwriteDrives() + return names } diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index d330311f..020961db 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -236,7 +236,7 @@ func installSpec() ops.DeviceInstallationSpec { } func wipeSpec() ops.DeviceWipeSpec { - return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + key}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + key}, BootInterface: "primary", Assurance: ops.AssuranceClear, Drives: []ops.PlannedDrive{overwriteDrive("disk-0")}} } // TestAUEFIOnlyImageSendsNothing refuses an image the local guest's BIOS @@ -442,6 +442,13 @@ func TestAFailedNetworkBootClosesItsAdmission(t *testing.T) { } } +// overwriteDrive is one planned drive the site cleans by overwriting it and +// reading it back. +func overwriteDrive(name string) ops.PlannedDrive { + return ops.PlannedDrive{ManifestDrive: ops.ManifestDrive{Name: name, SerialNumber: "EXAMPLE-SN-0001", Model: "EXAMPLE-NVME", Firmware: "EX1", Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD, CapacityBytes: 2 << 30, Rule: "nvme-ssd"}, + Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: &ops.VerifySpec{Mode: ops.VerifyFull}} +} + // sealedInstall is an install whose admitted inputs name a sealed payload, // with the payload stored at the site as the site API stores it. func (r *rig) sealedInstall(uid string, fence int64) (site.Assignment, site.Payload) {