diff --git a/docs/development/README.md b/docs/development/README.md index 59ca31b3..b55c796d 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -64,22 +64,14 @@ removed as a breaking `v1alpha1` change with no conversion or migration. Stored profiles with the old shape must be recreated before upgrading. The allocator matches capacity only when the observed cores and memory equal the request. -Private records retained before that change still decode, but only so they can -be released. `controller.RetainedRequirements` is the `acceptedRequirements` -encoding in asset records, custody proposals, and Milo authority records. It -reads exact requirements unchanged. It also reads the complete former -`{min, max, exact}` shape for `cpu.cores` and `memory.capacity` and re-encodes -that shape verbatim. Allocation retries, selection, `Install`, network refresh, -and Milo recovery return `controller.ErrLegacyRecord` for such a record. That -error wraps `ErrRecordInvalid`. Synthetic staging reports it on a live Machine -as `Bound=False` and `Ready=False` with reason `LegacyCustodyRecord`, and does -not requeue. Deletion releases the record through the same verified cleanup -path as any other record, even when the profile UIDs it names were deleted -and recreated. Tests cover the legacy fixture decode, refusal without record -changes or provider effects, release with replaced profiles and with -unverified cleanup, staging status and finalizer removal, and Milo digest -preservation. See the -[upgrade notes](../enhancements/machine-lifecycle/README.md#machineprofile). +Private asset records, custody proposals, and Milo authority records retain +`acceptedRequirements` as the exact `MachineProfileSpec`. A private record whose +requirements use any other shape fails to decode, like a version 1 +installation record or any other malformed record. Fleet keeps no decoder or +release path for older record shapes. How the coordinator contains such a +record, and how an operator removes it, is described in +[Undecodable private records](#undecodable-private-records). See the +[MachineProfile notes](../enhancements/machine-lifecycle/README.md#machineprofile). `requestedhardware.Project` is the one projection that writes `status.requestedHardware` and `RequestResolved`, and @@ -105,6 +97,86 @@ provenance, missing and invalid profiles, post-acceptance profile changes, inert-mode wiring, and staging and standalone carry-forward. See [requested hardware](../enhancements/machine-lifecycle/README.md#requested-hardware). +## Undecodable private records + +A private lifecycle record that does not decode into the current shape returns +`controller.ErrRecordUnreadable`, which wraps `ErrRecordInvalid`. This covers +asset, claim custody, installation, and Milo authority records. The record +blocks only the claim it belongs to (implemented): + +- **Attribution.** The coordinator does not trust the body of a record it cannot + decode. It attributes the record by the `fleet.datumapis.com/claim-uid` + label, which `encodeRecord` and the Milo record store write on every record. +- **Scans across claims.** The asset scan behind allocation, installation, + network refresh, and release, and the installation scan by binding, skip a + record labeled for another claim. A record labeled for the scanning claim + fails that claim closed. A record with no claim label might belong to any + claim, so it fails every claim-scoped scan closed. Fleet never writes an + unlabeled record, so this case means the Secret was edited by hand. One such + Secret halts allocation, installation, and release for every claim on the + coordinator until an operator removes it. +- **Release from a selection.** A claim released while its custody only + proposes an asset reads that asset's record by name. If the record is + labeled for another claim, that claim holds the asset and the releasing + claim never did, so its custody is released without touching the record. + The record keeps fencing the asset's epoch. A record labeled for the + releasing claim, or with no label, fails release closed. +- **Capacity and epoch fencing.** Allocation reads each candidate asset's + record by name. If that record, or the custody record of the claim that last + held the asset, cannot be decoded, the asset is never proposed and allocation + tries the next candidate. Nothing proves that asset was released or what + epoch it reached, so treating it as free could double-bind it or restart its + epoch below a stale operation. A retained `Released` record that cannot be + decoded therefore keeps its asset out of allocation. It does not admit any + operation for its former claim either, because that claim's own scans fail + closed on it. +- **The claim's own work.** Allocation, installation, and release for the + attributed claim return `ErrRecordUnreadable`. They do not treat the claim as + having no record, and they never rewrite the record. Synthetic staging + reports the Machine as `Phase=Pending` with `Bound=False` and `Ready=False`, + reason `UnreadablePrivateRecord`, and does not requeue it. The managed + Machine handler also stops requeueing, and sets no condition: it writes no + Machine status at all, so synthetic staging is the only writer of Machine + lifecycle conditions. Release never removes the finalizer through such a + record. +- **Signals.** Every lifecycle decode goes through one reporting decoder, so + each record is logged once per lifecycle call at error level, whichever read + found it. + The log names the Secret and the attributed claim UID, never record + contents. The counter `fleet_private_lifecycle_record_undecodable_total` + counts the same events, labeled only by `record_type` (`asset`, `custody`, + `installation`, or `milo-authority`). + +Fleet has no automated release for an undecodable record. To clear an affected +Machine, an operator does the following: + +1. Find the Machine's UID. List the Secrets in `fleet-system-private` that + carry `fleet.datumapis.com/claim-uid=`. The error log names the + undecodable one. +2. If the Machine held an asset, set that MachineCapacity's + `allocationPolicy` to `Disabled`. Removing the records discards the binding, + its epoch, and any pending cleanup, so the physical machine's state is + unknown. Re-enable allocation only after the machine has been verified clean. + The next binding starts again at epoch 1, and an executor that retained a + higher epoch refuses it until its own fence is reset. +3. Delete the Machine. Release stops at the undecodable record and leaves the + finalizer in place. +4. Remove the `fleet.datumapis.com/machine-protection` finalizer from the + Machine by hand. Fleet cannot release through the record, so it never + removes the finalizer itself. +5. Delete every listed private record Secret for that claim UID, not only the + undecodable one. The claim no longer exists, and a record left behind keeps + describing authority that nothing will ever release. + +A retained `Released` asset record whose Machine is already gone affects only +that asset. Delete that Secret after step 2 to return the asset to allocation. + +Event routing reads only records that decode, so editing or deleting an +undecodable Secret wakes no claim. This is why the procedure deletes the +Machine and removes its finalizer before deleting the records. A claim blocked +by an unlabeled record is reconciled again on its next own event, or when the +manager restarts. + ## Multi-project discovery `cmd/fleet-manager` runs one set of controllers over every project that @@ -539,11 +611,10 @@ provider effect, including the initiating principal and installation decision pl the image catalog authority, revision, and image decision. The operation also retains the installation and claim namespace, name, and UID, so an informer initial Add can route unfinished work after restart even when the public -Installation has been deleted. This is installation-record schema v2. A v1 -operation is upgraded atomically only when the exact public Installation and -claim request is still available to supply and verify the names omitted by v1; -otherwise it is quarantined from event routing and effects rather than guessed -or treated as ready. Image references must +Installation has been deleted. This is installation-record schema v2. A record +in any other schema version is invalid: it is quarantined from event routing +and effects and is never rewritten, guessed, or treated as ready. Image +references must resolve to canonical lowercase SHA-256 digests. Stable operation and result identities include the authority/project claim scope, so equal claim UIDs from independent project APIs cannot share an operation record. Installation custody diff --git a/docs/enhancements/machine-lifecycle/README.md b/docs/enhancements/machine-lifecycle/README.md index 651e968d..4b6ef688 100644 --- a/docs/enhancements/machine-lifecycle/README.md +++ b/docs/enhancements/machine-lifecycle/README.md @@ -358,36 +358,40 @@ fields, or migration logic. A stored profile with the former `cores: {min: ...}` or `capacity: {min: ...}` shape no longer decodes and must be deleted and recreated with exact values before upgrading the manager. -Allocations accepted before this change can be released after the upgrade, -but they are never resumed (implemented). Private asset, claim custody, and -Milo authority records embed the accepted profile requirements. A narrowly -scoped decoder on those private records only (`RetainedRequirements`) still -reads the former `cpu.cores` and `memory.capacity` `{min, max, exact}` shape. -It accepts that shape only when both fields use it and no unknown fields are -present. The original JSON is kept verbatim, so retained requirement digests -stay valid when release rewrites the record. The public `MachineProfileSpec` -and the CRD are unchanged. A record in the former shape: - -- never satisfies an allocation retry, selection, installation admission, - network refresh, or Milo authority recovery. Those paths return - `ErrLegacyRecord`, which wraps the generic invalid-record error, so they - fail closed. The record never produces `requestedHardware`, - `allocatedHardware`, or readiness. This holds even when the profile UIDs it - names still exist; -- is reported on a live Machine by synthetic staging as `Phase=Pending` with - `Bound=False` and `Ready=False`, reason `LegacyCustodyRecord`, without a retry - loop. The production Machine handler also stops retrying it; -- is released by the normal verified release path when the Machine is deleted: - cleanup must return correlated evidence, then the asset and custody records - become `Released`, the capacity becomes available again, and the finalizer - is removed. Release does not consult the profile, so profile UIDs that no - longer exist (a deleted and recreated profile) do not block it. Uncertain or - malformed cleanup evidence leaves the record `Releasing` and the finalizer in - place. - -Operators do not edit private records. Delete each affected Machine and wait -for the finalizer to clear. A released record in the former shape is retained -for epoch fencing and does not block the next allocation of that machine. +Private asset, claim custody, and Milo authority records embed the accepted +requirements as the exact `MachineProfileSpec` (implemented). Fleet keeps no +decoder for an earlier record shape. A private record whose requirements do +not decode as the exact shape is undecodable. It never produces +`requestedHardware`, `allocatedHardware`, or readiness, and it is never +rewritten. It blocks only the claim it belongs to (implemented): + +- The coordinator attributes an undecodable record by its + `fleet.datumapis.com/claim-uid` label, never by its body. Scans across + claims skip a record labeled for another claim. A record with no claim label + could belong to any claim, so it fails every claim-scoped scan closed: one + hand-edited Secret with no label halts allocation, installation, and release + for every claim until it is removed. +- A claim released while it only proposes an asset whose undecodable record + is labeled for another claim never held that asset, so it is released and + the record is left in place to keep fencing the asset. +- Allocation, installation admission, network refresh, Milo authority recovery, + and release fail closed for the attributed claim. Synthetic staging reports + the Machine as `Bound=False` and `Ready=False`, reason + `UnreadablePrivateRecord`, without a retry loop. Release never removes the + finalizer through such a record. +- Allocation never proposes an asset whose record, or whose previous claim's + custody record, cannot be decoded. Without the record there is no proof the + asset was released or of its epoch. A `Released` record kept for epoch + fencing that cannot be decoded therefore keeps its asset out of allocation + rather than restarting its epoch below a stale operation. +- Each such record is logged and counted in + `fleet_private_lifecycle_record_undecodable_total`, labeled by record type. + +Fleet has no automated recovery. An operator disables allocation on the +affected capacity, deletes the Machine, removes its finalizer by hand, then +deletes that claim's private record Secrets. The +[implementation status](../../development/README.md#undecodable-private-records) +lists the steps. GPU, disk, and interface requirements keep numeric constraints with inclusive `min` and optional `max`, or `exact` alone. Counts are integers, capacities are @@ -1455,6 +1459,17 @@ correctness violations. - 2026-11-18: Retained private records written before exact CPU and memory decode again for release only. Live Machines report `LegacyCustodyRecord` instead of looping, and deletion releases them through verified cleanup. +- 2026-11-23: Removed the decoder and release path for private records written + before exact CPU and memory, the `LegacyCustodyRecord` reason, and the + installation-record v1 upgrader. Records in older shapes or schema versions + are invalid. +- 2026-11-23: An undecodable private record blocks only the claim its + `claim-uid` label names, plus the asset it fences, instead of every claim on + the coordinator. It is reported as `UnreadablePrivateRecord` and counted in + `fleet_private_lifecycle_record_undecodable_total`. +- 2026-11-24: Release from a selection skips an undecodable proposed asset + record labeled for another claim. Every lifecycle decode reports through one + decoder. ## Drawbacks diff --git a/go.mod b/go.mod index af7cc58f..715832bd 100644 --- a/go.mod +++ b/go.mod @@ -50,7 +50,7 @@ require ( github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/emicklei/go-restful/v3 v3.13.0 // indirect - github.com/evanphx/json-patch/v5 v5.9.11 // indirect + github.com/evanphx/json-patch/v5 v5.9.11 github.com/fsnotify/fsnotify v1.10.1 // indirect github.com/fxamacker/cbor/v2 v2.9.1 // indirect github.com/go-logr/logr v1.4.4 // indirect @@ -75,8 +75,8 @@ require ( github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/prometheus/client_golang v1.24.0 // indirect - github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/client_golang v1.24.0 + github.com/prometheus/client_model v0.6.2 github.com/prometheus/common v0.70.0 // indirect github.com/prometheus/procfs v0.21.1 // indirect github.com/spf13/pflag v1.0.10 // indirect diff --git a/internal/controller/lifecycle.go b/internal/controller/lifecycle.go index 87b41e63..118b9819 100644 --- a/internal/controller/lifecycle.go +++ b/internal/controller/lifecycle.go @@ -31,8 +31,8 @@ import ( const ( MachineFinalizer = "fleet.datumapis.com/machine-protection" recordSchemaVersion = 1 - // Installation records gained retained public routing identities in v2. - // v1 is accepted only by the explicit request-bound upgrader below. + // Installation records carry retained public routing identities. Any + // other schema version is invalid. installationRecordSchemaVersion = 2 assetRecordPrefix = "fleet-asset-" custodyRecordPrefix = "fleet-claim-" @@ -108,37 +108,34 @@ const ( // AssetRecord is private coordination state. It is deliberately retained after // release so the next allocation can advance the executor epoch without -// reconstructing authority from public status. AcceptedRequirements may hold -// the pre-exact CPU and memory shape for records written before exact -// requests; such a record decodes only so it can be released (see -// RetainedRequirements and ErrLegacyRecord). +// reconstructing authority from public status. type AssetRecord struct { - SchemaVersion int `json:"schemaVersion"` - State AssetState `json:"state"` - AssetID string `json:"assetID"` - MachineNamespace string `json:"machineNamespace"` - MachineName string `json:"machineName"` - MachineUID types.UID `json:"machineUID"` - ClaimNamespace string `json:"claimNamespace"` - ClaimName string `json:"claimName"` - ClaimUID types.UID `json:"claimUID"` - ClaimScope ClaimScope `json:"claimScope"` - ClassUID types.UID `json:"classUID"` - ProfileUID types.UID `json:"profileUID"` - LocalClassUID types.UID `json:"localClassUID"` - LocalProfileUID types.UID `json:"localProfileUID"` - ConsumerProject ProjectIdentity `json:"consumerProject,omitempty"` - ProviderProject ProjectIdentity `json:"providerProject,omitempty"` - Authority AuthorityRef `json:"authority,omitempty"` - ExternalHold ExternalHoldRef `json:"externalHold,omitempty"` - BindingID string `json:"bindingID"` - Epoch int64 `json:"epoch"` - FenceToken string `json:"fenceToken"` - CurrentInstallationName string `json:"currentInstallationName"` - ActiveOperationID string `json:"activeOperationID,omitempty"` - AcceptedRequirements RetainedRequirements `json:"acceptedRequirements"` - Hardware fleetv1.Hardware `json:"hardware"` - Network *NetworkRecord `json:"network,omitempty"` + SchemaVersion int `json:"schemaVersion"` + State AssetState `json:"state"` + AssetID string `json:"assetID"` + MachineNamespace string `json:"machineNamespace"` + MachineName string `json:"machineName"` + MachineUID types.UID `json:"machineUID"` + ClaimNamespace string `json:"claimNamespace"` + ClaimName string `json:"claimName"` + ClaimUID types.UID `json:"claimUID"` + ClaimScope ClaimScope `json:"claimScope"` + ClassUID types.UID `json:"classUID"` + ProfileUID types.UID `json:"profileUID"` + LocalClassUID types.UID `json:"localClassUID"` + LocalProfileUID types.UID `json:"localProfileUID"` + ConsumerProject ProjectIdentity `json:"consumerProject,omitempty"` + ProviderProject ProjectIdentity `json:"providerProject,omitempty"` + Authority AuthorityRef `json:"authority,omitempty"` + ExternalHold ExternalHoldRef `json:"externalHold,omitempty"` + BindingID string `json:"bindingID"` + Epoch int64 `json:"epoch"` + FenceToken string `json:"fenceToken"` + CurrentInstallationName string `json:"currentInstallationName"` + ActiveOperationID string `json:"activeOperationID,omitempty"` + AcceptedRequirements fleetv1.MachineProfileSpec `json:"acceptedRequirements"` + Hardware fleetv1.Hardware `json:"hardware"` + Network *NetworkRecord `json:"network,omitempty"` } type ResolvedImage struct { @@ -277,6 +274,7 @@ func (c *Coordinator) EnsureClaimCustody(ctx context.Context, claim *fleetv1.Mac if claim == nil || claim.Namespace == "" || claim.Name == "" || claim.UID == "" || namespaceUID == "" || !admission.valid() { return errors.New("claim lifetime identity is required") } + ctx = withUndecodableReporting(ctx) scope := LocalClaimScope(namespaceUID) if len(project) > 1 || len(project) == 1 && !project[0].Valid() { return ErrRecordInvalid @@ -288,7 +286,7 @@ func (c *Coordinator) EnsureClaimCustody(ctx context.Context, claim *fleetv1.Mac var secret corev1.Secret err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret) if err == nil { - record, err := decodeCustodySecret(&secret) + record, err := decodeCustodySecret(ctx, &secret) if err != nil { return err } @@ -422,6 +420,7 @@ func (c *Coordinator) ClearSettledExternalHold(ctx context.Context, claimUID typ } func (c *Coordinator) Allocate(ctx context.Context, request AllocationRequest) (*AssetRecord, error) { + ctx = withUndecodableReporting(ctx) if err := validateAllocationRequest(request); err != nil { return nil, err } @@ -439,11 +438,6 @@ func (c *Coordinator) Allocate(ctx context.Context, request AllocationRequest) ( if custody.ClaimNamespace != request.Claim.Namespace || custody.ClaimName != request.Claim.Name || custody.NamespaceUID != request.NamespaceUID || custody.Admission != request.Admission || custody.State == CustodyReleased || !allocationAuthorityMatches(custody, request) { return nil, fmt.Errorf("%w: claim custody does not authorize allocation", ErrRecordInvalid) } - // A selection or binding accepted under the pre-exact requirements is - // never resumed, cleared, or reselected; only release may consume it. - if custody.ProposedAsset != nil && custody.ProposedAsset.AcceptedRequirements.Legacy() { - return nil, ErrLegacyRecord - } existing, err := c.recordsForClaimScoped(ctx, request.Claim.UID, custody.ConsumerProject) if err != nil { return nil, err @@ -560,9 +554,6 @@ func (c *Coordinator) recordCandidateEligible(record *AssetRecord, request Alloc } func validateAssetForRequest(record *AssetRecord, request AllocationRequest) error { - if record.AcceptedRequirements.Legacy() { - return ErrLegacyRecord - } // Specs contain slices, so compare their canonical JSON rather than // allowing a recovered Preparing record to drift across retries. got, _ := json.Marshal(record.AcceptedRequirements) @@ -714,9 +705,9 @@ func (c *Coordinator) prepareAsset(ctx context.Context, request AllocationReques var secret corev1.Secret err = c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret) if err == nil { - existing, decodeErr := decodeAssetSecret(&secret) + existing, decodeErr := decodeAssetSecret(ctx, &secret) if decodeErr != nil { - return nil, false, decodeErr + return nil, false, unreadableCandidate(&secret, request.Claim.UID, decodeErr) } if existing.State != AssetReleased { if existing.ClaimUID != request.Claim.UID { @@ -730,7 +721,10 @@ func (c *Coordinator) prepareAsset(ctx context.Context, request AllocationReques } return existing, sameRecord(existing, proposal), nil } - previousCustody, _, custodyErr := c.getCustodyForAsset(ctx, existing) + previousCustody, custodySecret, custodyErr := c.getCustodyForAsset(ctx, existing) + if errors.Is(custodyErr, ErrRecordUnreadable) { + return nil, false, unreadableCandidate(custodySecret, request.Claim.UID, custodyErr) + } if custodyErr != nil { return nil, false, custodyErr } @@ -779,12 +773,18 @@ func sameRecord(a, b *AssetRecord) bool { func (c *Coordinator) proposeAsset(ctx context.Context, request AllocationRequest, machine *fleetv1.MachineCapacity) (*AssetRecord, bool, error) { assetID := machineAssetID(machine, request.ProviderProject) epoch := int64(1) - existing, _, err := c.getAsset(ctx, assetID) + existing, secret, err := c.getAsset(ctx, assetID) + if errors.Is(err, ErrRecordUnreadable) { + return nil, false, unreadableCandidate(secret, request.Claim.UID, err) + } if err == nil { if existing.State != AssetReleased { return nil, false, nil } - previous, _, err := c.getCustodyForAsset(ctx, existing) + previous, custodySecret, err := c.getCustodyForAsset(ctx, existing) + if errors.Is(err, ErrRecordUnreadable) { + return nil, false, unreadableCandidate(custodySecret, request.Claim.UID, err) + } if err != nil { return nil, false, err } @@ -802,6 +802,20 @@ func (c *Coordinator) proposeAsset(ctx context.Context, request AllocationReques return newAssetRecord(request, machine, assetID, epoch, binding, fence), true, nil } +// unreadableCandidate handles a candidate asset whose asset record, or the +// custody record of its previous claim, cannot be decoded. The asset is never +// proposed: without the record there is no proof that it was released or of +// its epoch, so treating it as free could double-bind it or restart its epoch +// fence below a stale operation. Allocation moves on to the next candidate, +// unless the record is attributed to the allocating claim itself, which then +// fails closed. +func unreadableCandidate(secret *corev1.Secret, claimUID types.UID, err error) error { + if secret.Labels[claimUIDLabel] == string(claimUID) { + return err + } + return nil +} + func newAssetRecord(request AllocationRequest, machine *fleetv1.MachineCapacity, assetID string, epoch int64, bindingID, fenceToken string) *AssetRecord { record := &AssetRecord{SchemaVersion: recordSchemaVersion, State: AssetPreparing, AssetID: assetID, MachineNamespace: machine.Namespace, MachineName: machine.Name, MachineUID: machine.UID, @@ -809,7 +823,7 @@ func newAssetRecord(request AllocationRequest, machine *fleetv1.MachineCapacity, ClassUID: request.Class.UID, ProfileUID: request.Profile.UID, LocalClassUID: localClassUID(request), LocalProfileUID: localProfileUID(request), ConsumerProject: request.ConsumerProject, ProviderProject: request.ProviderProject, Authority: request.Authority, ExternalHold: request.ExternalHold, BindingID: bindingID, Epoch: epoch, - FenceToken: fenceToken, CurrentInstallationName: "None", AcceptedRequirements: ExactRequirements(request.Profile.Spec), Hardware: machine.Status.Hardware} + FenceToken: fenceToken, CurrentInstallationName: "None", AcceptedRequirements: request.Profile.Spec, Hardware: machine.Status.Hardware} if request.networkPlan != nil { record.Network = &NetworkRecord{Plan: *request.networkPlan} } @@ -860,6 +874,7 @@ func (c *Coordinator) ReconcileNetworkScoped(ctx context.Context, consumer Proje } func (c *Coordinator) reconcileNetwork(ctx context.Context, consumer ProjectIdentity, claimUID types.UID) (fleetnetwork.Observation, error) { + ctx = withUndecodableReporting(ctx) if c.networks == nil || claimUID == "" { return fleetnetwork.Observation{}, fleetnetwork.ErrAuthorizationUnavailable } @@ -871,9 +886,6 @@ func (c *Coordinator) reconcileNetwork(ctx context.Context, consumer ProjectIden return fleetnetwork.Observation{}, ErrRecordInvalid } asset := records[0] - if asset.AcceptedRequirements.Legacy() { - return fleetnetwork.Observation{}, ErrLegacyRecord - } if asset.State != AssetCommitted || asset.Network == nil { return fleetnetwork.Observation{}, ErrRecordInvalid } @@ -944,6 +956,7 @@ func (c *Coordinator) ReleaseScoped(ctx context.Context, consumer ProjectIdentit } func (c *Coordinator) release(ctx context.Context, scope ClaimScope, claimUID types.UID) (ReleaseResult, error) { + ctx = withUndecodableReporting(ctx) if claimUID == "" { return ReleaseResult{}, errors.New("claim UID is required") } @@ -955,7 +968,7 @@ func (c *Coordinator) release(ctx context.Context, scope ClaimScope, claimUID ty custody, _, err = c.getCustody(ctx, claimUID) } if err != nil { - return ReleaseResult{}, fmt.Errorf("%w: claim custody is missing or invalid: %v", ErrRecordInvalid, err) + return ReleaseResult{}, fmt.Errorf("%w: claim custody is missing or invalid: %w", ErrRecordInvalid, err) } // Released custody is the terminal authority for this claim lifetime. The // asset record may already belong to a later epoch and another claim by the @@ -1031,7 +1044,7 @@ func (c *Coordinator) release(ctx context.Context, scope ClaimScope, claimUID ty return ReleaseResult{State: AssetCleanupVerified, ExternalSettlementRequired: true}, nil } if record.State == AssetPreparing { - if operations, err := c.operationsForBinding(ctx, record.BindingID); err != nil { + if operations, err := c.operationsForBinding(ctx, record.ClaimUID, record.BindingID); err != nil { return ReleaseResult{}, err } else if len(operations) != 0 { return ReleaseResult{}, fmt.Errorf("%w: preparing binding has retained operations", ErrRecordInvalid) @@ -1105,6 +1118,7 @@ func (c *Coordinator) release(ctx context.Context, scope ClaimScope, claimUID ty // Object absence is not an acknowledgment and this method never queries the // external owner; callers must supply the retained authority and hold identities. func (c *Coordinator) CompleteExternalRelease(ctx context.Context, claimUID types.UID, authority AuthorityRef, hold ExternalHoldRef, project ...ProjectIdentity) (ReleaseResult, error) { + ctx = withUndecodableReporting(ctx) if claimUID == "" || !authority.Valid() || !hold.Valid() { return ReleaseResult{}, ErrRecordInvalid } @@ -1174,7 +1188,7 @@ func (c *Coordinator) retainNetworkRelease(ctx context.Context, assetID string, } func (c *Coordinator) settleActiveOperation(ctx context.Context, asset *AssetRecord) error { - operations, err := c.operationsForBinding(ctx, asset.BindingID) + operations, err := c.operationsForBinding(ctx, asset.ClaimUID, asset.BindingID) if err != nil { return err } @@ -1229,6 +1243,7 @@ type InstallationResult struct { } func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) (InstallationResult, error) { + ctx = withUndecodableReporting(ctx) if request.Claim == nil || request.Installation == nil || request.Claim.UID == "" || request.Installation.UID == "" || request.NamespaceUID == "" || !request.Admission.valid() { return InstallationResult{}, errors.New("claim, installation, and namespace lifetime identities are required") } @@ -1257,9 +1272,6 @@ func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) return InstallationResult{}, fmt.Errorf("%w: claim does not have one retained asset", ErrRecordInvalid) } asset := assets[0] - if asset.AcceptedRequirements.Legacy() { - return InstallationResult{}, ErrLegacyRecord - } if asset.State != AssetCommitted || asset.ClaimNamespace != request.Claim.Namespace || asset.ClaimName != request.Claim.Name || asset.ClaimUID != request.Claim.UID || asset.ClaimScope != scope || asset.ConsumerProject != request.ConsumerProject { return InstallationResult{}, ErrPredecessorConflict } @@ -1269,9 +1281,6 @@ func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) } operationName := operationRecordName(scope, request.Claim.UID, predecessor) operation, _, err := c.getOperation(ctx, operationName) - if errors.Is(err, ErrRecordInvalid) { - operation, err = c.upgradeLegacyOperation(ctx, operationName, request, asset, scope, predecessor) - } if apierrors.IsNotFound(err) { if asset.Network != nil && (!asset.Network.Observation.Prepared(asset.Network.Plan) || asset.Network.Observation.ObservedAt.After(c.now()) || c.now().Sub(asset.Network.Observation.ObservedAt) > c.maxEvidenceAge) { return InstallationResult{}, fleetnetwork.ErrEvidenceStale @@ -1371,7 +1380,7 @@ func (c *Coordinator) getOrCreateOperation(ctx context.Context, name string, req var secret corev1.Secret err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret) if err == nil { - record, decodeErr := decodeOperationSecret(&secret) + record, decodeErr := decodeOperationSecret(ctx, &secret) return record, &secret, decodeErr } if !apierrors.IsNotFound(err) { @@ -1411,49 +1420,10 @@ func (c *Coordinator) getOperation(ctx context.Context, name string) (*Installat if err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret); err != nil { return nil, nil, err } - record, err := decodeOperationSecret(&secret) + record, err := decodeOperationSecret(ctx, &secret) return record, &secret, err } -// upgradeLegacyOperation upgrades a v1 operation only while an exact public -// request is available to supply the names that v1 failed to retain. A v1 -// record without that request remains quarantined: guessing a name from a UID -// would retarget admitted provider authority. -func (c *Coordinator) upgradeLegacyOperation(ctx context.Context, name string, request InstallationRequest, asset *AssetRecord, scope ClaimScope, predecessor string) (*InstallationRecord, error) { - var result *InstallationRecord - err := retry.RetryOnConflict(retry.DefaultRetry, func() error { - var secret corev1.Secret - if err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret); err != nil { - return err - } - if current, err := decodeOperationSecret(&secret); err == nil { - result = current - return nil - } - legacy, err := decodeLegacyOperationSecret(&secret) - if err != nil { - return err - } - if legacy.InstallationUID != request.Installation.UID || legacy.NamespaceUID != request.NamespaceUID || legacy.ClaimUID != request.Claim.UID || legacy.ClaimScope != scope || legacy.ConsumerProject != request.ConsumerProject || legacy.AssetID != asset.AssetID || legacy.BindingID != asset.BindingID || legacy.Epoch != asset.Epoch || legacy.Predecessor != predecessor || legacy.ImageName != request.Installation.Spec.ImageRef.Name || legacy.Admission != request.Admission { - return ErrPredecessorConflict - } - legacy.SchemaVersion = installationRecordSchemaVersion - legacy.InstallationNamespace = request.Installation.Namespace - legacy.InstallationName = request.Installation.Name - legacy.ClaimNamespace = request.Claim.Namespace - legacy.ClaimName = request.Claim.Name - if err := encodeRecord(&secret, legacy, "installation"); err != nil { - return err - } - if err := c.client.Update(ctx, &secret); err != nil { - return err - } - result = legacy - return nil - }) - return result, err -} - func (c *Coordinator) activateOperation(ctx context.Context, assetID string, claimUID types.UID, predecessor, operationID string) error { record, secret, err := c.getAsset(ctx, assetID) if err != nil { @@ -1499,7 +1469,7 @@ func (c *Coordinator) markOperationSucceeded(ctx context.Context, name string, e if err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: name}, &secret); err != nil { return nil, err } - record, err := decodeOperationSecret(&secret) + record, err := decodeOperationSecret(ctx, &secret) if err != nil { return nil, err } @@ -1574,7 +1544,7 @@ func (c *Coordinator) getAsset(ctx context.Context, assetID string) (*AssetRecor if err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: assetRecordName(assetID)}, &secret); err != nil { return nil, nil, err } - record, err := decodeAssetSecret(&secret) + record, err := decodeAssetSecret(ctx, &secret) return record, &secret, err } @@ -1586,7 +1556,7 @@ func (c *Coordinator) getCustody(ctx context.Context, claimUID types.UID) (*Clai if len(list.Items) != 1 { return nil, nil, ErrRecordInvalid } - record, err := decodeCustodySecret(&list.Items[0]) + record, err := decodeCustodySecret(ctx, &list.Items[0]) return record, &list.Items[0], err } @@ -1598,7 +1568,7 @@ func (c *Coordinator) getCustodyScoped(ctx context.Context, scope ClaimScope, cl if err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: custodyRecordName(scope, claimUID)}, &secret); err != nil { return nil, nil, err } - record, err := decodeCustodySecret(&secret) + record, err := decodeCustodySecret(ctx, &secret) return record, &secret, err } @@ -1674,6 +1644,15 @@ func (c *Coordinator) selectCustody(ctx context.Context, request AllocationReque return c.client.Update(ctx, secret) } +// materializeSelectionForRelease settles a claim that is releasing while its +// custody still only proposes an asset. If the proposed asset's record already +// belongs to another claim, this claim never held the asset, so custody is +// released without touching that record. A record that cannot be decoded is +// attributed by its claim-uid label, as in unreadableCandidate: one labeled +// for another claim is that claim's binding, so release proceeds the same way +// and leaves the record, and the epoch it fences, unchanged. One labeled for +// this claim, or with no label, may be this claim's binding at an unknown +// state, so release fails closed and keeps the finalizer. func (c *Coordinator) materializeSelectionForRelease(ctx context.Context, custody *ClaimCustodyRecord) error { if custody.ProposedAsset == nil || custody.ProposedAsset.AssetID != custody.AssetID || custody.ProposedAsset.ClaimUID != custody.ClaimUID { return ErrRecordInvalid @@ -1682,9 +1661,12 @@ func (c *Coordinator) materializeSelectionForRelease(ctx context.Context, custod var secret corev1.Secret err := c.client.Get(ctx, client.ObjectKey{Namespace: c.namespace, Name: assetRecordName(proposal.AssetID)}, &secret) if err == nil { - existing, err := decodeAssetSecret(&secret) + existing, err := decodeAssetSecret(ctx, &secret) if err != nil { - return err + if recordMayBelongTo(&secret, custody.ClaimUID) { + return err + } + return c.releaseCustody(ctx, custody.ClaimUID, custody.AssetID, custody.Scope) } if existing.ClaimUID != custody.ClaimUID { return c.releaseCustody(ctx, custody.ClaimUID, custody.AssetID, custody.Scope) @@ -1774,6 +1756,11 @@ func (c *Coordinator) recordsForClaim(ctx context.Context, claimUID types.UID) ( return c.recordsForClaimScoped(ctx, claimUID, ProjectIdentity{}) } +// recordsForClaimScoped returns the asset records of one claim. A record that +// cannot be decoded blocks only the claim it is attributed to (see +// recordMayBelongTo); for every other claim it is reported and skipped. A +// skipped record still fences its asset, because allocation reads an asset's +// record by name and never proposes an asset whose record cannot be decoded. func (c *Coordinator) recordsForClaimScoped(ctx context.Context, claimUID types.UID, consumer ProjectIdentity) ([]*AssetRecord, error) { var list corev1.SecretList if err := c.client.List(ctx, &list, client.InNamespace(c.namespace)); err != nil { @@ -1785,9 +1772,12 @@ func (c *Coordinator) recordsForClaimScoped(ctx context.Context, claimUID types. if !strings.HasPrefix(secret.Name, assetRecordPrefix) { continue } - record, err := decodeAssetSecret(secret) + record, err := decodeAssetSecret(ctx, secret) if err != nil { - return nil, err + if recordMayBelongTo(secret, claimUID) { + return nil, err + } + continue } if record.ClaimUID == claimUID && (consumer.Valid() && record.ConsumerProject == consumer || !consumer.Valid() && !record.ConsumerProject.Valid()) { records = append(records, record) @@ -1796,7 +1786,11 @@ func (c *Coordinator) recordsForClaimScoped(ctx context.Context, claimUID types. return records, nil } -func (c *Coordinator) operationsForBinding(ctx context.Context, bindingID string) ([]*InstallationRecord, error) { +// operationsForBinding returns the installation records of one binding. A +// binding belongs to exactly one claim, so an undecodable record attributed to +// another claim cannot be one of its operations and is reported and skipped. +// One attributed to claimUID, or to no claim, fails the scan closed. +func (c *Coordinator) operationsForBinding(ctx context.Context, claimUID types.UID, bindingID string) ([]*InstallationRecord, error) { var list corev1.SecretList if err := c.client.List(ctx, &list, client.InNamespace(c.namespace)); err != nil { return nil, err @@ -1807,9 +1801,12 @@ func (c *Coordinator) operationsForBinding(ctx context.Context, bindingID string if !strings.HasPrefix(secret.Name, operationPrefix) { continue } - record, err := decodeOperationSecret(secret) + record, err := decodeOperationSecret(ctx, secret) if err != nil { - return nil, err + if recordMayBelongTo(secret, claimUID) { + return nil, err + } + continue } if record.BindingID == bindingID { records = append(records, record) @@ -1840,10 +1837,10 @@ func encodeRecord(secret *corev1.Secret, value any, recordType string) error { return nil } -func decodeCustodySecret(secret *corev1.Secret) (*ClaimCustodyRecord, error) { +func parseCustodySecret(secret *corev1.Secret) (*ClaimCustodyRecord, error) { var record ClaimCustodyRecord if secret.Type != corev1.SecretType("fleet.datumapis.com/private-lifecycle") || secret.Labels[recordTypeLabel] != "custody" || json.Unmarshal(secret.Data[recordDataKey], &record) != nil || validateCustodyRecord(&record) != nil || secret.Name != custodyRecordName(record.Scope, record.ClaimUID) || secret.Labels[claimUIDLabel] != string(record.ClaimUID) { - return nil, fmt.Errorf("%w: custody secret %s/%s", ErrRecordInvalid, secret.Namespace, secret.Name) + return nil, fmt.Errorf("%w: custody secret %s/%s", ErrRecordUnreadable, secret.Namespace, secret.Name) } return &record, nil } @@ -1878,18 +1875,18 @@ func validateCustodyRecord(r *ClaimCustodyRecord) error { return nil } -func decodeAssetSecret(secret *corev1.Secret) (*AssetRecord, error) { +func parseAssetSecret(secret *corev1.Secret) (*AssetRecord, error) { var record AssetRecord if secret.Type != corev1.SecretType("fleet.datumapis.com/private-lifecycle") || secret.Labels[recordTypeLabel] != "asset" || json.Unmarshal(secret.Data[recordDataKey], &record) != nil || validateAssetRecord(&record) != nil || secret.Name != assetRecordName(record.AssetID) || secret.Labels[claimUIDLabel] != string(record.ClaimUID) { - return nil, fmt.Errorf("%w: asset secret %s/%s", ErrRecordInvalid, secret.Namespace, secret.Name) + return nil, fmt.Errorf("%w: asset secret %s/%s", ErrRecordUnreadable, secret.Namespace, secret.Name) } return &record, nil } -func decodeOperationSecret(secret *corev1.Secret) (*InstallationRecord, error) { +func parseOperationSecret(secret *corev1.Secret) (*InstallationRecord, error) { var record InstallationRecord if secret.Type != corev1.SecretType("fleet.datumapis.com/private-lifecycle") || secret.Labels[recordTypeLabel] != "installation" || json.Unmarshal(secret.Data[recordDataKey], &record) != nil || validateInstallationRecord(&record) != nil || secret.Name != operationRecordName(record.ClaimScope, record.ClaimUID, record.Predecessor) || secret.Labels[claimUIDLabel] != string(record.ClaimUID) { - return nil, fmt.Errorf("%w: installation secret %s/%s", ErrRecordInvalid, secret.Namespace, secret.Name) + return nil, fmt.Errorf("%w: installation secret %s/%s", ErrRecordUnreadable, secret.Namespace, secret.Name) } return &record, nil } @@ -1923,7 +1920,7 @@ func DecodePrivateLifecycleRoute(secret *corev1.Secret) (PrivateRecordRoute, err } switch secret.Labels[recordTypeLabel] { case "custody": - record, err := decodeCustodySecret(secret) + record, err := parseCustodySecret(secret) if err != nil { return PrivateRecordRoute{}, err } @@ -1934,7 +1931,7 @@ func DecodePrivateLifecycleRoute(secret *corev1.Secret) (PrivateRecordRoute, err } return route, nil case "asset": - record, err := decodeAssetSecret(secret) + record, err := parseAssetSecret(secret) if err != nil { return PrivateRecordRoute{}, err } @@ -1942,7 +1939,7 @@ func DecodePrivateLifecycleRoute(secret *corev1.Secret) (PrivateRecordRoute, err appendAssetIndexes(&route, record) return route, nil case "installation": - record, err := decodeOperationSecret(secret) + record, err := parseOperationSecret(secret) if err != nil { return PrivateRecordRoute{}, err } @@ -1996,14 +1993,6 @@ func appendObservationIndexes(route *PrivateRecordRoute, observation fleetnetwor } } -func decodeLegacyOperationSecret(secret *corev1.Secret) (*InstallationRecord, error) { - var record InstallationRecord - if secret.Type != corev1.SecretType("fleet.datumapis.com/private-lifecycle") || secret.Labels[recordTypeLabel] != "installation" || json.Unmarshal(secret.Data[recordDataKey], &record) != nil || validateLegacyInstallationRecord(&record) != nil || secret.Name != operationRecordName(record.ClaimScope, record.ClaimUID, record.Predecessor) || secret.Labels[claimUIDLabel] != string(record.ClaimUID) { - return nil, fmt.Errorf("%w: legacy installation secret %s/%s", ErrRecordInvalid, secret.Namespace, secret.Name) - } - return &record, nil -} - func validateAssetRecord(r *AssetRecord) error { if r.SchemaVersion != recordSchemaVersion || r.AssetID == "" || r.MachineNamespace == "" || r.MachineName == "" || r.MachineUID == "" || r.ClaimNamespace == "" || r.ClaimName == "" || r.ClaimUID == "" || !r.ClaimScope.Valid() || r.ClassUID == "" || r.ProfileUID == "" || r.LocalClassUID == "" || r.LocalProfileUID == "" || r.BindingID == "" || r.Epoch < 1 || r.FenceToken == "" || r.CurrentInstallationName == "" { return ErrRecordInvalid @@ -2051,22 +2040,6 @@ func validateInstallationRecord(r *InstallationRecord) error { return nil } -func validateLegacyInstallationRecord(r *InstallationRecord) error { - if r.SchemaVersion != 1 || r.InstallationNamespace != "" || r.InstallationName != "" || r.ClaimNamespace != "" || r.ClaimName != "" || !strings.HasPrefix(r.OperationID, "install-") || r.InstallationUID == "" || r.NamespaceUID == "" || r.ClaimUID == "" || !r.ClaimScope.Valid() || r.AssetID == "" || r.BindingID == "" || r.Epoch < 1 || r.Predecessor == "" || !strings.HasPrefix(r.ResultRevision, "ir-") || r.ImageName == "" || !r.Admission.valid() || r.Image.Validate() != nil || r.Image.CatalogAuthority != r.Admission.CatalogAuthority || r.Image.CatalogRevision != r.Admission.CatalogRevision || r.Image.ImageDecisionID != r.Admission.ImageDecisionID { - return ErrRecordInvalid - } - if r.ConsumerProject.Valid() && r.ClaimScope != ProjectClaimScope(r.ConsumerProject) || !r.ConsumerProject.Valid() && r.ClaimScope != LocalClaimScope(r.NamespaceUID) { - return ErrRecordInvalid - } - if r.State != OperationAdmitted && r.State != OperationSucceeded { - return ErrRecordInvalid - } - if r.NetworkInputs != nil && (r.NetworkInputs.Revision == "" || r.NetworkInputs.ObservedAt.IsZero()) { - return ErrRecordInvalid - } - return nil -} - func assetRecordName(assetID string) string { return assetRecordPrefix + shortHash(assetID) } func custodyRecordName(scope ClaimScope, claimUID types.UID) string { return custodyRecordPrefix + shortHash(scope.AuthorityID+"/"+string(scope.ProjectUID)+"/"+string(claimUID)) diff --git a/internal/controller/lifecycle_test.go b/internal/controller/lifecycle_test.go index 5420f2ff..3ed1601d 100644 --- a/internal/controller/lifecycle_test.go +++ b/internal/controller/lifecycle_test.go @@ -1,7 +1,9 @@ package controller import ( + "bytes" "context" + "encoding/json" "errors" "fmt" "strings" @@ -13,6 +15,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" @@ -519,7 +522,7 @@ func TestInstallReplayRejectsRetainedRoutingIdentitySubstitution(t *testing.T) { } } -func TestInstallUpgradesAndRecoversLegacyV1Operation(t *testing.T) { +func TestInstallRejectsOperationRecordFromOlderSchema(t *testing.T) { ctx := context.Background() f := newFixture(t) request := f.request("claim") @@ -534,21 +537,65 @@ func TestInstallUpgradesAndRecoversLegacyV1Operation(t *testing.T) { installRequest := InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()} image, _ := f.coordinator.images.ResolveImage(ctx, ImageRequest{NamespaceUID: request.NamespaceUID, ClaimUID: request.Claim.UID, InstallationUID: installation.UID, ImageName: installation.Spec.ImageRef.Name}) scope := LocalClaimScope(request.NamespaceUID) - legacy := &InstallationRecord{SchemaVersion: 1, State: OperationAdmitted, OperationID: "install-legacy", InstallationUID: installation.UID, NamespaceUID: request.NamespaceUID, ClaimUID: request.Claim.UID, ClaimScope: scope, AssetID: asset.AssetID, BindingID: asset.BindingID, Epoch: asset.Epoch, Predecessor: "None", ResultRevision: "ir-legacy", Image: image, ImageName: installation.Spec.ImageRef.Name, Admission: installAdmission()} + // A schema-version-1 operation record lacks the retained routing names. It + // is invalid like any other malformed record and is never rewritten. + older := &InstallationRecord{SchemaVersion: 1, State: OperationAdmitted, OperationID: "install-older", InstallationUID: installation.UID, NamespaceUID: request.NamespaceUID, ClaimUID: request.Claim.UID, ClaimScope: scope, AssetID: asset.AssetID, BindingID: asset.BindingID, Epoch: asset.Epoch, Predecessor: "None", ResultRevision: "ir-older", Image: image, ImageName: installation.Spec.ImageRef.Name, Admission: installAdmission()} secret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "private", Name: operationRecordName(scope, request.Claim.UID, "None")}} - if err := encodeRecord(secret, legacy, "installation"); err != nil { + if err := encodeRecord(secret, older, "installation"); err != nil { t.Fatal(err) } if err := f.coordinator.client.Create(ctx, secret); err != nil { t.Fatal(err) } - result, err := f.coordinator.Install(ctx, installRequest) - if err != nil || result.Revision != "ir-legacy" || len(f.executor.requests) != 1 { - t.Fatalf("result=%#v err=%v requests=%#v", result, err, f.executor.requests) + before := append([]byte(nil), secret.Data[recordDataKey]...) + if _, err := f.coordinator.Install(ctx, installRequest); !errors.Is(err, ErrRecordInvalid) { + t.Fatalf("error=%v, want ErrRecordInvalid", err) } - upgraded, _, err := f.coordinator.getOperation(ctx, secret.Name) - if err != nil || upgraded.SchemaVersion != installationRecordSchemaVersion || upgraded.InstallationNamespace != installation.Namespace || upgraded.InstallationName != installation.Name || upgraded.ClaimNamespace != request.Claim.Namespace || upgraded.ClaimName != request.Claim.Name { - t.Fatalf("upgraded=%#v err=%v", upgraded, err) + if len(f.executor.requests) != 0 { + t.Fatalf("older operation record reached executor: %#v", f.executor.requests) + } + var stored corev1.Secret + if err := f.coordinator.client.Get(ctx, client.ObjectKeyFromObject(secret), &stored); err != nil { + t.Fatal(err) + } + if !bytes.Equal(stored.Data[recordDataKey], before) { + t.Fatalf("older operation record was rewritten: %s", stored.Data[recordDataKey]) + } +} + +func TestAssetRecordWithPreExactRequirementsIsInvalid(t *testing.T) { + ctx := context.Background() + f := newFixture(t) + request := f.request("claim") + if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { + t.Fatal(err) + } + asset, err := f.coordinator.Allocate(ctx, request) + if err != nil { + t.Fatal(err) + } + var secret corev1.Secret + if err := f.coordinator.client.Get(ctx, client.ObjectKey{Namespace: "private", Name: assetRecordName(asset.AssetID)}, &secret); err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(secret.Data[recordDataKey], &fields); err != nil { + t.Fatal(err) + } + fields["acceptedRequirements"] = json.RawMessage(`{"cpu":{"architecture":"amd64","cores":{"min":4}},"memory":{"capacity":{"min":"16Gi"}}}`) + data, err := json.Marshal(fields) + if err != nil { + t.Fatal(err) + } + secret.Data[recordDataKey] = data + if err := f.coordinator.client.Update(ctx, &secret); err != nil { + t.Fatal(err) + } + if _, err := parseAssetSecret(&secret); !errors.Is(err, ErrRecordInvalid) { + t.Fatalf("decode error=%v, want ErrRecordInvalid", err) + } + if _, err := f.coordinator.Allocate(ctx, request); !errors.Is(err, ErrRecordInvalid) { + t.Fatalf("allocate error=%v, want ErrRecordInvalid", err) } } diff --git a/internal/controller/retained_requirements.go b/internal/controller/retained_requirements.go deleted file mode 100644 index 2a2bf457..00000000 --- a/internal/controller/retained_requirements.go +++ /dev/null @@ -1,108 +0,0 @@ -package controller - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" -) - -// ReasonLegacyCustodyRecord is the Machine condition reason used when the -// retained private allocation for a Machine was accepted under the pre-exact -// MachineProfile CPU and memory contract. The allocation is never resumed; it -// is surfaced as not bound and not ready until the Machine is deleted and the -// normal verified release path returns the capacity. -const ReasonLegacyCustodyRecord = "LegacyCustodyRecord" - -// ErrLegacyRecord identifies a retained private record whose accepted -// requirements use the CPU and memory constraint shape that predates exact -// requests. It wraps ErrRecordInvalid so every caller that fails closed on an -// invalid record keeps doing so for continued use. Only release and cleanup -// may consume such a record. -var ErrLegacyRecord = fmt.Errorf("%w: retained allocation predates exact CPU and memory requirements and can only be released", ErrRecordInvalid) - -// RetainedRequirements is the private-record encoding of the MachineProfile -// requirements accepted for one allocation. It exists so that records written -// before CPU cores and memory capacity became exact values still decode for -// release, without changing the public MachineProfileSpec or its CRD. -// -// An exact value marshals byte-for-byte like the MachineProfileSpec it wraps, -// so record comparisons and requirement digests are unchanged. A legacy value -// keeps its original JSON verbatim and re-encodes it unchanged, so retained -// inputs (and any digest over them) are preserved exactly across rewrites; its -// requirements are deliberately not exposed as a MachineProfileSpec. -type RetainedRequirements struct { - spec fleetv1.MachineProfileSpec - legacy json.RawMessage -} - -// ExactRequirements wraps requirements accepted under the exact contract. -func ExactRequirements(spec fleetv1.MachineProfileSpec) RetainedRequirements { - return RetainedRequirements{spec: spec} -} - -// Legacy reports whether the retained requirements use the pre-exact CPU and -// memory constraint shape. -func (r RetainedRequirements) Legacy() bool { return r.legacy != nil } - -// Exact returns the retained requirements, or ErrLegacyRecord when they predate -// exact CPU and memory requests and therefore cannot satisfy any current use. -func (r RetainedRequirements) Exact() (fleetv1.MachineProfileSpec, error) { - if r.Legacy() { - return fleetv1.MachineProfileSpec{}, ErrLegacyRecord - } - return r.spec, nil -} - -func (r RetainedRequirements) MarshalJSON() ([]byte, error) { - if r.Legacy() { - return append([]byte(nil), r.legacy...), nil - } - return json.Marshal(r.spec) -} - -// UnmarshalJSON accepts the current exact shape, and otherwise only the -// complete pre-exact shape: cpu.cores as a {min,max,exact} count constraint -// and memory.capacity as a {min,max,exact} quantity constraint, with no -// unknown fields. A mixture of the two shapes was never written and is -// rejected. -func (r *RetainedRequirements) UnmarshalJSON(data []byte) error { - var spec fleetv1.MachineProfileSpec - exactErr := json.Unmarshal(data, &spec) - if exactErr == nil { - *r = RetainedRequirements{spec: spec} - return nil - } - var legacy legacyProfileSpec - decoder := json.NewDecoder(bytes.NewReader(data)) - decoder.DisallowUnknownFields() - if err := decoder.Decode(&legacy); err != nil { - return exactErr - } - if decoder.More() { - return errors.New("trailing data after retained requirements") - } - var compact bytes.Buffer - if err := json.Compact(&compact, data); err != nil { - return err - } - *r = RetainedRequirements{legacy: compact.Bytes()} - return nil -} - -// legacyProfileSpec is the MachineProfileSpec shape retained before CPU cores -// and memory capacity became exact. It is used only to recognize that shape. -type legacyProfileSpec struct { - CPU struct { - Architecture string `json:"architecture"` - Cores fleetv1.Constraint `json:"cores"` - } `json:"cpu"` - Memory struct { - Capacity fleetv1.QuantityConstraint `json:"capacity"` - } `json:"memory"` - GPUs *fleetv1.GPURequirement `json:"gpus,omitempty"` - Disks []fleetv1.DiskRequirement `json:"disks,omitempty"` - Interfaces []fleetv1.InterfaceRequirement `json:"interfaces,omitempty"` -} diff --git a/internal/controller/retained_requirements_test.go b/internal/controller/retained_requirements_test.go deleted file mode 100644 index 0a42031c..00000000 --- a/internal/controller/retained_requirements_test.go +++ /dev/null @@ -1,321 +0,0 @@ -package controller - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" -) - -// legacyAssetRecordFixture is a synthetic asset record in the shape written -// before MachineProfile CPU cores and memory capacity became exact values. -const legacyAssetRecordFixture = `{"schemaVersion":1,"state":"Committed","assetID":"provider/fleet.datumapis.com/Device/host-1","machineNamespace":"provider","machineName":"machine-1","machineUID":"machine-uid","claimNamespace":"project","claimName":"claim-legacy","claimUID":"legacy","claimScope":{"authorityID":"local","projectUID":"namespace-uid"},"classUID":"class-uid","profileUID":"deleted-profile-uid","localClassUID":"class-uid","localProfileUID":"deleted-profile-uid","bindingID":"binding-legacy","epoch":1,"fenceToken":"fence-legacy","currentInstallationName":"None","acceptedRequirements":{"cpu":{"architecture":"amd64","cores":{"min":24}},"memory":{"capacity":{"min":"128Gi"}}},"hardware":{"cpu":{"architecture":"amd64","cores":24},"memory":{"capacity":"128Gi"}}}` - -func TestRetainedRequirementsDecodesLegacyShapeVerbatim(t *testing.T) { - var record AssetRecord - if err := json.Unmarshal([]byte(legacyAssetRecordFixture), &record); err != nil { - t.Fatalf("legacy fixture does not decode: %v", err) - } - if !record.AcceptedRequirements.Legacy() || validateAssetRecord(&record) != nil { - t.Fatalf("legacy fixture decoded as %#v", record.AcceptedRequirements) - } - if _, err := record.AcceptedRequirements.Exact(); !errors.Is(err, ErrLegacyRecord) || !errors.Is(err, ErrRecordInvalid) { - t.Fatalf("legacy Exact() error = %v", err) - } - const legacyRequirements = `{"cpu":{"architecture":"amd64","cores":{"min":24}},"memory":{"capacity":{"min":"128Gi"}}}` - encoded, err := json.Marshal(record) - if err != nil || !bytes.Contains(encoded, []byte(`"acceptedRequirements":`+legacyRequirements)) { - t.Fatalf("legacy requirements did not re-encode verbatim: %s (err %v)", encoded, err) - } - var roundTrip AssetRecord - if err := json.Unmarshal(encoded, &roundTrip); err != nil || !sameRecord(&record, &roundTrip) || !roundTrip.AcceptedRequirements.Legacy() { - t.Fatalf("legacy record round trip = %#v, %v", roundTrip, err) - } - - for name, raw := range map[string]string{ - "exact constraint": `{"cpu":{"architecture":"amd64","cores":{"exact":24}},"memory":{"capacity":{"exact":"128Gi"}}}`, - "range": `{"cpu":{"architecture":"amd64","cores":{"min":16,"max":32}},"memory":{"capacity":{"min":"64Gi","max":"256Gi"}},"disks":[{"name":"root","count":{"min":1},"capacity":{"min":"480Gi"}}]}`, - "indented": "{\n \"cpu\": {\"architecture\": \"amd64\", \"cores\": {\"min\": 24}},\n \"memory\": {\"capacity\": {\"min\": \"128Gi\"}}\n}", - } { - var retained RetainedRequirements - if err := json.Unmarshal([]byte(raw), &retained); err != nil || !retained.Legacy() { - t.Fatalf("%s: legacy=%v err=%v", name, retained.Legacy(), err) - } - var want bytes.Buffer - _ = json.Compact(&want, []byte(raw)) - if got, err := json.Marshal(retained); err != nil || !bytes.Equal(got, want.Bytes()) { - t.Fatalf("%s: re-encoded %s, want %s (err %v)", name, got, want.Bytes(), err) - } - } - - for name, raw := range map[string]string{ - "mixed exact cores and legacy memory": `{"cpu":{"architecture":"amd64","cores":24},"memory":{"capacity":{"min":"128Gi"}}}`, - "mixed legacy cores and exact memory": `{"cpu":{"architecture":"amd64","cores":{"min":24}},"memory":{"capacity":"128Gi"}}`, - "unknown legacy field": `{"cpu":{"architecture":"amd64","cores":{"min":24,"preferred":32}},"memory":{"capacity":{"min":"128Gi"}}}`, - "not an object": `"24c-128g"`, - } { - var retained RetainedRequirements - if err := json.Unmarshal([]byte(raw), &retained); err == nil { - t.Fatalf("%s decoded as %#v", name, retained) - } - } - - // Exact requirements keep the public spec encoding byte-for-byte so record - // comparisons and retained digests are unchanged by the wrapper. - spec := fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 24}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}} - wrapped, _ := json.Marshal(ExactRequirements(spec)) - plain, _ := json.Marshal(spec) - var decoded RetainedRequirements - if !bytes.Equal(wrapped, plain) || json.Unmarshal(plain, &decoded) != nil || decoded.Legacy() { - t.Fatalf("exact encoding changed: %s vs %s", wrapped, plain) - } - if got, err := decoded.Exact(); err != nil || got.CPU.Cores != 24 || got.Memory.Capacity != "128Gi" { - t.Fatalf("exact decode = %#v, %v", got, err) - } -} - -// legacyizeClaimRecords rewrites the retained custody proposal and asset record -// of claimUID into the pre-exact requirements shape, and points them at -// profile lifetimes that no longer exist, as an upgraded deployment would see. -func legacyizeClaimRecords(t *testing.T, ctx context.Context, kube client.Client, namespace string, claimUID types.UID) { - t.Helper() - var list corev1.SecretList - if err := kube.List(ctx, &list, client.InNamespace(namespace), client.MatchingLabels{claimUIDLabel: string(claimUID)}); err != nil { - t.Fatal(err) - } - rewritten := 0 - for i := range list.Items { - secret := &list.Items[i] - var record map[string]any - if err := json.Unmarshal(secret.Data[recordDataKey], &record); err != nil { - t.Fatal(err) - } - switch secret.Labels[recordTypeLabel] { - case "asset": - legacyizeAssetJSON(t, record) - case "custody": - proposal, ok := record["proposedAsset"].(map[string]any) - if !ok { - continue - } - legacyizeAssetJSON(t, proposal) - default: - continue - } - data, err := json.Marshal(record) - if err != nil { - t.Fatal(err) - } - secret.Data[recordDataKey] = data - if err := kube.Update(ctx, secret); err != nil { - t.Fatal(err) - } - rewritten++ - } - if rewritten == 0 { - t.Fatal("no retained records were rewritten") - } -} - -func legacyizeAssetJSON(t *testing.T, record map[string]any) { - t.Helper() - requirements := record["acceptedRequirements"].(map[string]any) - cpu := requirements["cpu"].(map[string]any) - memory := requirements["memory"].(map[string]any) - cpu["cores"] = map[string]any{"min": cpu["cores"]} - memory["capacity"] = map[string]any{"min": memory["capacity"]} - record["profileUID"], record["localProfileUID"] = "deleted-profile-uid", "deleted-profile-uid" -} - -func TestLegacyRecordBlocksAllocationRetryInstallAndNetwork(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("legacy") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Allocate(ctx, request); err != nil { - t.Fatal(err) - } - legacyizeClaimRecords(t, ctx, f.coordinator.client, "private", request.Claim.UID) - before := snapshotSecrets(t, ctx, f.coordinator.client) - - // The retry uses a profile whose UID matches the legacy record, so only - // the legacy shape can be the reason the retained allocation is refused. - retry := f.request("legacy") - retry.Profile.UID = "deleted-profile-uid" - if record, err := f.coordinator.Allocate(ctx, retry); !errors.Is(err, ErrLegacyRecord) || !errors.Is(err, ErrRecordInvalid) || record != nil { - t.Fatalf("Allocate with legacy custody = %#v, %v", record, err) - } - records, err := f.coordinator.recordsForClaim(ctx, request.Claim.UID) - if err != nil || len(records) != 1 || !records[0].AcceptedRequirements.Legacy() { - t.Fatalf("legacy asset record = %#v, %v", records, err) - } - if err := validateAssetForRequest(records[0], retry); !errors.Is(err, ErrLegacyRecord) { - t.Fatalf("validateAssetForRequest = %v", err) - } - installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: "install-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} - if _, err := f.coordinator.Install(ctx, InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()}); !errors.Is(err, ErrLegacyRecord) { - t.Fatalf("Install on legacy asset = %v", err) - } - f.coordinator.networks = &fakeNetworkLifecycle{} - if _, err := f.coordinator.ReconcileNetwork(ctx, request.Claim.UID); !errors.Is(err, ErrLegacyRecord) { - t.Fatalf("ReconcileNetwork on legacy asset = %v", err) - } - if len(f.executor.requests) != 0 { - t.Fatalf("legacy record admitted provider effects: %#v", f.executor.requests) - } - if after := snapshotSecrets(t, ctx, f.coordinator.client); !equalSnapshots(before, after) { - t.Fatal("refusing a legacy record changed retained private records") - } -} - -func TestLegacySelectionIsNotClearedOrReselected(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("selecting") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - // Retain a selection whose asset record was never created, then rewrite - // it to the legacy shape. Allocation would otherwise clear and reselect it. - machine := &request.MachineCapacities[0] - proposal, reusable, err := f.coordinator.proposeAsset(ctx, request, machine) - if err != nil || !reusable { - t.Fatalf("proposeAsset = %v, %v", reusable, err) - } - if err := f.coordinator.selectCustody(ctx, request, proposal); err != nil { - t.Fatal(err) - } - legacyizeClaimRecords(t, ctx, f.coordinator.client, "private", request.Claim.UID) - if _, err := f.coordinator.Allocate(ctx, request); !errors.Is(err, ErrLegacyRecord) { - t.Fatalf("Allocate with legacy selection = %v", err) - } - custody, _, err := f.coordinator.getCustody(ctx, request.Claim.UID) - if err != nil || custody.State != CustodySelecting || custody.ProposedAsset == nil || !custody.ProposedAsset.AcceptedRequirements.Legacy() { - t.Fatalf("legacy selection was altered: %#v, %v", custody, err) - } - if records, err := f.coordinator.recordsForClaim(ctx, request.Claim.UID); err != nil || len(records) != 0 { - t.Fatalf("legacy selection materialized an asset record: %#v, %v", records, err) - } - - // Release materializes the exact retained proposal solely to release it. - result, err := f.coordinator.Release(ctx, request.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || result.State != AssetReleased { - t.Fatalf("Release of legacy selection = %#v, %v", result, err) - } - if len(f.executor.requests) != 0 { - t.Fatalf("Preparing release admitted provider effects: %#v", f.executor.requests) - } -} - -func TestLegacyRecordWithReplacedProfileReleasesThroughVerifiedCleanup(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - legacy, next := f.request("legacy"), f.request("next") - for _, request := range []AllocationRequest{legacy, next} { - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - } - if _, err := f.coordinator.Allocate(ctx, legacy); err != nil { - t.Fatal(err) - } - legacyizeClaimRecords(t, ctx, f.coordinator.client, "private", legacy.Claim.UID) - // The recreated profile has a new UID; the legacy record still names the - // deleted one. Capacity stays occupied until verified release. - next.Profile.UID = "recreated-profile-uid" - if _, err := f.coordinator.Allocate(ctx, next); !errors.Is(err, ErrInsufficientCapacity) { - t.Fatalf("capacity held by legacy record was reallocated: %v", err) - } - - // Uncertain cleanup stays unknown and never authorizes finalizer removal. - f.executor.malform = true - result, err := f.coordinator.Release(ctx, legacy.Claim.UID) - if err == nil || result.SafeToRemoveFinalizer || result.State != AssetReleasing { - t.Fatalf("Release with unverified cleanup = %#v, %v", result, err) - } - f.executor.malform = false - - result, err = f.coordinator.Release(ctx, legacy.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || result.State != AssetReleased { - t.Fatalf("Release of legacy record = %#v, %v", result, err) - } - cleanups := 0 - for _, request := range f.executor.requests { - if request.Kind == "cleanup" { - cleanups++ - } - } - if cleanups != 2 { - t.Fatalf("cleanup requests = %#v", f.executor.requests) - } - custody, _, err := f.coordinator.getCustody(ctx, legacy.Claim.UID) - if err != nil || custody.State != CustodyReleased { - t.Fatalf("legacy custody after release = %#v, %v", custody, err) - } - if again, err := f.coordinator.Release(ctx, legacy.Claim.UID); err != nil || !again.SafeToRemoveFinalizer { - t.Fatalf("idempotent release = %#v, %v", again, err) - } - - // The released legacy record is retained but never blocks reuse: the next - // exact claim advances the executor epoch over it. - record, err := f.coordinator.Allocate(ctx, next) - if err != nil || record.Epoch != 2 || record.ClaimUID != next.Claim.UID || record.AcceptedRequirements.Legacy() { - t.Fatalf("reallocation after legacy release = %#v, %v", record, err) - } -} - -func TestExactRecordWithReplacedProfileStillReleases(t *testing.T) { - ctx := context.Background() - f := newFixture(t) - request := f.request("exact") - if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { - t.Fatal(err) - } - if _, err := f.coordinator.Allocate(ctx, request); err != nil { - t.Fatal(err) - } - recreated := f.request("exact") - recreated.Profile.UID = "recreated-profile-uid" - if _, err := f.coordinator.Allocate(ctx, recreated); !errors.Is(err, ErrRecordInvalid) || errors.Is(err, ErrLegacyRecord) { - t.Fatalf("Allocate after profile recreation = %v", err) - } - result, err := f.coordinator.Release(ctx, request.Claim.UID) - if err != nil || !result.SafeToRemoveFinalizer || len(f.executor.requests) != 1 || f.executor.requests[0].Kind != "cleanup" { - t.Fatalf("Release after profile recreation = %#v, %v, %#v", result, err, f.executor.requests) - } -} - -func snapshotSecrets(t *testing.T, ctx context.Context, kube client.Client) map[string]string { - t.Helper() - var list corev1.SecretList - if err := kube.List(ctx, &list); err != nil { - t.Fatal(err) - } - out := map[string]string{} - for _, secret := range list.Items { - out[secret.Name] = secret.ResourceVersion + "/" + string(secret.Data[recordDataKey]) - } - return out -} - -func equalSnapshots(left, right map[string]string) bool { - if len(left) != len(right) { - return false - } - for key, value := range left { - if right[key] != value { - return false - } - } - return true -} diff --git a/internal/controller/unreadable_records.go b/internal/controller/unreadable_records.go new file mode 100644 index 00000000..3c837cd4 --- /dev/null +++ b/internal/controller/unreadable_records.go @@ -0,0 +1,106 @@ +package controller + +import ( + "context" + "fmt" + "sync" + + "github.com/prometheus/client_golang/prometheus" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/metrics" +) + +// ReasonUnreadablePrivateRecord is the Machine condition reason used when a +// private lifecycle record attributed to the Machine cannot be decoded. The +// Machine is not allocated, installed, or released through that record until +// an operator removes it. +const ReasonUnreadablePrivateRecord = "UnreadablePrivateRecord" + +// ErrRecordUnreadable identifies a private lifecycle record that does not +// decode into the current record shape. It wraps ErrRecordInvalid, so every +// caller that fails closed on an invalid record keeps doing so. +var ErrRecordUnreadable = fmt.Errorf("%w: private lifecycle record cannot be decoded and must be removed", ErrRecordInvalid) + +var undecodablePrivateRecords = prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "fleet_private_lifecycle_record_undecodable_total", + Help: "Private lifecycle records that failed to decode, counted once per record per lifecycle call. Labeled by record type only.", +}, []string{"record_type"}) + +func init() { + metrics.Registry.MustRegister(undecodablePrivateRecords) +} + +// recordMayBelongTo attributes a private record that failed to decode without +// trusting its body. encodeRecord writes the owning claim UID to the +// claim-uid label of every asset, installation, and custody record, so the +// label is the attribution. A record without that label cannot be attributed +// and may belong to any claim, so it is treated as belonging to the caller: +// the caller fails closed rather than proceeding as if the claim had no +// record, which could re-allocate its capacity or double-bind it. +func recordMayBelongTo(secret *corev1.Secret, claimUID types.UID) bool { + owner := secret.Labels[claimUIDLabel] + return owner == "" || types.UID(owner) == claimUID +} + +type undecodableSeenKey struct{} + +type undecodableSeen struct { + mu sync.Mutex + names map[string]struct{} +} + +// withUndecodableReporting scopes reporting to one lifecycle call, so a record +// seen by several scans in that call is logged and counted once. Nested calls +// share the outer scope. +func withUndecodableReporting(ctx context.Context) context.Context { + if _, ok := ctx.Value(undecodableSeenKey{}).(*undecodableSeen); ok { + return ctx + } + return context.WithValue(ctx, undecodableSeenKey{}, &undecodableSeen{names: map[string]struct{}{}}) +} + +// ReportUndecodableRecord logs and counts one private record that failed to +// decode. The log carries the Secret identity and attributed claim UID, never +// record contents. recordType must be a fixed record kind, not a value read +// from the Secret. +func ReportUndecodableRecord(ctx context.Context, recordType string, secret *corev1.Secret, err error) { + if seen, ok := ctx.Value(undecodableSeenKey{}).(*undecodableSeen); ok { + seen.mu.Lock() + _, dup := seen.names[secret.Name] + seen.names[secret.Name] = struct{}{} + seen.mu.Unlock() + if dup { + return + } + } + undecodablePrivateRecords.WithLabelValues(recordType).Inc() + log.FromContext(ctx).Error(err, "private lifecycle record cannot be decoded; remove it to unblock its claim", "recordType", recordType, "secret", secret.Namespace+"/"+secret.Name, "claimUID", secret.Labels[claimUIDLabel]) +} + +// decodeCustodySecret, decodeAssetSecret, and decodeOperationSecret are the +// only decoders lifecycle code calls. Each reports a record that fails to +// decode, so no read path can skip the log and counter. Route decoding for +// event mapping uses the parse functions directly: it runs on every Secret +// event outside any lifecycle call, and the lifecycle call it wakes reports +// the record. +func decodeCustodySecret(ctx context.Context, secret *corev1.Secret) (*ClaimCustodyRecord, error) { + return reportedDecode(ctx, "custody", secret, parseCustodySecret) +} + +func decodeAssetSecret(ctx context.Context, secret *corev1.Secret) (*AssetRecord, error) { + return reportedDecode(ctx, "asset", secret, parseAssetSecret) +} + +func decodeOperationSecret(ctx context.Context, secret *corev1.Secret) (*InstallationRecord, error) { + return reportedDecode(ctx, "installation", secret, parseOperationSecret) +} + +func reportedDecode[T any](ctx context.Context, recordType string, secret *corev1.Secret, parse func(*corev1.Secret) (*T, error)) (*T, error) { + record, err := parse(secret) + if err != nil { + ReportUndecodableRecord(ctx, recordType, secret, err) + } + return record, err +} diff --git a/internal/controller/unreadable_records_test.go b/internal/controller/unreadable_records_test.go new file mode 100644 index 00000000..1b074fc8 --- /dev/null +++ b/internal/controller/unreadable_records_test.go @@ -0,0 +1,464 @@ +package controller + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "testing" + + dto "github.com/prometheus/client_model/go" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" +) + +// withSecondMachine adds machine-2 after the fixture's machine-1, so an +// allocation that cannot use machine-1 has somewhere else to go. +func (f *fixture) withSecondMachine(request AllocationRequest) AllocationRequest { + second := request.MachineCapacities[0] + second.Name, second.UID, second.Spec.DeviceRef.Name = "machine-2", "machine-2-uid", "host-2" + request.MachineCapacities = append(request.MachineCapacities, second) + request.EvidenceObservedAt[second.UID] = f.now + return request +} + +func (f *fixture) allocate(t *testing.T, request AllocationRequest) *AssetRecord { + t.Helper() + ctx := context.Background() + if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { + t.Fatal(err) + } + record, err := f.coordinator.Allocate(ctx, request) + if err != nil { + t.Fatal(err) + } + return record +} + +// writeOlderAssetShape rewrites an asset record's accepted requirements into +// the pre-exact minimum and maximum CPU and memory shape, which no longer +// decodes. It returns the stored bytes so callers can prove nothing rewrote +// them. +func (f *fixture) writeOlderAssetShape(t *testing.T, assetID string, mutateLabels func(map[string]string)) []byte { + t.Helper() + ctx := context.Background() + var secret corev1.Secret + if err := f.coordinator.client.Get(ctx, client.ObjectKey{Namespace: "private", Name: assetRecordName(assetID)}, &secret); err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(secret.Data[recordDataKey], &fields); err != nil { + t.Fatal(err) + } + fields["acceptedRequirements"] = json.RawMessage(`{"cpu":{"architecture":"amd64","cores":{"min":4}},"memory":{"capacity":{"min":"16Gi"}}}`) + data, err := json.Marshal(fields) + if err != nil { + t.Fatal(err) + } + secret.Data[recordDataKey] = data + if mutateLabels != nil { + mutateLabels(secret.Labels) + } + if err := f.coordinator.client.Update(ctx, &secret); err != nil { + t.Fatal(err) + } + return data +} + +func (f *fixture) storedAsset(t *testing.T, assetID string) []byte { + t.Helper() + var secret corev1.Secret + if err := f.coordinator.client.Get(context.Background(), client.ObjectKey{Namespace: "private", Name: assetRecordName(assetID)}, &secret); err != nil { + t.Fatal(err) + } + return secret.Data[recordDataKey] +} + +func installRequestFor(request AllocationRequest, name string) InstallationRequest { + installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: name, UID: types.UID(name + "-uid")}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} + return InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()} +} + +func undecodableCount(t *testing.T, recordType string) float64 { + t.Helper() + var metric dto.Metric + if err := undecodablePrivateRecords.WithLabelValues(recordType).Write(&metric); err != nil { + t.Fatal(err) + } + return metric.GetCounter().GetValue() +} + +// An older-shape asset record must not stop the coordinator from serving +// other claims, and must keep its own claim blocked without being rewritten. +func TestUndecodableAssetRecordBlocksOnlyItsOwnClaim(t *testing.T) { + cases := []struct { + name string + run func(t *testing.T, f *fixture, other AllocationRequest) + }{ + {name: "allocate", run: func(t *testing.T, f *fixture, other AllocationRequest) { + record := f.allocate(t, other) + if record.MachineName != "machine-2" || record.State != AssetCommitted || record.Epoch != 1 { + t.Fatalf("other claim allocation = %#v", record) + } + }}, + {name: "install", run: func(t *testing.T, f *fixture, other AllocationRequest) { + f.allocate(t, other) + result, err := f.coordinator.Install(context.Background(), installRequestFor(other, "other-install")) + if err != nil || result.Revision == "" { + t.Fatalf("other claim install = %#v, %v", result, err) + } + }}, + {name: "release", run: func(t *testing.T, f *fixture, other AllocationRequest) { + f.allocate(t, other) + released, err := f.coordinator.Release(context.Background(), other.Claim.UID) + if err != nil || !released.SafeToRemoveFinalizer || released.State != AssetReleased { + t.Fatalf("other claim release = %#v, %v", released, err) + } + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + f := newFixture(t) + stale, other := f.withSecondMachine(f.request("stale")), f.withSecondMachine(f.request("other")) + asset := f.allocate(t, stale) + if asset.MachineName != "machine-1" { + t.Fatalf("stale claim allocated %s, want machine-1", asset.MachineName) + } + stored := f.writeOlderAssetShape(t, asset.AssetID, nil) + + tc.run(t, f, other) + + if _, err := f.coordinator.Allocate(ctx, stale); !errors.Is(err, ErrRecordUnreadable) { + t.Fatalf("stale allocate error = %v, want ErrRecordUnreadable", err) + } + if _, err := f.coordinator.Install(ctx, installRequestFor(stale, "stale-install")); !errors.Is(err, ErrRecordUnreadable) { + t.Fatalf("stale install error = %v, want ErrRecordUnreadable", err) + } + if released, err := f.coordinator.Release(ctx, stale.Claim.UID); !errors.Is(err, ErrRecordUnreadable) || released.SafeToRemoveFinalizer { + t.Fatalf("stale release = %#v, %v, want ErrRecordUnreadable", released, err) + } + if got := f.storedAsset(t, asset.AssetID); !bytes.Equal(got, stored) { + t.Fatalf("undecodable asset record was rewritten: %s", got) + } + for _, request := range f.executor.requests { + if request.AssetID == asset.AssetID { + t.Fatalf("executor received work for the undecodable asset: %#v", request) + } + } + }) + } +} + +// The claim-uid label attributes an undecodable record. Without it the record +// may belong to any claim, so every claim-scoped scan fails closed. +func TestUndecodableRecordAttribution(t *testing.T) { + cases := []struct { + name string + labels func(map[string]string) + otherBlocks bool + }{ + {name: "labeled for its claim", otherBlocks: false}, + {name: "label names a different claim", labels: func(l map[string]string) { l[claimUIDLabel] = "someone-else" }, otherBlocks: false}, + {name: "label missing", labels: func(l map[string]string) { delete(l, claimUIDLabel) }, otherBlocks: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + f := newFixture(t) + stale := f.request("stale") + asset := f.allocate(t, stale) + f.writeOlderAssetShape(t, asset.AssetID, tc.labels) + _, err := f.coordinator.recordsForClaimScoped(ctx, "other", ProjectIdentity{}) + if blocked := errors.Is(err, ErrRecordUnreadable); blocked != tc.otherBlocks { + t.Fatalf("asset scan for another claim error = %v, want blocked=%v", err, tc.otherBlocks) + } + if tc.labels == nil { + if _, err := f.coordinator.recordsForClaimScoped(ctx, stale.Claim.UID, ProjectIdentity{}); !errors.Is(err, ErrRecordUnreadable) { + t.Fatalf("asset scan for its own claim error = %v, want ErrRecordUnreadable", err) + } + } + + // The same rule applies to installation records scanned by binding. + operation := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "private", Name: operationPrefix + "older", Labels: map[string]string{recordTypeLabel: "installation", claimUIDLabel: string(stale.Claim.UID)}}, Type: corev1.SecretType("fleet.datumapis.com/private-lifecycle"), Data: map[string][]byte{recordDataKey: []byte(`{"schemaVersion":1}`)}} + if tc.labels != nil { + tc.labels(operation.Labels) + } + if err := f.coordinator.client.Create(ctx, operation); err != nil { + t.Fatal(err) + } + _, err = f.coordinator.operationsForBinding(ctx, "other", "other-binding") + if blocked := errors.Is(err, ErrRecordUnreadable); blocked != tc.otherBlocks { + t.Fatalf("operation scan for another claim error = %v, want blocked=%v", err, tc.otherBlocks) + } + if tc.labels == nil { + if _, err := f.coordinator.operationsForBinding(ctx, stale.Claim.UID, asset.BindingID); !errors.Is(err, ErrRecordUnreadable) { + t.Fatalf("operation scan for its own claim error = %v, want ErrRecordUnreadable", err) + } + } + }) + } +} + +// A Released asset record is retained so the next binding advances the +// executor epoch. If it cannot be decoded, its epoch is unknown, so the asset +// is never proposed again: a new binding at an earlier epoch could otherwise +// sit below a stale operation's fence. +func TestUndecodableReleasedRecordKeepsTheEpochFence(t *testing.T) { + cases := []struct { + name string + secondMachine bool + wantErr error + }{ + {name: "only the fenced asset", wantErr: ErrInsufficientCapacity}, + {name: "another asset available", secondMachine: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + f := newFixture(t) + first, next := f.request("first"), f.request("next") + if tc.secondMachine { + first, next = f.withSecondMachine(first), f.withSecondMachine(next) + } + asset := f.allocate(t, first) + if released, err := f.coordinator.Release(ctx, first.Claim.UID); err != nil || !released.SafeToRemoveFinalizer { + t.Fatalf("release = %#v, %v", released, err) + } + stored := f.writeOlderAssetShape(t, asset.AssetID, nil) + executed := len(f.executor.requests) + + if err := f.coordinator.EnsureClaimCustody(ctx, next.Claim, next.NamespaceUID, next.Admission); err != nil { + t.Fatal(err) + } + record, err := f.coordinator.Allocate(ctx, next) + if tc.wantErr != nil { + if !errors.Is(err, tc.wantErr) { + t.Fatalf("allocate error = %v, want %v", err, tc.wantErr) + } + } else if err != nil || record.AssetID == asset.AssetID || record.Epoch != 1 { + t.Fatalf("allocate = %#v, %v, want the other asset at epoch 1", record, err) + } + custody, _, err := f.coordinator.getCustody(ctx, next.Claim.UID) + if err != nil || custody.AssetID == asset.AssetID || custody.ProposedAsset != nil && custody.ProposedAsset.AssetID == asset.AssetID { + t.Fatalf("custody selected the fenced asset: %#v, %v", custody, err) + } + // The released claim's retained operations cannot run again. + if _, err := f.coordinator.Install(ctx, installRequestFor(first, "stale-install")); !errors.Is(err, ErrRecordInvalid) { + t.Fatalf("stale install error = %v, want ErrRecordInvalid", err) + } + if got := f.storedAsset(t, asset.AssetID); !bytes.Equal(got, stored) { + t.Fatalf("undecodable Released record was rewritten: %s", got) + } + for _, request := range f.executor.requests[executed:] { + if request.AssetID == asset.AssetID { + t.Fatalf("executor received work for the fenced asset: %#v", request) + } + } + }) + } +} + +func TestUndecodableRecordsAreCountedOncePerCall(t *testing.T) { + ctx := context.Background() + f := newFixture(t) + stale, other := f.withSecondMachine(f.request("stale")), f.withSecondMachine(f.request("other")) + asset := f.allocate(t, stale) + f.writeOlderAssetShape(t, asset.AssetID, nil) + if err := f.coordinator.EnsureClaimCustody(ctx, other.Claim, other.NamespaceUID, other.Admission); err != nil { + t.Fatal(err) + } + + before := undecodableCount(t, "asset") + // The record is seen by the claim scan and again as candidate machine-1. + if _, err := f.coordinator.Allocate(ctx, other); err != nil { + t.Fatal(err) + } + if got := undecodableCount(t, "asset") - before; got != 1 { + t.Fatalf("asset counter advanced by %v in one call, want 1", got) + } + if _, err := f.coordinator.Allocate(ctx, stale); !errors.Is(err, ErrRecordUnreadable) { + t.Fatalf("stale allocate error = %v", err) + } + if got := undecodableCount(t, "asset") - before; got != 2 { + t.Fatalf("asset counter advanced by %v after two calls, want 2", got) + } +} + +// selectingOn leaves request's claim in Selecting custody with a proposal for +// the asset another claim already holds, as when two claims race for the +// same free asset and the other claim's exclusive create wins. +func (f *fixture) selectingOn(t *testing.T, request AllocationRequest, held *AssetRecord) { + t.Helper() + ctx := context.Background() + if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { + t.Fatal(err) + } + binding, fence, err := f.coordinator.authorityIDs() + if err != nil { + t.Fatal(err) + } + proposal := newAssetRecord(request, &request.MachineCapacities[0], held.AssetID, held.Epoch, binding, fence) + if err := f.coordinator.selectCustody(ctx, request, proposal); err != nil { + t.Fatal(err) + } +} + +// A claim releasing from Selecting reads its proposed asset's record by name. +// An undecodable record labeled for another claim is that claim's binding, so +// the releasing claim never held the asset: it releases without touching the +// record. A record labeled for the releasing claim, or with no label, might be +// its binding, so release fails closed and keeps the finalizer. +func TestReleaseFromSelectionAttributesAnUndecodableProposedAsset(t *testing.T) { + cases := []struct { + name string + labels func(releasing types.UID) func(map[string]string) + released bool + }{ + {name: "labeled for another claim", released: true}, + {name: "labeled for the releasing claim", labels: func(releasing types.UID) func(map[string]string) { + return func(l map[string]string) { l[claimUIDLabel] = string(releasing) } + }}, + {name: "label missing", labels: func(types.UID) func(map[string]string) { + return func(l map[string]string) { delete(l, claimUIDLabel) } + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + f := newFixture(t) + holder, releasing := f.request("holder"), f.request("releasing") + held := f.allocate(t, holder) + f.selectingOn(t, releasing, held) + var labels func(map[string]string) + if tc.labels != nil { + labels = tc.labels(releasing.Claim.UID) + } + stored := f.writeOlderAssetShape(t, held.AssetID, labels) + executed := len(f.executor.requests) + + result, err := f.coordinator.Release(ctx, releasing.Claim.UID) + custody, _, custodyErr := f.coordinator.getCustody(ctx, releasing.Claim.UID) + if custodyErr != nil { + t.Fatal(custodyErr) + } + if tc.released { + if err != nil || !result.SafeToRemoveFinalizer || custody.State != CustodyReleased { + t.Fatalf("release = %#v, %v, custody %s; want released", result, err, custody.State) + } + } else if !errors.Is(err, ErrRecordUnreadable) || result.SafeToRemoveFinalizer || custody.State != CustodySelecting { + t.Fatalf("release = %#v, %v, custody %s; want ErrRecordUnreadable with custody kept", result, err, custody.State) + } + if !tc.released { + // The claim's own asset scan stops Release first, so check the + // selection path directly as well. + if err := f.coordinator.materializeSelectionForRelease(ctx, custody); !errors.Is(err, ErrRecordUnreadable) { + t.Fatalf("materialize selection error = %v, want ErrRecordUnreadable", err) + } + } + if got := f.storedAsset(t, held.AssetID); !bytes.Equal(got, stored) { + t.Fatalf("undecodable proposed asset record was rewritten: %s", got) + } + if len(f.executor.requests) != executed { + t.Fatalf("release sent executor work: %#v", f.executor.requests[executed:]) + } + // The holder's binding is still fenced by its undecodable record. + if tc.released { + if released, err := f.coordinator.Release(ctx, holder.Claim.UID); !errors.Is(err, ErrRecordUnreadable) || released.SafeToRemoveFinalizer { + t.Fatalf("holder release = %#v, %v, want ErrRecordUnreadable", released, err) + } + } + }) + } +} + +// Every lifecycle read that decodes a private record by name reports a record +// that cannot be decoded, not only the scans across claims. +func TestUndecodableRecordsAreReportedOnEveryDecodePath(t *testing.T) { + undecodable := func(name, recordType string, claimUID types.UID) *corev1.Secret { + return &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "private", Name: name, Labels: map[string]string{recordTypeLabel: recordType, claimUIDLabel: string(claimUID)}}, Type: corev1.SecretType("fleet.datumapis.com/private-lifecycle"), Data: map[string][]byte{recordDataKey: []byte(`{"schemaVersion":1}`)}} + } + cases := []struct { + name string + recordType string + run func(t *testing.T, f *fixture) error + // released is set where the record belongs to another claim, so the + // call succeeds after reporting it. + released bool + }{ + {name: "EnsureClaimCustody", recordType: "custody", run: func(t *testing.T, f *fixture) error { + request := f.request("claim") + name := custodyRecordName(LocalClaimScope(request.NamespaceUID), request.Claim.UID) + if err := f.coordinator.client.Create(context.Background(), undecodable(name, "custody", request.Claim.UID)); err != nil { + t.Fatal(err) + } + return f.coordinator.EnsureClaimCustody(context.Background(), request.Claim, request.NamespaceUID, request.Admission) + }}, + {name: "getOrCreateOperation", recordType: "installation", run: func(t *testing.T, f *fixture) error { + if err := f.coordinator.client.Create(context.Background(), undecodable(operationPrefix+"existing", "installation", "claim")); err != nil { + t.Fatal(err) + } + _, _, err := f.coordinator.getOrCreateOperation(context.Background(), operationPrefix+"existing", InstallationRequest{}, &AssetRecord{}, "None", ResolvedImage{}) + return err + }}, + {name: "markOperationSucceeded", recordType: "installation", run: func(t *testing.T, f *fixture) error { + if err := f.coordinator.client.Create(context.Background(), undecodable(operationPrefix+"running", "installation", "claim")); err != nil { + t.Fatal(err) + } + _, err := f.coordinator.markOperationSucceeded(context.Background(), operationPrefix+"running", &InstallationRecord{}) + return err + }}, + {name: "materializeSelectionForRelease", recordType: "asset", released: true, run: func(t *testing.T, f *fixture) error { + holder, releasing := f.request("holder"), f.request("releasing") + held := f.allocate(t, holder) + f.selectingOn(t, releasing, held) + f.writeOlderAssetShape(t, held.AssetID, nil) + custody, _, err := f.coordinator.getCustody(context.Background(), releasing.Claim.UID) + if err != nil { + t.Fatal(err) + } + return f.coordinator.materializeSelectionForRelease(context.Background(), custody) + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + before := undecodableCount(t, tc.recordType) + err := tc.run(t, f) + if tc.released && err != nil || !tc.released && !errors.Is(err, ErrRecordUnreadable) { + t.Fatalf("error = %v, want released=%v", err, tc.released) + } + if got := undecodableCount(t, tc.recordType) - before; got != 1 { + t.Fatalf("%s counter advanced by %v, want 1", tc.recordType, got) + } + }) + } +} + +// A claim whose own custody record cannot be decoded is not allocated or +// released through it, and both calls report the record as unreadable so +// callers stop retrying. +func TestUndecodableOwnCustodyBlocksAllocateAndRelease(t *testing.T) { + ctx := context.Background() + f := newFixture(t) + request := f.request("a") + f.allocate(t, request) + _, secret, err := f.coordinator.getCustody(ctx, request.Claim.UID) + if err != nil { + t.Fatal(err) + } + secret.Data[recordDataKey] = []byte(`{"schemaVersion":99}`) + if err := f.coordinator.client.Update(ctx, secret); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrRecordUnreadable) { + t.Fatalf("release error = %v, want ErrRecordUnreadable", err) + } + if _, err := f.coordinator.Allocate(ctx, request); !errors.Is(err, ErrRecordUnreadable) { + t.Fatalf("allocate error = %v, want ErrRecordUnreadable", err) + } +} diff --git a/internal/manager/indexes.go b/internal/manager/indexes.go index 672d927d..c5637517 100644 --- a/internal/manager/indexes.go +++ b/internal/manager/indexes.go @@ -196,6 +196,11 @@ func uniqueStrings(values []string) []string { return result } +// routePrivate routes only records whose owner validated the complete record. +// An undecodable record routes nowhere, even by its claim-uid label: the label +// carries no project or claim name, and routing never trusts an unvalidated +// field. Removing such a record therefore wakes no claim; the operator +// procedure deletes the Machine before removing its records. func routePrivate(secret *corev1.Secret, privateNamespace string) (controller.PrivateRecordRoute, bool) { if secret == nil || privateNamespace == "" || secret.Namespace != privateNamespace { return controller.PrivateRecordRoute{}, false diff --git a/internal/manager/machine_handler.go b/internal/manager/machine_handler.go index 2819b2b4..c3b805f6 100644 --- a/internal/manager/machine_handler.go +++ b/internal/manager/machine_handler.go @@ -109,7 +109,7 @@ func (h MachineHandler) ReconcileEvent(ctx context.Context, request ProjectReque return Outcome{RetryError: ErrEventWiringUnavailable} } if err := h.Lifecycle.RetainAuthority(ctx, h.Project, &claim, inputs); err != nil { - return allocationOutcome(err) + return recordOutcome(err) } deadline := deadlineFor(inputs.EvidenceExpiresAt) if !containsString(claim.Finalizers, controller.MachineFinalizer) { @@ -121,7 +121,7 @@ func (h MachineHandler) ReconcileEvent(ctx context.Context, request ProjectReque return Outcome{Deadline: deadline} } if err := h.Lifecycle.Allocate(ctx, h.Project, &claim, inputs); err != nil { - outcome := allocationOutcome(err) + outcome := recordOutcome(err) if outcome.RetryError == nil { outcome.Deadline = deadline } @@ -140,7 +140,7 @@ func (h MachineHandler) releaseUID(ctx context.Context, uid types.UID, claim *fl if errors.Is(err, ErrMachineAuthorityNotFound) { return Outcome{Deadline: CancelDeadline()} } - return dependencyOutcome(err) + return recordOutcome(err) } if !result.SafeToRemoveFinalizer { return Outcome{RetryError: ErrEventWiringUnavailable} @@ -154,12 +154,14 @@ func (h MachineHandler) releaseUID(ctx context.Context, uid types.UID, claim *fl return Outcome{Deadline: CancelDeadline()} } -// allocationOutcome classifies admission and allocation errors for a live -// Machine. Retained authority accepted under the pre-exact CPU and memory -// contract is terminal for continued use: retrying cannot make it valid, so it -// is not requeued. Deleting the Machine is a new primary event that releases it. -func allocationOutcome(err error) Outcome { - if errors.Is(err, controller.ErrLegacyRecord) { +// recordOutcome does not requeue a Machine whose own private record cannot be +// decoded: retrying cannot make it readable, and the coordinator has already +// logged and counted it. The finalizer stays until an operator removes the +// record. The handler sets no condition because it writes no Machine status; +// synthetic staging is the only writer of Machine lifecycle conditions. Every +// other error is classified by dependencyOutcome. +func recordOutcome(err error) Outcome { + if errors.Is(err, controller.ErrRecordUnreadable) { return Outcome{} } return dependencyOutcome(err) diff --git a/internal/manager/machine_handler_test.go b/internal/manager/machine_handler_test.go index 16247ba7..fcf0f2e4 100644 --- a/internal/manager/machine_handler_test.go +++ b/internal/manager/machine_handler_test.go @@ -3,6 +3,7 @@ package manager import ( "context" "errors" + "fmt" "testing" "time" @@ -242,35 +243,64 @@ func TestMachineHandlerReleaseRemovesFinalizerOnlyAfterSafeSettlement(t *testing } } -func TestMachineHandlerDoesNotRetryLegacyAuthorityButStillReleases(t *testing.T) { - handler, kube, lifecycle, request, _ := newMachineHandlerFixture(t) - if first := handler.ReconcileEvent(context.Background(), request); first.RetryError != nil { - t.Fatal(first.RetryError) - } - lifecycle.allocateErr = controller.ErrLegacyRecord - if outcome := handler.ReconcileEvent(context.Background(), request); outcome.RetryError != nil { - t.Fatalf("legacy allocation outcome = %#v", outcome) - } - lifecycle.allocateErr, lifecycle.retainErr = nil, controller.ErrLegacyRecord - if outcome := handler.ReconcileEvent(context.Background(), request); outcome.RetryError != nil { - t.Fatalf("legacy recovery outcome = %#v", outcome) +// A Machine whose own private record cannot be decoded is not requeued, and +// release through that record keeps the finalizer. +func TestMachineHandlerDoesNotRequeueUnreadablePrivateRecord(t *testing.T) { + unreadable := fmt.Errorf("%w: asset secret private/fleet-asset-x", controller.ErrRecordUnreadable) + cases := []struct { + name string + setup func(t *testing.T, kube client.Client, lifecycle *fakeMachineLifecycle, key client.ObjectKey) + verify func(t *testing.T, kube client.Client, key client.ObjectKey) + }{ + {name: "retain authority", setup: func(_ *testing.T, _ client.Client, l *fakeMachineLifecycle, _ client.ObjectKey) { + l.retainErr = unreadable + }}, + {name: "allocate", setup: func(t *testing.T, kube client.Client, l *fakeMachineLifecycle, key client.ObjectKey) { + setFinalizer(t, kube, key) + l.allocateErr = unreadable + }}, + {name: "release", setup: func(t *testing.T, kube client.Client, l *fakeMachineLifecycle, key client.ObjectKey) { + setFinalizer(t, kube, key) + var claim fleetv1.Machine + if err := kube.Get(context.Background(), key, &claim); err != nil { + t.Fatal(err) + } + if err := kube.Delete(context.Background(), &claim); err != nil { + t.Fatal(err) + } + l.releaseErr = unreadable + }, verify: func(t *testing.T, kube client.Client, key client.ObjectKey) { + var claim fleetv1.Machine + if err := kube.Get(context.Background(), key, &claim); err != nil || !containsString(claim.Finalizers, controller.MachineFinalizer) { + t.Fatalf("finalizer was removed through an unreadable record: %#v, %v", claim.Finalizers, err) + } + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + handler, kube, lifecycle, request, _ := newMachineHandlerFixture(t) + key := client.ObjectKey{Namespace: request.Namespace, Name: request.Name} + tc.setup(t, kube, lifecycle, key) + if outcome := handler.ReconcileEvent(context.Background(), request); outcome.RetryError != nil { + t.Fatalf("outcome = %#v, want no requeue", outcome) + } + if tc.verify != nil { + tc.verify(t, kube, key) + } + }) } +} +func setFinalizer(t *testing.T, kube client.Client, key client.ObjectKey) { + t.Helper() var claim fleetv1.Machine - key := client.ObjectKey{Namespace: request.Namespace, Name: request.Name} if err := kube.Get(context.Background(), key, &claim); err != nil { t.Fatal(err) } - if err := kube.Delete(context.Background(), &claim); err != nil { + claim.Finalizers = []string{controller.MachineFinalizer} + if err := kube.Update(context.Background(), &claim); err != nil { t.Fatal(err) } - lifecycle.release.SafeToRemoveFinalizer = true - if outcome := handler.ReconcileEvent(context.Background(), request); outcome.RetryError != nil || lifecycle.releases != 1 { - t.Fatalf("legacy release outcome = %#v releases=%d", outcome, lifecycle.releases) - } - if err := kube.Get(context.Background(), key, &claim); !apierrors.IsNotFound(err) { - t.Fatalf("finalizer retained after legacy release: %v", err) - } } func TestMachineHandlerRetriesInfrastructureFailure(t *testing.T) { diff --git a/internal/manager/manager_test.go b/internal/manager/manager_test.go index f3946897..a57996e4 100644 --- a/internal/manager/manager_test.go +++ b/internal/manager/manager_test.go @@ -573,7 +573,7 @@ func privateMiloAuthoritySecret(t *testing.T, project controller.ProjectIdentity Request milo.SourceUseRequest `json:"request"` Receipt milo.SourceUseReceipt `json:"receipt"` }{request, receipt} - record := milo.AuthorityRecord{SchemaVersion: 1, RecordID: "authority-record", State: milo.StatePrepared, ClaimNamespace: namespace, ClaimName: name, ClaimUID: claimUID, SourceRequest: request, SourceReceipt: receipt, ContractDigest: testDigest(t, contract), AcceptedRequirements: controller.ExactRequirements(accepted)} + record := milo.AuthorityRecord{SchemaVersion: 1, RecordID: "authority-record", State: milo.StatePrepared, ClaimNamespace: namespace, ClaimName: name, ClaimUID: claimUID, SourceRequest: request, SourceReceipt: receipt, ContractDigest: testDigest(t, contract), AcceptedRequirements: accepted} data, err := json.Marshal(record) if err != nil { t.Fatal(err) diff --git a/internal/milo/adapter.go b/internal/milo/adapter.go index 07894b9b..c26db79e 100644 --- a/internal/milo/adapter.go +++ b/internal/milo/adapter.go @@ -125,7 +125,7 @@ func (a *Adapter) PrepareClaim(ctx context.Context, request PrepareRequest) (Pre if err != nil { return PreparedClaim{}, err } - record := AuthorityRecord{SchemaVersion: authoritySchemaVersion, RecordID: shortDigest(contractDigest + "/" + string(request.Claim.UID)), State: StatePrepared, ClaimNamespace: request.Claim.Namespace, ClaimName: request.Claim.Name, ClaimUID: request.Claim.UID, SourceRequest: source, SourceReceipt: receipt, ContractDigest: contractDigest, AcceptedRequirements: controller.ExactRequirements(request.LocalProfile.Spec)} + record := AuthorityRecord{SchemaVersion: authoritySchemaVersion, RecordID: shortDigest(contractDigest + "/" + string(request.Claim.UID)), State: StatePrepared, ClaimNamespace: request.Claim.Namespace, ClaimName: request.Claim.Name, ClaimUID: request.Claim.UID, SourceRequest: source, SourceReceipt: receipt, ContractDigest: contractDigest, AcceptedRequirements: request.LocalProfile.Spec} ref, err := a.Records.Create(ctx, record) if err != nil { return PreparedClaim{}, err @@ -206,11 +206,6 @@ func validateRecoveredPrepare(record *AuthorityRecord, request PrepareRequest, c if record == nil || request.Claim == nil || request.LocalClass == nil || request.SourceClass == nil || request.LocalProfile == nil || request.NamespaceUID == "" || request.PublicationRevision == "" || !request.Location.Valid() { return ErrAuthorityInvalid } - // Authority accepted under the pre-exact CPU and memory contract is never - // recovered for continued use; release does not pass through here. - if record.AcceptedRequirements.Legacy() { - return controller.ErrLegacyRecord - } if record.ClaimNamespace != request.Claim.Namespace || record.ClaimName != request.Claim.Name || record.ClaimUID != request.Claim.UID || request.LocalClass.Name != request.Claim.Spec.MachineClassRef.Name || request.LocalProfile.Name != request.Claim.Spec.MachineProfileRef.Name { return ErrAuthorityInvalid } @@ -544,9 +539,6 @@ func (a *Adapter) finishAbortedSettlement(ctx context.Context, authority control } func validatePreparedAllocation(record *AuthorityRecord, prepared PreparedClaim, request controller.AllocationRequest) error { - if record != nil && record.AcceptedRequirements.Legacy() { - return controller.ErrLegacyRecord - } if record == nil || request.Claim == nil || request.Class == nil || request.Profile == nil || prepared.Authority.ContractDigest != record.ContractDigest || record.SourceRequest.ConsumerProject != prepared.ConsumerProject || record.SourceRequest.ProviderProject != prepared.ProviderProject || record.SourceRequest.NamespaceUID != prepared.NamespaceUID || record.SourceReceipt.PrincipalUID != prepared.PrincipalUID || record.SourceReceipt.DecisionID != prepared.DecisionID || request.Claim.Namespace != record.ClaimNamespace || request.Claim.Name != record.ClaimName || request.Claim.UID != record.ClaimUID || prepared.LocalClassUID != record.SourceRequest.LocalClassUID || prepared.SourceClassUID != record.SourceRequest.SourceClassUID || prepared.LocalProfileUID != record.SourceRequest.LocalProfileUID || prepared.SourceProfileUID != record.SourceRequest.SourceProfileUID || !sameLocationLifetime(prepared.Location, record.SourceRequest.Location) || !sameLocationLifetime(request.Location, record.SourceRequest.Location) || request.Claim.Spec.LocationRef.Name != record.SourceRequest.Location.Name || request.Class.UID != record.SourceRequest.SourceClassUID || request.Class.Status.EvaluatedRevision == "" { return ErrAuthorityInvalid } diff --git a/internal/milo/authority_test.go b/internal/milo/authority_test.go index 72ed6f12..f167a993 100644 --- a/internal/milo/authority_test.go +++ b/internal/milo/authority_test.go @@ -55,7 +55,7 @@ func TestAuthorityRecordConcurrentCreateIsExactAndPrivate(t *testing.T) { Receipt SourceUseReceipt `json:"receipt"` }{request, receipt} contractDigest, _ := digest(contract) - record := AuthorityRecord{SchemaVersion: authoritySchemaVersion, RecordID: "record-id", State: StatePrepared, ClaimNamespace: "default", ClaimName: "allocation", ClaimUID: request.ClaimUID, SourceRequest: request, SourceReceipt: receipt, ContractDigest: contractDigest, AcceptedRequirements: controller.ExactRequirements(accepted)} + record := AuthorityRecord{SchemaVersion: authoritySchemaVersion, RecordID: "record-id", State: StatePrepared, ClaimNamespace: "default", ClaimName: "allocation", ClaimUID: request.ClaimUID, SourceRequest: request, SourceReceipt: receipt, ContractDigest: contractDigest, AcceptedRequirements: accepted} mismatched := record mismatched.ClaimUID = "other-claim" if !errors.Is(validateAuthorityRecord(&mismatched), ErrAuthorityInvalid) { diff --git a/internal/milo/legacy_test.go b/internal/milo/legacy_test.go deleted file mode 100644 index 5328516e..00000000 --- a/internal/milo/legacy_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package milo - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "testing" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - - "go.datum.net/fleet/internal/controller" - fleetnetwork "go.datum.net/fleet/internal/network" -) - -// TestLegacyAuthorityRequirementsDecodeForReleaseOnly proves an authority -// record retained before CPU and memory became exact still decodes with its -// original requirements digest, survives the record rewrites release performs, -// and is refused for recovery and allocation. -func TestLegacyAuthorityRequirementsDecodeForReleaseOnly(t *testing.T) { - ctx := context.Background() - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - store, _ := NewRecordStore(fake.NewClientBuilder().WithScheme(scheme).Build(), "private") - legacyJSON := []byte(`{"cpu":{"architecture":"amd64","cores":{"min":24}},"memory":{"capacity":{"min":"128Gi"}}}`) - var accepted controller.RetainedRequirements - if err := json.Unmarshal(legacyJSON, &accepted); err != nil || !accepted.Legacy() { - t.Fatalf("legacy requirements = %v, %v", accepted.Legacy(), err) - } - // The digest a pre-exact manager retained was computed over this JSON. - sum := sha256.Sum256(legacyJSON) - request := SourceUseRequest{ConsumerProject: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "consumer", UID: "consumer-uid"}, ProviderProject: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "provider-uid"}, NamespaceUID: "namespace-uid", ClaimUID: "claim-uid", LocalClassUID: "local-class", SourceClassUID: "source-class", SourceClassRevision: "r1", SourceClassDigest: "class-digest", LocalProfileUID: "deleted-profile-uid", ProfileKind: ProfileCustom, RequirementsDigest: hex.EncodeToString(sum[:]), PublicationRevision: "publication", Location: fleetnetwork.LocationAuthority{Name: "us-central-1", UID: "location-uid", Revision: "location-r1"}} - receipt, _ := (&testSource{}).AuthorizeSource(ctx, request) - contract := struct { - Request SourceUseRequest `json:"request"` - Receipt SourceUseReceipt `json:"receipt"` - }{request, receipt} - contractDigest, _ := digest(contract) - record := AuthorityRecord{SchemaVersion: authoritySchemaVersion, RecordID: "record-id", State: StatePrepared, ClaimNamespace: "default", ClaimName: "allocation", ClaimUID: request.ClaimUID, SourceRequest: request, SourceReceipt: receipt, ContractDigest: contractDigest, AcceptedRequirements: accepted} - ref, err := store.Create(ctx, record) - if err != nil { - t.Fatalf("legacy authority record rejected: %v", err) - } - stored, err := store.Get(ctx, ref) - if err != nil || !stored.AcceptedRequirements.Legacy() { - t.Fatalf("legacy authority decode = %#v, %v", stored, err) - } - if _, err := store.Update(ctx, ref, func(*AuthorityRecord) error { return nil }); err != nil { - t.Fatalf("legacy authority rewrite: %v", err) - } - if stored, err = store.Get(ctx, ref); err != nil || !stored.AcceptedRequirements.Legacy() { - t.Fatalf("legacy authority after rewrite = %#v, %v", stored, err) - } - - f := newAdapterFixture(t) - if err := validateRecoveredPrepare(stored, f.prepare, request.ConsumerProject, request.ProviderProject); !errors.Is(err, controller.ErrLegacyRecord) { - t.Fatalf("recovery of legacy authority = %v", err) - } - if err := validatePreparedAllocation(stored, PreparedClaim{}, f.allocation); !errors.Is(err, controller.ErrLegacyRecord) { - t.Fatalf("allocation with legacy authority = %v", err) - } -} diff --git a/internal/milo/records.go b/internal/milo/records.go index 30535318..f8b1e547 100644 --- a/internal/milo/records.go +++ b/internal/milo/records.go @@ -123,6 +123,12 @@ func (s *RecordStore) getByName(ctx context.Context, name string) (*AuthorityRec return nil, nil, err } record, err := decodeAuthoritySecret(&secret) + if err != nil { + // Authority records are read only by their claim's deterministic + // name, so an unreadable one blocks only that claim. + controller.ReportUndecodableRecord(ctx, "milo-authority", &secret, err) + return nil, &secret, fmt.Errorf("%w: %w", err, controller.ErrRecordUnreadable) + } return record, &secret, err } diff --git a/internal/milo/types.go b/internal/milo/types.go index 7a67f5de..47d43654 100644 --- a/internal/milo/types.go +++ b/internal/milo/types.go @@ -196,30 +196,27 @@ const ( ) // AuthorityRecord is the private Milo authority state for one claim lifetime. -// AcceptedRequirements may hold the pre-exact CPU and memory shape for records -// written before exact requests. It re-encodes verbatim, so the retained -// requirements digest stays valid; see controller.RetainedRequirements. type AuthorityRecord struct { - SchemaVersion int `json:"schemaVersion"` - RecordID string `json:"recordID"` - State AuthorityState `json:"state"` - ClaimNamespace string `json:"claimNamespace"` - ClaimName string `json:"claimName"` - ClaimUID types.UID `json:"claimUID"` - SourceRequest SourceUseRequest `json:"sourceRequest"` - SourceReceipt SourceUseReceipt `json:"sourceReceipt"` - ContractDigest string `json:"contractDigest"` - AcceptedRequirements controller.RetainedRequirements `json:"acceptedRequirements"` - Entitlement *EntitlementEvidence `json:"entitlement,omitempty"` - QuotaIntent *QuotaIntent `json:"quotaIntent,omitempty"` - QuotaHold *QuotaHold `json:"quotaHold,omitempty"` - FenceReceipt *AdmissionCommitReceipt `json:"fenceReceipt,omitempty"` - AssetID string `json:"assetID,omitempty"` - BindingID string `json:"bindingID,omitempty"` - Settlement *SettlementReceipt `json:"settlement,omitempty"` - LastSettledHold *QuotaHold `json:"lastSettledHold,omitempty"` - LastSettlement *SettlementReceipt `json:"lastSettlement,omitempty"` - NoHold *NoHoldReceipt `json:"noHold,omitempty"` + SchemaVersion int `json:"schemaVersion"` + RecordID string `json:"recordID"` + State AuthorityState `json:"state"` + ClaimNamespace string `json:"claimNamespace"` + ClaimName string `json:"claimName"` + ClaimUID types.UID `json:"claimUID"` + SourceRequest SourceUseRequest `json:"sourceRequest"` + SourceReceipt SourceUseReceipt `json:"sourceReceipt"` + ContractDigest string `json:"contractDigest"` + AcceptedRequirements fleetv1.MachineProfileSpec `json:"acceptedRequirements"` + Entitlement *EntitlementEvidence `json:"entitlement,omitempty"` + QuotaIntent *QuotaIntent `json:"quotaIntent,omitempty"` + QuotaHold *QuotaHold `json:"quotaHold,omitempty"` + FenceReceipt *AdmissionCommitReceipt `json:"fenceReceipt,omitempty"` + AssetID string `json:"assetID,omitempty"` + BindingID string `json:"bindingID,omitempty"` + Settlement *SettlementReceipt `json:"settlement,omitempty"` + LastSettledHold *QuotaHold `json:"lastSettledHold,omitempty"` + LastSettlement *SettlementReceipt `json:"lastSettlement,omitempty"` + NoHold *NoHoldReceipt `json:"noHold,omitempty"` } func digest(value any) (string, error) { diff --git a/internal/staging/handler.go b/internal/staging/handler.go index 7ad6daaf..c65484a1 100644 --- a/internal/staging/handler.go +++ b/internal/staging/handler.go @@ -137,17 +137,17 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ admission := controller.AdmissionAuthority{PrincipalUID: "synthetic-staging:" + string(h.Project.UID), DecisionID: "synthetic-staging:" + string(claim.UID)} if crossProject { if err := h.Coordinator.EnsureClaimCustody(ctx, &claim, namespace.UID, admission, h.Project); err != nil { - return manager.Outcome{RetryError: err} + return h.lifecycleError(ctx, &claim, err) } authority, hold := syntheticCrossProjectAuthority(claim.UID, claim.Namespace, h.Project, h.ProviderProject) if err := h.Coordinator.RetainClaimAuthority(ctx, claim.UID, h.Project, h.ProviderProject, authority); err != nil { - return manager.Outcome{RetryError: err} + return h.lifecycleError(ctx, &claim, err) } if err := h.Coordinator.RetainAllocationAuthority(ctx, claim.UID, h.Project, h.ProviderProject, authority, hold); err != nil { - return manager.Outcome{RetryError: err} + return h.lifecycleError(ctx, &claim, err) } } else if err := h.Coordinator.EnsureClaimCustody(ctx, &claim, namespace.UID, admission); err != nil { - return manager.Outcome{RetryError: err} + return h.lifecycleError(ctx, &claim, err) } if !contains(claim.Finalizers, controller.MachineFinalizer) { updated := claim.DeepCopyObject().(*fleetv1.Machine) @@ -171,13 +171,8 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ if errors.Is(err, controller.ErrInsufficientCapacity) { return h.pending(ctx, &claim, "InsufficientCapacity", "No matching synthetic machine is currently available.", nil) } - if errors.Is(err, controller.ErrLegacyRecord) { - // Retrying cannot make a pre-exact allocation valid. Report it as - // explicitly not bound and not ready; deletion releases it. - return h.pending(ctx, &claim, controller.ReasonLegacyCustodyRecord, legacyCustodyMessage, nil) - } if err != nil { - return manager.Outcome{RetryError: err} + return h.lifecycleError(ctx, &claim, err) } for i := range list.Items { if list.Items[i].UID == record.MachineUID { @@ -213,6 +208,18 @@ func (h Handler) ReconcileEvent(ctx context.Context, request manager.ProjectRequ return manager.Outcome{} } +// lifecycleError reports a private record of this Machine that cannot be +// decoded as not bound and not ready, without retrying: retrying cannot make +// the record readable. Every other error is retried. +func (h Handler) lifecycleError(ctx context.Context, claim *fleetv1.Machine, err error) manager.Outcome { + if errors.Is(err, controller.ErrRecordUnreadable) { + return h.pending(ctx, claim, controller.ReasonUnreadablePrivateRecord, unreadableRecordMessage, nil) + } + return manager.Outcome{RetryError: err} +} + +const unreadableRecordMessage = "A private lifecycle record for this Machine cannot be decoded. Fleet will not allocate, install, or release through it; an operator must remove the record." + func (h Handler) dependency(ctx context.Context, claim *fleetv1.Machine, reason string, err error) manager.Outcome { if apierrors.IsNotFound(err) { return h.pending(ctx, claim, reason, err.Error(), nil) @@ -267,11 +274,19 @@ func (h Handler) release(ctx context.Context, namespace string, uid types.UID, c if errors.Is(err, controller.ErrRecordInvalid) && (claim == nil || !contains(claim.Finalizers, controller.MachineFinalizer)) { return manager.Outcome{} } + // The finalizer stays until an operator removes the record; see + // docs/development/README.md. + if errors.Is(err, controller.ErrRecordUnreadable) { + return h.pending(ctx, claim, controller.ReasonUnreadablePrivateRecord, unreadableRecordMessage, nil) + } return manager.Outcome{RetryError: err} } if crossProject && result.ExternalSettlementRequired { authority, hold := syntheticCrossProjectAuthority(uid, namespace, h.Project, h.ProviderProject) result, err = h.Coordinator.CompleteExternalRelease(ctx, uid, authority, hold, h.Project) + if errors.Is(err, controller.ErrRecordUnreadable) { + return h.pending(ctx, claim, controller.ReasonUnreadablePrivateRecord, unreadableRecordMessage, nil) + } if err != nil { return manager.Outcome{RetryError: err} } @@ -343,8 +358,6 @@ func syntheticCrossProjectAuthority(claimUID types.UID, namespace string, consum return authority, hold } -const legacyCustodyMessage = "Private custody for this Machine was accepted before MachineProfile CPU and memory became exact and cannot be resumed. Delete the Machine to release the allocation through verified cleanup." - func admissionReason(crossProject bool) string { if crossProject { return "SyntheticCrossProjectAdmission" diff --git a/internal/staging/legacy_test.go b/internal/staging/legacy_test.go deleted file mode 100644 index 92f1d1ea..00000000 --- a/internal/staging/legacy_test.go +++ /dev/null @@ -1,209 +0,0 @@ -package staging - -import ( - "context" - "encoding/json" - "testing" - "time" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - apiMeta "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - "go.datum.net/fleet/internal/manager" - "go.datum.net/fleet/internal/simulator" -) - -// TestLegacyCustodyIsReportedThenReleasedOnDeletion reproduces an upgrade over -// synthetic staging: a Machine allocated before CPU and memory became exact, -// whose profile was then deleted and recreated with a new UID. The Machine is -// reported as not ready without a retry loop, and deleting it performs the -// normal verified release so the capacity returns and the finalizer clears. -func TestLegacyCustodyIsReportedThenReleasedOnDeletion(t *testing.T) { - ctx := context.Background() - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - if err := fleetv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-uid"}} - class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose", UID: "class-uid"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: "default"}}}} - profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose-24c-128g", UID: "original-profile-uid", Generation: 1}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 24}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} - capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "central-metal-01", UID: "capacity-uid"}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "central-metal-01"}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "synthetic-reuse"}, ReclaimPolicy: "Retain"}} - machine := func(name, uid string) *fleetv1.Machine { - return &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name, UID: types.UID(uid), Generation: 1}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: class.Name}, MachineProfileRef: fleetv1.LocalReference{Name: profile.Name}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}} - } - runner := machine("legacy-machine", "legacy-machine-uid") - public := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&fleetv1.MachineCapacity{}, &fleetv1.Machine{}).WithObjects(namespace, class, profile, capacity, runner).Build() - private := fake.NewClientBuilder().WithScheme(scheme).Build() - provider := &executor{results: map[string]simulator.OperationResult{}} - coordinator, err := controller.NewCoordinator(private, "fleet-system-private", provider, controller.LocalDigestImageResolver{}, nil, 10*time.Minute) - if err != nil { - t.Fatal(err) - } - project := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "datum-cloud", UID: "project-uid"} - handler := Handler{Public: public, Coordinator: coordinator, Project: project, Location: "us-central-1", Now: time.Now} - request := func(object *fleetv1.Machine) manager.ProjectRequest { - return manager.ProjectRequest{AuthorityID: project.AuthorityID, ProjectUID: project.UID, Namespace: object.Namespace, Name: object.Name, UID: object.UID} - } - - // Before the upgrade: allocate, then rewrite the retained records into the - // pre-exact shape and recreate the profile under a new UID. - for i := 0; i < 2; i++ { - if out := handler.ReconcileEvent(ctx, request(runner)); out.RetryError != nil { - t.Fatal(out.RetryError) - } - } - assertPhase(t, ctx, public, client.ObjectKeyFromObject(runner), "Ready") - legacyizeStagingRecords(t, ctx, private, runner.UID) - if err := public.Delete(ctx, &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: profile.Name}}); err != nil { - t.Fatal(err) - } - recreated := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: profile.Name, UID: "recreated-profile-uid", Generation: 1}, Spec: profile.Spec} - if err := public.Create(ctx, recreated); err != nil { - t.Fatal(err) - } - - // After the upgrade: every event settles without a retry error and the - // Machine reports the legacy custody explicitly instead of readiness. - owner := manager.NewLifecycleOwner(handler, manager.RequestedHardwareProjector{Client: public, Project: project}, nil) - for i := 0; i < 3; i++ { - if out := owner.ReconcileEvent(ctx, request(runner)); out.RetryError != nil { - t.Fatalf("legacy custody produced a retry loop: %v", out.RetryError) - } - } - var current fleetv1.Machine - if err := public.Get(ctx, client.ObjectKeyFromObject(runner), ¤t); err != nil { - t.Fatal(err) - } - for _, conditionType := range []string{"Bound", "Ready"} { - condition := apiMeta.FindStatusCondition(current.Status.Conditions, conditionType) - if condition == nil || condition.Status != metav1.ConditionFalse || condition.Reason != controller.ReasonLegacyCustodyRecord { - t.Fatalf("%s condition = %#v", conditionType, condition) - } - } - if current.Status.Phase != "Pending" || current.Status.AllocatedHardware != nil { - t.Fatalf("legacy custody status = %#v", current.Status) - } - assertAvailable(t, ctx, public, capacity, metav1.ConditionFalse) - - // Deleting the Machine releases through verified cleanup. - if err := public.Delete(ctx, ¤t); err != nil { - t.Fatal(err) - } - if out := owner.ReconcileEvent(ctx, request(runner)); out.RetryError != nil { - t.Fatalf("release with legacy custody: %v", out.RetryError) - } - if err := public.Get(ctx, client.ObjectKeyFromObject(runner), ¤t); !apierrors.IsNotFound(err) { - t.Fatalf("finalizer was not removed: %v, %#v", err, current.Finalizers) - } - cleaned := false - for _, result := range provider.results { - cleaned = cleaned || result.Kind == "cleanup" - } - if !cleaned { - t.Fatal("release did not run verified cleanup") - } - assertAvailable(t, ctx, public, capacity, metav1.ConditionTrue) - if state := custodyState(t, ctx, private, runner.UID); state != string(controller.CustodyReleased) { - t.Fatalf("custody state = %q", state) - } - - // The returned capacity serves a new exact Machine. - next := machine("next-runner", "next-runner-uid") - if err := public.Create(ctx, next); err != nil { - t.Fatal(err) - } - for i := 0; i < 3; i++ { - if out := owner.ReconcileEvent(ctx, request(next)); out.RetryError != nil { - t.Fatal(out.RetryError) - } - } - assertPhase(t, ctx, public, client.ObjectKeyFromObject(next), "Ready") -} - -func assertAvailable(t *testing.T, ctx context.Context, kube client.Client, capacity *fleetv1.MachineCapacity, want metav1.ConditionStatus) { - t.Helper() - var current fleetv1.MachineCapacity - if err := kube.Get(ctx, client.ObjectKeyFromObject(capacity), ¤t); err != nil { - t.Fatal(err) - } - if condition := apiMeta.FindStatusCondition(current.Status.Conditions, "Available"); condition == nil || condition.Status != want { - t.Fatalf("Available = %#v, want %s", condition, want) - } -} - -func custodyState(t *testing.T, ctx context.Context, private client.Client, claimUID types.UID) string { - t.Helper() - var list corev1.SecretList - if err := private.List(ctx, &list, client.MatchingLabels{"fleet.datumapis.com/private-record": "custody", "fleet.datumapis.com/claim-uid": string(claimUID)}); err != nil || len(list.Items) != 1 { - t.Fatalf("custody records = %d, %v", len(list.Items), err) - } - var record struct { - State string `json:"state"` - } - if err := json.Unmarshal(list.Items[0].Data["record.json"], &record); err != nil { - t.Fatal(err) - } - return record.State -} - -// legacyizeStagingRecords rewrites the claim's retained custody proposal and -// asset record into the pre-exact requirements shape with deleted profile -// lifetimes. It uses synthetic data only. -func legacyizeStagingRecords(t *testing.T, ctx context.Context, private client.Client, claimUID types.UID) { - t.Helper() - var list corev1.SecretList - if err := private.List(ctx, &list, client.MatchingLabels{"fleet.datumapis.com/claim-uid": string(claimUID)}); err != nil { - t.Fatal(err) - } - legacyize := func(record map[string]any) { - requirements := record["acceptedRequirements"].(map[string]any) - cpu := requirements["cpu"].(map[string]any) - memory := requirements["memory"].(map[string]any) - cpu["cores"] = map[string]any{"min": cpu["cores"]} - memory["capacity"] = map[string]any{"min": memory["capacity"]} - record["profileUID"], record["localProfileUID"] = "original-profile-uid-deleted", "original-profile-uid-deleted" - } - rewritten := 0 - for i := range list.Items { - secret := &list.Items[i] - var record map[string]any - if err := json.Unmarshal(secret.Data["record.json"], &record); err != nil { - t.Fatal(err) - } - switch secret.Labels["fleet.datumapis.com/private-record"] { - case "asset": - legacyize(record) - case "custody": - proposal, ok := record["proposedAsset"].(map[string]any) - if !ok { - t.Fatal("bound custody has no retained proposal") - } - legacyize(proposal) - default: - continue - } - data, err := json.Marshal(record) - if err != nil { - t.Fatal(err) - } - secret.Data["record.json"] = data - if err := private.Update(ctx, secret); err != nil { - t.Fatal(err) - } - rewritten++ - } - if rewritten != 2 { - t.Fatalf("rewrote %d records, want custody and asset", rewritten) - } -} diff --git a/internal/staging/unreadable_test.go b/internal/staging/unreadable_test.go new file mode 100644 index 00000000..f849f329 --- /dev/null +++ b/internal/staging/unreadable_test.go @@ -0,0 +1,162 @@ +package staging + +import ( + "context" + "encoding/json" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/manager" + "go.datum.net/fleet/internal/simulator" +) + +// An unreadable asset record, in the older CPU and memory shape, or an +// unreadable custody record is reported on its own Machine only. Other +// Machines still allocate and release, and the affected Machine keeps its +// finalizer until an operator removes the record. +func TestUnreadablePrivateRecordIsReportedOnlyOnItsMachine(t *testing.T) { + for record, corrupt := range map[string]func(*testing.T, context.Context, client.Client, types.UID){"asset": writeOlderAssetShape, "custody": writeUnreadableCustody} { + t.Run(record, func(t *testing.T) { testUnreadablePrivateRecord(t, corrupt) }) + } +} + +func testUnreadablePrivateRecord(t *testing.T, corrupt func(*testing.T, context.Context, client.Client, types.UID)) { + ctx := context.Background() + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := fleetv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-uid"}} + class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose", UID: "class-uid"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: "default", Selector: metav1.LabelSelector{MatchLabels: map[string]string{"fleet.datumapis.com/capacity-pool": "central"}}}}}} + profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "general-purpose-24c-128g", UID: "profile-uid"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 24}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} + capacity := func(name string) *fleetv1.MachineCapacity { + return &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name, UID: types.UID(name + "-uid"), Labels: map[string]string{"fleet.datumapis.com/capacity-pool": "central"}}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: name}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "synthetic-reuse"}, ReclaimPolicy: "Retain"}} + } + claim := func(name string) *fleetv1.Machine { + return &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name, UID: types.UID(name + "-uid")}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: class.Name}, MachineProfileRef: fleetv1.LocalReference{Name: profile.Name}, LocationRef: fleetv1.LocalReference{Name: "us-central-1"}, PowerState: "Off"}} + } + stale, other := claim("stale"), claim("other") + public := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&fleetv1.MachineCapacity{}, &fleetv1.Machine{}).WithObjects(namespace, class, profile, capacity("central-metal-01"), capacity("central-metal-02"), stale, other).Build() + private := fake.NewClientBuilder().WithScheme(scheme).Build() + coordinator, err := controller.NewCoordinator(private, "fleet-system-private", &executor{results: map[string]simulator.OperationResult{}}, controller.LocalDigestImageResolver{}, nil, 10*time.Minute) + if err != nil { + t.Fatal(err) + } + project := controller.ProjectIdentity{AuthorityID: "staging", RouteName: "datum-cloud", UID: "project-uid"} + handler := Handler{Public: public, Coordinator: coordinator, Project: project, Location: "us-central-1", Now: time.Now} + reconcile := func(key client.ObjectKey) manager.Outcome { + var current fleetv1.Machine + if err := public.Get(ctx, key, ¤t); err != nil { + t.Fatal(err) + } + return handler.ReconcileEvent(ctx, manager.ProjectRequest{AuthorityID: project.AuthorityID, ProjectUID: project.UID, Namespace: current.Namespace, Name: current.Name, UID: current.UID}) + } + staleKey, otherKey := client.ObjectKeyFromObject(stale), client.ObjectKeyFromObject(other) + + for i := 0; i < 2; i++ { + if out := reconcile(staleKey); out.RetryError != nil { + t.Fatal(out.RetryError) + } + } + assertPhase(t, ctx, public, staleKey, "Ready") + corrupt(t, ctx, private, stale.UID) + + assertUnreadable := func() { + t.Helper() + if out := reconcile(staleKey); out.RetryError != nil { + t.Fatalf("unreadable record was requeued: %v", out.RetryError) + } + var current fleetv1.Machine + if err := public.Get(ctx, staleKey, ¤t); err != nil { + t.Fatal(err) + } + ready := apiMeta.FindStatusCondition(current.Status.Conditions, "Ready") + if current.Status.Phase != "Pending" || ready == nil || ready.Status != metav1.ConditionFalse || ready.Reason != controller.ReasonUnreadablePrivateRecord { + t.Fatalf("stale status = %#v", current.Status) + } + } + assertUnreadable() + + for i := 0; i < 2; i++ { + if out := reconcile(otherKey); out.RetryError != nil { + t.Fatal(out.RetryError) + } + } + assertPhase(t, ctx, public, otherKey, "Ready") + + for _, key := range []client.ObjectKey{staleKey, otherKey} { + var current fleetv1.Machine + if err := public.Get(ctx, key, ¤t); err != nil { + t.Fatal(err) + } + if err := public.Delete(ctx, ¤t); err != nil { + t.Fatal(err) + } + } + if out := reconcile(otherKey); out.RetryError != nil { + t.Fatal(out.RetryError) + } + var released fleetv1.Machine + if err := public.Get(ctx, otherKey, &released); err == nil { + t.Fatalf("other Machine kept its finalizer: %#v", released.Finalizers) + } + assertUnreadable() + var kept fleetv1.Machine + if err := public.Get(ctx, staleKey, &kept); err != nil || !contains(kept.Finalizers, controller.MachineFinalizer) { + t.Fatalf("stale Machine lost its finalizer: %#v, %v", kept.Finalizers, err) + } +} + +func writeOlderAssetShape(t *testing.T, ctx context.Context, private client.Client, claimUID types.UID) { + t.Helper() + var secrets corev1.SecretList + if err := private.List(ctx, &secrets, client.MatchingLabels{"fleet.datumapis.com/private-record": "asset", "fleet.datumapis.com/claim-uid": string(claimUID)}); err != nil { + t.Fatal(err) + } + if len(secrets.Items) != 1 { + t.Fatalf("asset records for %s = %d, want 1", claimUID, len(secrets.Items)) + } + secret := &secrets.Items[0] + var fields map[string]json.RawMessage + if err := json.Unmarshal(secret.Data["record.json"], &fields); err != nil { + t.Fatal(err) + } + fields["acceptedRequirements"] = json.RawMessage(`{"cpu":{"architecture":"amd64","cores":{"min":4}},"memory":{"capacity":{"min":"16Gi"}}}`) + data, err := json.Marshal(fields) + if err != nil { + t.Fatal(err) + } + secret.Data["record.json"] = data + if err := private.Update(ctx, secret); err != nil { + t.Fatal(err) + } +} + +func writeUnreadableCustody(t *testing.T, ctx context.Context, private client.Client, claimUID types.UID) { + t.Helper() + var secrets corev1.SecretList + if err := private.List(ctx, &secrets, client.MatchingLabels{"fleet.datumapis.com/private-record": "custody", "fleet.datumapis.com/claim-uid": string(claimUID)}); err != nil { + t.Fatal(err) + } + if len(secrets.Items) != 1 { + t.Fatalf("custody records for %s = %d, want 1", claimUID, len(secrets.Items)) + } + secret := &secrets.Items[0] + secret.Data["record.json"] = []byte(`{"schemaVersion":99}`) + if err := private.Update(ctx, secret); err != nil { + t.Fatal(err) + } +}