diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 881aad4d..e184cd8e 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -89,6 +89,41 @@ spec: minLength: 1 maxLength: 63 x-kubernetes-list-type: set + disposedDrives: + type: array + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - name + items: + type: object + properties: + name: + type: string + pattern: ^disk-[0-9]+$ + maxLength: 12 + serialNumber: + type: string + maxLength: 253 + method: + type: string + enum: + - Destroyed + - Removed + reference: + type: string + minLength: 1 + maxLength: 256 + recovery: + type: string + minLength: 1 + maxLength: 253 + required: + - name + - serialNumber + - method + - reference + - recovery required: - type x-kubernetes-validations: @@ -96,6 +131,8 @@ spec: 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 + - rule: self.type == 'Release' || !has(self.disposedDrives) || size(self.disposedDrives) == 0 + message: only Release records disposed drives fence: type: integer format: int64 @@ -322,6 +359,31 @@ spec: retryName: type: string maxLength: 253 + drives: + type: array + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - name + items: + type: object + properties: + name: + type: string + pattern: ^disk-[0-9]+$ + maxLength: 12 + serialNumber: + type: string + maxLength: 253 + state: + type: string + enum: + - Missing + - Uncovered + required: + - name + - serialNumber + - state waiting: type: object properties: @@ -1365,6 +1427,7 @@ spec: - Retry - Retire - Resolve + - DisposeDrive hold: type: object properties: @@ -1418,6 +1481,26 @@ spec: required: - method - reference + drive: + type: object + properties: + name: + type: string + pattern: ^disk-[0-9]+$ + maxLength: 12 + method: + type: string + enum: + - Destroyed + - Removed + reference: + type: string + minLength: 1 + maxLength: 256 + required: + - name + - method + - reference resolve: type: object properties: @@ -1451,9 +1534,11 @@ spec: - 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 + message: Settle, Retry, Retire and DisposeDrive name the hold - rule: '!has(self.diskDisposal) || self.decision == ''Retire''' message: only Retire records disk disposal + - rule: (self.decision == 'DisposeDrive') == has(self.drive) + message: drive is set exactly for DisposeDrive status: type: object properties: diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 4102258f..0c7d7a6f 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -797,6 +797,8 @@ guarded, and a test fails if its guard is removed: | 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` | +| Wipe, against a drive disposal | `DisposeDrive` reads the held drives custody recorded with the hold, never the wipe object | `TestWipeAdmissionChecksThePlan` (a wipe recreated under the held wipe's name) | +| Wipe, after rebuild | A rebuilt hold records no drives, so `DisposeDrive` is refused | `TestARebuiltHoldCannotBeDisposed` | | 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` | @@ -871,12 +873,41 @@ lab's targets each have one emulated NVMe drive. 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`. +- **Missing and uncovered drives.** While a planned drive is `Missing` or + `Uncovered`, the release controller sets the allocation's `Cleaning` + condition to `False` with reason `DriveMissing` or `DriveUncovered`, and + waits 10 minutes (the allocator's `CleaningGrace`) for discovery to report + the drive again. A brief gap in discovery therefore spends no wipe step and + pages nobody. After the grace it creates the wipe. Admission checks its + plan, then admits it and ends it `OutcomeUnknown` with that reason in the + same custody update (a kind's `HoldOnAdmit`), so the fence rises, nothing is + delivered, and the server is under a recovery hold. If that wipe was + settling an installation hold, the drive hold replaces it: every drive the + installation could have written is then wiped by a later step or recorded + as disposed of, which is what settling it requires. A rebuild holds the + installation again, which fails closed. Each blocked plan gets its own + grace: settling a drive hold restarts it. +- **DisposeDrive.** A `DeviceRecovery` with decision `DisposeDrive` names the + hold, the drive, and how it was destroyed or removed, with a reference. It + is admitted only from a `Release` holder under that hold, for a drive the + held wipe planned as `Missing` or `Uncovered` and that discovery no longer + reports, so an uncovered drive is pulled first. When it forms the hold, the + coordinator records in custody, with the hold, each drive the wipe could + not clean, by name, serial number and state. `DisposeDrive` reads only that + record, never the wipe object, so a wipe recreated under the same name, + which never matches custody, cannot authorize a disposal. Discovery proves only that + no drive reports the planned serial number; for a drive whose serial + changed, the recorded method and reference are the proof. Retry is refused for this + hold, because a retried wipe would plan the same drive. Like every + recovery, it applies once the sites report its fence. It clears the hold + and records the drive in custody's `holder.disposedDrives`; the planner + omits it only while its serial number remains absent. If discovery reports + the serial again, the planner marks it `Uncovered` and the normal drive + hold applies after the grace period. If every pinned drive was disposed + of and discovery reports no drives, no wipe remains and the `Cleaning` gate + closes. The record ends when the holder leaves `Release`; rebuilt custody + does not have it, so staff record the disposal again. The recovery operator + role, which creates `DeviceRecovery`, can record it. - **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' @@ -885,7 +916,7 @@ lab's targets each have one emulated NVMe drive. 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`. +and the plan-derived deadline. ### Cutover decisions diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 5140579f..fa78ec9e 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -19,6 +19,7 @@ import ( "slices" "sort" "strings" + "time" apierrors "k8s.io/apimachinery/pkg/api/errors" apiMeta "k8s.io/apimachinery/pkg/api/meta" @@ -148,6 +149,11 @@ type Allocator struct { // in it too. Namespace string Quota Quota + // CleaningGrace is how long release waits for a drive it cannot clean + // before it holds the server for staff. Nil means DefaultCleaningGrace. + CleaningGrace *time.Duration + // Now is the clock; nil means time.Now. + Now func() time.Time // Capacity decides which capacity may be offered. Capacity Offers // BootInterface and TargetDisks are pinned on each allocation. diff --git a/internal/allocation/cleaning_test.go b/internal/allocation/cleaning_test.go index 2fb13fec..08ed47b1 100644 --- a/internal/allocation/cleaning_test.go +++ b/internal/allocation/cleaning_test.go @@ -2,8 +2,10 @@ package allocation import ( "errors" + "slices" "strings" "testing" + "time" apierrors "k8s.io/apimachinery/pkg/api/errors" apiMeta "k8s.io/apimachinery/pkg/api/meta" @@ -313,3 +315,156 @@ func TestAWipeIsNeverPlannedForARecreatedDevice(t *testing.T) { t.Fatalf("no wipe may be created for a recreated Device: %v", err) } } + +// TestAPulledDriveIsDisposedAndReleaseFinishes holds the server once a pinned +// drive stays missing past the grace, and finishes release after staff record +// the drive's disposal. +func TestAPulledDriveIsDisposedAndReleaseFinishes(t *testing.T) { + testDriveDisposal(t, false) +} + +func TestReturnedDisposedDriveHoldsReleaseDespiteRetryLineage(t *testing.T) { + testDriveDisposal(t, true) +} + +func testDriveDisposal(t *testing.T, returns bool) { + t.Helper() + e := startEnv(t) + device := e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + zero := time.Duration(0) + e.allocator.CleaningGrace = &zero + pulled := e.device(device.Name) + original := pulled.Status.Discovery.Inventory.Systems[0].Storage.Drives + pulled.Status.Discovery.Inventory.Systems[0].Storage.Drives = nil + if err := e.admin.Status().Update(e.ctx, pulled); err != nil { + t.Fatal(err) + } + var hold *ops.RecoveryHold + e.until("the release holds the server for the missing drive", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + t.Fatal(err) + } + if _, err := e.allocator.Release(e.ctx, allocation, machine(1)); err != nil && !errors.Is(err, ErrCleaningBlocked) { + t.Logf("release: %v", err) + } + hold = e.custody(device.Name).Spec.RecoveryHold + return hold != nil && hold.Reason == custody.ReasonDriveMissing + }) + staff := ops.Creator{Username: "staff-example@example.com", UID: uid(803)} + recovery := &ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: "dispose-", Namespace: namespace, Labels: map[string]string{ops.LabelDeviceUID: string(device.UID)}}, Spec: ops.DeviceRecoverySpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: staff, DeviceRef: ops.DeviceReference{Name: device.Name}, + Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "drive pulled during the allocation"}}}, + Decision: ops.DecisionDisposeDrive, + Hold: &ops.HeldOperationReference{Kind: hold.Kind, Name: hold.Name, Fence: hold.Fence}, + Evidence: ops.RecoveryEvidence{ObservedAt: metav1.Now(), Summary: "drive destroyed after removal"}, + Drive: &ops.DriveDisposal{Name: "disk-0", Method: ops.DisposalDestroyed, Reference: "ticket-example-1"}, + }} + e.create(recovery) + if returns { + e.until("disposal recorded before the next release pass", func() bool { + state := e.custody(device.Name) + return state.Spec.RecoveryHold == nil && len(state.Spec.Holder.DisposedDrives) == 1 + }) + current := e.device(device.Name) + current.Status.Discovery.Inventory.Systems[0].Storage.Drives = original + if err := e.admin.Status().Update(e.ctx, current); err != nil { + t.Fatal(err) + } + e.until("returned serial produces an uncovered drive hold", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + t.Fatal(err) + } + if done, err := e.allocator.Release(e.ctx, allocation, machine(1)); done || (err != nil && !errors.Is(err, ErrCleaningBlocked)) { + t.Fatalf("release with returned drive = %v, %v", done, err) + } + newHold := e.custody(device.Name).Spec.RecoveryHold + return newHold != nil && newHold.Reason == custody.ReasonDriveUncovered + }) + state := e.custody(device.Name) + if state.Spec.Holder.Type != ops.HolderRelease || !slices.Contains(state.Spec.Holder.OpenGates, ops.GateCleaning) || + !slices.Contains(state.Spec.RecoveryHold.Drives, ops.HeldDrive{Name: "disk-0", SerialNumber: original[0].SerialNumber, State: ops.DriveUncovered}) { + t.Fatalf("wrong custody for returned drive: %+v", state.Spec) + } + state.Spec.RecoveryHold.RetryName = hold.Name + before := *allocation.Status.Wipe + if done, err := e.allocator.clean(e.ctx, state, allocation); done || err != nil || *allocation.Status.Wipe != before { + t.Fatalf("retry lineage advanced held wipe: done=%v err=%v wipe=%+v, want %+v", done, err, allocation.Status.Wipe, before) + } + return + } + e.release(allocation, machine(1)) + state := e.custody(device.Name) + if state.Spec.Holder.Type != ops.HolderNone || len(state.Spec.Holder.DisposedDrives) != 0 { + t.Fatalf("after release: holder %+v", state.Spec.Holder) + } +} + +// TestEachBlockedDriveGetsItsOwnGrace waits the full grace for a second drive +// that cannot be cleaned after staff disposed of the first, instead of +// holding the server at once. +func TestEachBlockedDriveGetsItsOwnGrace(t *testing.T) { + e := startEnv(t) + e.disks = []string{"disk-0", "disk-1"} + device := e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + now := time.Now() + e.allocator.Now = func() time.Time { return now } + all := 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) + } + } + step := func() error { + t.Helper() + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + t.Fatal(err) + } + _, err := e.allocator.Release(e.ctx, allocation, machine(1)) + return err + } + // disk-1 goes missing: release waits within the grace. + setDrives(all[0]) + e.until("release waits for disk-1", func() bool { return errors.Is(step(), ErrCleaningBlocked) }) + // Past the grace, the server is held for disk-1. + now = now.Add(DefaultCleaningGrace + time.Minute) + var hold *ops.RecoveryHold + e.until("the server is held for disk-1", func() bool { + _ = step() + hold = e.custody(device.Name).Spec.RecoveryHold + return hold != nil && hold.Reason == custody.ReasonDriveMissing + }) + e.create(&ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: "dispose-", Namespace: namespace, Labels: map[string]string{ops.LabelDeviceUID: string(device.UID)}}, Spec: ops.DeviceRecoverySpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: ops.Creator{Username: "staff-example@example.com", UID: uid(803)}, DeviceRef: ops.DeviceReference{Name: device.Name}, + Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "disk-1 pulled"}}}, + Decision: ops.DecisionDisposeDrive, Hold: &ops.HeldOperationReference{Kind: hold.Kind, Name: hold.Name, Fence: hold.Fence}, + Evidence: ops.RecoveryEvidence{ObservedAt: metav1.Now(), Summary: "destroyed"}, + Drive: &ops.DriveDisposal{Name: "disk-1", Method: ops.DisposalDestroyed, Reference: "ticket-example-2"}, + }}) + e.until("the disposal clears the hold", func() bool { return e.custody(device.Name).Spec.RecoveryHold == nil }) + // Now disk-0 goes missing as well. Release must wait a fresh grace + // rather than hold the server at once. + setDrives() + e.until("release waits for disk-0", func() bool { return errors.Is(step(), ErrCleaningBlocked) }) + for range 3 { + if err := step(); !errors.Is(err, ErrCleaningBlocked) { + t.Fatalf("release = %v, want it still waiting within the grace", err) + } + } + if hold := e.custody(device.Name).Spec.RecoveryHold; hold != nil { + t.Fatalf("held within the grace: %+v", hold) + } + // disk-0 returns, and release finishes with disk-1 disposed of. + setDrives(all[0]) + e.release(allocation, machine(1)) +} diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index b7443e11..7febdfb8 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -55,6 +55,9 @@ func uid(n int) string { return fmt.Sprintf("00000000-0000-4000-8000-%012d", n) // env is a real API server with the metal, inventory and custody CRDs, one // simulator site behind its HTTP API, and the coordinator loop. type env struct { + // disks are the disks the site enrolls for each new server; empty means + // disk-0. + disks []string t *testing.T ctx context.Context admin client.Client @@ -198,7 +201,7 @@ func (e *env) server(n int) *inventory.Device { }} e.create(device) key := fmt.Sprintf("%064x", n) - e.enrollment[namespace+"/"+name] = fixture.Target{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: uid(100 + n), BootMACAddress: mac, BMCPublicKeySHA256: key, Disks: []string{"disk-0"}, + e.enrollment[namespace+"/"+name] = fixture.Target{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: uid(100 + n), BootMACAddress: mac, BMCPublicKeySHA256: key, Disks: e.diskNames(), Hardware: &ops.InspectedHardware{BootMode: fleetv1.FirmwareUEFI, CPU: ops.InspectedCPU{Architecture: "amd64", Cores: 2}, Memory: "2Gi", Disks: []ops.InspectedDisk{{Name: "disk-0", Capacity: "2Gi"}}, Interfaces: []ops.InspectedInterface{{Name: "primary", MACAddress: mac}}}} e.loop.Courier.Sites.Devices[name] = []string{siteName} capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "capacity-" + name, Namespace: namespace, Labels: map[string]string{"pool": "example"}}, @@ -364,3 +367,11 @@ func (e *env) addDrive(name, disk string) { e.t.Fatal(err) } } + +// diskNames are the disks the site enrolls for each new server. +func (e *env) diskNames() []string { + if len(e.disks) == 0 { + return []string{"disk-0"} + } + return e.disks +} diff --git a/internal/allocation/release.go b/internal/allocation/release.go index 0ab0579c..5a31c5fb 100644 --- a/internal/allocation/release.go +++ b/internal/allocation/release.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "slices" + "time" apierrors "k8s.io/apimachinery/pkg/api/errors" apiMeta "k8s.io/apimachinery/pkg/api/meta" @@ -38,10 +39,16 @@ const ConditionCleaning = "Cleaning" 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. +// report a pinned drive, or reports one no method covers. For the +// allocator's CleaningGrace no wipe is created, so a brief gap in discovery +// spends no wipe step; after it the wipe is created, and admission holds it +// for staff to settle with DisposeDrive. var ErrCleaningBlocked = errors.New("a drive cannot be cleaned") +// DefaultCleaningGrace is how long release waits for a drive it cannot clean +// to reappear before it holds the server for staff. +const DefaultCleaningGrace = 10 * time.Minute + // 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 @@ -316,12 +323,12 @@ func (a *Allocator) installing(ctx context.Context, state *ops.DeviceCustody, al func (a *Allocator) clean(ctx context.Context, state *ops.DeviceCustody, allocation *fleetv1.MachineAllocation) (bool, error) { current := allocation.Status.Wipe if current == nil { - return false, a.wipe(ctx, allocation, fleetv1.WipeReference{Name: custody.WipeName(allocation.Name, 1), Step: 1}) + return a.startWipe(ctx, allocation, fleetv1.WipeReference{Name: custody.WipeName(allocation.Name, 1), Step: 1}) } wipe := &ops.DeviceWipe{} if err := a.Releaser.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: current.Name}, wipe); apierrors.IsNotFound(err) { // The status was written but the create was lost. - return false, a.wipe(ctx, allocation, *current) + return a.startWipe(ctx, allocation, *current) } else if err != nil { return false, err } @@ -337,16 +344,50 @@ func (a *Allocator) clean(ctx context.Context, state *ops.DeviceCustody, allocat return false, fmt.Errorf("%w: %s: %s", ErrWipeFailed, wipe.Status.Reason, wipe.Status.Message) } step := current.Step + 1 - return false, a.wipe(ctx, allocation, fleetv1.WipeReference{Name: custody.WipeName(allocation.Name, step), Step: step}) + return a.startWipe(ctx, allocation, fleetv1.WipeReference{Name: custody.WipeName(allocation.Name, step), Step: step}) case ops.PhaseOutcomeUnknown: hold := state.Spec.RecoveryHold - if hold != nil && hold.Kind == "DeviceWipe" && hold.Name == current.Name && hold.RetryName != "" { - return false, a.wipe(ctx, allocation, fleetv1.WipeReference{Name: hold.RetryName, Step: current.Step + 1}) + drives := wipe.Status.Reason == custody.ReasonDriveMissing || wipe.Status.Reason == custody.ReasonDriveUncovered + // A drive hold is settled by DisposeDrive, never by a Retry, even + // when it carries the lineage of a retried wipe. + if !drives && hold != nil && hold.Kind == "DeviceWipe" && hold.Name == current.Name && hold.RetryName != "" { + return a.startWipe(ctx, allocation, fleetv1.WipeReference{Name: hold.RetryName, Step: current.Step + 1}) + } + // A wipe held for a drive it could not clean, whose hold staff + // settled with DisposeDrive: plan the next step without that drive. + held := hold != nil && hold.Kind == "DeviceWipe" && hold.Name == current.Name + if !held && drives { + if current.Step >= maxPlanSteps { + return false, fmt.Errorf("%w: %s", ErrWipeFailed, wipe.Status.Reason) + } + // Restart the grace: another drive that cannot be cleaned now + // gets its own wait before it holds the server again. + if apiMeta.RemoveStatusCondition(&allocation.Status.Conditions, ConditionCleaning) { + if err := a.Provider.Status().Update(ctx, allocation); err != nil { + return false, err + } + } + step := current.Step + 1 + return a.startWipe(ctx, allocation, fleetv1.WipeReference{Name: custody.WipeName(allocation.Name, step), Step: step}) } } return false, nil } +// startWipe creates the next wipe and reports whether cleaning is done +// without one: every pinned drive was disposed of, so no drive is left whose +// data a wipe could reach. +func (a *Allocator) startWipe(ctx context.Context, allocation *fleetv1.MachineAllocation, reference fleetv1.WipeReference) (bool, error) { + err := a.wipe(ctx, allocation, reference) + if errors.Is(err, errNothingToClean) { + return true, nil + } + return false, err +} + +// errNothingToClean means every drive the plan would cover was disposed of. +var errNothingToClean = errors.New("every pinned drive was disposed of") + // 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) { @@ -380,20 +421,34 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat if string(device.UID) != allocation.Labels[fleetv1.LabelDeviceUID] { return fmt.Errorf("%w: the Device is another incarnation", ErrCustodyLost) } + state := &ops.DeviceCustody{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: allocation.Spec.DeviceRef.Name}, state); err != nil { + return err + } pin := allocation.Spec.CleaningPolicy - plan, err := cleaning.Plan(pin.Spec, allocation.Spec.Drives, cleaning.StorageOf(device), nil) + plan, err := cleaning.Plan(pin.Spec, allocation.Spec.Drives, cleaning.StorageOf(device), custody.DisposedDriveNames(state)) if err != nil { return fmt.Errorf("plan the wipe: %w", err) } + if len(plan) == 0 { + return errNothingToClean + } if blocked := blockedReason(plan); blocked != nil { + // The grace runs on the allocator's clock from when the plan first + // blocked. + blocked.LastTransitionTime = metav1.NewTime(a.now()) 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) { + since := apiMeta.FindStatusCondition(allocation.Status.Conditions, ConditionCleaning).LastTransitionTime.Time + if a.now().Sub(since) < a.cleaningGrace() { + return fmt.Errorf("%w: %s", ErrCleaningBlocked, blocked.Message) + } + // The drive has stayed uncleanable past the grace: create the wipe, + // and admission holds the server for staff. + } else if apiMeta.RemoveStatusCondition(&allocation.Status.Conditions, ConditionCleaning) { if err := a.Provider.Status().Update(ctx, allocation); err != nil { return err } @@ -458,6 +513,20 @@ func blockedReason(plan []ops.PlannedDrive) *metav1.Condition { return nil } +func (a *Allocator) cleaningGrace() time.Duration { + if a.CleaningGrace != nil { + return *a.CleaningGrace + } + return DefaultCleaningGrace +} + +func (a *Allocator) now() time.Time { + if a.Now != nil { + return a.Now() + } + return time.Now() +} + // 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/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 181bf6e1..d45495bd 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -104,11 +104,33 @@ type LocalReference struct { } // Holder is who holds the Device. AllocationRef is set only for Allocation -// and Release, and OpenGates only for Release. +// and Release, and OpenGates and DisposedDrives only for Release. type Holder struct { Type HolderType `json:"type"` AllocationRef *LocalReference `json:"allocationRef,omitempty"` OpenGates []ReleaseGate `json:"openGates,omitempty"` + // DisposedDrives are pinned drives staff recorded as destroyed or + // removed with DisposeDrive. The release's wipes omit them. The record + // ends when the holder leaves Release. + DisposedDrives []DisposedDrive `json:"disposedDrives,omitempty"` +} + +// HeldDrive is one drive a held wipe could not clean, as its plan named it. +type HeldDrive struct { + Name string `json:"name"` + SerialNumber string `json:"serialNumber"` + State DriveState `json:"state"` +} + +// DisposedDrive is one drive a DisposeDrive recovery settled. +type DisposedDrive struct { + Name string `json:"name"` + SerialNumber string `json:"serialNumber"` + Method DiskDisposalMethod `json:"method"` + Reference string `json:"reference"` + // Recovery names the DeviceRecovery that recorded the disposal, for + // audit. It is not a join key; recoveries get generated names. + Recovery string `json:"recovery"` } // OperationReference names an operation by kind and name. Custody always @@ -174,6 +196,10 @@ type RecoveryHold struct { Deadline *metav1.Time `json:"deadline,omitempty"` // Snapshot is the Device snapshot the held operation was admitted with. Snapshot *DeviceSnapshot `json:"snapshot,omitempty"` + // Drives are the drives a wipe held at admission could not clean. Only + // these can be settled with DisposeDrive, so a same-name wipe created + // later never authorizes a disposal. + Drives []HeldDrive `json:"drives,omitempty"` // RetryAuthorizedBy names the DeviceRecovery with Retry, and the fence it // was admitted at, that lets the held operation's requester create one // settling operation. @@ -523,6 +549,9 @@ const ( DecisionRetry RecoveryDecision = "Retry" DecisionRetire RecoveryDecision = "Retire" DecisionResolve RecoveryDecision = "Resolve" + // DecisionDisposeDrive records that a drive a held wipe could not clean + // was destroyed or removed, and clears that hold. + DecisionDisposeDrive RecoveryDecision = "DisposeDrive" ) type DeviceRecoverySpec struct { @@ -537,6 +566,16 @@ type DeviceRecoverySpec struct { DiskDisposal *DiskDisposal `json:"diskDisposal,omitempty"` // Resolve names the holder of Unverified custody. Resolve *ResolveInput `json:"resolve,omitempty"` + // Drive names the drive a DisposeDrive disposed of and how. Required for + // DisposeDrive only. + Drive *DriveDisposal `json:"drive,omitempty"` +} + +// DriveDisposal is how one drive a held wipe could not clean was disposed of. +type DriveDisposal struct { + Name string `json:"name"` + Method DiskDisposalMethod `json:"method"` + Reference string `json:"reference"` } // HeldOperationReference names an operation and the fence it was admitted diff --git a/internal/cleaning/plan.go b/internal/cleaning/plan.go index 24ea8282..714dd274 100644 --- a/internal/cleaning/plan.go +++ b/internal/cleaning/plan.go @@ -67,9 +67,10 @@ func Manifest(spec ops.CleaningPolicySpec, storage *inventory.ObservedStorage) ( } // 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 +// wipe, and admission uses it to check one. Every pinned drive gets a step +// unless it was disposed of and remains absent. A disposed serial reported +// again is Uncovered. Drives outside the manifest also get a step. +// 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 @@ -115,10 +116,13 @@ func Plan(policy ops.CleaningPolicySpec, manifest []ops.ManifestDrive, storage * for _, m := range manifest { pinned[m.SerialNumber] = true used[m.Name] = true + d, ok := current[m.SerialNumber] if slices.Contains(disposed, m.Name) { + if ok { + out = append(out, uncovered(ops.PlannedDrive{ManifestDrive: m})) + } continue } - d, ok := current[m.SerialNumber] switch { case !ok: out = append(out, ops.PlannedDrive{ManifestDrive: m, State: ops.DriveMissing}) diff --git a/internal/cleaning/plan_test.go b/internal/cleaning/plan_test.go index 3cde661f..64d1ad4b 100644 --- a/internal/cleaning/plan_test.go +++ b/internal/cleaning/plan_test.go @@ -72,6 +72,8 @@ func TestPlan(t *testing.T) { {"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:"}}, + {"disposed serial returns", storage(nvme("SN-B", "EX1.3"), nvme("SN-A", "EX1.3")), []string{"disk-1"}, []string{"disk-0=SN-A:", "disk-1=SN-B:Uncovered"}}, + {"all disposed serials return", storage(nvme("SN-A", "EX1.3"), nvme("SN-B", "EX1.3")), []string{"disk-0", "disk-1"}, []string{"disk-0=SN-A:Uncovered", "disk-1=SN-B:Uncovered"}}, {"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:"}}, @@ -140,3 +142,41 @@ func withCapacity(d inventory.ObservedDrive, bytes int64) inventory.ObservedDriv d.CapacityBytes = bytes return d } + +// TestPlanRequiresThePinnedIdentity marks a pinned drive Uncovered when its +// model, protocol, media type or capacity changed, even though a rule of the +// pinned policy would still clean the drive it reports now. +func TestPlanRequiresThePinnedIdentity(t *testing.T) { + overwrite := func(name string, protocol ops.DriveProtocol, media ops.MediaType) ops.CleaningRule { + return ops.CleaningRule{Name: name, Match: ops.DriveMatch{Protocol: protocol, MediaType: media}, Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: ops.VerifySpec{Mode: ops.VerifyFull}, TimePerTiB: hour} + } + policy := ops.CleaningPolicySpec{Assurance: ops.AssuranceClear, Rules: []ops.CleaningRule{ + overwrite("nvme-ssd", ops.ProtocolNVMe, ops.MediaSSD), overwrite("nvme-hdd", ops.ProtocolNVMe, ops.MediaHDD), overwrite("sata-ssd", ops.ProtocolSATA, ops.MediaSSD)}} + pinned := nvme("SN-A", "EX1.3") + manifest, err := Manifest(policy, storage(pinned)) + if err != nil { + t.Fatal(err) + } + for name, change := range map[string]func(*inventory.ObservedDrive){ + "unchanged": func(*inventory.ObservedDrive) {}, + "firmware": func(d *inventory.ObservedDrive) { d.Firmware = "EX9.9" }, + "model": func(d *inventory.ObservedDrive) { d.Model = "OTHER-MODEL" }, + "protocol": func(d *inventory.ObservedDrive) { d.Protocol = "SATA" }, + "media type": func(d *inventory.ObservedDrive) { d.MediaType = "HDD" }, + "capacity": func(d *inventory.ObservedDrive) { d.CapacityBytes = 1 << 30 }, + } { + now := pinned + change(&now) + plan, err := Plan(policy, manifest, storage(now), nil) + if err != nil { + t.Fatal(err) + } + want := ops.DriveState("") + if name != "unchanged" && name != "firmware" { + want = ops.DriveUncovered + } + if len(plan) != 1 || plan[0].State != want { + t.Errorf("%s: plan = %+v, want state %q", name, plan, want) + } + } +} diff --git a/internal/custody/cleaning_test.go b/internal/custody/cleaning_test.go index 02f7c3fd..0ac4a548 100644 --- a/internal/custody/cleaning_test.go +++ b/internal/custody/cleaning_test.go @@ -2,8 +2,10 @@ package custody import ( "fmt" + "slices" "testing" + apierrors "k8s.io/apimachinery/pkg/api/errors" "sigs.k8s.io/controller-runtime/pkg/client" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" @@ -45,9 +47,10 @@ func TestWipeAdmissionChecksThePlan(t *testing.T) { e.requireUntouched(device.Name, fence) }) - t.Run("a pinned drive discovery no longer reports is refused", func(t *testing.T) { + t.Run("a pinned drive discovery no longer reports holds the server until staff dispose of it", func(t *testing.T) { release(782, "alloc-dm") device := e.read("server-example-782") + saved := device.Status.Discovery.Inventory.Systems[0].Storage.Drives device.Status.Discovery.Inventory.Systems[0].Storage.Drives = nil if err := e.admin.Status().Update(e.ctx, device); err != nil { t.Fatal(err) @@ -63,8 +66,111 @@ func TestWipeAdmissionChecksThePlan(t *testing.T) { 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) + // Admitted and held in one update: the fence rose, nothing is + // active, so nothing was delivered. + e.requirePhase(wipe, ops.PhaseOutcomeUnknown, ReasonDriveMissing) + state := e.custody(device.Name) + if state.Spec.ActiveOperation != nil || state.Spec.Fence <= fence || state.Spec.RecoveryHold == nil || state.Spec.RecoveryHold.Name != wipe.Name || state.Spec.RecoveryHold.Reason != ReasonDriveMissing { + t.Fatalf("custody = %+v", state.Spec) + } + hold := *state.Spec.RecoveryHold + // A retried wipe would plan the same drive. + retry := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetry, Hold: heldRef(hold)}) + e.settle(device.Name) + e.requirePhase(retry, ops.PhaseFailed, ReasonNotRetryable) + // Only a drive the held wipe could not clean can be disposed of. + wrong := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionDisposeDrive, Hold: heldRef(hold), Drive: &ops.DriveDisposal{Name: "disk-7", Method: ops.DisposalDestroyed, Reference: "ticket-1"}}) + e.settle(device.Name) + e.requirePhase(wrong, ops.PhaseFailed, ReasonDisposalInvalid) + dispose := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionDisposeDrive, Hold: heldRef(hold), Drive: &ops.DriveDisposal{Name: "disk-0", Method: ops.DisposalRemoved, Reference: "ticket-2"}}) + e.settle(device.Name) + // Like every recovery, it applies once the site reports its fence. + e.sites.report(device.Name, e.custody(device.Name).Spec.Fence) + e.settle(device.Name) + e.requirePhase(dispose, ops.PhaseSucceeded, "") + state = e.custody(device.Name) + disposed := state.Spec.Holder.DisposedDrives + if state.Spec.RecoveryHold != nil || state.Spec.Holder.Type != ops.HolderRelease || len(disposed) != 1 || disposed[0].Name != "disk-0" || disposed[0].SerialNumber != saved[0].SerialNumber || disposed[0].Recovery != dispose.Name { + t.Fatalf("custody after DisposeDrive = %+v", state.Spec) + } + // The disposed drive is not planned again. + next := e.planWith(e.read(device.Name), "alloc-dm") + if len(next) != 0 { + t.Fatalf("the next plan must omit the disposed drive: %+v", next) + } + }) + + t.Run("a wipe recreated under the held wipe's name authorizes no disposal", func(t *testing.T) { + release(785, "alloc-dr") + device := e.read("server-example-785") + 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-dr") + newWipe := func(drives []ops.PlannedDrive) *ops.DeviceWipe { + wipe := &ops.DeviceWipe{} + wipe.Name, wipe.Namespace = WipeName("alloc-dr", 1), "default" + wipe.Labels = map[string]string{ops.LabelDeviceUID: string(device.UID)} + wipe.Spec = ops.DeviceWipeSpec{OperationEnvelope: envelope(device, releaseUser, allocated("alloc-dr")), Step: 1, + Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, BootInterface: "primary", Assurance: ops.AssuranceClear, Drives: drives} + return wipe + } + held := newWipe(plan) + e.create(held) + e.settle(device.Name) + e.requirePhase(held, ops.PhaseOutcomeUnknown, ReasonDriveMissing) + hold := *e.custody(device.Name).Spec.RecoveryHold + // Custody records the drives the held wipe could not clean. + if len(hold.Drives) != 1 || hold.Drives[0].Name != "disk-0" || hold.Drives[0].State != ops.DriveMissing || hold.Drives[0].SerialNumber != plan[0].SerialNumber { + t.Fatalf("hold drives = %+v", hold.Drives) + } + // The held wipe is deleted, and a new wipe under its name plans a + // drive the hold never held as missing. + if err := e.admin.Delete(e.ctx, held); err != nil { + t.Fatal(err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(held), &ops.DeviceWipe{}); !apierrors.IsNotFound(err) { + t.Fatalf("the held wipe must be gone: %v", err) + } + forged := slices.Clone(plan) + forged[0].Name, forged[0].SerialNumber = "disk-9", "EXAMPLE-SN-FORGED" + e.create(newWipe(forged)) + e.settle(device.Name) + dispose := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionDisposeDrive, Hold: heldRef(hold), Drive: &ops.DriveDisposal{Name: "disk-9", Method: ops.DisposalRemoved, Reference: "ticket-4"}}) + e.settle(device.Name) + e.requirePhase(dispose, ops.PhaseFailed, ReasonDisposalInvalid) + if state := e.custody(device.Name); state.Spec.RecoveryHold == nil || state.Spec.RecoveryHold.Name != hold.Name || len(state.Spec.Holder.DisposedDrives) != 0 { + t.Fatalf("custody = %+v", state.Spec) + } + }) + + t.Run("an uncovered drive still in the server cannot be disposed of", func(t *testing.T) { + release(784, "alloc-du") + device := e.read("server-example-784") + device.Status.Discovery.Inventory.Systems[0].Storage.Drives[0].Firmware = "UNQUALIFIED" + device.Status.Discovery.Inventory.Systems[0].Storage.Drives[0].Protocol = "SAS" + if err := e.admin.Status().Update(e.ctx, device); err != nil { + t.Fatal(err) + } + plan := e.planWith(device, "alloc-du") + if len(plan) != 1 || plan[0].State != ops.DriveUncovered { + t.Fatalf("plan = %+v", plan) + } + wipe := &ops.DeviceWipe{} + wipe.Name, wipe.Namespace = WipeName("alloc-du", 1), "default" + wipe.Spec = ops.DeviceWipeSpec{OperationEnvelope: envelope(device, releaseUser, allocated("alloc-du")), Step: 1, + Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, BootInterface: "primary", Assurance: ops.AssuranceClear, Drives: plan} + e.create(wipe) + e.settle(device.Name) + e.requirePhase(wipe, ops.PhaseOutcomeUnknown, ReasonDriveUncovered) + hold := *e.custody(device.Name).Spec.RecoveryHold + dispose := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionDisposeDrive, Hold: heldRef(hold), Drive: &ops.DriveDisposal{Name: "disk-0", Method: ops.DisposalDestroyed, Reference: "ticket-3"}}) + e.settle(device.Name) + e.requirePhase(dispose, ops.PhaseFailed, ReasonDisposalInvalid) + if e.custody(device.Name).Spec.RecoveryHold == nil { + t.Fatal("the hold must stay while the uncovered drive is in the server") + } }) t.Run("the planner's plan is admitted", func(t *testing.T) { @@ -96,7 +202,7 @@ func (e *env) planWith(device *inventory.Device, allocation string) []ops.Planne 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) + plan, err := cleaning.Plan(pinned.Spec.CleaningPolicy.Spec, pinned.Spec.Drives, cleaning.StorageOf(device), DisposedDriveNames(e.custody(device.Name))) if err != nil { e.t.Fatal(err) } diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index b0e0713f..3fb124a3 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -607,6 +607,9 @@ type decision struct { row Rule settles *ops.HeldOperationReference extra map[string]string + // hold, when set, admits the operation and ends it OutcomeUnknown at + // once with this reason. Nothing is delivered. + hold *Refusal // retry means a check could not decide; the operation waits and is // checked again. retry bool @@ -864,7 +867,16 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper return fail(ReasonSnapshotInvalid, "%s", err.Error()) } } - return decision{row: row, settles: settles, extra: extra} + var hold *Refusal + if kind.HoldOnAdmit != nil { + if refusal := kind.HoldOnAdmit(ctx, admission); refusal != nil { + if !c.Registry.Declared(kind.GVK.Kind, refusal.Reason, RaisedByCoordinator) { + return fail(ReasonUndeclared, "the %s hold reason %s is not declared", kind.GVK.Kind, refusal.Reason) + } + hold = refusal + } + } + return decision{row: row, settles: settles, extra: extra, hold: hold} } // waitingSince is when the operation could first have been admitted: when it @@ -1045,6 +1057,14 @@ func (c *Coordinator) admitOne(ctx context.Context, custody *ops.DeviceCustody, } } } + // An outcome already unproven is held in the same update, so the + // operation is never active and never delivered. + if d.hold != nil { + c.holdUnknown(custody, *active, d.hold.Reason, d.hold.Message, nil) + if kind.HeldDrives != nil { + spec.RecoveryHold.Drives = kind.HeldDrives(operation) + } + } outcome, err := c.writeCustody(ctx, custody) outcome.RequeueAfter = 0 return outcome, err diff --git a/internal/custody/dispose_test.go b/internal/custody/dispose_test.go new file mode 100644 index 00000000..84a50a27 --- /dev/null +++ b/internal/custody/dispose_test.go @@ -0,0 +1,23 @@ +package custody + +import ( + "context" + "testing" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// TestARebuiltHoldCannotBeDisposed refuses DisposeDrive under a hold that +// rebuild formed. A rebuilt hold has no record of which drives were held, so +// nothing could say which drive is disposed of. +func TestARebuiltHoldCannotBeDisposed(t *testing.T) { + custody := &ops.DeviceCustody{Spec: ops.DeviceCustodySpec{ + Holder: ops.Holder{Type: ops.HolderRelease, AllocationRef: &ops.LocalReference{Name: "alloc-r"}}, + RecoveryHold: &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceWipe", Name: "alloc-r-wipe-1"}, Fence: 4, Reason: ReasonRebuilt}, + }} + recovery := &ops.DeviceRecovery{Spec: ops.DeviceRecoverySpec{Decision: ops.DecisionDisposeDrive, + Drive: &ops.DriveDisposal{Name: "disk-0", Method: ops.DisposalRemoved, Reference: "ticket-r"}}} + if _, refusal := disposedDrive(context.Background(), recovery, custody, &Admission{}); refusal == nil || refusal.Reason != ReasonNotSettleable { + t.Fatalf("refusal = %+v, want NotSettleable", refusal) + } +} diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index a4347ccd..57fc5369 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -9,6 +9,7 @@ import ( "strconv" "time" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" metal "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/sealed" @@ -47,10 +48,13 @@ 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. + // A wipe plans a drive it cannot clean. The wipe is admitted and held + // at once: nothing is sent, and DisposeDrive settles the hold. ReasonDriveMissing = "DriveMissing" ReasonDriveUncovered = "DriveUncovered" + // A DisposeDrive names a drive the held wipe did not hold for, or one + // discovery still reports. + ReasonDisposalInvalid = "DisposalInvalid" // ReasonBootAddress means the boot address claim's source could not be // read. The operation waits and is checked again. ReasonBootAddress = "BootAddressUnavailable" @@ -273,9 +277,11 @@ func DeviceWipeKind() Kind { }, // 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: ReasonPlanMismatch, RaisedBy: RaisedByCoordinator}, {Name: ReasonDriveMissing, RaisedBy: RaisedByCoordinator}, {Name: ReasonDriveUncovered, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryMismatch, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryNotOffered, RaisedBy: RaisedByCoordinator}}, networkBootReasons...), workerReasons...), + HoldOnAdmit: holdUncleanableDrive, + HeldDrives: heldDrives, + Settles: []SettleRule{{Held: "DeviceInstallation"}, {Held: "DeviceWipe", RequiresRetry: true}}, + Retryable: true, + 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") @@ -300,14 +306,21 @@ func checkWipePlan(ctx context.Context, admission *Admission) *Refusal { 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) + plan, err := cleaning.Plan(pin.Spec, allocation.Spec.Drives, cleaning.StorageOf(admission.Device), DisposedDriveNames(admission.Custody)) 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 { + return nil +} + +// holdUncleanableDrive holds a wipe whose checked plan has a drive it cannot +// clean: Fleet cannot account for that drive's data, so the outcome is +// already unknown. Nothing is sent. +func holdUncleanableDrive(_ context.Context, admission *Admission) *Refusal { + for _, d := range admission.Operation.(*ops.DeviceWipe).Spec.Drives { switch d.State { case ops.DriveMissing: return refuse(ReasonDriveMissing, "drive %s (%s) is pinned but discovery no longer reports it", d.Name, d.SerialNumber) @@ -318,6 +331,35 @@ func checkWipePlan(ctx context.Context, admission *Admission) *Refusal { return nil } +// DisposedDriveNames returns the drives a Release holder records as disposed. +func DisposedDriveNames(custody *ops.DeviceCustody) []string { + var names []string + if custody != nil && custody.Spec.Holder.Type == ops.HolderRelease { + for _, d := range custody.Spec.Holder.DisposedDrives { + names = append(names, d.Name) + } + } + return names +} + +// heldDrives returns the drives a wipe's plan cannot clean, which custody +// records with the hold. +func heldDrives(operation ops.Operation) []ops.HeldDrive { + var out []ops.HeldDrive + for _, d := range operation.(*ops.DeviceWipe).Spec.Drives { + if d.State != "" { + out = append(out, ops.HeldDrive{Name: d.Name, SerialNumber: d.SerialNumber, State: d.State}) + } + } + return out +} + +// drivesHold reports whether a hold is a wipe held for a drive it could not +// clean, which only DisposeDrive or Retire settles. +func drivesHold(hold *ops.RecoveryHold) bool { + return hold != nil && hold.Kind == "DeviceWipe" && (hold.Reason == ReasonDriveMissing || hold.Reason == ReasonDriveUncovered) +} + // 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 @@ -337,7 +379,8 @@ func DeviceRecoveryKind() Kind { 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}}, + {Name: ReasonRetryAuthorized, RaisedBy: RaisedByCoordinator}, {Name: ReasonDisposalRequired, RaisedBy: RaisedByCoordinator}, {Name: ReasonInvalidResolve, RaisedBy: RaisedByCoordinator}, + {Name: ReasonDisposalInvalid, 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 { @@ -350,7 +393,7 @@ func DeviceRecoveryKind() Kind { Apply: applyRecovery, Clears: func(operation ops.Operation) *ops.HeldOperationReference { spec := operation.(*ops.DeviceRecovery).Spec - if spec.Decision == ops.DecisionSettle || spec.Decision == ops.DecisionRetire { + if spec.Decision == ops.DecisionSettle || spec.Decision == ops.DecisionRetire || spec.Decision == ops.DecisionDisposeDrive { return spec.Hold } return nil @@ -394,6 +437,9 @@ func checkRecovery(ctx context.Context, recovery *ops.DeviceRecovery, custody *o } return held.RecoverySettle(ctx, &RecoverySettleContext{Hold: *hold, Recovery: recovery, Device: admission.Device, Custody: custody, Now: admission.Now}) case ops.DecisionRetry: + if drivesHold(hold) { + return refuse(ReasonNotRetryable, "a retried wipe would plan the same drive; record DisposeDrive or retire the server") + } if hold.RetryAuthorizedBy != nil { return refuse(ReasonRetryAuthorized, "a retry is already authorized for this hold") } @@ -413,10 +459,44 @@ func checkRecovery(ctx context.Context, recovery *ops.DeviceRecovery, custody *o return refuse(ReasonDisposalRequired, "retiring from Release records how the disks were disposed of") } return nil + case ops.DecisionDisposeDrive: + _, refusal := disposedDrive(ctx, recovery, custody, admission) + return refusal } return refuse(ReasonCreatorNotPermitted, "unknown decision %q", spec.Decision) } +// disposedDrive checks a DisposeDrive and returns the disposed drive's serial +// number. The hold must be a wipe held for drives it could not clean, the +// holder Release, and the drive one that custody recorded with that hold and +// that is not already disposed of. Discovery must no longer report it: an +// uncovered drive is pulled before its disposal is recorded. +func disposedDrive(_ context.Context, recovery *ops.DeviceRecovery, custody *ops.DeviceCustody, admission *Admission) (string, *Refusal) { + hold, drive := custody.Spec.RecoveryHold, recovery.Spec.Drive + switch { + case !drivesHold(hold): + return "", refuse(ReasonNotSettleable, "DisposeDrive settles only a wipe held for a drive it could not clean") + case custody.Spec.Holder.Type != ops.HolderRelease: + return "", refuse(ReasonDisposalInvalid, "DisposeDrive applies only while the server is in Release") + case drive == nil || drive.Reference == "": + return "", refuse(ReasonDisposalInvalid, "DisposeDrive names the drive and a disposal reference") + case slices.Contains(DisposedDriveNames(custody), drive.Name): + return "", refuse(ReasonDisposalInvalid, "drive %s is already disposed of", drive.Name) + } + // Custody recorded, when it formed the hold, the drives the held wipe + // could not clean. Only those can be disposed of; a same-name wipe + // created later never matches custody, and its plan is never read. + i := slices.IndexFunc(hold.Drives, func(d ops.HeldDrive) bool { return d.Name == drive.Name }) + if i < 0 { + return "", refuse(ReasonDisposalInvalid, "the hold records no drive %s the wipe could not clean", drive.Name) + } + serial := hold.Drives[i].SerialNumber + if storage := cleaning.StorageOf(admission.Device); storage == nil || slices.ContainsFunc(storage.Drives, func(d inventory.ObservedDrive) bool { return d.SerialNumber == serial }) { + return "", refuse(ReasonDisposalInvalid, "discovery still reports drive %s (%s), or reports no drives; pull it first", drive.Name, serial) + } + return serial, nil +} + // 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. @@ -473,6 +553,15 @@ func applyRecovery(ctx context.Context, apply *ApplyContext) (*ops.DeviceCustody case ops.DecisionRetire: spec.RecoveryHold = nil spec.Holder = ops.Holder{Type: ops.HolderRetired} + case ops.DecisionDisposeDrive: + serial, refusal := disposedDrive(ctx, recovery, custody, &Admission{Operation: recovery, Custody: custody, Device: apply.Device, Registry: apply.Registry, Reader: apply.Reader, Now: apply.Now}) + if refusal != nil { + return nil, refusal + } + drive := recovery.Spec.Drive + spec.RecoveryHold = nil + spec.Holder.DisposedDrives = append(slices.Clone(spec.Holder.DisposedDrives), ops.DisposedDrive{Name: drive.Name, SerialNumber: serial, + Method: drive.Method, Reference: drive.Reference, Recovery: recovery.Name}) case ops.DecisionResolve: resolve := recovery.Spec.Resolve spec.State = ops.CustodyVerified @@ -520,6 +609,9 @@ func DefaultRules() []Rule { {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}, + // #183: DisposeDrive settles a wipe held for a drive it could not + // clean, only while the server is in Release. + {Kind: "DeviceRecovery", Variant: string(ops.DecisionDisposeDrive), Creator: CreatorStaff, Authority: AuthorityService, Holders: []ops.HolderType{ops.HolderRelease}, Hold: HoldRequired}, } } diff --git a/internal/custody/registry.go b/internal/custody/registry.go index 85eccb20..a12e4999 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -92,6 +92,14 @@ type Kind struct { // ends the operation Failed with that reason, and nothing is sent, // unless the refusal sets Wait and the operation's row queues. Check func(context.Context, *Admission) *Refusal + // HoldOnAdmit, when it returns a reason, admits the operation and ends it + // OutcomeUnknown in the same custody update, so the server is held and + // nothing is delivered. It is for an outcome that is already unproven + // before anything runs, such as a drive whose data a wipe cannot reach. + // Its reasons must be declared as raised by the coordinator. + HoldOnAdmit func(context.Context, *Admission) *Refusal + // HeldDrives returns the drives to record with a hold HoldOnAdmit forms. + HeldDrives func(ops.Operation) []ops.HeldDrive // 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. diff --git a/internal/custody/seams_test.go b/internal/custody/seams_test.go index f9f259d2..f375b92d 100644 --- a/internal/custody/seams_test.go +++ b/internal/custody/seams_test.go @@ -325,6 +325,19 @@ func TestCRDRules(t *testing.T) { s.Decision, s.Hold, s.DiskDisposal = ops.DecisionSettle, &ops.HeldOperationReference{Kind: "k", Name: "n"}, &ops.DiskDisposal{Method: ops.DisposalDestroyed, Reference: "r"} return s }, + // DisposeDrive names its drive and hold, and only it names a drive. + func(s ops.DeviceRecoverySpec) ops.DeviceRecoverySpec { + s.Decision, s.Hold = ops.DecisionDisposeDrive, &ops.HeldOperationReference{Kind: "k", Name: "n"} + return s + }, + func(s ops.DeviceRecoverySpec) ops.DeviceRecoverySpec { + s.Decision, s.Drive = ops.DecisionDisposeDrive, &ops.DriveDisposal{Name: "disk-0", Method: ops.DisposalRemoved, Reference: "r"} + return s + }, + func(s ops.DeviceRecoverySpec) ops.DeviceRecoverySpec { + s.Decision, s.Hold, s.Drive = ops.DecisionSettle, &ops.HeldOperationReference{Kind: "k", Name: "n"}, &ops.DriveDisposal{Name: "disk-0", Method: ops.DisposalRemoved, Reference: "r"} + return s + }, } { requireInvalid(t, e.admin.Create(ctx, &ops.DeviceRecovery{ObjectMeta: metav1.ObjectMeta{GenerateName: "r-", Namespace: "default"}, Spec: spec(base)})) } @@ -340,6 +353,9 @@ func TestCRDRules(t *testing.T) { custody = e.custody(device.Name) custody.Spec.Holder = ops.Holder{Type: ops.HolderAllocation} requireInvalid(t, e.admin.Update(ctx, custody)) + custody = e.custody(device.Name) + custody.Spec.Holder.DisposedDrives = []ops.DisposedDrive{{Name: "disk-0", SerialNumber: "SN", Method: ops.DisposalRemoved, Reference: "r", Recovery: "rec"}} + requireInvalid(t, e.admin.Update(ctx, custody)) }) } diff --git a/internal/site/simwork/kinds.go b/internal/site/simwork/kinds.go index 48e3fc0f..89faa54d 100644 --- a/internal/site/simwork/kinds.go +++ b/internal/site/simwork/kinds.go @@ -88,6 +88,23 @@ func checkDisks(work *site.Work, disks []string) *custody.Refusal { return nil } +// wipeDisks requires every planned drive to be an enrolled disk. A plan may +// cover fewer than all of them once staff disposed of a drive. +func wipeDisks(work *site.Work, disks []string) *custody.Refusal { + if connection(work) == nil { + return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "this site does not run the simulator"} + } + for _, disk := range disks { + if !slices.Contains(connection(work).Target.Disks, disk) { + return &custody.Refusal{Reason: custody.ReasonTargetDisks, Message: "drive " + disk + " is not one of the site's enrolled disks"} + } + } + if len(disks) == 0 { + return &custody.Refusal{Reason: custody.ReasonTargetDisks, Message: "the wipe plans no drive"} + } + return nil +} + // Installation is the simulator's DeviceInstallation worker. type Installation struct{} @@ -205,7 +222,7 @@ func (Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { 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) + return wipeDisks(work, names) } func (Wipe) Run(ctx context.Context, work *site.Work) (any, error) { diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index dd37b92a..e98ff3f2 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -273,6 +273,9 @@ func (r Runner) release(ctx context.Context) error { return err } if current != nil { + // A drive that cannot be cleaned keeps the release waiting. Name + // it if the wait times out, rather than reporting only a timeout. + var blocked error if err := r.await(ctx, "the first allocation is Released", func() (bool, error) { if err := r.Client.Get(ctx, client.ObjectKeyFromObject(current), current); err != nil { return false, err @@ -281,8 +284,14 @@ func (r Runner) release(ctx context.Context) error { if errors.Is(err, allocation.ErrWipeFailed) { return false, err } + if errors.Is(err, allocation.ErrCleaningBlocked) { + blocked = err + } return released, nil }); err != nil { + if blocked != nil { + return fmt.Errorf("%w: %v", err, blocked) + } return err } }