diff --git a/api/v1/clusterobjectset_types.go b/api/v1/clusterobjectset_types.go index d95d3c4759..a35d06f381 100644 --- a/api/v1/clusterobjectset_types.go +++ b/api/v1/clusterobjectset_types.go @@ -571,8 +571,8 @@ type ClusterObjectSetStatus struct { // - False with reason ObjectsNotReady: one or more objects are still being applied or have not yet passed their readiness probes during rollout. // - False with reason Superseded: one or more objects have been adopted by a newer revision of the object set. // - False with reason ObjectCollision: one or more objects are controlled by another owner, or are unowned while collision protection prevents adoption, so this revision cannot take ownership of them. - // - False with reason PreconditionsNotMet: a precondition for applying the revision is not yet satisfied (a referenced Secret is mutable or has invalid or changed content, or a preflight dry-run was rejected, e.g. an immutable field, a conflicting object, or RBAC/dependency CRDs not yet propagated); the revision keeps retrying and recovers once the precondition is met. - // - False with reason InvalidSpecification: the revision spec is invalid (a malformed revision/phase object or progression probe) and requires a spec change to proceed. + // - False with reason PreconditionsNotMet: a precondition for applying the revision is not yet satisfied (a referenced Secret is mutable or has invalid or changed content, a revision-wide preflight check was rejected, or a phase's preflight dry-run was rejected because RBAC or dependency CRDs have not yet propagated or a dependency such as the target namespace does not exist yet); the revision keeps retrying and recovers once the precondition is met. + // - False with reason InvalidSpecification: the revision spec is invalid (a malformed revision/phase object or progression probe, or a phase's preflight dry-run was rejected permanently, e.g. a schema violation or an immutable field) and requires a spec change to proceed. // - False with reason Archiving: the revision is being archived and its owned objects are still being torn down. // - False with reason Archived: the revision has been archived and its objects have been torn down. // @@ -613,7 +613,9 @@ type ClusterObjectSetStatus struct { CompletedAt metav1.Time `json:"completedAt,omitempty,omitzero"` } -// ObservedPhase records the observed content digest of a resolved phase. +// ObservedPhase reports a phase's current lifecycle state and sparse +// diagnostics together with its pinned content digest and historical +// completion. // +kubebuilder:validation:XValidation:rule="!has(oldSelf.completedAt) || has(self.completedAt)",message="completedAt cannot be removed once set" type ObservedPhase struct { // name is the phase name matching a phase in spec.phases. @@ -624,23 +626,48 @@ type ObservedPhase struct { // +kubebuilder:validation:XValidation:rule=`!format.dns1123Label().validate(self).hasValue()`,message="the value must consist of only lowercase alphanumeric characters and hyphens, and must start and end with an alphanumeric character." Name string `json:"name,omitempty"` - // status is the current state of this phase in the rollout. Must be one of - // InvalidSpecification, PreconditionsNotMet, Pending, Reconciling, - // Stabilizing, Ready, Unknown, Superseded, Archiving, or Archived. + // status summarizes the current lifecycle state of this phase: + // - Unknown: no usable evaluation of the phase exists yet. + // - Pending: application is waiting for an earlier phase, or teardown is + // waiting for a later phase. + // - Stabilizing: all objects are synced to this ClusterObjectSet, but at least one + // progression-probe result is false or unknown. + // - Ready: all objects are synced to this ClusterObjectSet and pass their + // progression probes, if any are defined. + // - PreconditionsNotMet: a precondition for applying the phase is not yet + // satisfied, for example a rejected preflight dry-run; the ClusterObjectSet + // keeps retrying and recovers once the precondition is met. + // - InvalidSpecification: the phase's declared content is malformed; + // correcting the configuration requires creating a replacement + // ClusterObjectSet. + // - ObjectCollision: one or more objects are controlled by another + // owner, or are unowned while collision protection prevents adoption, + // so this ClusterObjectSet cannot take ownership of them. + // - Superseded: at least one object is controlled by another + // ClusterObjectSet in the same group with a higher .spec.revision. + // - Archiving: this is the active teardown phase and owned objects remain to be removed. + // - Archived: this ClusterObjectSet's teardown responsibility for the phase is complete; + // objects adopted by newer ClusterObjectSets may still exist. + // + // Superseded does not imply that progression probes pass. Failing or unknown + // probes may still prevent later phases from advancing. + // PreconditionsNotMet, InvalidSpecification, and ObjectCollision statuses + // do not imply a terminal failure or a fixed retry policy. // +required Status PhaseStatus `json:"status,omitempty"` - // completedAt is the timestamp when this phase first became Ready. - // Set once and never modified. Nil means the phase has never been - // Ready. + // completedAt is the timestamp when this phase was first observed Ready. + // Omitted until that observation. Once recorded, it cannot change or be + // removed, even if the phase later fails its progression probes or is + // superseded. // +optional // +kubebuilder:validation:XValidation:rule="self == oldSelf || oldSelf == null",message="completedAt is immutable, once set" CompletedAt metav1.Time `json:"completedAt,omitempty,omitzero"` - // message is a phase-level message providing context about the - // current status (e.g. a validation error for InvalidSpecification - // phases, or a summary for Pending phases). At most 1024 characters; - // longer messages are truncated by the controller. + // message provides human-readable context, such as a phase-wide validation + // failure or the reason a phase is waiting. Consumers must not parse this + // message. At most 1024 characters; longer messages are truncated by the + // controller. // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MaxLength=1024 // +optional @@ -657,20 +684,22 @@ type ObservedPhase struct { // +kubebuilder:validation:XValidation:rule=`self.matches('^[a-z0-9]+:[a-f0-9]+$')`,message="digest must be in the format ':'" Digest string `json:"digest,omitempty"` - // lastTransitionTime is the last time the phase transitioned from one status to another. + // lastTransitionTime is the timestamp when the current status was first + // reported or last changed. Changes to message alone do not update this + // timestamp. // +required // +kubebuilder:validation:Type=string // +kubebuilder:validation:Format=date-time LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty,omitzero"` - // objectDetails lists objects in this phase that are not yet - // complete. For Reconciling, Pending, and Stabilizing phases, this - // includes probe failures, collisions, creation/update errors, and - // any other condition preventing completion. For Archiving phases, - // this lists objects still awaiting deletion. Each entry identifies - // the object and carries failure messages. Empty when status is - // Ready, Superseded, Archived, or Unknown. The list may contain at - // most 50 entries, matching the maximum number of objects per phase. + // objectDetails reports per-object facts for objects with current problems or + // notable ownership; it is not a full object inventory. An object is listed + // when it has progression probes that are not passing (objects in phases that + // are waiting for an earlier phase excluded), when this ClusterObjectSet cannot + // take ownership of it (including in phases that are waiting), when it has been + // adopted by a newer ClusterObjectSet, or when it awaits deletion in the active + // teardown phase. Entries are removed when those facts no longer apply. + // At most 50 entries, matching the maximum number of objects per phase. // +kubebuilder:validation:MaxItems=50 // +listType=atomic // +optional @@ -709,29 +738,68 @@ type ObjectCounts struct { Ready *int64 `json:"ready,omitempty"` } -// ObjectStatus identifies a managed object and its failure messages. +// ObjectStatus reports observed facts about an object with current problems or +// notable ownership. The object may be missing or controlled by a conflicting +// owner; it is not necessarily managed by this ClusterObjectSet. At least one of +// probeResults, ownership, or deletion is set. +// +kubebuilder:validation:XValidation:rule="has(self.probeResults) || has(self.ownership) || has(self.deletion)",message="at least one of probeResults, ownership, or deletion must be set" type ObjectStatus struct { - // group is the API group of the object (empty string for core - // resources). At most 253 characters (DNS subdomain max). - // +kubebuilder:validation:MinLength=1 - // +kubebuilder:validation:MaxLength=253 - // +kubebuilder:validation:XValidation:rule=`!format.dns1123Subdomain().validate(self).hasValue()`,message="the value must be a valid DNS subdomain: lowercase alphanumeric characters, hyphens, and dots, starting and ending with an alphanumeric character." + // object identifies the object by apiVersion, kind, namespace, and name, + // matching the declared object manifest. + // +required + Object ObjectReference `json:"object,omitzero"` + + // probeResults lists the object's progression probe results that are not passing, + // keyed by probe type. Probes of objects in phases that are waiting for an + // earlier phase are not reported. At most 8 entries. + // +kubebuilder:validation:MaxItems=8 + // +listType=map + // +listMapKey=type // +optional - Group string `json:"group,omitempty"` + ProbeResults []ObjectProbeResult `json:"probeResults,omitempty"` + + // ownership reports when this ClusterObjectSet does not control the object: + // - Colliding: the object exists but this ClusterObjectSet cannot take + // ownership of it under the configured collision protection policy. + // - Superseded: the object is controlled by another ClusterObjectSet in the + // same group with a higher .spec.revision. + // + // Omitted when this ClusterObjectSet controls the object. + // +optional + Ownership ObjectOwnership `json:"ownership,omitempty"` + + // deletion reports the object's teardown state: + // - AwaitingDeletion: the object is owned by this ClusterObjectSet, has been + // requested for deletion, and is not yet gone from the cluster. + // + // Omitted when the object is not being torn down. + // +optional + Deletion ObjectDeletion `json:"deletion,omitempty"` +} - // resource is the lowercase, plural resource type of the object - // (for example, "pods" or "configmaps"). Must be between 1 and 63 - // characters. +// ObjectReference identifies an object by apiVersion, kind, namespace, and name, +// matching the target identity fields of the declared object manifests. +type ObjectReference struct { + // apiVersion is the API version of the object, for example "v1" or + // "apps/v1". It matches the apiVersion of the declared object manifest. + // +required // +kubebuilder:validation:MinLength=1 - // +kubebuilder:validation:MaxLength=63 - // +kubebuilder:validation:XValidation:rule=`!format.dns1035Label().validate(self).hasValue()`,message="the value must consist of only lowercase alphanumeric characters and hyphens, must start with a letter, and must end with an alphanumeric character." + // +kubebuilder:validation:MaxLength=317 + // +kubebuilder:validation:XValidation:rule=`self.matches('^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[a-z]([-a-z0-9]*[a-z0-9])?$')`,message="apiVersion must be a version or group/version" + APIVersion string `json:"apiVersion,omitempty"` + + // kind is the kind of the object, for example "ConfigMap". It matches the + // kind of the declared object manifest. // +required - Resource string `json:"resource,omitempty"` + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:XValidation:rule=`self.matches('^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$')`,message="kind must start with a letter and contain only letters, digits, or hyphens, ending with an alphanumeric character" + Kind string `json:"kind,omitempty"` - // namespace is the namespace of the object. Empty for cluster-scoped - // resources. At most 253 characters (DNS subdomain max). + // namespace is the namespace of the object. Omitted for cluster-scoped + // resources. At most 63 characters (DNS label max). // +kubebuilder:validation:MinLength=1 - // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:MaxLength=63 // +kubebuilder:validation:XValidation:rule=`!format.dns1123Label().validate(self).hasValue()`,message="the value must consist of only lowercase alphanumeric characters and hyphens, and must start and end with an alphanumeric character." // +optional Namespace string `json:"namespace,omitempty"` @@ -743,12 +811,27 @@ type ObjectStatus struct { // +kubebuilder:validation:XValidation:rule=`self != "." && self != ".." && !self.contains("/") && !self.contains("%")`,message="name must be a valid object name: it may not be '.' or '..' or contain '/' or '%'" // +required Name string `json:"name,omitempty"` +} - // messages lists the failure reasons for this object. The maximum - // of 18 entries accounts for up to 16 assertion probe failures, - // one collision message, and one message to note truncation if necessary. - // Each message is at most 1024 characters; longer messages are truncated - // by the controller. +// ObjectProbeResult reports a progression probe result that is not passing. +type ObjectProbeResult struct { + // type is the probe type, for example "Progress", the aggregate of the + // ClusterObjectSet's progression probes that apply to the object. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + Type string `json:"type,omitempty"` + + // status is the probe result: + // - False: the probe evaluated to false. + // - Unknown: the probe result could not be determined, for example because + // the object's status has not yet been reported or is outdated. + // +required + Status ObjectProbeResultStatus `json:"status,omitempty"` + + // messages provides bounded human-readable explanations of the result. + // Consumers must not parse these messages. Messages describe an aggregate + // result; their number is not the number of failed assertions. // +kubebuilder:validation:MaxItems=18 // +kubebuilder:validation:items:MinLength=1 // +kubebuilder:validation:items:MaxLength=1024 @@ -757,56 +840,88 @@ type ObjectStatus struct { Messages []string `json:"messages,omitempty"` } +// ObjectProbeResultStatus is the status of a progression probe result that is not passing. +// +kubebuilder:validation:Enum=False;Unknown +type ObjectProbeResultStatus string + +const ( + // ObjectProbeResultStatusFalse indicates the probe evaluated to false. + ObjectProbeResultStatusFalse ObjectProbeResultStatus = "False" + // ObjectProbeResultStatusUnknown indicates the probe result could not be determined. + ObjectProbeResultStatusUnknown ObjectProbeResultStatus = "Unknown" +) + +// ObjectOwnership describes why a ClusterObjectSet does not control an object. +// +kubebuilder:validation:Enum=Colliding;Superseded +type ObjectOwnership string + +const ( + // ObjectOwnershipColliding indicates the object exists but the ClusterObjectSet + // cannot take ownership of it under the configured collision protection policy. + ObjectOwnershipColliding ObjectOwnership = "Colliding" + // ObjectOwnershipSuperseded indicates the object is controlled by another + // ClusterObjectSet in the same group with a higher .spec.revision. + ObjectOwnershipSuperseded ObjectOwnership = "Superseded" +) + +// ObjectDeletion describes an object's teardown state. +// +kubebuilder:validation:Enum=AwaitingDeletion +type ObjectDeletion string + +const ( + // ObjectDeletionAwaitingDeletion indicates the object is owned by the + // ClusterObjectSet, has been requested for deletion, and is not yet gone. + ObjectDeletionAwaitingDeletion ObjectDeletion = "AwaitingDeletion" +) + // PhaseStatus describes the current state of a phase in the rollout. // -// +kubebuilder:validation:Enum=InvalidSpecification;PreconditionsNotMet;Pending;Reconciling;Stabilizing;Ready;Unknown;Superseded;Archiving;Archived +// +kubebuilder:validation:Enum=Unknown;Pending;Stabilizing;Ready;PreconditionsNotMet;InvalidSpecification;ObjectCollision;Superseded;Archiving;Archived type PhaseStatus string const ( - // PhaseStatusInvalidSpecification indicates the phase failed preflight validation - // in a permanent way that requires a spec change to resolve (e.g. a schema - // violation, cross-phase object duplication, or an invalid phase name). - PhaseStatusInvalidSpecification PhaseStatus = "InvalidSpecification" + // PhaseStatusObjectCollision indicates one or more objects are controlled + // by another owner, or are unowned while collision protection prevents + // adoption, so this ClusterObjectSet cannot take ownership of them. + PhaseStatusObjectCollision PhaseStatus = "ObjectCollision" - // PhaseStatusPreconditionsNotMet indicates the phase failed a recoverable preflight - // dry-run check — for example, RBAC permissions or a dependency CRD that has not - // yet propagated to the cluster. The controller retries automatically; no spec - // change is required. - PhaseStatusPreconditionsNotMet PhaseStatus = "PreconditionsNotMet" - - // PhaseStatusPending indicates the phase is not being actively - // reconciled, but the controller has checked and some objects do not - // match the desired state. + // PhaseStatusPending indicates writes are waiting for an earlier application + // phase or a later teardown phase. PhaseStatusPending PhaseStatus = "Pending" - // PhaseStatusReconciling indicates the controller is actively applying - // objects in this phase and not all objects are synced yet. - PhaseStatusReconciling PhaseStatus = "Reconciling" - - // PhaseStatusStabilizing indicates all objects in this phase are - // synced but some assertions are not yet passing. The controller is - // not actively writing; it is waiting for other controllers or - // external actions to bring the objects into the expected state. + // PhaseStatusStabilizing indicates all objects in this phase are synced to + // this ClusterObjectSet, but at least one progression-probe result is false or unknown. PhaseStatusStabilizing PhaseStatus = "Stabilizing" - // PhaseStatusReady indicates all objects in this phase are synced - // and pass their assertions. + // PhaseStatusReady indicates all objects in this phase are synced to this + // ClusterObjectSet and pass their progression probes, if any are defined. PhaseStatusReady PhaseStatus = "Ready" - // PhaseStatusUnknown indicates this phase was not evaluated during - // the most recent reconcile. + // PhaseStatusPreconditionsNotMet indicates a precondition for applying the + // phase is not yet satisfied; the ClusterObjectSet keeps retrying and + // recovers once the precondition is met. + PhaseStatusPreconditionsNotMet PhaseStatus = "PreconditionsNotMet" + + // PhaseStatusInvalidSpecification indicates the phase's declared content is + // malformed; correcting the configuration requires creating a replacement + // ClusterObjectSet. + PhaseStatusInvalidSpecification PhaseStatus = "InvalidSpecification" + + // PhaseStatusUnknown indicates no usable evaluation of this phase exists yet. PhaseStatusUnknown PhaseStatus = "Unknown" - // PhaseStatusSuperseded indicates all objects in this phase have been - // adopted by a newer revision. + // PhaseStatusSuperseded indicates at least one object in this phase has been + // adopted by a newer ClusterObjectSet in the same group. Failing or unknown + // progression probes may still prevent later phases from advancing and remain + // visible in objectDetails. PhaseStatusSuperseded PhaseStatus = "Superseded" - // PhaseStatusArchiving indicates the controller is actively deleting - // objects in this phase. + // PhaseStatusArchiving indicates this is the active teardown phase and + // owned objects remain to be removed. PhaseStatusArchiving PhaseStatus = "Archiving" - // PhaseStatusArchived indicates all objects in this phase have - // been deleted from the cluster. + // PhaseStatusArchived indicates this ClusterObjectSet's teardown responsibility for + // the phase is complete. Objects adopted by newer ClusterObjectSets may still exist. PhaseStatusArchived PhaseStatus = "Archived" ) diff --git a/api/v1/validation_test.go b/api/v1/validation_test.go index 9304206b08..b73731bbcc 100644 --- a/api/v1/validation_test.go +++ b/api/v1/validation_test.go @@ -413,3 +413,162 @@ func TestClusterObjectSetDigestImmutable(t *testing.T) { err := c.Status().Update(t.Context(), cos) require.True(t, errors.IsInvalid(err), "expected update to fail as invalid, but got: %v", err) } + +func TestClusterObjectSetObservedPhaseValidation(t *testing.T) { + c := newClient(t) + + cmRef := func() ObjectReference { + return ObjectReference{APIVersion: "v1", Kind: "ConfigMap", Namespace: "ns", Name: "cm"} + } + withEntry := func(entry ObjectStatus) ObservedPhase { + return ObservedPhase{Status: PhaseStatusStabilizing, ObjectDetails: []ObjectStatus{entry}} + } + + for _, tc := range []struct { + name string + cosName string + phase ObservedPhase + wantInvalid string + }{ + { + name: "entry with probes and ownership is valid", + cosName: "cos-phase-valid-1", + phase: withEntry(ObjectStatus{ + Object: cmRef(), + ProbeResults: []ObjectProbeResult{{Type: "Progress", Status: ObjectProbeResultStatusFalse, Messages: []string{"m"}}}, + Ownership: ObjectOwnershipSuperseded, + }), + }, + { + name: "entry awaiting deletion is valid", + cosName: "cos-phase-deletion-1", + phase: withEntry(ObjectStatus{Object: cmRef(), Deletion: ObjectDeletionAwaitingDeletion}), + }, + { + name: "ObjectCollision status is valid", + cosName: "cos-phase-collision-1", + phase: ObservedPhase{Status: PhaseStatusObjectCollision}, + }, + { + name: "Reconciling status is rejected", + cosName: "cos-phase-reconciling-1", + phase: ObservedPhase{Status: PhaseStatus("Reconciling")}, + wantInvalid: "Unsupported value", + }, + { + name: "entry without probeResults, ownership, or deletion is rejected", + cosName: "cos-phase-empty-1", + phase: withEntry(ObjectStatus{Object: cmRef()}), + wantInvalid: "at least one of probeResults, ownership, or deletion must be set", + }, + { + name: "probe types must be unique", + cosName: "cos-phase-dupprobe-1", + phase: withEntry(ObjectStatus{Object: cmRef(), ProbeResults: []ObjectProbeResult{ + {Type: "Progress", Status: ObjectProbeResultStatusFalse}, + {Type: "Progress", Status: ObjectProbeResultStatusUnknown}, + }}), + wantInvalid: "Duplicate value", + }, + { + name: "passing probe status is rejected", + cosName: "cos-phase-probetrue-1", + phase: withEntry(ObjectStatus{Object: cmRef(), ProbeResults: []ObjectProbeResult{{Type: "Progress", Status: ObjectProbeResultStatus("True")}}}), + wantInvalid: "Unsupported value", + }, + { + name: "unknown ownership is rejected", + cosName: "cos-phase-badownership-1", + phase: withEntry(ObjectStatus{Object: cmRef(), Ownership: ObjectOwnership("Owned")}), + wantInvalid: "Unsupported value", + }, + { + name: "object apiVersion is required", + cosName: "cos-phase-noapiversion-1", + phase: withEntry(ObjectStatus{ + Object: ObjectReference{Kind: "ConfigMap", Namespace: "ns", Name: "cm"}, + Ownership: ObjectOwnershipColliding, + }), + wantInvalid: "apiVersion: Required value", + }, + { + name: "object apiVersion must be a version or group/version", + cosName: "cos-phase-badapiversion-1", + phase: withEntry(ObjectStatus{ + Object: ObjectReference{APIVersion: "Apps/V1", Kind: "Deployment", Namespace: "ns", Name: "d"}, + Ownership: ObjectOwnershipColliding, + }), + wantInvalid: "apiVersion must be a version or group/version", + }, + { + name: "object kind is required", + cosName: "cos-phase-nokind-1", + phase: withEntry(ObjectStatus{ + Object: ObjectReference{APIVersion: "v1", Namespace: "ns", Name: "cm"}, + Ownership: ObjectOwnershipColliding, + }), + wantInvalid: "kind: Required value", + }, + } { + t.Run(tc.name, func(t *testing.T) { + cos := &ClusterObjectSet{ + ObjectMeta: metav1.ObjectMeta{Name: tc.cosName}, + Spec: ClusterObjectSetSpec{ + Group: strings.TrimSuffix(tc.cosName, "-1"), + Revision: 1, + LifecycleState: ClusterObjectSetLifecycleStateActive, + ClusterObjectSetContent: ClusterObjectSetContent{ + CollisionProtection: CollisionProtectionPrevent, + Phases: []ClusterObjectSetPhase{{Name: "deploy", Objects: []ClusterObjectSetObject{}}}, + }, + }, + } + require.NoError(t, c.Create(t.Context(), cos)) + + phase := tc.phase + phase.Name = "deploy" + phase.Digest = "sha256:abc123" + phase.LastTransitionTime = metav1.Now() + cos.Status.ObservedPhases = []ObservedPhase{phase} + err := c.Status().Update(t.Context(), cos) + if tc.wantInvalid == "" { + require.NoError(t, err) + return + } + require.True(t, errors.IsInvalid(err), "expected update to fail as invalid, but got: %v", err) + require.ErrorContains(t, err, tc.wantInvalid) + }) + } +} + +func TestClusterObjectSetObservedPhaseCompletedAtCannotBeRemoved(t *testing.T) { + c := newClient(t) + + cos := &ClusterObjectSet{ + ObjectMeta: metav1.ObjectMeta{Name: "cos-phase-completedat-noremove-1"}, + Spec: ClusterObjectSetSpec{ + Group: "cos-phase-completedat-noremove", + Revision: 1, + LifecycleState: ClusterObjectSetLifecycleStateActive, + ClusterObjectSetContent: ClusterObjectSetContent{ + CollisionProtection: CollisionProtectionPrevent, + Phases: []ClusterObjectSetPhase{{Name: "deploy", Objects: []ClusterObjectSetObject{}}}, + }, + }, + } + require.NoError(t, c.Create(t.Context(), cos)) + + cos.Status.ObservedPhases = []ObservedPhase{{ + Name: "deploy", + Digest: "sha256:abc123", + Status: PhaseStatusReady, + CompletedAt: metav1.NewTime(time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC)), + LastTransitionTime: metav1.Now(), + }} + require.NoError(t, c.Status().Update(t.Context(), cos)) + + cos.Status.ObservedPhases[0].CompletedAt = metav1.Time{} + err := c.Status().Update(t.Context(), cos) + require.True(t, errors.IsInvalid(err), "expected removal to fail as invalid, but got: %v", err) + require.ErrorContains(t, err, "completedAt cannot be removed once set") +} diff --git a/api/v1/zz_generated.deepcopy.go b/api/v1/zz_generated.deepcopy.go index e5627866a4..481657fad1 100644 --- a/api/v1/zz_generated.deepcopy.go +++ b/api/v1/zz_generated.deepcopy.go @@ -854,6 +854,41 @@ func (in *ObjectCounts) DeepCopy() *ObjectCounts { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ObjectProbeResult) DeepCopyInto(out *ObjectProbeResult) { + *out = *in + if in.Messages != nil { + in, out := &in.Messages, &out.Messages + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectProbeResult. +func (in *ObjectProbeResult) DeepCopy() *ObjectProbeResult { + if in == nil { + return nil + } + out := new(ObjectProbeResult) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ObjectReference) DeepCopyInto(out *ObjectReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectReference. +func (in *ObjectReference) DeepCopy() *ObjectReference { + if in == nil { + return nil + } + out := new(ObjectReference) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ObjectSelector) DeepCopyInto(out *ObjectSelector) { *out = *in @@ -874,10 +909,13 @@ func (in *ObjectSelector) DeepCopy() *ObjectSelector { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ObjectStatus) DeepCopyInto(out *ObjectStatus) { *out = *in - if in.Messages != nil { - in, out := &in.Messages, &out.Messages - *out = make([]string, len(*in)) - copy(*out, *in) + out.Object = in.Object + if in.ProbeResults != nil { + in, out := &in.ProbeResults, &out.ProbeResults + *out = make([]ObjectProbeResult, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } } diff --git a/applyconfigurations/api/v1/clusterobjectsetstatus.go b/applyconfigurations/api/v1/clusterobjectsetstatus.go index c6724c8083..7f1eda601d 100644 --- a/applyconfigurations/api/v1/clusterobjectsetstatus.go +++ b/applyconfigurations/api/v1/clusterobjectsetstatus.go @@ -44,8 +44,8 @@ type ClusterObjectSetStatusApplyConfiguration struct { // - False with reason ObjectsNotReady: one or more objects are still being applied or have not yet passed their readiness probes during rollout. // - False with reason Superseded: one or more objects have been adopted by a newer revision of the object set. // - False with reason ObjectCollision: one or more objects are controlled by another owner, or are unowned while collision protection prevents adoption, so this revision cannot take ownership of them. - // - False with reason PreconditionsNotMet: a precondition for applying the revision is not yet satisfied (a referenced Secret is mutable or has invalid or changed content, or a preflight dry-run was rejected, e.g. an immutable field, a conflicting object, or RBAC/dependency CRDs not yet propagated); the revision keeps retrying and recovers once the precondition is met. - // - False with reason InvalidSpecification: the revision spec is invalid (a malformed revision/phase object or progression probe) and requires a spec change to proceed. + // - False with reason PreconditionsNotMet: a precondition for applying the revision is not yet satisfied (a referenced Secret is mutable or has invalid or changed content, a revision-wide preflight check was rejected, or a phase's preflight dry-run was rejected because RBAC or dependency CRDs have not yet propagated or a dependency such as the target namespace does not exist yet); the revision keeps retrying and recovers once the precondition is met. + // - False with reason InvalidSpecification: the revision spec is invalid (a malformed revision/phase object or progression probe, or a phase's preflight dry-run was rejected permanently, e.g. a schema violation or an immutable field) and requires a spec change to proceed. // - False with reason Archiving: the revision is being archived and its owned objects are still being torn down. // - False with reason Archived: the revision has been archived and its objects have been torn down. // diff --git a/applyconfigurations/api/v1/objectproberesult.go b/applyconfigurations/api/v1/objectproberesult.go new file mode 100644 index 0000000000..f6be99e843 --- /dev/null +++ b/applyconfigurations/api/v1/objectproberesult.go @@ -0,0 +1,74 @@ +/* +Copyright 2026. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by controller-gen. DO NOT EDIT. + +package v1 + +import ( + apiv1 "github.com/operator-framework/operator-controller/api/v1" +) + +// ObjectProbeResultApplyConfiguration represents a declarative configuration of the ObjectProbeResult type for use +// with apply. +// +// ObjectProbeResult reports a progression probe result that is not passing. +type ObjectProbeResultApplyConfiguration struct { + // type is the probe type, for example "Progress", the aggregate of the + // ClusterObjectSet's progression probes that apply to the object. + Type *string `json:"type,omitempty"` + // status is the probe result: + // - False: the probe evaluated to false. + // - Unknown: the probe result could not be determined, for example because + // the object's status has not yet been reported or is outdated. + Status *apiv1.ObjectProbeResultStatus `json:"status,omitempty"` + // messages provides bounded human-readable explanations of the result. + // Consumers must not parse these messages. Messages describe an aggregate + // result; their number is not the number of failed assertions. + Messages []string `json:"messages,omitempty"` +} + +// ObjectProbeResultApplyConfiguration constructs a declarative configuration of the ObjectProbeResult type for use with +// apply. +func ObjectProbeResult() *ObjectProbeResultApplyConfiguration { + return &ObjectProbeResultApplyConfiguration{} +} + +// WithType sets the Type field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Type field is set to the value of the last call. +func (b *ObjectProbeResultApplyConfiguration) WithType(value string) *ObjectProbeResultApplyConfiguration { + b.Type = &value + return b +} + +// WithStatus sets the Status field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Status field is set to the value of the last call. +func (b *ObjectProbeResultApplyConfiguration) WithStatus(value apiv1.ObjectProbeResultStatus) *ObjectProbeResultApplyConfiguration { + b.Status = &value + return b +} + +// WithMessages adds the given value to the Messages field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Messages field. +func (b *ObjectProbeResultApplyConfiguration) WithMessages(values ...string) *ObjectProbeResultApplyConfiguration { + for i := range values { + b.Messages = append(b.Messages, values[i]) + } + return b +} diff --git a/applyconfigurations/api/v1/objectreference.go b/applyconfigurations/api/v1/objectreference.go new file mode 100644 index 0000000000..9d7efa0c6e --- /dev/null +++ b/applyconfigurations/api/v1/objectreference.go @@ -0,0 +1,77 @@ +/* +Copyright 2026. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by controller-gen. DO NOT EDIT. + +package v1 + +// ObjectReferenceApplyConfiguration represents a declarative configuration of the ObjectReference type for use +// with apply. +// +// ObjectReference identifies an object by apiVersion, kind, namespace, and name, +// matching the target identity fields of the declared object manifests. +type ObjectReferenceApplyConfiguration struct { + // apiVersion is the API version of the object, for example "v1" or + // "apps/v1". It matches the apiVersion of the declared object manifest. + APIVersion *string `json:"apiVersion,omitempty"` + // kind is the kind of the object, for example "ConfigMap". It matches the + // kind of the declared object manifest. + Kind *string `json:"kind,omitempty"` + // namespace is the namespace of the object. Omitted for cluster-scoped + // resources. At most 63 characters (DNS label max). + Namespace *string `json:"namespace,omitempty"` + // name is the name of the object. Must be between 1 and 253 + // characters (DNS subdomain max). + Name *string `json:"name,omitempty"` +} + +// ObjectReferenceApplyConfiguration constructs a declarative configuration of the ObjectReference type for use with +// apply. +func ObjectReference() *ObjectReferenceApplyConfiguration { + return &ObjectReferenceApplyConfiguration{} +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *ObjectReferenceApplyConfiguration) WithAPIVersion(value string) *ObjectReferenceApplyConfiguration { + b.APIVersion = &value + return b +} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *ObjectReferenceApplyConfiguration) WithKind(value string) *ObjectReferenceApplyConfiguration { + b.Kind = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *ObjectReferenceApplyConfiguration) WithNamespace(value string) *ObjectReferenceApplyConfiguration { + b.Namespace = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ObjectReferenceApplyConfiguration) WithName(value string) *ObjectReferenceApplyConfiguration { + b.Name = &value + return b +} diff --git a/applyconfigurations/api/v1/objectstatus.go b/applyconfigurations/api/v1/objectstatus.go index 8a148bfe15..eb5fcb609b 100644 --- a/applyconfigurations/api/v1/objectstatus.go +++ b/applyconfigurations/api/v1/objectstatus.go @@ -18,30 +18,39 @@ limitations under the License. package v1 +import ( + apiv1 "github.com/operator-framework/operator-controller/api/v1" +) + // ObjectStatusApplyConfiguration represents a declarative configuration of the ObjectStatus type for use // with apply. // -// ObjectStatus identifies a managed object and its failure messages. +// ObjectStatus reports observed facts about an object with current problems or +// notable ownership. The object may be missing or controlled by a conflicting +// owner; it is not necessarily managed by this ClusterObjectSet. At least one of +// probeResults, ownership, or deletion is set. type ObjectStatusApplyConfiguration struct { - // group is the API group of the object (empty string for core - // resources). At most 253 characters (DNS subdomain max). - Group *string `json:"group,omitempty"` - // resource is the lowercase, plural resource type of the object - // (for example, "pods" or "configmaps"). Must be between 1 and 63 - // characters. - Resource *string `json:"resource,omitempty"` - // namespace is the namespace of the object. Empty for cluster-scoped - // resources. At most 253 characters (DNS subdomain max). - Namespace *string `json:"namespace,omitempty"` - // name is the name of the object. Must be between 1 and 253 - // characters (DNS subdomain max). - Name *string `json:"name,omitempty"` - // messages lists the failure reasons for this object. The maximum - // of 18 entries accounts for up to 16 assertion probe failures, - // one collision message, and one message to note truncation if necessary. - // Each message is at most 1024 characters; longer messages are truncated - // by the controller. - Messages []string `json:"messages,omitempty"` + // object identifies the object by apiVersion, kind, namespace, and name, + // matching the declared object manifest. + Object *ObjectReferenceApplyConfiguration `json:"object,omitempty"` + // probeResults lists the object's progression probe results that are not passing, + // keyed by probe type. Probes of objects in phases that are waiting for an + // earlier phase are not reported. At most 8 entries. + ProbeResults []ObjectProbeResultApplyConfiguration `json:"probeResults,omitempty"` + // ownership reports when this ClusterObjectSet does not control the object: + // - Colliding: the object exists but this ClusterObjectSet cannot take + // ownership of it under the configured collision protection policy. + // - Superseded: the object is controlled by another ClusterObjectSet in the + // same group with a higher .spec.revision. + // + // Omitted when this ClusterObjectSet controls the object. + Ownership *apiv1.ObjectOwnership `json:"ownership,omitempty"` + // deletion reports the object's teardown state: + // - AwaitingDeletion: the object is owned by this ClusterObjectSet, has been + // requested for deletion, and is not yet gone from the cluster. + // + // Omitted when the object is not being torn down. + Deletion *apiv1.ObjectDeletion `json:"deletion,omitempty"` } // ObjectStatusApplyConfiguration constructs a declarative configuration of the ObjectStatus type for use with @@ -50,44 +59,39 @@ func ObjectStatus() *ObjectStatusApplyConfiguration { return &ObjectStatusApplyConfiguration{} } -// WithGroup sets the Group field in the declarative configuration to the given value +// WithObject sets the Object field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the Group field is set to the value of the last call. -func (b *ObjectStatusApplyConfiguration) WithGroup(value string) *ObjectStatusApplyConfiguration { - b.Group = &value +// If called multiple times, the Object field is set to the value of the last call. +func (b *ObjectStatusApplyConfiguration) WithObject(value *ObjectReferenceApplyConfiguration) *ObjectStatusApplyConfiguration { + b.Object = value return b } -// WithResource sets the Resource field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the Resource field is set to the value of the last call. -func (b *ObjectStatusApplyConfiguration) WithResource(value string) *ObjectStatusApplyConfiguration { - b.Resource = &value +// WithProbeResults adds the given value to the ProbeResults field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ProbeResults field. +func (b *ObjectStatusApplyConfiguration) WithProbeResults(values ...*ObjectProbeResultApplyConfiguration) *ObjectStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithProbeResults") + } + b.ProbeResults = append(b.ProbeResults, *values[i]) + } return b } -// WithNamespace sets the Namespace field in the declarative configuration to the given value +// WithOwnership sets the Ownership field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the Namespace field is set to the value of the last call. -func (b *ObjectStatusApplyConfiguration) WithNamespace(value string) *ObjectStatusApplyConfiguration { - b.Namespace = &value +// If called multiple times, the Ownership field is set to the value of the last call. +func (b *ObjectStatusApplyConfiguration) WithOwnership(value apiv1.ObjectOwnership) *ObjectStatusApplyConfiguration { + b.Ownership = &value return b } -// WithName sets the Name field in the declarative configuration to the given value +// WithDeletion sets the Deletion field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the Name field is set to the value of the last call. -func (b *ObjectStatusApplyConfiguration) WithName(value string) *ObjectStatusApplyConfiguration { - b.Name = &value - return b -} - -// WithMessages adds the given value to the Messages field in the declarative configuration -// and returns the receiver, so that objects can be build by chaining "With" function invocations. -// If called multiple times, values provided by each call will be appended to the Messages field. -func (b *ObjectStatusApplyConfiguration) WithMessages(values ...string) *ObjectStatusApplyConfiguration { - for i := range values { - b.Messages = append(b.Messages, values[i]) - } +// If called multiple times, the Deletion field is set to the value of the last call. +func (b *ObjectStatusApplyConfiguration) WithDeletion(value apiv1.ObjectDeletion) *ObjectStatusApplyConfiguration { + b.Deletion = &value return b } diff --git a/applyconfigurations/api/v1/observedphase.go b/applyconfigurations/api/v1/observedphase.go index 3b3bee5435..bd6a23aa9d 100644 --- a/applyconfigurations/api/v1/observedphase.go +++ b/applyconfigurations/api/v1/observedphase.go @@ -26,37 +26,66 @@ import ( // ObservedPhaseApplyConfiguration represents a declarative configuration of the ObservedPhase type for use // with apply. // -// ObservedPhase records the observed content digest of a resolved phase. +// ObservedPhase reports a phase's current lifecycle state and sparse +// diagnostics together with its pinned content digest and historical +// completion. type ObservedPhaseApplyConfiguration struct { // name is the phase name matching a phase in spec.phases. Name *string `json:"name,omitempty"` - // status is the current state of this phase in the rollout. Must be one of - // InvalidSpecification, PreconditionsNotMet, Pending, Reconciling, - // Stabilizing, Ready, Unknown, Superseded, Archiving, or Archived. + // status summarizes the current lifecycle state of this phase: + // - Unknown: no usable evaluation of the phase exists yet. + // - Pending: application is waiting for an earlier phase, or teardown is + // waiting for a later phase. + // - Stabilizing: all objects are synced to this ClusterObjectSet, but at least one + // progression-probe result is false or unknown. + // - Ready: all objects are synced to this ClusterObjectSet and pass their + // progression probes, if any are defined. + // - PreconditionsNotMet: a precondition for applying the phase is not yet + // satisfied, for example a rejected preflight dry-run; the ClusterObjectSet + // keeps retrying and recovers once the precondition is met. + // - InvalidSpecification: the phase's declared content is malformed; + // correcting the configuration requires creating a replacement + // ClusterObjectSet. + // - ObjectCollision: one or more objects are controlled by another + // owner, or are unowned while collision protection prevents adoption, + // so this ClusterObjectSet cannot take ownership of them. + // - Superseded: at least one object is controlled by another + // ClusterObjectSet in the same group with a higher .spec.revision. + // - Archiving: this is the active teardown phase and owned objects remain to be removed. + // - Archived: this ClusterObjectSet's teardown responsibility for the phase is complete; + // objects adopted by newer ClusterObjectSets may still exist. + // + // Superseded does not imply that progression probes pass. Failing or unknown + // probes may still prevent later phases from advancing. + // PreconditionsNotMet, InvalidSpecification, and ObjectCollision statuses + // do not imply a terminal failure or a fixed retry policy. Status *apiv1.PhaseStatus `json:"status,omitempty"` - // completedAt is the timestamp when this phase first became Ready. - // Set once and never modified. Nil means the phase has never been - // Ready. + // completedAt is the timestamp when this phase was first observed Ready. + // Omitted until that observation. Once recorded, it cannot change or be + // removed, even if the phase later fails its progression probes or is + // superseded. CompletedAt *metav1.Time `json:"completedAt,omitempty"` - // message is a phase-level message providing context about the - // current status (e.g. a validation error for InvalidSpecification - // phases, or a summary for Pending phases). At most 1024 characters; - // longer messages are truncated by the controller. + // message provides human-readable context, such as a phase-wide validation + // failure or the reason a phase is waiting. Consumers must not parse this + // message. At most 1024 characters; longer messages are truncated by the + // controller. Message *string `json:"message,omitempty"` // digest is the digest of the phase's resolved object content // at first successful resolution, in the format ":". // Currently, sha256 is the only supported algorithm. Digest *string `json:"digest,omitempty"` - // lastTransitionTime is the last time the phase transitioned from one status to another. + // lastTransitionTime is the timestamp when the current status was first + // reported or last changed. Changes to message alone do not update this + // timestamp. LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` - // objectDetails lists objects in this phase that are not yet - // complete. For Reconciling, Pending, and Stabilizing phases, this - // includes probe failures, collisions, creation/update errors, and - // any other condition preventing completion. For Archiving phases, - // this lists objects still awaiting deletion. Each entry identifies - // the object and carries failure messages. Empty when status is - // Ready, Superseded, Archived, or Unknown. The list may contain at - // most 50 entries, matching the maximum number of objects per phase. + // objectDetails reports per-object facts for objects with current problems or + // notable ownership; it is not a full object inventory. An object is listed + // when it has progression probes that are not passing (objects in phases that + // are waiting for an earlier phase excluded), when this ClusterObjectSet cannot + // take ownership of it (including in phases that are waiting), when it has been + // adopted by a newer ClusterObjectSet, or when it awaits deletion in the active + // teardown phase. Entries are removed when those facts no longer apply. + // At most 50 entries, matching the maximum number of objects per phase. ObjectDetails []ObjectStatusApplyConfiguration `json:"objectDetails,omitempty"` } diff --git a/applyconfigurations/internal/internal.go b/applyconfigurations/internal/internal.go index a628fe4149..bbcaa71398 100644 --- a/applyconfigurations/internal/internal.go +++ b/applyconfigurations/internal/internal.go @@ -478,6 +478,42 @@ var schemaYAML = typed.YAMLObject(`types: - name: total type: scalar: numeric +- name: com.github.operator-framework.operator-controller.api.v1.ObjectDeletion + scalar: string +- name: com.github.operator-framework.operator-controller.api.v1.ObjectOwnership + scalar: string +- name: com.github.operator-framework.operator-controller.api.v1.ObjectProbeResult + map: + fields: + - name: messages + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: status + type: + namedType: com.github.operator-framework.operator-controller.api.v1.ObjectProbeResultStatus + - name: type + type: + scalar: string +- name: com.github.operator-framework.operator-controller.api.v1.ObjectProbeResultStatus + scalar: string +- name: com.github.operator-framework.operator-controller.api.v1.ObjectReference + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: name + type: + scalar: string + - name: namespace + type: + scalar: string - name: com.github.operator-framework.operator-controller.api.v1.ObjectSelector map: fields: @@ -493,24 +529,23 @@ var schemaYAML = typed.YAMLObject(`types: - name: com.github.operator-framework.operator-controller.api.v1.ObjectStatus map: fields: - - name: group - type: - scalar: string - - name: messages + - name: deletion type: - list: - elementType: - scalar: string - elementRelationship: atomic - - name: name + namedType: com.github.operator-framework.operator-controller.api.v1.ObjectDeletion + - name: object type: - scalar: string - - name: namespace + namedType: com.github.operator-framework.operator-controller.api.v1.ObjectReference + - name: ownership type: - scalar: string - - name: resource + namedType: com.github.operator-framework.operator-controller.api.v1.ObjectOwnership + - name: probeResults type: - scalar: string + list: + elementType: + namedType: com.github.operator-framework.operator-controller.api.v1.ObjectProbeResult + elementRelationship: associative + keys: + - type - name: com.github.operator-framework.operator-controller.api.v1.ObjectType scalar: string - name: com.github.operator-framework.operator-controller.api.v1.ObservedPhase diff --git a/applyconfigurations/utils.go b/applyconfigurations/utils.go index f0bc2bb5c8..f82e8bb898 100644 --- a/applyconfigurations/utils.go +++ b/applyconfigurations/utils.go @@ -96,6 +96,10 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &apiv1.ImageSourceApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ObjectCounts"): return &apiv1.ObjectCountsApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("ObjectProbeResult"): + return &apiv1.ObjectProbeResultApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("ObjectReference"): + return &apiv1.ObjectReferenceApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ObjectSelector"): return &apiv1.ObjectSelectorApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ObjectStatus"): diff --git a/docs/api-reference/olmv1-api-reference.md b/docs/api-reference/olmv1-api-reference.md index a9a76cdd66..e4a886fe43 100644 --- a/docs/api-reference/olmv1-api-reference.md +++ b/docs/api-reference/olmv1-api-reference.md @@ -675,6 +675,97 @@ _Appears in:_ +#### ObjectDeletion + +_Underlying type:_ _string_ + +ObjectDeletion describes an object's teardown state. + +_Validation:_ +- Enum: [AwaitingDeletion] + +_Appears in:_ +- [ObjectStatus](#objectstatus) + +| Field | Description | +| --- | --- | +| `AwaitingDeletion` | ObjectDeletionAwaitingDeletion indicates the object is owned by the
ClusterObjectSet, has been requested for deletion, and is not yet gone.
| + + +#### ObjectOwnership + +_Underlying type:_ _string_ + +ObjectOwnership describes why a ClusterObjectSet does not control an object. + +_Validation:_ +- Enum: [Colliding Superseded] + +_Appears in:_ +- [ObjectStatus](#objectstatus) + +| Field | Description | +| --- | --- | +| `Colliding` | ObjectOwnershipColliding indicates the object exists but the ClusterObjectSet
cannot take ownership of it under the configured collision protection policy.
| +| `Superseded` | ObjectOwnershipSuperseded indicates the object is controlled by another
ClusterObjectSet in the same group with a higher .spec.revision.
| + + +#### ObjectProbeResult + + + +ObjectProbeResult reports a progression probe result that is not passing. + + + +_Appears in:_ +- [ObjectStatus](#objectstatus) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `type` _string_ | type is the probe type, for example "Progress", the aggregate of the
ClusterObjectSet's progression probes that apply to the object. | | MaxLength: 63
MinLength: 1
Required: \{\}
| +| `status` _[ObjectProbeResultStatus](#objectproberesultstatus)_ | status is the probe result:
- False: the probe evaluated to false.
- Unknown: the probe result could not be determined, for example because
the object's status has not yet been reported or is outdated. | | Enum: [False Unknown]
Required: \{\}
| +| `messages` _string array_ | messages provides bounded human-readable explanations of the result.
Consumers must not parse these messages. Messages describe an aggregate
result; their number is not the number of failed assertions. | | MaxItems: 18
items:MaxLength: 1024
items:MinLength: 1
Optional: \{\}
| + + +#### ObjectProbeResultStatus + +_Underlying type:_ _string_ + +ObjectProbeResultStatus is the status of a progression probe result that is not passing. + +_Validation:_ +- Enum: [False Unknown] + +_Appears in:_ +- [ObjectProbeResult](#objectproberesult) + +| Field | Description | +| --- | --- | +| `False` | ObjectProbeResultStatusFalse indicates the probe evaluated to false.
| +| `Unknown` | ObjectProbeResultStatusUnknown indicates the probe result could not be determined.
| + + +#### ObjectReference + + + +ObjectReference identifies an object by apiVersion, kind, namespace, and name, +matching the target identity fields of the declared object manifests. + + + +_Appears in:_ +- [ObjectStatus](#objectstatus) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `apiVersion` _string_ | apiVersion is the API version of the object, for example "v1" or
"apps/v1". It matches the apiVersion of the declared object manifest. | | MaxLength: 317
MinLength: 1
Required: \{\}
| +| `kind` _string_ | kind is the kind of the object, for example "ConfigMap". It matches the
kind of the declared object manifest. | | MaxLength: 63
MinLength: 1
Required: \{\}
| +| `namespace` _string_ | namespace is the namespace of the object. Omitted for cluster-scoped
resources. At most 63 characters (DNS label max). | | MaxLength: 63
MinLength: 1
Optional: \{\}
| +| `name` _string_ | name is the name of the object. Must be between 1 and 253
characters (DNS subdomain max). | | MaxLength: 253
MinLength: 1
Required: \{\}
| + + #### ObjectSelector diff --git a/helm/olmv1/base/object-controller/crd/experimental/olm.operatorframework.io_clusterobjectsets.yaml b/helm/olmv1/base/object-controller/crd/experimental/olm.operatorframework.io_clusterobjectsets.yaml index 3ccf6424f9..9170a2668e 100644 --- a/helm/olmv1/base/object-controller/crd/experimental/olm.operatorframework.io_clusterobjectsets.yaml +++ b/helm/olmv1/base/object-controller/crd/experimental/olm.operatorframework.io_clusterobjectsets.yaml @@ -662,8 +662,8 @@ spec: - False with reason ObjectsNotReady: one or more objects are still being applied or have not yet passed their readiness probes during rollout. - False with reason Superseded: one or more objects have been adopted by a newer revision of the object set. - False with reason ObjectCollision: one or more objects are controlled by another owner, or are unowned while collision protection prevents adoption, so this revision cannot take ownership of them. - - False with reason PreconditionsNotMet: a precondition for applying the revision is not yet satisfied (a referenced Secret is mutable or has invalid or changed content, or a preflight dry-run was rejected, e.g. an immutable field, a conflicting object, or RBAC/dependency CRDs not yet propagated); the revision keeps retrying and recovers once the precondition is met. - - False with reason InvalidSpecification: the revision spec is invalid (a malformed revision/phase object or progression probe) and requires a spec change to proceed. + - False with reason PreconditionsNotMet: a precondition for applying the revision is not yet satisfied (a referenced Secret is mutable or has invalid or changed content, a revision-wide preflight check was rejected, or a phase's preflight dry-run was rejected because RBAC or dependency CRDs have not yet propagated or a dependency such as the target namespace does not exist yet); the revision keeps retrying and recovers once the precondition is met. + - False with reason InvalidSpecification: the revision spec is invalid (a malformed revision/phase object or progression probe, or a phase's preflight dry-run was rejected permanently, e.g. a schema violation or an immutable field) and requires a spec change to proceed. - False with reason Archiving: the revision is being archived and its owned objects are still being torn down. - False with reason Archived: the revision has been archived and its objects have been torn down. @@ -779,14 +779,17 @@ spec: different content. Each entry covers all fully-resolved object manifests within a phase, making it source-agnostic. items: - description: ObservedPhase records the observed content digest of - a resolved phase. + description: |- + ObservedPhase reports a phase's current lifecycle state and sparse + diagnostics together with its pinned content digest and historical + completion. properties: completedAt: description: |- - completedAt is the timestamp when this phase first became Ready. - Set once and never modified. Nil means the phase has never been - Ready. + completedAt is the timestamp when this phase was first observed Ready. + Omitted until that observation. Once recorded, it cannot change or be + removed, even if the phase later fails its progression probes or is + superseded. format: date-time type: string x-kubernetes-validations: @@ -806,16 +809,18 @@ spec: - message: digest must be in the format ':' rule: self.matches('^[a-z0-9]+:[a-f0-9]+$') lastTransitionTime: - description: lastTransitionTime is the last time the phase transitioned - from one status to another. + description: |- + lastTransitionTime is the timestamp when the current status was first + reported or last changed. Changes to message alone do not update this + timestamp. format: date-time type: string message: description: |- - message is a phase-level message providing context about the - current status (e.g. a validation error for InvalidSpecification - phases, or a summary for Pending phases). At most 1024 characters; - longer messages are truncated by the controller. + message provides human-readable context, such as a phase-wide validation + failure or the reason a phase is waiting. Consumers must not parse this + message. At most 1024 characters; longer messages are truncated by the + controller. maxLength: 1024 minLength: 1 type: string @@ -831,101 +836,194 @@ spec: rule: '!format.dns1123Label().validate(self).hasValue()' objectDetails: description: |- - objectDetails lists objects in this phase that are not yet - complete. For Reconciling, Pending, and Stabilizing phases, this - includes probe failures, collisions, creation/update errors, and - any other condition preventing completion. For Archiving phases, - this lists objects still awaiting deletion. Each entry identifies - the object and carries failure messages. Empty when status is - Ready, Superseded, Archived, or Unknown. The list may contain at - most 50 entries, matching the maximum number of objects per phase. + objectDetails reports per-object facts for objects with current problems or + notable ownership; it is not a full object inventory. An object is listed + when it has progression probes that are not passing (objects in phases that + are waiting for an earlier phase excluded), when this ClusterObjectSet cannot + take ownership of it (including in phases that are waiting), when it has been + adopted by a newer ClusterObjectSet, or when it awaits deletion in the active + teardown phase. Entries are removed when those facts no longer apply. + At most 50 entries, matching the maximum number of objects per phase. items: - description: ObjectStatus identifies a managed object and - its failure messages. + description: |- + ObjectStatus reports observed facts about an object with current problems or + notable ownership. The object may be missing or controlled by a conflicting + owner; it is not necessarily managed by this ClusterObjectSet. At least one of + probeResults, ownership, or deletion is set. properties: - group: + deletion: description: |- - group is the API group of the object (empty string for core - resources). At most 253 characters (DNS subdomain max). - maxLength: 253 - minLength: 1 + deletion reports the object's teardown state: + - AwaitingDeletion: the object is owned by this ClusterObjectSet, has been + requested for deletion, and is not yet gone from the cluster. + + Omitted when the object is not being torn down. + enum: + - AwaitingDeletion type: string - x-kubernetes-validations: - - message: 'the value must be a valid DNS subdomain: lowercase - alphanumeric characters, hyphens, and dots, starting - and ending with an alphanumeric character.' - rule: '!format.dns1123Subdomain().validate(self).hasValue()' - messages: + object: description: |- - messages lists the failure reasons for this object. The maximum - of 18 entries accounts for up to 16 assertion probe failures, - one collision message, and one message to note truncation if necessary. - Each message is at most 1024 characters; longer messages are truncated - by the controller. - items: - maxLength: 1024 - minLength: 1 - type: string - maxItems: 18 - type: array - x-kubernetes-list-type: atomic - name: - description: |- - name is the name of the object. Must be between 1 and 253 - characters (DNS subdomain max). - maxLength: 253 - minLength: 1 - type: string - x-kubernetes-validations: - - message: 'name must be a valid object name: it may not - be ''.'' or ''..'' or contain ''/'' or ''%''' - rule: self != "." && self != ".." && !self.contains("/") - && !self.contains("%") - namespace: + object identifies the object by apiVersion, kind, namespace, and name, + matching the declared object manifest. + properties: + apiVersion: + description: |- + apiVersion is the API version of the object, for example "v1" or + "apps/v1". It matches the apiVersion of the declared object manifest. + maxLength: 317 + minLength: 1 + type: string + x-kubernetes-validations: + - message: apiVersion must be a version or group/version + rule: self.matches('^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[a-z]([-a-z0-9]*[a-z0-9])?$') + kind: + description: |- + kind is the kind of the object, for example "ConfigMap". It matches the + kind of the declared object manifest. + maxLength: 63 + minLength: 1 + type: string + x-kubernetes-validations: + - message: kind must start with a letter and contain + only letters, digits, or hyphens, ending with + an alphanumeric character + rule: self.matches('^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$') + name: + description: |- + name is the name of the object. Must be between 1 and 253 + characters (DNS subdomain max). + maxLength: 253 + minLength: 1 + type: string + x-kubernetes-validations: + - message: 'name must be a valid object name: it may + not be ''.'' or ''..'' or contain ''/'' or ''%''' + rule: self != "." && self != ".." && !self.contains("/") + && !self.contains("%") + namespace: + description: |- + namespace is the namespace of the object. Omitted for cluster-scoped + resources. At most 63 characters (DNS label max). + maxLength: 63 + minLength: 1 + type: string + x-kubernetes-validations: + - message: the value must consist of only lowercase + alphanumeric characters and hyphens, and must + start and end with an alphanumeric character. + rule: '!format.dns1123Label().validate(self).hasValue()' + required: + - apiVersion + - kind + - name + type: object + ownership: description: |- - namespace is the namespace of the object. Empty for cluster-scoped - resources. At most 253 characters (DNS subdomain max). - maxLength: 253 - minLength: 1 + ownership reports when this ClusterObjectSet does not control the object: + - Colliding: the object exists but this ClusterObjectSet cannot take + ownership of it under the configured collision protection policy. + - Superseded: the object is controlled by another ClusterObjectSet in the + same group with a higher .spec.revision. + + Omitted when this ClusterObjectSet controls the object. + enum: + - Colliding + - Superseded type: string - x-kubernetes-validations: - - message: the value must consist of only lowercase alphanumeric - characters and hyphens, and must start and end with - an alphanumeric character. - rule: '!format.dns1123Label().validate(self).hasValue()' - resource: + probeResults: description: |- - resource is the lowercase, plural resource type of the object - (for example, "pods" or "configmaps"). Must be between 1 and 63 - characters. - maxLength: 63 - minLength: 1 - type: string - x-kubernetes-validations: - - message: the value must consist of only lowercase alphanumeric - characters and hyphens, must start with a letter, - and must end with an alphanumeric character. - rule: '!format.dns1035Label().validate(self).hasValue()' + probeResults lists the object's progression probe results that are not passing, + keyed by probe type. Probes of objects in phases that are waiting for an + earlier phase are not reported. At most 8 entries. + items: + description: ObjectProbeResult reports a progression + probe result that is not passing. + properties: + messages: + description: |- + messages provides bounded human-readable explanations of the result. + Consumers must not parse these messages. Messages describe an aggregate + result; their number is not the number of failed assertions. + items: + maxLength: 1024 + minLength: 1 + type: string + maxItems: 18 + type: array + x-kubernetes-list-type: atomic + status: + description: |- + status is the probe result: + - False: the probe evaluated to false. + - Unknown: the probe result could not be determined, for example because + the object's status has not yet been reported or is outdated. + enum: + - "False" + - Unknown + type: string + type: + description: |- + type is the probe type, for example "Progress", the aggregate of the + ClusterObjectSet's progression probes that apply to the object. + maxLength: 63 + minLength: 1 + type: string + required: + - status + - type + type: object + maxItems: 8 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map required: - - name - - resource + - object type: object + x-kubernetes-validations: + - message: at least one of probeResults, ownership, or deletion + must be set + rule: has(self.probeResults) || has(self.ownership) || has(self.deletion) maxItems: 50 type: array x-kubernetes-list-type: atomic status: description: |- - status is the current state of this phase in the rollout. Must be one of - InvalidSpecification, PreconditionsNotMet, Pending, Reconciling, - Stabilizing, Ready, Unknown, Superseded, Archiving, or Archived. + status summarizes the current lifecycle state of this phase: + - Unknown: no usable evaluation of the phase exists yet. + - Pending: application is waiting for an earlier phase, or teardown is + waiting for a later phase. + - Stabilizing: all objects are synced to this ClusterObjectSet, but at least one + progression-probe result is false or unknown. + - Ready: all objects are synced to this ClusterObjectSet and pass their + progression probes, if any are defined. + - PreconditionsNotMet: a precondition for applying the phase is not yet + satisfied, for example a rejected preflight dry-run; the ClusterObjectSet + keeps retrying and recovers once the precondition is met. + - InvalidSpecification: the phase's declared content is malformed; + correcting the configuration requires creating a replacement + ClusterObjectSet. + - ObjectCollision: one or more objects are controlled by another + owner, or are unowned while collision protection prevents adoption, + so this ClusterObjectSet cannot take ownership of them. + - Superseded: at least one object is controlled by another + ClusterObjectSet in the same group with a higher .spec.revision. + - Archiving: this is the active teardown phase and owned objects remain to be removed. + - Archived: this ClusterObjectSet's teardown responsibility for the phase is complete; + objects adopted by newer ClusterObjectSets may still exist. + + Superseded does not imply that progression probes pass. Failing or unknown + probes may still prevent later phases from advancing. + PreconditionsNotMet, InvalidSpecification, and ObjectCollision statuses + do not imply a terminal failure or a fixed retry policy. enum: - - InvalidSpecification - - PreconditionsNotMet + - Unknown - Pending - - Reconciling - Stabilizing - Ready - - Unknown + - PreconditionsNotMet + - InvalidSpecification + - ObjectCollision - Superseded - Archiving - Archived diff --git a/internal/object-controller/controllers/clusterobjectset_controller.go b/internal/object-controller/controllers/clusterobjectset_controller.go index 0d325c8ee3..a8855653bc 100644 --- a/internal/object-controller/controllers/clusterobjectset_controller.go +++ b/internal/object-controller/controllers/clusterobjectset_controller.go @@ -11,7 +11,6 @@ import ( "errors" "fmt" "io" - "slices" "strings" "time" @@ -27,7 +26,6 @@ import ( "k8s.io/client-go/util/workqueue" "k8s.io/utils/clock" "pkg.package-operator.run/boxcutter" - "pkg.package-operator.run/boxcutter/machinery" machinerytypes "pkg.package-operator.run/boxcutter/machinery/types" "pkg.package-operator.run/boxcutter/ownerhandling" "pkg.package-operator.run/boxcutter/probing" @@ -248,7 +246,7 @@ func (c *ClusterObjectSetReconciler) reconcile(ctx context.Context, cos *ocv1.Cl reconcileTime := metav1.NewTime(c.Clock.Now()) // Set object counts and phase status // TODO: refactor and move condition setting operations into status pkg - status.UpdateObservedPhasesForReconcile(c.Client.RESTMapper(), cos, rres, reconcileTime) + status.UpdateObservedPhasesForReconcile(cos, rres, reconcileTime) // Report revision-level preflight validation failures and re-check on a flat timer: // the dry-run can be rejected for reasons that clear without a spec change (e.g. RBAC @@ -259,125 +257,29 @@ func (c *ClusterObjectSetReconciler) reconcile(ctx context.Context, cos *ocv1.Cl return ctrl.Result{RequeueAfter: validationRetryInterval}, nil } - // Phases are reconciled in order; once a phase is incomplete, later phases are - // only observed read-only (paused). A paused phase's preflight dry-run can fail - // for reasons that resolve once earlier phases roll out (e.g. a Namespace a - // later phase depends on has not been created yet), so its validation error is - // not actionable yet. Only treat a phase's validation error as a terminal - // validation failure while every preceding phase is complete; otherwise skip it - // and let the rollout status (and the progress deadline) below take over. - // Collisions are still reported for paused phases below: an object owned by - // another controller does not become ownable just because earlier phases roll - // out, so it remains actionable regardless of phase ordering. - precedingPhasesComplete := true - for _, pres := range rres.GetPhases() { - if verr := pres.GetValidationError(); verr != nil { - if !precedingPhasesComplete { - // Paused downstream phase: an earlier phase is still rolling out. - l.V(1).Info("ignoring paused phase preflight validation error while an earlier phase rolls out", "phase", pres.GetName(), "err", verr.Error()) - continue - } - l.Error(fmt.Errorf("%w", verr), "phase preflight validation failed, retrying after 10s", "phase", pres.GetName()) - markAsNotReady(cos, ocv1.ClusterObjectSetReasonPreconditionsNotMet, fmt.Sprintf("A preflight check rejected phase %q: %v.", pres.GetName(), verr)) + // The Ready condition is derived from the phase statuses computed above. See + // status.DeriveReadyCondition for the order in which phase statuses decide it. + outcome := status.DeriveReadyCondition(cos.Status.ObservedPhases) + if !outcome.Ready { + l.V(1).Info("revision not ready", "reason", outcome.Reason, "message", outcome.Message) + markAsNotReady(cos, outcome.Reason, outcome.Message) + if outcome.Retry { + // Preflight checks and collisions can clear without a spec change (e.g. RBAC + // or a dependency CRD still propagating, or a conflicting object removed), + // and those inputs are not watched, so re-check on a flat timer. return ctrl.Result{RequeueAfter: validationRetryInterval}, nil } - - if !pres.IsComplete() { - precedingPhasesComplete = false - } - - var collidingObjs []string - for _, ores := range pres.GetObjects() { - if ores.Action() != machinery.ActionCollision { - continue - } - obj := ores.Object() - name := obj.GetName() - if ns := obj.GetNamespace(); ns != "" { - name = ns + "/" + name - } - gvk := obj.GetObjectKind().GroupVersionKind() - desc := fmt.Sprintf("%s.%s %q", gvk.Kind, gvk.GroupVersion().String(), name) - if coll, ok := ores.(machinery.ObjectResultCollision); ok { - if owner, hasOwner := coll.ConflictingOwner(); hasOwner { - desc += fmt.Sprintf(" is owned by %s %q", owner.Kind, owner.Name) - } - } - collidingObjs = append(collidingObjs, desc) - } - - if len(collidingObjs) > 0 { - l.Error(fmt.Errorf("object collision detected"), "object collision, retrying after 10s", "phase", pres.GetName(), "collisions", collidingObjs) - markAsNotReady(cos, ocv1.ClusterObjectSetReasonObjectCollision, - fmt.Sprintf("Cannot take ownership of %d object(s) in phase %q because they are owned by another controller or already exist. Remove the conflicting owner or object, or create a new ClusterObjectSet with a more permissive collisionProtection setting.", len(collidingObjs), pres.GetName())) - return ctrl.Result{RequeueAfter: 10 * time.Second}, nil - } + return ctrl.Result{}, nil } - // A revision whose objects have all been adopted by a newer sibling revision can - // report IsComplete() (progressed objects count as complete), but it is superseded, - // not successfully rolled out: skip the completion branch so it does not - // report AllObjectsReady or record a first completion - // (completedAt) that would identify it as the installed revision. - superseded := slices.ContainsFunc(rres.GetPhases(), status.HasSupersededObject) - //nolint:nestif // Keep completion and per-phase readiness reporting together. - if rres.IsComplete() && !superseded { - markAsReady(cos, ocv1.ClusterObjectSetReasonAllObjectsReady, "All objects are at the desired state") - - // Record the timestamp of the first time the revision was observed to be - // ready. This is set once and never changes for subsequent reconciliations. - // It also serves as the signal that the revision has completed its rollout, - // which the ClusterExtension controller uses to determine the installed revision. - if cos.Status.CompletedAt.IsZero() { - cos.Status.CompletedAt = reconcileTime - } - } else { - var notReadyMsgs []string - for _, pres := range rres.GetPhases() { - if pres.IsComplete() { - continue - } - for _, ores := range pres.GetObjects() { - if ores.IsPaused() && ores.Action() == machinery.ActionCreated { - // Skip probe checks of objects not yet created - continue - } - // we probably want an AvailabilityProbeType and run through all of them independently of whether - // the revision is complete or not - pr := ores.ProbeResults()[boxcutter.ProgressProbeType] - if pr.Status == machinerytypes.ProbeStatusTrue { - continue - } - obj := ores.Object() - gvk := obj.GetObjectKind().GroupVersionKind() - // Count every not-ready object (the condition reports the count); the - // per-object detail here is for the V(1) debug log, not the message. - notReadyMsgs = append(notReadyMsgs, fmt.Sprintf( - "Object %s.%s %s/%s: %v", - gvk.Kind, gvk.GroupVersion().String(), - obj.GetNamespace(), obj.GetName(), strings.Join(pr.Messages, " and "), - )) - } - } + markAsReady(cos, outcome.Reason, outcome.Message) - // Stable generic summary used when there is no per-object detail; the detailed - // path reports the count. Per-object detail is kept out of the condition message - // and logged at V(1) for debugging. - const genericNotReadyMsg = "Objects are not yet ready." - if len(notReadyMsgs) > 0 { - l.V(1).Info("objects not yet ready", "count", len(notReadyMsgs), "details", notReadyMsgs) - } - // Precedence: Superseded > ObjectsNotReady. - switch { - case superseded: - markAsNotReady(cos, ocv1.ClusterObjectSetReasonSuperseded, "Object(s) have been adopted by a newer revision of the object set.") - default: - notReadyMsg := genericNotReadyMsg - if len(notReadyMsgs) > 0 { - notReadyMsg = fmt.Sprintf("%d object(s) are not yet ready.", len(notReadyMsgs)) - } - markAsNotReady(cos, ocv1.ClusterObjectSetReasonObjectsNotReady, notReadyMsg) - } + // Record the timestamp of the first time the revision was observed to be + // ready. This is set once and never changes for subsequent reconciliations. + // It also serves as the signal that the revision has completed its rollout, + // which the ClusterExtension controller uses to determine the installed revision. + if cos.Status.CompletedAt.IsZero() { + cos.Status.CompletedAt = reconcileTime } return ctrl.Result{}, nil @@ -403,7 +305,7 @@ func (c *ClusterObjectSetReconciler) archive(ctx context.Context, revisionEngine return ctrl.Result{}, fmt.Errorf("error archiving revision: %v", err) } teardownTime := metav1.NewTime(c.Clock.Now()) - status.UpdateObservedPhasesForTeardown(c.Client.RESTMapper(), cos, tdres, teardownTime) + status.UpdateObservedPhasesForTeardown(cos, tdres, teardownTime) if tdres != nil && !tdres.IsComplete() { markAsArchiving(cos) return ctrl.Result{RequeueAfter: 5 * time.Second}, nil diff --git a/internal/object-controller/controllers/clusterobjectset_controller_test.go b/internal/object-controller/controllers/clusterobjectset_controller_test.go index 33dbcd8baf..8db8257e2a 100644 --- a/internal/object-controller/controllers/clusterobjectset_controller_test.go +++ b/internal/object-controller/controllers/clusterobjectset_controller_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -560,10 +561,8 @@ func Test_ClusterObjectSetReconciler_Reconcile_RevisionReconciliation(t *testing }, }, { - name: "set Ready:True:AllObjectsReady condition and completedAt on successful revision rollout", - revisionResult: newMockRevisionResult(mockCtrl, revisionResultConfig{ - isComplete: true, - }), + name: "set Ready:True:AllObjectsReady condition and completedAt on successful revision rollout", + revisionResult: newCompletedRevisionResult(mockCtrl, "everything"), reconcilingRevisionName: clusterObjectSetName, existingObjs: func() []client.Object { ext := newTestClusterExtension() @@ -587,10 +586,8 @@ func Test_ClusterObjectSetReconciler_Reconcile_RevisionReconciliation(t *testing }, }, { - name: "completion leaves same-group predecessor lifecycles unchanged regardless of ownership", - revisionResult: newMockRevisionResult(mockCtrl, revisionResultConfig{ - isComplete: true, - }), + name: "completion leaves same-group predecessor lifecycles unchanged regardless of ownership", + revisionResult: newCompletedRevisionResult(mockCtrl, "everything"), reconcilingRevisionName: "test-ext-4", existingObjs: func() []client.Object { ext := newTestClusterExtension() @@ -690,11 +687,9 @@ func Test_ClusterObjectSetReconciler_Reconcile_CompletedAt(t *testing.T) { validate func(*testing.T, *ocv1.ClusterObjectSet) }{ { - name: "sets completedAt to the current time on first successful rollout", - revisionResult: newMockRevisionResult(gomock.NewController(t), revisionResultConfig{ - isComplete: true, - }), - clock: clocktesting.NewFakeClock(firstReady.Time), + name: "sets completedAt to the current time on first successful rollout", + revisionResult: newCompletedRevisionResult(gomock.NewController(t), "everything"), + clock: clocktesting.NewFakeClock(firstReady.Time), existingObjs: func() []client.Object { ext := newTestClusterExtension() rev := newTestClusterObjectSet(t, clusterObjectSetName, ext, testScheme) @@ -706,11 +701,9 @@ func Test_ClusterObjectSetReconciler_Reconcile_CompletedAt(t *testing.T) { }, }, { - name: "does not overwrite completedAt on a subsequent successful rollout", - revisionResult: newMockRevisionResult(gomock.NewController(t), revisionResultConfig{ - isComplete: true, - }), - clock: clocktesting.NewFakeClock(laterReady.Time), + name: "does not overwrite completedAt on a subsequent successful rollout", + revisionResult: newCompletedRevisionResult(gomock.NewController(t), "everything"), + clock: clocktesting.NewFakeClock(laterReady.Time), existingObjs: func() []client.Object { ext := newTestClusterExtension() rev := newTestClusterObjectSet(t, clusterObjectSetName, ext, testScheme) @@ -779,6 +772,7 @@ func Test_ClusterObjectSetReconciler_Reconcile_ValidationError_Retries(t *testin for _, tc := range []struct { name string revisionResult machinery.RevisionResult + wantReason string }{ { name: "retries on revision result validation error", @@ -813,9 +807,32 @@ func Test_ClusterObjectSetReconciler_Reconcile_ValidationError_Retries(t *testin }, }, }), + wantReason: ocv1.ClusterObjectSetReasonPreconditionsNotMet, + }, + { + name: "retries on recoverable phase validation error", + revisionResult: newMockRevisionResult(mockCtrl, revisionResultConfig{ + phases: []machinery.PhaseResult{ + newMockPhaseResult(mockCtrl, phaseResultConfig{ + validationError: &validation.PhaseValidationError{ + PhaseName: "everything", + Objects: []validation.ObjectValidationError{ + { + ObjectRef: machinerytypes.ObjectRef{ + GroupVersionKind: schema.GroupVersionKind{Version: "v1", Kind: "ConfigMap"}, + ObjectKey: client.ObjectKey{Name: "my-configmap", Namespace: "my-namespace"}, + }, + Errors: []error{apierrors.NewForbidden(schema.GroupResource{Resource: "configmaps"}, "my-configmap", fmt.Errorf("not allowed"))}, + }, + }, + }, + }), + }, + }), + wantReason: ocv1.ClusterObjectSetReasonPreconditionsNotMet, }, { - name: "retries on revision result phase validation error", + name: "retries on permanent phase validation error", revisionResult: newMockRevisionResult(mockCtrl, revisionResultConfig{ phases: []machinery.PhaseResult{ newMockPhaseResult(mockCtrl, phaseResultConfig{ @@ -845,6 +862,7 @@ func Test_ClusterObjectSetReconciler_Reconcile_ValidationError_Retries(t *testin }), }, }), + wantReason: ocv1.ClusterObjectSetReasonInvalidSpecification, }, } { t.Run(tc.name, func(t *testing.T) { @@ -880,13 +898,14 @@ func Test_ClusterObjectSetReconciler_Reconcile_ValidationError_Retries(t *testin }, result) require.NoError(t, err) - // preflight validation failures surface as Ready=False/PreconditionsNotMet. + // Preflight validation failures surface as Ready=False with the reason of the + // failure: PreconditionsNotMet when recoverable, InvalidSpecification when permanent. updated := &ocv1.ClusterObjectSet{} require.NoError(t, testClient.Get(t.Context(), client.ObjectKey{Name: clusterObjectSetName}, updated)) cond := meta.FindStatusCondition(updated.Status.Conditions, ocv1.ClusterObjectSetTypeReady) require.NotNil(t, cond) require.Equal(t, metav1.ConditionFalse, cond.Status) - require.Equal(t, ocv1.ClusterObjectSetReasonPreconditionsNotMet, cond.Reason) + require.Equal(t, tc.wantReason, cond.Reason) }) } } @@ -1030,7 +1049,7 @@ func Test_ClusterObjectSetReconciler_Reconcile_ReferencedContentValidationRecove engine := newMockRevisionEngineWithReconcile(mockCtrl, func(context.Context, machinerytypes.Revision, ...machinerytypes.RevisionReconcileOption) (machinery.RevisionResult, error) { - return newMockRevisionResult(mockCtrl, revisionResultConfig{isComplete: true}), nil + return newCompletedRevisionResult(mockCtrl, "everything"), nil }, nil) r := &controllers.ClusterObjectSetReconciler{ Client: testClient, @@ -1097,7 +1116,7 @@ func Test_ClusterObjectSetReconciler_Reconcile_MissingReferencedSecretRecovers(t engine := newMockRevisionEngineWithReconcile(mockCtrl, func(context.Context, machinerytypes.Revision, ...machinerytypes.RevisionReconcileOption) (machinery.RevisionResult, error) { - return newMockRevisionResult(mockCtrl, revisionResultConfig{isComplete: true}), nil + return newCompletedRevisionResult(mockCtrl, "everything"), nil }, nil) r := &controllers.ClusterObjectSetReconciler{ Client: testClient, @@ -1672,6 +1691,18 @@ func newMockRevisionResult(ctrl *gomock.Controller, cfg revisionResultConfig) *m return m } +// newCompletedRevisionResult returns a complete revision result reporting one +// complete phase result, without objects, for each of the given phase names. The +// Ready condition is derived from phase statuses, so a complete result must +// report every phase declared by the ClusterObjectSet. +func newCompletedRevisionResult(ctrl *gomock.Controller, phaseNames ...string) *mockmachinery.MockRevisionResult { + phases := make([]machinery.PhaseResult, 0, len(phaseNames)) + for _, name := range phaseNames { + phases = append(phases, newMockPhaseResult(ctrl, phaseResultConfig{name: name, isComplete: true})) + } + return newMockRevisionResult(ctrl, revisionResultConfig{isComplete: true, phases: phases}) +} + type phaseResultConfig struct { name string validationError *validation.PhaseValidationError diff --git a/internal/object-controller/status/phase_status_test.go b/internal/object-controller/status/phase_status_test.go new file mode 100644 index 0000000000..ee8612726c --- /dev/null +++ b/internal/object-controller/status/phase_status_test.go @@ -0,0 +1,341 @@ +package status + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "pkg.package-operator.run/boxcutter/machinery" + boxcuttertypes "pkg.package-operator.run/boxcutter/machinery/types" + + ocv1 "github.com/operator-framework/operator-controller/api/v1" +) + +func testConfigMap(name string) *unstructured.Unstructured { + obj := &unstructured.Unstructured{} + obj.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("ConfigMap")) + obj.SetNamespace("ns") + obj.SetName(name) + return obj +} + +func probePass() boxcuttertypes.ProbeResultContainer { + return boxcuttertypes.ProbeResultContainer{boxcuttertypes.ProgressProbeType: {Status: boxcuttertypes.ProbeStatusTrue}} +} + +func probeFail(msgs ...string) boxcuttertypes.ProbeResultContainer { + return boxcuttertypes.ProbeResultContainer{boxcuttertypes.ProgressProbeType: {Status: boxcuttertypes.ProbeStatusFalse, Messages: msgs}} +} + +func probeUnknown() boxcuttertypes.ProbeResultContainer { + return boxcuttertypes.ProbeResultContainer{boxcuttertypes.ProgressProbeType: {Status: boxcuttertypes.ProbeStatusUnknown}} +} + +func cmEntry(name string, mods ...func(*ocv1.ObjectStatus)) ocv1.ObjectStatus { + entry := ocv1.ObjectStatus{Object: ocv1.ObjectReference{APIVersion: "v1", Kind: "ConfigMap", Namespace: "ns", Name: name}} + for _, mod := range mods { + mod(&entry) + } + return entry +} + +func colliding(o *ocv1.ObjectStatus) { o.Ownership = ocv1.ObjectOwnershipColliding } +func superseded(o *ocv1.ObjectStatus) { o.Ownership = ocv1.ObjectOwnershipSuperseded } +func awaitingDeletion(o *ocv1.ObjectStatus) { o.Deletion = ocv1.ObjectDeletionAwaitingDeletion } + +func failingProbe(msgs ...string) func(*ocv1.ObjectStatus) { + return func(o *ocv1.ObjectStatus) { + o.ProbeResults = append(o.ProbeResults, ocv1.ObjectProbeResult{Type: boxcuttertypes.ProgressProbeType, Status: ocv1.ObjectProbeResultStatusFalse, Messages: msgs}) + } +} + +func unknownProbe(o *ocv1.ObjectStatus) { + o.ProbeResults = append(o.ProbeResults, ocv1.ObjectProbeResult{Type: boxcuttertypes.ProgressProbeType, Status: ocv1.ObjectProbeResultStatusUnknown}) +} + +func TestUpdateObservedPhasesForReconcile_StatusAndDetails(t *testing.T) { + now := metav1.Now() + manyMessages := make([]string, 20) + for i := range manyMessages { + manyMessages[i] = fmt.Sprintf("message %d", i) + } + truncatedMessages := append(append([]string{}, manyMessages[:17]...), "additional messages were removed for size constraints") + + for _, tc := range []struct { + name string + // prior is the status.observedPhases before the update; one entry per phase in phases. + prior []ocv1.ObservedPhase + phases []machinery.PhaseResult + wantStatus []ocv1.PhaseStatus + wantDetails [][]ocv1.ObjectStatus + }{ + { + name: "collision in an unpaused phase reports ObjectCollision and lists the object as colliding", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionIdle, probes: probePass()}, + &fakeCollisionResult{fakeObjectResult: fakeObjectResult{obj: testConfigMap("cm-b")}}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusObjectCollision}, + wantDetails: [][]ocv1.ObjectStatus{{ + cmEntry("cm-b", colliding), + }}, + }, + { + name: "collision in a paused later phase reports ObjectCollision", + prior: []ocv1.ObservedPhase{{Name: "p1"}, {Name: "p2"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionIdle, probes: probeFail("not ready")}, + }}, + &fakePhaseResult{name: "p2", objects: []machinery.ObjectResult{ + &fakeCollisionResult{fakeObjectResult: fakeObjectResult{obj: testConfigMap("cm-b"), paused: true}}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusStabilizing, ocv1.PhaseStatusObjectCollision}, + wantDetails: [][]ocv1.ObjectStatus{ + {cmEntry("cm-a", failingProbe("not ready"))}, + {cmEntry("cm-b", colliding)}, + }, + }, + { + name: "one object adopted by a newer revision reports Superseded and lists it as superseded", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionProgressed, probes: probePass()}, + &fakeObjectResult{obj: testConfigMap("cm-b"), action: machinery.ActionIdle, probes: probePass()}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusSuperseded}, + wantDetails: [][]ocv1.ObjectStatus{{cmEntry("cm-a", superseded)}}, + }, + { + name: "collision takes precedence over a superseded object, which keeps its failing probe", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionProgressed, probes: probeFail("x")}, + &fakeCollisionResult{fakeObjectResult: fakeObjectResult{obj: testConfigMap("cm-b")}}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusObjectCollision}, + wantDetails: [][]ocv1.ObjectStatus{{ + cmEntry("cm-a", superseded, failingProbe("x")), + cmEntry("cm-b", colliding), + }}, + }, + { + name: "superseded object with a failing probe lists both facts", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionProgressed, probes: probeFail("x")}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusSuperseded}, + wantDetails: [][]ocv1.ObjectStatus{{ + cmEntry("cm-a", superseded, failingProbe("x")), + }}, + }, + { + name: "all objects synced with passing probes reports Ready", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionIdle, probes: probePass()}, + &fakeObjectResult{obj: testConfigMap("cm-b"), action: machinery.ActionCreated, probes: probePass()}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusReady}, + wantDetails: [][]ocv1.ObjectStatus{nil}, + }, + { + name: "object without a progression probe result counts as passing", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionIdle, probes: boxcuttertypes.ProbeResultContainer{}}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusReady}, + wantDetails: [][]ocv1.ObjectStatus{nil}, + }, + { + name: "all objects synced with a failing probe reports Stabilizing", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionIdle, probes: probeFail("replicas not ready")}, + &fakeObjectResult{obj: testConfigMap("cm-b"), action: machinery.ActionIdle, probes: probePass()}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusStabilizing}, + wantDetails: [][]ocv1.ObjectStatus{{ + cmEntry("cm-a", failingProbe("replicas not ready")), + }}, + }, + { + name: "unknown probe result without messages reports Stabilizing with an unknown probe", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionIdle, probes: probeUnknown()}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusStabilizing}, + wantDetails: [][]ocv1.ObjectStatus{{ + cmEntry("cm-a", unknownProbe), + }}, + }, + { + name: "paused phase with objects not yet created reports Pending without details", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionCreated, paused: true}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusPending}, + wantDetails: [][]ocv1.ObjectStatus{nil}, + }, + { + name: "paused object with a failing probe is not listed", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionIdle, paused: true, probes: probeFail("x")}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusStabilizing}, + wantDetails: [][]ocv1.ObjectStatus{nil}, + }, + { + name: "more than 18 probe messages are cut to 17 plus a truncation notice", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionIdle, probes: probeFail(manyMessages...)}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusStabilizing}, + wantDetails: [][]ocv1.ObjectStatus{{ + cmEntry("cm-a", failingProbe(truncatedMessages...)), + }}, + }, + { + name: "an entry written by the previous controller is fully replaced", + prior: []ocv1.ObservedPhase{{ + Name: "p1", + Status: ocv1.PhaseStatus("Reconciling"), + ObjectDetails: []ocv1.ObjectStatus{ + cmEntry("old", failingProbe()), + }, + }}, + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", objects: []machinery.ObjectResult{ + &fakeObjectResult{obj: testConfigMap("cm-a"), action: machinery.ActionIdle, probes: probePass()}, + }}, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusReady}, + wantDetails: [][]ocv1.ObjectStatus{nil}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + cos := ocv1.ClusterObjectSet{Status: ocv1.ClusterObjectSetStatus{ObservedPhases: tc.prior}} + UpdateObservedPhasesForReconcile(&cos, &fakeRevisionResult{phases: tc.phases}, now) + + require.Len(t, cos.Status.ObservedPhases, len(tc.wantStatus)) + for i, phase := range cos.Status.ObservedPhases { + assert.Equal(t, tc.wantStatus[i], phase.Status, "status of phase %q", phase.Name) + assert.Equal(t, tc.wantDetails[i], phase.ObjectDetails, "objectDetails of phase %q", phase.Name) + } + }) + } +} + +func TestUpdateObservedPhasesForTeardown_Details(t *testing.T) { + now := metav1.Now() + refA := boxcuttertypes.ToObjectRef(testConfigMap("cm-a")) + refB := boxcuttertypes.ToObjectRef(testConfigMap("cm-b")) + + for _, tc := range []struct { + name string + prior []ocv1.ObservedPhase + result *fakeTeardownResult + wantStatus []ocv1.PhaseStatus + wantDetails [][]ocv1.ObjectStatus + }{ + { + name: "active phase lists objects awaiting deletion", + prior: []ocv1.ObservedPhase{{Name: "p1"}}, + result: &fakeTeardownResult{ + active: "p1", + phases: []machinery.PhaseTeardownResult{ + &fakePhaseTeardownResult{name: "p1", waiting: []boxcuttertypes.ObjectRef{refA}}, + }, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusArchiving}, + wantDetails: [][]ocv1.ObjectStatus{{ + cmEntry("cm-a", awaitingDeletion), + }}, + }, + { + name: "phase waiting for a later phase lists no objects", + prior: []ocv1.ObservedPhase{{Name: "p1"}, {Name: "p2"}}, + result: &fakeTeardownResult{ + active: "p2", + phases: []machinery.PhaseTeardownResult{ + &fakePhaseTeardownResult{name: "p2", waiting: []boxcuttertypes.ObjectRef{refB}}, + &fakePhaseTeardownResult{name: "p1", waiting: []boxcuttertypes.ObjectRef{refA}}, + }, + }, + wantStatus: []ocv1.PhaseStatus{ocv1.PhaseStatusPending, ocv1.PhaseStatusArchiving}, + wantDetails: [][]ocv1.ObjectStatus{ + nil, + {cmEntry("cm-b", awaitingDeletion)}, + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + cos := ocv1.ClusterObjectSet{Status: ocv1.ClusterObjectSetStatus{ObservedPhases: tc.prior}} + UpdateObservedPhasesForTeardown(&cos, tc.result, now) + + require.Len(t, cos.Status.ObservedPhases, len(tc.wantStatus)) + for i, phase := range cos.Status.ObservedPhases { + assert.Equal(t, tc.wantStatus[i], phase.Status, "status of phase %q", phase.Name) + assert.Equal(t, tc.wantDetails[i], phase.ObjectDetails, "objectDetails of phase %q", phase.Name) + } + }) + } +} + +func TestObjectReference(t *testing.T) { + for _, tc := range []struct { + name string + gvk schema.GroupVersionKind + want ocv1.ObjectReference + }{ + { + name: "core object reports a bare version", + gvk: corev1.SchemeGroupVersion.WithKind("ConfigMap"), + want: ocv1.ObjectReference{APIVersion: "v1", Kind: "ConfigMap", Namespace: "ns", Name: "obj"}, + }, + { + name: "grouped object reports group/version", + gvk: schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}, + want: ocv1.ObjectReference{APIVersion: "apps/v1", Kind: "Deployment", Namespace: "ns", Name: "obj"}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, objectReference(tc.gvk, "ns", "obj")) + }) + } +} diff --git a/internal/object-controller/status/ready.go b/internal/object-controller/status/ready.go new file mode 100644 index 0000000000..b1038e9c0b --- /dev/null +++ b/internal/object-controller/status/ready.go @@ -0,0 +1,97 @@ +package status + +import ( + "fmt" + "slices" + + ocv1 "github.com/operator-framework/operator-controller/api/v1" +) + +// ReadyOutcome is the ClusterObjectSet Ready condition derived from its phase statuses. +type ReadyOutcome struct { + // Ready is true only for reason AllObjectsReady. + Ready bool + // Reason is one of the ocv1.ClusterObjectSetReason* values. + Reason string + // Message is the human-readable condition message. + Message string + // Retry reports that the outcome depends on inputs that are not watched + // (preflight checks and collisions), so reconciliation should be retried + // periodically. + Retry bool +} + +// DeriveReadyCondition derives the Ready condition from the phase statuses +// computed by UpdateObservedPhasesForReconcile: +// +// 1. The first phase, in spec order, that is PreconditionsNotMet, +// InvalidSpecification, or ObjectCollision sets that reason. +// 2. Otherwise, any Superseded phase sets Superseded. +// 3. Otherwise, the ClusterObjectSet is ready when every phase is Ready. +// 4. Otherwise, ObjectsNotReady, counting objects with probe diagnostics. +func DeriveReadyCondition(phases []ocv1.ObservedPhase) ReadyOutcome { + for _, phase := range phases { + switch phase.Status { + case ocv1.PhaseStatusPreconditionsNotMet: + return ReadyOutcome{ + Reason: ocv1.ClusterObjectSetReasonPreconditionsNotMet, + Message: fmt.Sprintf("A preflight check rejected phase %q: %s.", phase.Name, phase.Message), + Retry: true, + } + case ocv1.PhaseStatusInvalidSpecification: + return ReadyOutcome{ + Reason: ocv1.ClusterObjectSetReasonInvalidSpecification, + Message: fmt.Sprintf("A preflight check rejected phase %q: %s.", phase.Name, phase.Message), + Retry: true, + } + case ocv1.PhaseStatusObjectCollision: + return ReadyOutcome{ + Reason: ocv1.ClusterObjectSetReasonObjectCollision, + Message: fmt.Sprintf("Cannot take ownership of %d object(s) in phase %q because they are owned by another controller or already exist. "+ + "Remove the conflicting owner or object, or create a new ClusterObjectSet with a more permissive collisionProtection setting.", + countObjects(phase, isColliding), phase.Name), + Retry: true, + } + } + } + + if slices.ContainsFunc(phases, func(p ocv1.ObservedPhase) bool { return p.Status == ocv1.PhaseStatusSuperseded }) { + return ReadyOutcome{ + Reason: ocv1.ClusterObjectSetReasonSuperseded, + Message: "Object(s) have been adopted by a newer revision of the object set.", + } + } + + if !slices.ContainsFunc(phases, func(p ocv1.ObservedPhase) bool { return p.Status != ocv1.PhaseStatusReady }) { + return ReadyOutcome{ + Ready: true, + Reason: ocv1.ClusterObjectSetReasonAllObjectsReady, + Message: "All objects are at the desired state", + } + } + + var notReady int + for _, phase := range phases { + notReady += countObjects(phase, hasFailingProbe) + } + msg := "Objects are not yet ready." + if notReady > 0 { + msg = fmt.Sprintf("%d object(s) are not yet ready.", notReady) + } + return ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonObjectsNotReady, Message: msg} +} + +// countObjects counts the phase's objectDetails entries matching match. +func countObjects(phase ocv1.ObservedPhase, match func(ocv1.ObjectStatus) bool) int { + var n int + for _, obj := range phase.ObjectDetails { + if match(obj) { + n++ + } + } + return n +} + +func isColliding(obj ocv1.ObjectStatus) bool { return obj.Ownership == ocv1.ObjectOwnershipColliding } + +func hasFailingProbe(obj ocv1.ObjectStatus) bool { return len(obj.ProbeResults) > 0 } diff --git a/internal/object-controller/status/ready_test.go b/internal/object-controller/status/ready_test.go new file mode 100644 index 0000000000..97d48fd802 --- /dev/null +++ b/internal/object-controller/status/ready_test.go @@ -0,0 +1,101 @@ +package status + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + ocv1 "github.com/operator-framework/operator-controller/api/v1" +) + +func TestDeriveReadyCondition(t *testing.T) { + collidingDetail := func(name string) ocv1.ObjectStatus { return cmEntry(name, colliding) } + probeFailedDetail := func(name string) ocv1.ObjectStatus { return cmEntry(name, failingProbe()) } + const collisionMsgPhaseB = "Cannot take ownership of 2 object(s) in phase \"b\" because they are owned by another controller or already exist. Remove the conflicting owner or object, or create a new ClusterObjectSet with a more permissive collisionProtection setting." + const collisionMsgPhaseA = "Cannot take ownership of 1 object(s) in phase \"a\" because they are owned by another controller or already exist. Remove the conflicting owner or object, or create a new ClusterObjectSet with a more permissive collisionProtection setting." + + for _, tc := range []struct { + name string + phases []ocv1.ObservedPhase + want ReadyOutcome + }{ + { + name: "all phases Ready", + phases: []ocv1.ObservedPhase{{Name: "a", Status: ocv1.PhaseStatusReady}, {Name: "b", Status: ocv1.PhaseStatusReady}}, + want: ReadyOutcome{Ready: true, Reason: ocv1.ClusterObjectSetReasonAllObjectsReady, Message: "All objects are at the desired state"}, + }, + { + name: "recoverable phase validation failure reports PreconditionsNotMet", + phases: []ocv1.ObservedPhase{ + {Name: "a", Status: ocv1.PhaseStatusReady}, + {Name: "b", Status: ocv1.PhaseStatusPreconditionsNotMet, Message: "rbac"}, + }, + want: ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonPreconditionsNotMet, Message: "A preflight check rejected phase \"b\": rbac.", Retry: true}, + }, + { + name: "permanent phase validation failure reports InvalidSpecification", + phases: []ocv1.ObservedPhase{{Name: "a", Status: ocv1.PhaseStatusInvalidSpecification, Message: "bad"}}, + want: ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonInvalidSpecification, Message: "A preflight check rejected phase \"a\": bad.", Retry: true}, + }, + { + name: "collision in a later phase reports ObjectCollision naming that phase", + phases: []ocv1.ObservedPhase{ + {Name: "a", Status: ocv1.PhaseStatusReady}, + {Name: "b", Status: ocv1.PhaseStatusObjectCollision, ObjectDetails: []ocv1.ObjectStatus{collidingDetail("cm-1"), collidingDetail("cm-2")}}, + }, + want: ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonObjectCollision, Message: collisionMsgPhaseB, Retry: true}, + }, + { + name: "the first blocking phase decides the outcome", + phases: []ocv1.ObservedPhase{ + {Name: "a", Status: ocv1.PhaseStatusObjectCollision, ObjectDetails: []ocv1.ObjectStatus{collidingDetail("cm-1")}}, + {Name: "b", Status: ocv1.PhaseStatusInvalidSpecification, Message: "bad"}, + }, + want: ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonObjectCollision, Message: collisionMsgPhaseA, Retry: true}, + }, + { + name: "any Superseded phase reports Superseded", + phases: []ocv1.ObservedPhase{{Name: "a", Status: ocv1.PhaseStatusSuperseded}, {Name: "b", Status: ocv1.PhaseStatusStabilizing}}, + want: ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonSuperseded, Message: "Object(s) have been adopted by a newer revision of the object set."}, + }, + { + name: "objects with probe diagnostics are counted as not ready", + phases: []ocv1.ObservedPhase{ + {Name: "a", Status: ocv1.PhaseStatusStabilizing, ObjectDetails: []ocv1.ObjectStatus{probeFailedDetail("cm-1")}}, + {Name: "b", Status: ocv1.PhaseStatusPending}, + }, + want: ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonObjectsNotReady, Message: "1 object(s) are not yet ready."}, + }, + { + name: "superseded objects without failing probes are not counted as not ready", + phases: []ocv1.ObservedPhase{{Name: "a", Status: ocv1.PhaseStatusStabilizing, ObjectDetails: []ocv1.ObjectStatus{ + cmEntry("cm-1", superseded), + cmEntry("cm-2", failingProbe("not ready")), + }}}, + want: ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonObjectsNotReady, Message: "1 object(s) are not yet ready."}, + }, + { + name: "only colliding objects are counted in the collision message", + phases: []ocv1.ObservedPhase{{Name: "b", Status: ocv1.PhaseStatusObjectCollision, ObjectDetails: []ocv1.ObjectStatus{ + cmEntry("cm-1", colliding), + cmEntry("cm-2", colliding), + cmEntry("cm-3", superseded), + }}}, + want: ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonObjectCollision, Message: collisionMsgPhaseB, Retry: true}, + }, + { + name: "pending phase without details reports the generic not-ready message", + phases: []ocv1.ObservedPhase{{Name: "a", Status: ocv1.PhaseStatusPending}}, + want: ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonObjectsNotReady, Message: "Objects are not yet ready."}, + }, + { + name: "unevaluated phase is not ready", + phases: []ocv1.ObservedPhase{{Name: "a", Status: ocv1.PhaseStatusUnknown}}, + want: ReadyOutcome{Reason: ocv1.ClusterObjectSetReasonObjectsNotReady, Message: "Objects are not yet ready."}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, DeriveReadyCondition(tc.phases)) + }) + } +} diff --git a/internal/object-controller/status/status.go b/internal/object-controller/status/status.go index cbeb247d34..214d3c7f48 100644 --- a/internal/object-controller/status/status.go +++ b/internal/object-controller/status/status.go @@ -1,19 +1,17 @@ package status import ( - "fmt" "maps" "slices" - "strings" 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/schema" "k8s.io/utils/ptr" "pkg.package-operator.run/boxcutter/machinery" "pkg.package-operator.run/boxcutter/machinery/types" "pkg.package-operator.run/boxcutter/validation" - "sigs.k8s.io/structured-merge-diff/v6/fieldpath" ocv1 "github.com/operator-framework/operator-controller/api/v1" ) @@ -39,7 +37,7 @@ func addObjectCounts(agg *ocv1.ObjectCounts, counts ocv1.ObjectCounts) { *agg.Ready += ptr.Deref(counts.Ready, 0) } -func UpdateObservedPhasesForReconcile(mapper apimeta.RESTMapper, objSet *ocv1.ClusterObjectSet, rres machinery.RevisionResult, now metav1.Time) { +func UpdateObservedPhasesForReconcile(objSet *ocv1.ClusterObjectSet, rres machinery.RevisionResult, now metav1.Time) { if objSet == nil || rres == nil { return } @@ -100,81 +98,75 @@ func UpdateObservedPhasesForReconcile(mapper apimeta.RESTMapper, objSet *ocv1.Cl precedingPhasesComplete = false } - isPaused := false + var ( + hasCollision bool + hasProgressed bool + allSynced = true + allProbesPass = true + ) for _, pobj := range pres.GetObjects() { if pobj.IsComplete() { *phaseObjectCounts.Ready++ } + synced := false switch pobj.Action() { case machinery.ActionCreated: if !pobj.IsPaused() { *phaseObjectCounts.Present++ *phaseObjectCounts.Synced++ + synced = true } case machinery.ActionIdle: *phaseObjectCounts.Present++ *phaseObjectCounts.Synced++ + synced = true case machinery.ActionProgressed: *phaseObjectCounts.Present++ + hasProgressed = true case machinery.ActionUpdated, machinery.ActionRecovered: *phaseObjectCounts.Present++ if !pobj.IsPaused() { *phaseObjectCounts.Synced++ + synced = true } case machinery.ActionCollision: - // TODO: collect object collisions and put in status + hasCollision = true } + allSynced = allSynced && synced + allProbesPass = allProbesPass && progressionProbePasses(pobj) - // track for phase status derivation - if pobj.IsPaused() { - isPaused = true + // Probe results of paused objects describe expected pending work; only + // collisions are actionable while a phase is paused. + if details, ok := objectEntry(pobj, !pobj.IsPaused()); ok { + observedPhase.ObjectDetails = append(observedPhase.ObjectDetails, details) } } - var ( - // TODO: consider reframing as one or more objects have transitioned (rather than all - since there can be differences b/w the revisions) - isSuperseded = (HasSupersededObject(pres) && pres.IsComplete()) || (len(pres.GetObjects()) > 0 && pres.HasProgressed()) - isReady = pres.IsComplete() && !isSuperseded - isSynced = *phaseObjectCounts.Synced == *phaseObjectCounts.Total - isReconciling = !isSynced && !isPaused - ) - switch { - case isReady: + case hasCollision: + observedPhase.Status = ocv1.PhaseStatusObjectCollision + observedPhase.Message = "one or more objects cannot be adopted under the collision protection policy" + case hasProgressed: + observedPhase.Status = ocv1.PhaseStatusSuperseded + observedPhase.Message = "at least one object has been adopted by a newer revision" + case allSynced && allProbesPass: observedPhase.Status = ocv1.PhaseStatusReady observedPhase.Message = "all objects are ready" - case isSuperseded: - observedPhase.Status = ocv1.PhaseStatusSuperseded - observedPhase.Message = "all objects have progressed to a new revision" - case isSynced: + case allSynced: observedPhase.Status = ocv1.PhaseStatusStabilizing observedPhase.Message = "all objects are synced; waiting for them to become ready" - case isReconciling: - // TODO: deal with surfacing collisions - // TODO: reconsider splitting into the cases where reconciling might appear (e.g. ObjectCollision, objects are transitioning to another revision, etc.) - observedPhase.Status = ocv1.PhaseStatusReconciling - observedPhase.Message = "phase is being reconciled" default: - // read-only while an earlier phase is still rolling out. observedPhase.Status = ocv1.PhaseStatusPending observedPhase.Message = "waiting for previous phases to be ready" } - if !isReady && !isSuperseded { - for _, obj := range pres.GetObjects() { - if obj.IsComplete() || obj.Action() == machinery.ActionProgressed { - continue - } - observedPhase.ObjectDetails = append(observedPhase.ObjectDetails, objectStatus(mapper, obj)) - } - } addObjectCounts(&aggregate, phaseObjectCounts) updateObservedPhaseStatus(objSet, observedPhase, now) } objSet.Status.ObjectCounts = aggregate } -func UpdateObservedPhasesForTeardown(mapper apimeta.RESTMapper, objSet *ocv1.ClusterObjectSet, tres machinery.RevisionTeardownResult, now metav1.Time) { +func UpdateObservedPhasesForTeardown(objSet *ocv1.ClusterObjectSet, tres machinery.RevisionTeardownResult, now metav1.Time) { if objSet == nil || tres == nil { return } @@ -204,6 +196,13 @@ func UpdateObservedPhasesForTeardown(mapper apimeta.RESTMapper, objSet *ocv1.Clu if name, ok := tres.GetActivePhaseName(); ok && name == pres.GetName() { observedPhase.Status = ocv1.PhaseStatusArchiving observedPhase.Message = "removing all phase objects owned by this object set" + // Only the active teardown phase lists its objects awaiting deletion. + for _, ref := range pres.Waiting() { + observedPhase.ObjectDetails = append(observedPhase.ObjectDetails, ocv1.ObjectStatus{ + Object: objectReference(ref.GroupVersionKind, ref.Namespace, ref.Name), + Deletion: ocv1.ObjectDeletionAwaitingDeletion, + }) + } } else if slices.Contains(tres.GetGonePhaseNames(), pres.GetName()) { observedPhase.Status = ocv1.PhaseStatusArchived observedPhase.Message = "all phase objects owned by this object set have been removed" @@ -211,15 +210,6 @@ func UpdateObservedPhasesForTeardown(mapper apimeta.RESTMapper, objSet *ocv1.Clu observedPhase.Status = ocv1.PhaseStatusPending observedPhase.Message = "waiting for later phases to complete teardown" } - for _, ref := range pres.Waiting() { - observedPhase.ObjectDetails = append(observedPhase.ObjectDetails, ocv1.ObjectStatus{ - Group: ref.Group, - Resource: resourceFor(mapper, ref), - Namespace: ref.Namespace, - Name: ref.Name, - Messages: []string{"awaiting deletion"}, - }) - } updateObservedPhaseStatus(objSet, observedPhase, now) } objSet.Status.ObjectCounts = aggregate @@ -262,146 +252,86 @@ func updateObservedPhaseStatus(objSet *ocv1.ClusterObjectSet, observedPhase ocv1 objSet.Status.ObservedPhases = append(objSet.Status.ObservedPhases, observedPhase) } -// HasSupersededObject reports whether any object in the phase has been adopted -// by a newer sibling revision (machinery.ActionProgressed). boxcutter only emits -// ActionProgressed for a newer sibling (a foreign owner is a collision), so no -// revision comparison is needed here. -func HasSupersededObject(pres machinery.PhaseResult) bool { - for _, ores := range pres.GetObjects() { - if ores.Action() == machinery.ActionProgressed { - return true - } - } - return false -} - -// resourceFor returns the lowercase, plural resource name for ref's GroupVersionKind, -// as required by ObjectStatus.resource. It resolves the resource via the RESTMapper so -// that, e.g., a ConfigMap is reported as "configmaps" rather than the "ConfigMap" kind -// (which would fail the field's dns1035 label validation and cause the status update to -// be rejected). When the type is not yet known to the mapper (for example a CRD applied -// by an earlier phase whose discovery has not propagated), it falls back to the -// lowercased kind, which is still a dns1035-valid identifier for the type. -func resourceFor(mapper apimeta.RESTMapper, ref types.ObjectRef) string { - if mapper != nil { - var versions []string - if ref.Version != "" { - versions = []string{ref.Version} - } - if mapping, err := mapper.RESTMapping(ref.GroupKind(), versions...); err == nil { - return mapping.Resource.Resource - } - } - return strings.ToLower(ref.Kind) +// progressionProbePasses reports whether obj's progression probe result is True. +// An object without a progression probe result has no probe to fail. +func progressionProbePasses(obj machinery.ObjectResult) bool { + result, ok := obj.ProbeResults()[types.ProgressProbeType] + return !ok || result.Status == types.ProbeStatusTrue } -// objectStatus returns details describing why obj is not yet complete. -func objectStatus(mapper apimeta.RESTMapper, obj machinery.ObjectResult) ocv1.ObjectStatus { - ref := types.ToObjectRef(obj.Object()) - objStatus := ocv1.ObjectStatus{ - Group: ref.Group, - Resource: resourceFor(mapper, ref), - Namespace: ref.Namespace, - Name: ref.Name, - } - - if obj.IsPaused() && obj.Action() != machinery.ActionIdle { - objStatus.Messages = pausedObjectMessages(obj) - return objStatus - } +// maxProbeMessages is the maximum number of messages in an ObjectProbeResult. +const maxProbeMessages = 18 - var msgs []string +// objectEntry returns obj's objectDetails entry and true when obj has at least one +// reportable fact: an ownership it does not hold (Colliding or Superseded), or +// (when includeProbes is set) a progression probe result that is False or Unknown. +func objectEntry(obj machinery.ObjectResult, includeProbes bool) (ocv1.ObjectStatus, bool) { + var entry ocv1.ObjectStatus - if obj.Action() == machinery.ActionCollision { - msgs = append(msgs, "object ownership collision") + switch obj.Action() { + case machinery.ActionCollision: + entry.Ownership = ocv1.ObjectOwnershipColliding + case machinery.ActionProgressed: + entry.Ownership = ocv1.ObjectOwnershipSuperseded } - probes := obj.ProbeResults() - for _, probeType := range slices.Sorted(maps.Keys(probes)) { - result := probes[probeType] - if result.Status == types.ProbeStatusTrue { - continue - } - for _, m := range result.Messages { - msgs = append(msgs, truncateMessage(fmt.Sprintf("%s: %s", probeType, m))) - } - if len(result.Messages) == 0 { - msgs = append(msgs, truncateMessage(fmt.Sprintf("%s: %s", probeType, result.Status))) + if includeProbes { + probes := obj.ProbeResults() + for _, probeType := range slices.Sorted(maps.Keys(probes)) { + var status ocv1.ObjectProbeResultStatus + switch result := probes[probeType]; result.Status { + case types.ProbeStatusFalse: + status = ocv1.ObjectProbeResultStatusFalse + case types.ProbeStatusUnknown: + status = ocv1.ObjectProbeResultStatusUnknown + default: + continue + } + entry.ProbeResults = append(entry.ProbeResults, ocv1.ObjectProbeResult{ + Type: probeType, + Status: status, + Messages: boundedMessages(probes[probeType].Messages), + }) } } - if len(msgs) == 0 { - msgs = append(msgs, "not yet complete") - } else if len(msgs) > 18 { - msgs = msgs[:17] - msgs = append(msgs, "additional objectDetails messages were removed for size constraints") + if entry.Ownership == "" && len(entry.ProbeResults) == 0 { + return ocv1.ObjectStatus{}, false } - - objStatus.Messages = msgs - return objStatus + o := obj.Object() + entry.Object = objectReference(o.GetObjectKind().GroupVersionKind(), o.GetNamespace(), o.GetName()) + return entry, true } -// pausedObjectMessages returns messages describing why a paused object is not -// idle, including field-level diff details when available. -func pausedObjectMessages(obj machinery.ObjectResult) []string { - var summary string - switch obj.Action() { - case machinery.ActionCreated: - return []string{"object does not exist"} - case machinery.ActionRecovered: - summary = "object was modified by another actor" - case machinery.ActionCollision: - summary = "object ownership collision" - default: - summary = "object content has changed" - } - - if details := compareDetails(obj); len(details) > 0 { - summary += "\n" + strings.Join(details, "\n") +// objectReference returns the objectDetails identity of an object. +func objectReference(gvk schema.GroupVersionKind, namespace, name string) ocv1.ObjectReference { + return ocv1.ObjectReference{ + APIVersion: gvk.GroupVersion().String(), + Kind: gvk.Kind, + Namespace: namespace, + Name: name, } - return []string{truncateMessage(summary)} } -// compareResulter is implemented by ObjectResult types that expose field-level -// comparison results. -type compareResulter interface { - CompareResult() machinery.CompareResult -} - -// compareDetails extracts human-readable field diff lines (added, modified, -// removed) from obj's CompareResult, if obj implements compareResulter. -func compareDetails(obj machinery.ObjectResult) []string { - cr, ok := obj.(compareResulter) - if !ok { - return nil - } - comp := cr.CompareResult().Comparison - if comp == nil { - return nil - } - var details []string - if comp.Added != nil && !comp.Added.Empty() { - comp.Added.Leaves().Iterate(func(p fieldpath.Path) { - details = append(details, fmt.Sprintf(" - added: %s", p)) - }) - } - if comp.Modified != nil && !comp.Modified.Empty() { - comp.Modified.Leaves().Iterate(func(p fieldpath.Path) { - details = append(details, fmt.Sprintf(" - modified: %s", p)) - }) +// boundedMessages truncates messages to the API limits: each message to +// maxMessageLength runes, and at most maxProbeMessages messages, the last +// noting that others were removed. +func boundedMessages(messages []string) []string { + var out []string + for _, m := range messages { + out = append(out, truncateMessage(m)) } - if comp.Removed != nil && !comp.Removed.Empty() { - comp.Removed.Leaves().Iterate(func(p fieldpath.Path) { - details = append(details, fmt.Sprintf(" - removed: %s", p)) - }) + if len(out) > maxProbeMessages { + out = append(out[:maxProbeMessages-1], "additional messages were removed for size constraints") } - return details + return out } // isRecoverablePhaseValidation reports whether a PhaseValidationError represents a // recoverable precondition failure — specifically, a dry-run rejection caused by RBAC -// not yet propagated (Forbidden/Unauthorized) or a dependency CRD not yet registered -// (NoMatch). The controller retries automatically; no spec change is required. +// not yet propagated (Forbidden/Unauthorized), a dependency CRD not yet registered +// (NoMatch), or a dependency such as the target namespace not existing yet (NotFound). +// The controller retries automatically; no spec change is required. // Returns false for permanent failures (invalid phase name, schema violations, // duplicate objects) or any mixture of recoverable and permanent errors. func isRecoverablePhaseValidation(verr *validation.PhaseValidationError) bool { @@ -419,13 +349,15 @@ func isRecoverablePhaseValidation(verr *validation.PhaseValidationError) bool { } // isRecoverableObjectError reports whether an object-level error is a recoverable -// dry-run rejection: Forbidden or Unauthorized (RBAC not yet propagated) or a -// NoMatch error (dependency CRD not yet registered). errors.As traverses the unwrap +// dry-run rejection: Forbidden or Unauthorized (RBAC not yet propagated), a NoMatch +// error (dependency CRD not yet registered), or NotFound (a dependency such as the +// target namespace does not exist yet). errors.As traverses the unwrap // chain, so this works whether or not the error is further wrapped in a // validation.DryRunValidationError. func isRecoverableObjectError(err error) bool { return apierrors.IsForbidden(err) || apierrors.IsUnauthorized(err) || + apierrors.IsNotFound(err) || apimeta.IsNoMatchError(err) } diff --git a/internal/object-controller/status/status_test.go b/internal/object-controller/status/status_test.go index 98bd76ecfb..f990df2d5d 100644 --- a/internal/object-controller/status/status_test.go +++ b/internal/object-controller/status/status_test.go @@ -10,7 +10,6 @@ import ( "github.com/stretchr/testify/require" 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/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" @@ -18,23 +17,10 @@ import ( "pkg.package-operator.run/boxcutter/machinery" boxcuttertypes "pkg.package-operator.run/boxcutter/machinery/types" "pkg.package-operator.run/boxcutter/validation" - "sigs.k8s.io/structured-merge-diff/v6/fieldpath" - "sigs.k8s.io/structured-merge-diff/v6/typed" ocv1 "github.com/operator-framework/operator-controller/api/v1" ) -// testMapper resolves the GroupVersionKinds exercised by these tests to their plural -// resource names, mirroring how the controller's real RESTMapper populates -// ObjectStatus.resource. Types it does not know fall back to the lowercased kind. -var testMapper = func() apimeta.RESTMapper { - m := apimeta.NewDefaultRESTMapper(nil) - m.Add(corev1.SchemeGroupVersion.WithKind("ConfigMap"), apimeta.RESTScopeNamespace) - m.Add(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}, apimeta.RESTScopeNamespace) - m.Add(schema.GroupVersionKind{Group: "apiextensions.k8s.io", Version: "v1", Kind: "CustomResourceDefinition"}, apimeta.RESTScopeRoot) - return m -}() - func TestUpdateObservedPhasesForReconcile(t *testing.T) { now := metav1.Now() @@ -47,16 +33,16 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { name string objects int }{"p1", 1}) - cos.Status.ObservedPhases[0].Status = ocv1.PhaseStatusReconciling + cos.Status.ObservedPhases[0].Status = ocv1.PhaseStatusStabilizing result := &fakeRevisionResult{ validationError: &validation.RevisionValidationError{}, phases: []machinery.PhaseResult{ &fakePhaseResult{name: "p1", complete: true}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) // phases must not be updated when there is a revision-level validation error - assert.Equal(t, ocv1.PhaseStatusReconciling, cos.Status.ObservedPhases[0].Status) + assert.Equal(t, ocv1.PhaseStatusStabilizing, cos.Status.ObservedPhases[0].Status) }) t.Run("phase validation error when preceding phases are complete reports InvalidSpecification", func(t *testing.T) { @@ -70,7 +56,7 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { &fakePhaseResult{name: "p1", complete: true, validationError: ve}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusInvalidSpecification, cos.Status.ObservedPhases[0].Status) assert.Equal(t, int64(1), *cos.Status.ObjectCounts.Total) }) @@ -101,7 +87,33 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { &fakePhaseResult{name: "p1", complete: false, validationError: ve}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) + assert.Equal(t, ocv1.PhaseStatusPreconditionsNotMet, cos.Status.ObservedPhases[0].Status) + }) + + t.Run("not found dry-run response (missing namespace) reports PreconditionsNotMet not InvalidSpecification", func(t *testing.T) { + // A NotFound response means a dependency such as the target namespace does not + // exist yet; it can appear without a spec change, so the phase keeps retrying. + cos := cosWithPhaseObjects(struct { + name string + objects int + }{"p1", 1}) + notFoundErr := apierrors.NewNotFound(schema.GroupResource{Resource: "namespaces"}, "missing") + ve := &validation.PhaseValidationError{ + PhaseName: "p1", + Objects: []validation.ObjectValidationError{ + { + ObjectRef: boxcuttertypes.ToObjectRef(obj), + Errors: []error{notFoundErr}, + }, + }, + } + result := &fakeRevisionResult{ + phases: []machinery.PhaseResult{ + &fakePhaseResult{name: "p1", complete: false, validationError: ve}, + }, + } + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusPreconditionsNotMet, cos.Status.ObservedPhases[0].Status) }) @@ -129,7 +141,7 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { &fakePhaseResult{name: "p1", complete: false, validationError: ve}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusInvalidSpecification, cos.Status.ObservedPhases[0].Status) }) @@ -155,7 +167,7 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { &fakePhaseResult{name: "p2", complete: false, validationError: ve}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusPending, cos.Status.ObservedPhases[1].Status) assert.Equal(t, int64(2), *cos.Status.ObjectCounts.Total) }) @@ -184,7 +196,7 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) require.Len(t, cos.Status.ObservedPhases, 2) assert.Equal(t, ocv1.PhaseStatusSuperseded, cos.Status.ObservedPhases[0].Status) assert.Equal(t, ocv1.PhaseStatusSuperseded, cos.Status.ObservedPhases[1].Status) @@ -203,7 +215,7 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { &fakePhaseResult{name: "p1", complete: true, progressed: true}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusReady, cos.Status.ObservedPhases[0].Status) }) @@ -223,7 +235,7 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusSuperseded, cos.Status.ObservedPhases[0].Status) }) @@ -241,10 +253,10 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) require.NotNil(t, cos.Status.ObservedPhases) assert.Equal(t, ocv1.ObjectCounts{Total: ptr.To(int64(1)), Present: ptr.To(int64(0)), Synced: ptr.To(int64(0)), Ready: ptr.To(int64(0))}, cos.Status.ObjectCounts) - assert.Equal(t, ocv1.PhaseStatusReconciling, cos.Status.ObservedPhases[0].Status) + assert.Equal(t, ocv1.PhaseStatusObjectCollision, cos.Status.ObservedPhases[0].Status) }) t.Run("complete phase reports Ready with full counts", func(t *testing.T) { @@ -260,7 +272,7 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusReady, cos.Status.ObservedPhases[0].Status) assert.Equal(t, ocv1.ObjectCounts{Total: ptr.To(int64(2)), Present: ptr.To(int64(2)), Synced: ptr.To(int64(2)), Ready: ptr.To(int64(2))}, cos.Status.ObjectCounts) }) @@ -273,12 +285,12 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { result := &fakeRevisionResult{ phases: []machinery.PhaseResult{ &fakePhaseResult{name: "p1", complete: false, objects: []machinery.ObjectResult{ - &fakeObjectResult{obj: obj, complete: true, action: machinery.ActionIdle}, - &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionIdle}, + &fakeObjectResult{obj: obj, complete: true, action: machinery.ActionIdle, probes: probePass()}, + &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionIdle, probes: probeFail("not ready")}, }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusStabilizing, cos.Status.ObservedPhases[0].Status) assert.Equal(t, ocv1.ObjectCounts{Total: ptr.To(int64(2)), Present: ptr.To(int64(2)), Synced: ptr.To(int64(2)), Ready: ptr.To(int64(1))}, cos.Status.ObjectCounts) }) @@ -293,13 +305,13 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { result := &fakeRevisionResult{ phases: []machinery.PhaseResult{ &fakePhaseResult{name: "p1", complete: false, objects: []machinery.ObjectResult{ - &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionCreated}, - &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionUpdated}, - &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionRecovered}, + &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionCreated, probes: probeUnknown()}, + &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionUpdated, probes: probeUnknown()}, + &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionRecovered, probes: probeUnknown()}, }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusStabilizing, cos.Status.ObservedPhases[0].Status) assert.Equal(t, ocv1.ObjectCounts{Total: ptr.To(int64(3)), Present: ptr.To(int64(3)), Synced: ptr.To(int64(3)), Ready: ptr.To(int64(0))}, cos.Status.ObjectCounts) }) @@ -320,7 +332,7 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) // isPaused=true → default case → Pending (read-only while earlier phase is rolling out) assert.Equal(t, ocv1.PhaseStatusPending, cos.Status.ObservedPhases[0].Status) // ActionUpdated+paused: Present; ActionRecovered+paused: Present; ActionCreated+paused: nothing @@ -351,12 +363,13 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) require.Len(t, cos.Status.ObservedPhases, 2) assert.Equal(t, ocv1.PhaseStatusPending, cos.Status.ObservedPhases[1].Status) // p1: Total2,Present2,Synced2,Ready2 — p2: Total3,Present2,Synced1,Ready1 assert.Equal(t, ocv1.ObjectCounts{Total: ptr.To(int64(5)), Present: ptr.To(int64(4)), Synced: ptr.To(int64(3)), Ready: ptr.To(int64(3))}, cos.Status.ObjectCounts) - assert.Len(t, cos.Status.ObservedPhases[1].ObjectDetails, 2) + // Pending work of paused objects is expected and not reported. + assert.Empty(t, cos.Status.ObservedPhases[1].ObjectDetails) }) t.Run("Ready phase has no objectDetails", func(t *testing.T) { @@ -372,12 +385,12 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusReady, cos.Status.ObservedPhases[0].Status) assert.Empty(t, cos.Status.ObservedPhases[0].ObjectDetails) }) - t.Run("Superseded phase has no objectDetails", func(t *testing.T) { + t.Run("Superseded phase lists its superseded objects", func(t *testing.T) { cos := cosWithPhaseObjects(struct { name string objects int @@ -390,9 +403,13 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusSuperseded, cos.Status.ObservedPhases[0].Status) - assert.Empty(t, cos.Status.ObservedPhases[0].ObjectDetails) + require.Len(t, cos.Status.ObservedPhases[0].ObjectDetails, 2) + for _, entry := range cos.Status.ObservedPhases[0].ObjectDetails { + assert.Equal(t, ocv1.ObjectOwnershipSuperseded, entry.Ownership) + assert.Empty(t, entry.ProbeResults) + } }) t.Run("Stabilizing phase populates objectDetails", func(t *testing.T) { @@ -403,55 +420,16 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { result := &fakeRevisionResult{ phases: []machinery.PhaseResult{ &fakePhaseResult{name: "p1", complete: false, objects: []machinery.ObjectResult{ - &fakeObjectResult{obj: obj, complete: true, action: machinery.ActionIdle}, - &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionIdle}, + &fakeObjectResult{obj: obj, complete: true, action: machinery.ActionIdle, probes: probePass()}, + &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionIdle, probes: probeFail("not ready")}, }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) assert.Equal(t, ocv1.PhaseStatusStabilizing, cos.Status.ObservedPhases[0].Status) assert.Len(t, cos.Status.ObservedPhases[0].ObjectDetails, 1) }) - t.Run("Reconciling phase populates objectDetails", func(t *testing.T) { - // ActionProgressed counts as Present but not Synced, so isSynced=false and isPaused=false → Reconciling. - cos := cosWithPhaseObjects(struct { - name string - objects int - }{"p1", 2}) - result := &fakeRevisionResult{ - phases: []machinery.PhaseResult{ - &fakePhaseResult{name: "p1", complete: false, objects: []machinery.ObjectResult{ - &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionIdle}, - &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionProgressed}, - }}, - }, - } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) - assert.Equal(t, ocv1.PhaseStatusReconciling, cos.Status.ObservedPhases[0].Status) - assert.Len(t, cos.Status.ObservedPhases[0].ObjectDetails, 1) - }) - - t.Run("ActionProgressed objects are excluded from objectDetails", func(t *testing.T) { - // ActionProgressed means the object has been claimed by a newer revision; - // it is not a failure condition and must not appear in objectDetails. - cos := cosWithPhaseObjects(struct { - name string - objects int - }{"p1", 2}) - result := &fakeRevisionResult{ - phases: []machinery.PhaseResult{ - &fakePhaseResult{name: "p1", complete: false, objects: []machinery.ObjectResult{ - &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionProgressed}, - &fakeObjectResult{obj: obj, complete: false, action: machinery.ActionCreated}, - }}, - }, - } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) - require.Len(t, cos.Status.ObservedPhases[0].ObjectDetails, 1) - assert.Equal(t, "my-cm", cos.Status.ObservedPhases[0].ObjectDetails[0].Name) - }) - t.Run("aggregate ObjectCounts sums across phases", func(t *testing.T) { cos := cosWithPhaseObjects( struct { @@ -474,7 +452,7 @@ func TestUpdateObservedPhasesForReconcile(t *testing.T) { }}, }, } - UpdateObservedPhasesForReconcile(testMapper, &cos, result, now) + UpdateObservedPhasesForReconcile(&cos, result, now) // p1: Total=2,Present=2,Synced=2,Ready=2 — p2: Total=3,Present=1,Synced=1,Ready=0 assert.Equal(t, ocv1.ObjectCounts{Total: ptr.To(int64(5)), Present: ptr.To(int64(3)), Synced: ptr.To(int64(3)), Ready: ptr.To(int64(2))}, cos.Status.ObjectCounts) }) @@ -494,7 +472,7 @@ func TestUpdateObservedPhasesForTeardown(t *testing.T) { &fakePhaseTeardownResult{name: "p1", waiting: []boxcuttertypes.ObjectRef{{}, {}}}, }, } - UpdateObservedPhasesForTeardown(testMapper, &cos, result, now) + UpdateObservedPhasesForTeardown(&cos, result, now) require.Len(t, cos.Status.ObservedPhases, 1) phase := cos.Status.ObservedPhases[0] assert.Equal(t, ocv1.PhaseStatusArchiving, phase.Status) @@ -503,7 +481,7 @@ func TestUpdateObservedPhasesForTeardown(t *testing.T) { assert.Len(t, phase.ObjectDetails, 2) }) - t.Run("objectDetails contain awaiting deletion with correct object identity", func(t *testing.T) { + t.Run("objectDetails report awaiting deletion with the object identity", func(t *testing.T) { waitingObj := &unstructured.Unstructured{} waitingObj.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("ConfigMap")) waitingObj.SetName("my-cm") @@ -520,14 +498,11 @@ func TestUpdateObservedPhasesForTeardown(t *testing.T) { &fakePhaseTeardownResult{name: "p1", waiting: []boxcuttertypes.ObjectRef{ref}}, }, } - UpdateObservedPhasesForTeardown(testMapper, &cos, result, now) + UpdateObservedPhasesForTeardown(&cos, result, now) require.Len(t, cos.Status.ObservedPhases[0].ObjectDetails, 1) detail := cos.Status.ObservedPhases[0].ObjectDetails[0] - assert.Equal(t, corev1.SchemeGroupVersion.Group, detail.Group) - assert.Equal(t, "configmaps", detail.Resource) - assert.Equal(t, "default", detail.Namespace) - assert.Equal(t, "my-cm", detail.Name) - assert.Equal(t, []string{"awaiting deletion"}, detail.Messages) + assert.Equal(t, ocv1.ObjectReference{APIVersion: "v1", Kind: "ConfigMap", Namespace: "default", Name: "my-cm"}, detail.Object) + assert.Equal(t, ocv1.ObjectDeletionAwaitingDeletion, detail.Deletion) }) t.Run("gone phase gets Archived status with message", func(t *testing.T) { @@ -541,7 +516,7 @@ func TestUpdateObservedPhasesForTeardown(t *testing.T) { &fakePhaseTeardownResult{name: "p1"}, }, } - UpdateObservedPhasesForTeardown(testMapper, &cos, result, now) + UpdateObservedPhasesForTeardown(&cos, result, now) require.Len(t, cos.Status.ObservedPhases, 1) phase := cos.Status.ObservedPhases[0] assert.Equal(t, ocv1.PhaseStatusArchived, phase.Status) @@ -574,7 +549,7 @@ func TestUpdateObservedPhasesForTeardown(t *testing.T) { &fakePhaseTeardownResult{name: "p1", waiting: []boxcuttertypes.ObjectRef{{}, {}}}, }, } - UpdateObservedPhasesForTeardown(testMapper, &cos, result, now) + UpdateObservedPhasesForTeardown(&cos, result, now) require.Len(t, cos.Status.ObservedPhases, 3) phases := cos.Status.ObservedPhases @@ -582,7 +557,8 @@ func TestUpdateObservedPhasesForTeardown(t *testing.T) { // p1 — pending, waiting for later phases to complete assert.Equal(t, ocv1.PhaseStatusPending, phases[0].Status) assert.Equal(t, "waiting for later phases to complete teardown", phases[0].Message) - assert.Len(t, phases[0].ObjectDetails, 2) + // Only the active teardown phase lists its objects. + assert.Empty(t, phases[0].ObjectDetails) // p2 — active teardown assert.Equal(t, ocv1.PhaseStatusArchiving, phases[1].Status) @@ -610,7 +586,7 @@ func TestUpdateObservedPhasesForTeardown(t *testing.T) { }{"p2", 3}, ) // Set a recognisable prior status on p1 - cos.Status.ObservedPhases[0].Status = ocv1.PhaseStatusReconciling + cos.Status.ObservedPhases[0].Status = ocv1.PhaseStatusStabilizing // Only p2 has a result; p1 is absent from GetPhases result := &fakeTeardownResult{ active: "p2", @@ -618,10 +594,10 @@ func TestUpdateObservedPhasesForTeardown(t *testing.T) { &fakePhaseTeardownResult{name: "p2", waiting: []boxcuttertypes.ObjectRef{{}}}, }, } - UpdateObservedPhasesForTeardown(testMapper, &cos, result, now) + UpdateObservedPhasesForTeardown(&cos, result, now) require.Len(t, cos.Status.ObservedPhases, 2) // p1 not in GetPhases — must not be touched - assert.Equal(t, ocv1.PhaseStatusReconciling, cos.Status.ObservedPhases[0].Status) + assert.Equal(t, ocv1.PhaseStatusStabilizing, cos.Status.ObservedPhases[0].Status) }) t.Run("CompletedAt is not stamped on non-Ready teardown phases", func(t *testing.T) { @@ -635,7 +611,7 @@ func TestUpdateObservedPhasesForTeardown(t *testing.T) { &fakePhaseTeardownResult{name: "p1", waiting: []boxcuttertypes.ObjectRef{{}}}, }, } - UpdateObservedPhasesForTeardown(testMapper, &cos, result, now) + UpdateObservedPhasesForTeardown(&cos, result, now) assert.True(t, cos.Status.ObservedPhases[0].CompletedAt.IsZero()) }) @@ -652,7 +628,7 @@ func TestUpdateObservedPhasesForTeardown(t *testing.T) { &fakePhaseTeardownResult{name: "p1", waiting: []boxcuttertypes.ObjectRef{{}}}, }, } - UpdateObservedPhasesForTeardown(testMapper, &cos, result, now) + UpdateObservedPhasesForTeardown(&cos, result, now) require.NotNil(t, cos.Status.ObservedPhases[0].CompletedAt) assert.Equal(t, earlier, cos.Status.ObservedPhases[0].CompletedAt) }) @@ -677,7 +653,7 @@ func TestUpdateObservedPhaseStatus(t *testing.T) { name string objects int }{"p1", 1}) - updateObservedPhaseStatus(&cos, ocv1.ObservedPhase{Name: "p1", Status: ocv1.PhaseStatusReconciling}, fixedNow) + updateObservedPhaseStatus(&cos, ocv1.ObservedPhase{Name: "p1", Status: ocv1.PhaseStatusStabilizing}, fixedNow) assert.True(t, cos.Status.ObservedPhases[0].CompletedAt.IsZero()) }) @@ -697,7 +673,7 @@ func TestUpdateObservedPhaseStatus(t *testing.T) { name string objects int }{"p1", 1}) - cos.Status.ObservedPhases[0].Status = ocv1.PhaseStatusReconciling + cos.Status.ObservedPhases[0].Status = ocv1.PhaseStatusPending cos.Status.ObservedPhases[0].LastTransitionTime = earlier updateObservedPhaseStatus(&cos, ocv1.ObservedPhase{Name: "p1", Status: ocv1.PhaseStatusStabilizing}, fixedNow) assert.Equal(t, fixedNow, cos.Status.ObservedPhases[0].LastTransitionTime) @@ -708,9 +684,9 @@ func TestUpdateObservedPhaseStatus(t *testing.T) { name string objects int }{"p1", 1}) - cos.Status.ObservedPhases[0].Status = ocv1.PhaseStatusReconciling + cos.Status.ObservedPhases[0].Status = ocv1.PhaseStatusStabilizing cos.Status.ObservedPhases[0].LastTransitionTime = earlier - updateObservedPhaseStatus(&cos, ocv1.ObservedPhase{Name: "p1", Status: ocv1.PhaseStatusReconciling}, fixedNow) + updateObservedPhaseStatus(&cos, ocv1.ObservedPhase{Name: "p1", Status: ocv1.PhaseStatusStabilizing}, fixedNow) assert.Equal(t, earlier, cos.Status.ObservedPhases[0].LastTransitionTime) }) @@ -720,7 +696,7 @@ func TestUpdateObservedPhaseStatus(t *testing.T) { objects int }{"p1", 1}) cos.Status.ObservedPhases[0].Digest = "sha256:abc123" - updateObservedPhaseStatus(&cos, ocv1.ObservedPhase{Name: "p1", Status: ocv1.PhaseStatusReconciling}, fixedNow) + updateObservedPhaseStatus(&cos, ocv1.ObservedPhase{Name: "p1", Status: ocv1.PhaseStatusStabilizing}, fixedNow) assert.Equal(t, "sha256:abc123", cos.Status.ObservedPhases[0].Digest) }) @@ -732,10 +708,10 @@ func TestUpdateObservedPhaseStatus(t *testing.T) { objects int }{"p1", 1}), } - updateObservedPhaseStatus(&cos, ocv1.ObservedPhase{Name: "p1", Status: ocv1.PhaseStatusReconciling}, fixedNow) + updateObservedPhaseStatus(&cos, ocv1.ObservedPhase{Name: "p1", Status: ocv1.PhaseStatusStabilizing}, fixedNow) require.Len(t, cos.Status.ObservedPhases, 1) assert.Equal(t, "p1", cos.Status.ObservedPhases[0].Name) - assert.Equal(t, ocv1.PhaseStatusReconciling, cos.Status.ObservedPhases[0].Status) + assert.Equal(t, ocv1.PhaseStatusStabilizing, cos.Status.ObservedPhases[0].Status) assert.Equal(t, fixedNow, cos.Status.ObservedPhases[0].LastTransitionTime) }) } @@ -757,247 +733,6 @@ func TestTruncateMessage(t *testing.T) { }) } -func TestObjectStatus(t *testing.T) { - obj := &unstructured.Unstructured{} - obj.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("ConfigMap")) - obj.SetName("my-cm") - obj.SetNamespace("default") - - t.Run("populates object identity from GVK and object ref", func(t *testing.T) { - result := objectStatus(testMapper, &fakeObjectResult{obj: obj, probes: boxcuttertypes.ProbeResultContainer{}}) - assert.Equal(t, corev1.SchemeGroupVersion.Group, result.Group) - assert.Equal(t, "configmaps", result.Resource) - assert.Equal(t, "default", result.Namespace) - assert.Equal(t, "my-cm", result.Name) - }) - - t.Run("collision returns ownership collision message", func(t *testing.T) { - result := objectStatus(testMapper, &fakeCollisionResult{ - fakeObjectResult: fakeObjectResult{obj: obj, probes: boxcuttertypes.ProbeResultContainer{}}, - }) - assert.Equal(t, []string{"object ownership collision"}, result.Messages) - }) - - t.Run("failing probe with message", func(t *testing.T) { - result := objectStatus(testMapper, &fakeObjectResult{ - obj: obj, - probes: boxcuttertypes.ProbeResultContainer{ - "readiness": {Status: boxcuttertypes.ProbeStatusFalse, Messages: []string{"not ready"}}, - }, - }) - assert.Equal(t, []string{"readiness: not ready"}, result.Messages) - }) - - t.Run("failing probe without message shows status", func(t *testing.T) { - result := objectStatus(testMapper, &fakeObjectResult{ - obj: obj, - probes: boxcuttertypes.ProbeResultContainer{ - "readiness": {Status: boxcuttertypes.ProbeStatusFalse}, - }, - }) - assert.Equal(t, []string{"readiness: False"}, result.Messages) - }) - - t.Run("passing probe is omitted and falls back to not yet complete", func(t *testing.T) { - result := objectStatus(testMapper, &fakeObjectResult{ - obj: obj, - probes: boxcuttertypes.ProbeResultContainer{ - "readiness": {Status: boxcuttertypes.ProbeStatusTrue}, - }, - }) - assert.Equal(t, []string{"not yet complete"}, result.Messages) - }) - - t.Run("paused non-idle delegates to pausedObjectMessages", func(t *testing.T) { - result := objectStatus(testMapper, &fakeObjectResult{ - obj: obj, - paused: true, - action: machinery.ActionCreated, - probes: boxcuttertypes.ProbeResultContainer{}, - }) - assert.Equal(t, []string{"object does not exist"}, result.Messages) - }) - - t.Run("no issues returns not yet complete", func(t *testing.T) { - result := objectStatus(testMapper, &fakeObjectResult{ - obj: obj, - action: machinery.ActionIdle, - probes: boxcuttertypes.ProbeResultContainer{}, - }) - assert.Equal(t, []string{"not yet complete"}, result.Messages) - }) - - t.Run("more than 18 messages are cut to 17 plus a truncation notice", func(t *testing.T) { - probes := boxcuttertypes.ProbeResultContainer{} - for i := range 20 { - probes[fmt.Sprintf("probe-%02d", i)] = boxcuttertypes.ProbeResult{ - Status: boxcuttertypes.ProbeStatusFalse, - Messages: []string{"failed"}, - } - } - result := objectStatus(testMapper, &fakeObjectResult{obj: obj, probes: probes}) - require.Len(t, result.Messages, 18) - assert.Equal(t, "additional objectDetails messages were removed for size constraints", result.Messages[17]) - }) -} - -func TestPausedObjectMessages(t *testing.T) { - obj := &unstructured.Unstructured{} - obj.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("ConfigMap")) - obj.SetName("my-cm") - - t.Run("ActionCreated returns object does not exist", func(t *testing.T) { - msgs := pausedObjectMessages(&fakeObjectResult{obj: obj, paused: true, action: machinery.ActionCreated}) - assert.Equal(t, []string{"object does not exist"}, msgs) - }) - - t.Run("ActionCollision without compare result returns ownership collision", func(t *testing.T) { - msgs := pausedObjectMessages(&fakeObjectResult{obj: obj, paused: true, action: machinery.ActionCollision}) - assert.Equal(t, []string{"object ownership collision"}, msgs) - }) - - t.Run("ActionCollision with compare result includes diff details", func(t *testing.T) { - msgs := pausedObjectMessages(&fakeCompareObjectResult{ - fakeObjectResult: fakeObjectResult{obj: obj, paused: true, action: machinery.ActionCollision}, - compareResult: machinery.CompareResult{ - Comparison: &typed.Comparison{ - Modified: fieldpath.NewSet(fieldpath.MakePathOrDie("metadata", "annotations")), - }, - }, - }) - require.Len(t, msgs, 1) - assert.Contains(t, msgs[0], "object ownership collision") - assert.Contains(t, msgs[0], " - modified: .metadata.annotations") - }) - - t.Run("ActionRecovered without compare result", func(t *testing.T) { - msgs := pausedObjectMessages(&fakeObjectResult{obj: obj, paused: true, action: machinery.ActionRecovered}) - assert.Equal(t, []string{"object was modified by another actor"}, msgs) - }) - - t.Run("ActionRecovered with compare result", func(t *testing.T) { - msgs := pausedObjectMessages(&fakeCompareObjectResult{ - fakeObjectResult: fakeObjectResult{obj: obj, paused: true, action: machinery.ActionRecovered}, - compareResult: machinery.CompareResult{ - Comparison: &typed.Comparison{ - Modified: fieldpath.NewSet(fieldpath.MakePathOrDie("data", "key")), - }, - }, - }) - require.Len(t, msgs, 1) - assert.Contains(t, msgs[0], "object was modified by another actor") - assert.Contains(t, msgs[0], " - modified: .data.key") - }) - - t.Run("default action without compare result", func(t *testing.T) { - msgs := pausedObjectMessages(&fakeObjectResult{obj: obj, paused: true, action: machinery.ActionUpdated}) - assert.Equal(t, []string{"object content has changed"}, msgs) - }) - - t.Run("default action with compare result", func(t *testing.T) { - msgs := pausedObjectMessages(&fakeCompareObjectResult{ - fakeObjectResult: fakeObjectResult{obj: obj, paused: true, action: machinery.ActionUpdated}, - compareResult: machinery.CompareResult{ - Comparison: &typed.Comparison{ - Added: fieldpath.NewSet(fieldpath.MakePathOrDie("data", "new-key")), - }, - }, - }) - require.Len(t, msgs, 1) - assert.Contains(t, msgs[0], "object content has changed") - assert.Contains(t, msgs[0], " - added: .data.new-key") - }) - - t.Run("long summary is truncated to maxMessageLength", func(t *testing.T) { - modified := fieldpath.NewSet() - for i := range 200 { - modified.Insert(fieldpath.MakePathOrDie("data", strings.Repeat("k", i+1))) - } - msgs := pausedObjectMessages(&fakeCompareObjectResult{ - fakeObjectResult: fakeObjectResult{obj: obj, paused: true, action: machinery.ActionRecovered}, - compareResult: machinery.CompareResult{ - Comparison: &typed.Comparison{Modified: modified}, - }, - }) - require.Len(t, msgs, 1) - assert.LessOrEqual(t, len([]rune(msgs[0])), maxMessageLength) - }) -} - -func TestCompareDetails(t *testing.T) { - obj := &unstructured.Unstructured{} - obj.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("ConfigMap")) - obj.SetName("my-cm") - - t.Run("object without compareResulter returns nil", func(t *testing.T) { - result := compareDetails(&fakeObjectResult{obj: obj}) - assert.Nil(t, result) - }) - - t.Run("nil Comparison returns nil", func(t *testing.T) { - result := compareDetails(&fakeCompareObjectResult{ - fakeObjectResult: fakeObjectResult{obj: obj}, - compareResult: machinery.CompareResult{Comparison: nil}, - }) - assert.Nil(t, result) - }) - - t.Run("added fields only", func(t *testing.T) { - result := compareDetails(&fakeCompareObjectResult{ - fakeObjectResult: fakeObjectResult{obj: obj}, - compareResult: machinery.CompareResult{ - Comparison: &typed.Comparison{ - Added: fieldpath.NewSet(fieldpath.MakePathOrDie("data", "foo")), - }, - }, - }) - assert.Equal(t, []string{" - added: .data.foo"}, result) - }) - - t.Run("modified fields only", func(t *testing.T) { - result := compareDetails(&fakeCompareObjectResult{ - fakeObjectResult: fakeObjectResult{obj: obj}, - compareResult: machinery.CompareResult{ - Comparison: &typed.Comparison{ - Modified: fieldpath.NewSet(fieldpath.MakePathOrDie("data", "bar")), - }, - }, - }) - assert.Equal(t, []string{" - modified: .data.bar"}, result) - }) - - t.Run("removed fields only", func(t *testing.T) { - result := compareDetails(&fakeCompareObjectResult{ - fakeObjectResult: fakeObjectResult{obj: obj}, - compareResult: machinery.CompareResult{ - Comparison: &typed.Comparison{ - Removed: fieldpath.NewSet(fieldpath.MakePathOrDie("data", "old")), - }, - }, - }) - assert.Equal(t, []string{" - removed: .data.old"}, result) - }) - - t.Run("all three field types", func(t *testing.T) { - result := compareDetails(&fakeCompareObjectResult{ - fakeObjectResult: fakeObjectResult{obj: obj}, - compareResult: machinery.CompareResult{ - Comparison: &typed.Comparison{ - Added: fieldpath.NewSet(fieldpath.MakePathOrDie("data", "new")), - Modified: fieldpath.NewSet(fieldpath.MakePathOrDie("data", "changed")), - Removed: fieldpath.NewSet(fieldpath.MakePathOrDie("data", "gone")), - }, - }, - }) - require.Len(t, result, 3) - assert.Equal(t, " - added: .data.new", result[0]) - assert.Equal(t, " - modified: .data.changed", result[1]) - assert.Equal(t, " - removed: .data.gone", result[2]) - }) -} - -// Test fakes - type fakeRevisionResult struct { validationError *validation.RevisionValidationError phases []machinery.PhaseResult @@ -1049,17 +784,14 @@ func (f *fakeObjectResult) String() string { type fakeCollisionResult struct { fakeObjectResult + owner *metav1.OwnerReference } func (f *fakeCollisionResult) Action() machinery.Action { return machinery.ActionCollision } - -type fakeCompareObjectResult struct { - fakeObjectResult - compareResult machinery.CompareResult +func (f *fakeCollisionResult) ConflictingOwner() (*metav1.OwnerReference, bool) { + return f.owner, f.owner != nil } -func (f *fakeCompareObjectResult) CompareResult() machinery.CompareResult { return f.compareResult } - type fakeTeardownResult struct { complete bool active string diff --git a/manifests/experimental-e2e.yaml b/manifests/experimental-e2e.yaml index 04465770b6..c7abd13239 100644 --- a/manifests/experimental-e2e.yaml +++ b/manifests/experimental-e2e.yaml @@ -2750,8 +2750,8 @@ spec: - False with reason ObjectsNotReady: one or more objects are still being applied or have not yet passed their readiness probes during rollout. - False with reason Superseded: one or more objects have been adopted by a newer revision of the object set. - False with reason ObjectCollision: one or more objects are controlled by another owner, or are unowned while collision protection prevents adoption, so this revision cannot take ownership of them. - - False with reason PreconditionsNotMet: a precondition for applying the revision is not yet satisfied (a referenced Secret is mutable or has invalid or changed content, or a preflight dry-run was rejected, e.g. an immutable field, a conflicting object, or RBAC/dependency CRDs not yet propagated); the revision keeps retrying and recovers once the precondition is met. - - False with reason InvalidSpecification: the revision spec is invalid (a malformed revision/phase object or progression probe) and requires a spec change to proceed. + - False with reason PreconditionsNotMet: a precondition for applying the revision is not yet satisfied (a referenced Secret is mutable or has invalid or changed content, a revision-wide preflight check was rejected, or a phase's preflight dry-run was rejected because RBAC or dependency CRDs have not yet propagated or a dependency such as the target namespace does not exist yet); the revision keeps retrying and recovers once the precondition is met. + - False with reason InvalidSpecification: the revision spec is invalid (a malformed revision/phase object or progression probe, or a phase's preflight dry-run was rejected permanently, e.g. a schema violation or an immutable field) and requires a spec change to proceed. - False with reason Archiving: the revision is being archived and its owned objects are still being torn down. - False with reason Archived: the revision has been archived and its objects have been torn down. @@ -2867,14 +2867,17 @@ spec: different content. Each entry covers all fully-resolved object manifests within a phase, making it source-agnostic. items: - description: ObservedPhase records the observed content digest of - a resolved phase. + description: |- + ObservedPhase reports a phase's current lifecycle state and sparse + diagnostics together with its pinned content digest and historical + completion. properties: completedAt: description: |- - completedAt is the timestamp when this phase first became Ready. - Set once and never modified. Nil means the phase has never been - Ready. + completedAt is the timestamp when this phase was first observed Ready. + Omitted until that observation. Once recorded, it cannot change or be + removed, even if the phase later fails its progression probes or is + superseded. format: date-time type: string x-kubernetes-validations: @@ -2894,16 +2897,18 @@ spec: - message: digest must be in the format ':' rule: self.matches('^[a-z0-9]+:[a-f0-9]+$') lastTransitionTime: - description: lastTransitionTime is the last time the phase transitioned - from one status to another. + description: |- + lastTransitionTime is the timestamp when the current status was first + reported or last changed. Changes to message alone do not update this + timestamp. format: date-time type: string message: description: |- - message is a phase-level message providing context about the - current status (e.g. a validation error for InvalidSpecification - phases, or a summary for Pending phases). At most 1024 characters; - longer messages are truncated by the controller. + message provides human-readable context, such as a phase-wide validation + failure or the reason a phase is waiting. Consumers must not parse this + message. At most 1024 characters; longer messages are truncated by the + controller. maxLength: 1024 minLength: 1 type: string @@ -2919,101 +2924,194 @@ spec: rule: '!format.dns1123Label().validate(self).hasValue()' objectDetails: description: |- - objectDetails lists objects in this phase that are not yet - complete. For Reconciling, Pending, and Stabilizing phases, this - includes probe failures, collisions, creation/update errors, and - any other condition preventing completion. For Archiving phases, - this lists objects still awaiting deletion. Each entry identifies - the object and carries failure messages. Empty when status is - Ready, Superseded, Archived, or Unknown. The list may contain at - most 50 entries, matching the maximum number of objects per phase. + objectDetails reports per-object facts for objects with current problems or + notable ownership; it is not a full object inventory. An object is listed + when it has progression probes that are not passing (objects in phases that + are waiting for an earlier phase excluded), when this ClusterObjectSet cannot + take ownership of it (including in phases that are waiting), when it has been + adopted by a newer ClusterObjectSet, or when it awaits deletion in the active + teardown phase. Entries are removed when those facts no longer apply. + At most 50 entries, matching the maximum number of objects per phase. items: - description: ObjectStatus identifies a managed object and - its failure messages. + description: |- + ObjectStatus reports observed facts about an object with current problems or + notable ownership. The object may be missing or controlled by a conflicting + owner; it is not necessarily managed by this ClusterObjectSet. At least one of + probeResults, ownership, or deletion is set. properties: - group: + deletion: description: |- - group is the API group of the object (empty string for core - resources). At most 253 characters (DNS subdomain max). - maxLength: 253 - minLength: 1 + deletion reports the object's teardown state: + - AwaitingDeletion: the object is owned by this ClusterObjectSet, has been + requested for deletion, and is not yet gone from the cluster. + + Omitted when the object is not being torn down. + enum: + - AwaitingDeletion type: string - x-kubernetes-validations: - - message: 'the value must be a valid DNS subdomain: lowercase - alphanumeric characters, hyphens, and dots, starting - and ending with an alphanumeric character.' - rule: '!format.dns1123Subdomain().validate(self).hasValue()' - messages: + object: description: |- - messages lists the failure reasons for this object. The maximum - of 18 entries accounts for up to 16 assertion probe failures, - one collision message, and one message to note truncation if necessary. - Each message is at most 1024 characters; longer messages are truncated - by the controller. - items: - maxLength: 1024 - minLength: 1 - type: string - maxItems: 18 - type: array - x-kubernetes-list-type: atomic - name: - description: |- - name is the name of the object. Must be between 1 and 253 - characters (DNS subdomain max). - maxLength: 253 - minLength: 1 - type: string - x-kubernetes-validations: - - message: 'name must be a valid object name: it may not - be ''.'' or ''..'' or contain ''/'' or ''%''' - rule: self != "." && self != ".." && !self.contains("/") - && !self.contains("%") - namespace: + object identifies the object by apiVersion, kind, namespace, and name, + matching the declared object manifest. + properties: + apiVersion: + description: |- + apiVersion is the API version of the object, for example "v1" or + "apps/v1". It matches the apiVersion of the declared object manifest. + maxLength: 317 + minLength: 1 + type: string + x-kubernetes-validations: + - message: apiVersion must be a version or group/version + rule: self.matches('^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[a-z]([-a-z0-9]*[a-z0-9])?$') + kind: + description: |- + kind is the kind of the object, for example "ConfigMap". It matches the + kind of the declared object manifest. + maxLength: 63 + minLength: 1 + type: string + x-kubernetes-validations: + - message: kind must start with a letter and contain + only letters, digits, or hyphens, ending with + an alphanumeric character + rule: self.matches('^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$') + name: + description: |- + name is the name of the object. Must be between 1 and 253 + characters (DNS subdomain max). + maxLength: 253 + minLength: 1 + type: string + x-kubernetes-validations: + - message: 'name must be a valid object name: it may + not be ''.'' or ''..'' or contain ''/'' or ''%''' + rule: self != "." && self != ".." && !self.contains("/") + && !self.contains("%") + namespace: + description: |- + namespace is the namespace of the object. Omitted for cluster-scoped + resources. At most 63 characters (DNS label max). + maxLength: 63 + minLength: 1 + type: string + x-kubernetes-validations: + - message: the value must consist of only lowercase + alphanumeric characters and hyphens, and must + start and end with an alphanumeric character. + rule: '!format.dns1123Label().validate(self).hasValue()' + required: + - apiVersion + - kind + - name + type: object + ownership: description: |- - namespace is the namespace of the object. Empty for cluster-scoped - resources. At most 253 characters (DNS subdomain max). - maxLength: 253 - minLength: 1 + ownership reports when this ClusterObjectSet does not control the object: + - Colliding: the object exists but this ClusterObjectSet cannot take + ownership of it under the configured collision protection policy. + - Superseded: the object is controlled by another ClusterObjectSet in the + same group with a higher .spec.revision. + + Omitted when this ClusterObjectSet controls the object. + enum: + - Colliding + - Superseded type: string - x-kubernetes-validations: - - message: the value must consist of only lowercase alphanumeric - characters and hyphens, and must start and end with - an alphanumeric character. - rule: '!format.dns1123Label().validate(self).hasValue()' - resource: + probeResults: description: |- - resource is the lowercase, plural resource type of the object - (for example, "pods" or "configmaps"). Must be between 1 and 63 - characters. - maxLength: 63 - minLength: 1 - type: string - x-kubernetes-validations: - - message: the value must consist of only lowercase alphanumeric - characters and hyphens, must start with a letter, - and must end with an alphanumeric character. - rule: '!format.dns1035Label().validate(self).hasValue()' + probeResults lists the object's progression probe results that are not passing, + keyed by probe type. Probes of objects in phases that are waiting for an + earlier phase are not reported. At most 8 entries. + items: + description: ObjectProbeResult reports a progression + probe result that is not passing. + properties: + messages: + description: |- + messages provides bounded human-readable explanations of the result. + Consumers must not parse these messages. Messages describe an aggregate + result; their number is not the number of failed assertions. + items: + maxLength: 1024 + minLength: 1 + type: string + maxItems: 18 + type: array + x-kubernetes-list-type: atomic + status: + description: |- + status is the probe result: + - False: the probe evaluated to false. + - Unknown: the probe result could not be determined, for example because + the object's status has not yet been reported or is outdated. + enum: + - "False" + - Unknown + type: string + type: + description: |- + type is the probe type, for example "Progress", the aggregate of the + ClusterObjectSet's progression probes that apply to the object. + maxLength: 63 + minLength: 1 + type: string + required: + - status + - type + type: object + maxItems: 8 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map required: - - name - - resource + - object type: object + x-kubernetes-validations: + - message: at least one of probeResults, ownership, or deletion + must be set + rule: has(self.probeResults) || has(self.ownership) || has(self.deletion) maxItems: 50 type: array x-kubernetes-list-type: atomic status: description: |- - status is the current state of this phase in the rollout. Must be one of - InvalidSpecification, PreconditionsNotMet, Pending, Reconciling, - Stabilizing, Ready, Unknown, Superseded, Archiving, or Archived. + status summarizes the current lifecycle state of this phase: + - Unknown: no usable evaluation of the phase exists yet. + - Pending: application is waiting for an earlier phase, or teardown is + waiting for a later phase. + - Stabilizing: all objects are synced to this ClusterObjectSet, but at least one + progression-probe result is false or unknown. + - Ready: all objects are synced to this ClusterObjectSet and pass their + progression probes, if any are defined. + - PreconditionsNotMet: a precondition for applying the phase is not yet + satisfied, for example a rejected preflight dry-run; the ClusterObjectSet + keeps retrying and recovers once the precondition is met. + - InvalidSpecification: the phase's declared content is malformed; + correcting the configuration requires creating a replacement + ClusterObjectSet. + - ObjectCollision: one or more objects are controlled by another + owner, or are unowned while collision protection prevents adoption, + so this ClusterObjectSet cannot take ownership of them. + - Superseded: at least one object is controlled by another + ClusterObjectSet in the same group with a higher .spec.revision. + - Archiving: this is the active teardown phase and owned objects remain to be removed. + - Archived: this ClusterObjectSet's teardown responsibility for the phase is complete; + objects adopted by newer ClusterObjectSets may still exist. + + Superseded does not imply that progression probes pass. Failing or unknown + probes may still prevent later phases from advancing. + PreconditionsNotMet, InvalidSpecification, and ObjectCollision statuses + do not imply a terminal failure or a fixed retry policy. enum: - - InvalidSpecification - - PreconditionsNotMet + - Unknown - Pending - - Reconciling - Stabilizing - Ready - - Unknown + - PreconditionsNotMet + - InvalidSpecification + - ObjectCollision - Superseded - Archiving - Archived diff --git a/manifests/experimental.yaml b/manifests/experimental.yaml index dc19d99e89..478212d195 100644 --- a/manifests/experimental.yaml +++ b/manifests/experimental.yaml @@ -2711,8 +2711,8 @@ spec: - False with reason ObjectsNotReady: one or more objects are still being applied or have not yet passed their readiness probes during rollout. - False with reason Superseded: one or more objects have been adopted by a newer revision of the object set. - False with reason ObjectCollision: one or more objects are controlled by another owner, or are unowned while collision protection prevents adoption, so this revision cannot take ownership of them. - - False with reason PreconditionsNotMet: a precondition for applying the revision is not yet satisfied (a referenced Secret is mutable or has invalid or changed content, or a preflight dry-run was rejected, e.g. an immutable field, a conflicting object, or RBAC/dependency CRDs not yet propagated); the revision keeps retrying and recovers once the precondition is met. - - False with reason InvalidSpecification: the revision spec is invalid (a malformed revision/phase object or progression probe) and requires a spec change to proceed. + - False with reason PreconditionsNotMet: a precondition for applying the revision is not yet satisfied (a referenced Secret is mutable or has invalid or changed content, a revision-wide preflight check was rejected, or a phase's preflight dry-run was rejected because RBAC or dependency CRDs have not yet propagated or a dependency such as the target namespace does not exist yet); the revision keeps retrying and recovers once the precondition is met. + - False with reason InvalidSpecification: the revision spec is invalid (a malformed revision/phase object or progression probe, or a phase's preflight dry-run was rejected permanently, e.g. a schema violation or an immutable field) and requires a spec change to proceed. - False with reason Archiving: the revision is being archived and its owned objects are still being torn down. - False with reason Archived: the revision has been archived and its objects have been torn down. @@ -2828,14 +2828,17 @@ spec: different content. Each entry covers all fully-resolved object manifests within a phase, making it source-agnostic. items: - description: ObservedPhase records the observed content digest of - a resolved phase. + description: |- + ObservedPhase reports a phase's current lifecycle state and sparse + diagnostics together with its pinned content digest and historical + completion. properties: completedAt: description: |- - completedAt is the timestamp when this phase first became Ready. - Set once and never modified. Nil means the phase has never been - Ready. + completedAt is the timestamp when this phase was first observed Ready. + Omitted until that observation. Once recorded, it cannot change or be + removed, even if the phase later fails its progression probes or is + superseded. format: date-time type: string x-kubernetes-validations: @@ -2855,16 +2858,18 @@ spec: - message: digest must be in the format ':' rule: self.matches('^[a-z0-9]+:[a-f0-9]+$') lastTransitionTime: - description: lastTransitionTime is the last time the phase transitioned - from one status to another. + description: |- + lastTransitionTime is the timestamp when the current status was first + reported or last changed. Changes to message alone do not update this + timestamp. format: date-time type: string message: description: |- - message is a phase-level message providing context about the - current status (e.g. a validation error for InvalidSpecification - phases, or a summary for Pending phases). At most 1024 characters; - longer messages are truncated by the controller. + message provides human-readable context, such as a phase-wide validation + failure or the reason a phase is waiting. Consumers must not parse this + message. At most 1024 characters; longer messages are truncated by the + controller. maxLength: 1024 minLength: 1 type: string @@ -2880,101 +2885,194 @@ spec: rule: '!format.dns1123Label().validate(self).hasValue()' objectDetails: description: |- - objectDetails lists objects in this phase that are not yet - complete. For Reconciling, Pending, and Stabilizing phases, this - includes probe failures, collisions, creation/update errors, and - any other condition preventing completion. For Archiving phases, - this lists objects still awaiting deletion. Each entry identifies - the object and carries failure messages. Empty when status is - Ready, Superseded, Archived, or Unknown. The list may contain at - most 50 entries, matching the maximum number of objects per phase. + objectDetails reports per-object facts for objects with current problems or + notable ownership; it is not a full object inventory. An object is listed + when it has progression probes that are not passing (objects in phases that + are waiting for an earlier phase excluded), when this ClusterObjectSet cannot + take ownership of it (including in phases that are waiting), when it has been + adopted by a newer ClusterObjectSet, or when it awaits deletion in the active + teardown phase. Entries are removed when those facts no longer apply. + At most 50 entries, matching the maximum number of objects per phase. items: - description: ObjectStatus identifies a managed object and - its failure messages. + description: |- + ObjectStatus reports observed facts about an object with current problems or + notable ownership. The object may be missing or controlled by a conflicting + owner; it is not necessarily managed by this ClusterObjectSet. At least one of + probeResults, ownership, or deletion is set. properties: - group: + deletion: description: |- - group is the API group of the object (empty string for core - resources). At most 253 characters (DNS subdomain max). - maxLength: 253 - minLength: 1 + deletion reports the object's teardown state: + - AwaitingDeletion: the object is owned by this ClusterObjectSet, has been + requested for deletion, and is not yet gone from the cluster. + + Omitted when the object is not being torn down. + enum: + - AwaitingDeletion type: string - x-kubernetes-validations: - - message: 'the value must be a valid DNS subdomain: lowercase - alphanumeric characters, hyphens, and dots, starting - and ending with an alphanumeric character.' - rule: '!format.dns1123Subdomain().validate(self).hasValue()' - messages: + object: description: |- - messages lists the failure reasons for this object. The maximum - of 18 entries accounts for up to 16 assertion probe failures, - one collision message, and one message to note truncation if necessary. - Each message is at most 1024 characters; longer messages are truncated - by the controller. - items: - maxLength: 1024 - minLength: 1 - type: string - maxItems: 18 - type: array - x-kubernetes-list-type: atomic - name: - description: |- - name is the name of the object. Must be between 1 and 253 - characters (DNS subdomain max). - maxLength: 253 - minLength: 1 - type: string - x-kubernetes-validations: - - message: 'name must be a valid object name: it may not - be ''.'' or ''..'' or contain ''/'' or ''%''' - rule: self != "." && self != ".." && !self.contains("/") - && !self.contains("%") - namespace: + object identifies the object by apiVersion, kind, namespace, and name, + matching the declared object manifest. + properties: + apiVersion: + description: |- + apiVersion is the API version of the object, for example "v1" or + "apps/v1". It matches the apiVersion of the declared object manifest. + maxLength: 317 + minLength: 1 + type: string + x-kubernetes-validations: + - message: apiVersion must be a version or group/version + rule: self.matches('^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[a-z]([-a-z0-9]*[a-z0-9])?$') + kind: + description: |- + kind is the kind of the object, for example "ConfigMap". It matches the + kind of the declared object manifest. + maxLength: 63 + minLength: 1 + type: string + x-kubernetes-validations: + - message: kind must start with a letter and contain + only letters, digits, or hyphens, ending with + an alphanumeric character + rule: self.matches('^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$') + name: + description: |- + name is the name of the object. Must be between 1 and 253 + characters (DNS subdomain max). + maxLength: 253 + minLength: 1 + type: string + x-kubernetes-validations: + - message: 'name must be a valid object name: it may + not be ''.'' or ''..'' or contain ''/'' or ''%''' + rule: self != "." && self != ".." && !self.contains("/") + && !self.contains("%") + namespace: + description: |- + namespace is the namespace of the object. Omitted for cluster-scoped + resources. At most 63 characters (DNS label max). + maxLength: 63 + minLength: 1 + type: string + x-kubernetes-validations: + - message: the value must consist of only lowercase + alphanumeric characters and hyphens, and must + start and end with an alphanumeric character. + rule: '!format.dns1123Label().validate(self).hasValue()' + required: + - apiVersion + - kind + - name + type: object + ownership: description: |- - namespace is the namespace of the object. Empty for cluster-scoped - resources. At most 253 characters (DNS subdomain max). - maxLength: 253 - minLength: 1 + ownership reports when this ClusterObjectSet does not control the object: + - Colliding: the object exists but this ClusterObjectSet cannot take + ownership of it under the configured collision protection policy. + - Superseded: the object is controlled by another ClusterObjectSet in the + same group with a higher .spec.revision. + + Omitted when this ClusterObjectSet controls the object. + enum: + - Colliding + - Superseded type: string - x-kubernetes-validations: - - message: the value must consist of only lowercase alphanumeric - characters and hyphens, and must start and end with - an alphanumeric character. - rule: '!format.dns1123Label().validate(self).hasValue()' - resource: + probeResults: description: |- - resource is the lowercase, plural resource type of the object - (for example, "pods" or "configmaps"). Must be between 1 and 63 - characters. - maxLength: 63 - minLength: 1 - type: string - x-kubernetes-validations: - - message: the value must consist of only lowercase alphanumeric - characters and hyphens, must start with a letter, - and must end with an alphanumeric character. - rule: '!format.dns1035Label().validate(self).hasValue()' + probeResults lists the object's progression probe results that are not passing, + keyed by probe type. Probes of objects in phases that are waiting for an + earlier phase are not reported. At most 8 entries. + items: + description: ObjectProbeResult reports a progression + probe result that is not passing. + properties: + messages: + description: |- + messages provides bounded human-readable explanations of the result. + Consumers must not parse these messages. Messages describe an aggregate + result; their number is not the number of failed assertions. + items: + maxLength: 1024 + minLength: 1 + type: string + maxItems: 18 + type: array + x-kubernetes-list-type: atomic + status: + description: |- + status is the probe result: + - False: the probe evaluated to false. + - Unknown: the probe result could not be determined, for example because + the object's status has not yet been reported or is outdated. + enum: + - "False" + - Unknown + type: string + type: + description: |- + type is the probe type, for example "Progress", the aggregate of the + ClusterObjectSet's progression probes that apply to the object. + maxLength: 63 + minLength: 1 + type: string + required: + - status + - type + type: object + maxItems: 8 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map required: - - name - - resource + - object type: object + x-kubernetes-validations: + - message: at least one of probeResults, ownership, or deletion + must be set + rule: has(self.probeResults) || has(self.ownership) || has(self.deletion) maxItems: 50 type: array x-kubernetes-list-type: atomic status: description: |- - status is the current state of this phase in the rollout. Must be one of - InvalidSpecification, PreconditionsNotMet, Pending, Reconciling, - Stabilizing, Ready, Unknown, Superseded, Archiving, or Archived. + status summarizes the current lifecycle state of this phase: + - Unknown: no usable evaluation of the phase exists yet. + - Pending: application is waiting for an earlier phase, or teardown is + waiting for a later phase. + - Stabilizing: all objects are synced to this ClusterObjectSet, but at least one + progression-probe result is false or unknown. + - Ready: all objects are synced to this ClusterObjectSet and pass their + progression probes, if any are defined. + - PreconditionsNotMet: a precondition for applying the phase is not yet + satisfied, for example a rejected preflight dry-run; the ClusterObjectSet + keeps retrying and recovers once the precondition is met. + - InvalidSpecification: the phase's declared content is malformed; + correcting the configuration requires creating a replacement + ClusterObjectSet. + - ObjectCollision: one or more objects are controlled by another + owner, or are unowned while collision protection prevents adoption, + so this ClusterObjectSet cannot take ownership of them. + - Superseded: at least one object is controlled by another + ClusterObjectSet in the same group with a higher .spec.revision. + - Archiving: this is the active teardown phase and owned objects remain to be removed. + - Archived: this ClusterObjectSet's teardown responsibility for the phase is complete; + objects adopted by newer ClusterObjectSets may still exist. + + Superseded does not imply that progression probes pass. Failing or unknown + probes may still prevent later phases from advancing. + PreconditionsNotMet, InvalidSpecification, and ObjectCollision statuses + do not imply a terminal failure or a fixed retry policy. enum: - - InvalidSpecification - - PreconditionsNotMet + - Unknown - Pending - - Reconciling - Stabilizing - Ready - - Unknown + - PreconditionsNotMet + - InvalidSpecification + - ObjectCollision - Superseded - Archiving - Archived diff --git a/test/e2e/object-controller/features/cod_handoff.feature b/test/e2e/object-controller/features/cod_handoff.feature index 604048577d..3e701bb708 100644 --- a/test/e2e/object-controller/features/cod_handoff.feature +++ b/test/e2e/object-controller/features/cod_handoff.feature @@ -100,6 +100,12 @@ Feature: ClusterObjectDeployment multi-revision handoff spec: lifecycleState: Active """ + # The successor adopted the shared object (superseding the predecessor's phase) + # and is refused the pre-existing blocking object. + And ClusterObjectSet "${NAME}-1" reports phase "resources" with status Superseded + And ClusterObjectSet "${NAME}-1" reports phase "resources" object ConfigMap/cod-shared-cm with ownership Superseded + And ClusterObjectSet "${NAME}-2" reports phase "resources" with status ObjectCollision + And ClusterObjectSet "${NAME}-2" reports phase "resources" object ConfigMap/cod-block-cm with ownership Colliding # Unblock: remove the conflicting object so the successor can adopt its objects. When resource "configmap/cod-block-cm" is removed Then ClusterObjectSet "${NAME}-2" reports Ready as True with Reason AllObjectsReady diff --git a/test/e2e/object-controller/features/cos_object_collision_and_adoption.feature b/test/e2e/object-controller/features/cos_object_collision_and_adoption.feature index c15c72e879..55a02c41af 100644 --- a/test/e2e/object-controller/features/cos_object_collision_and_adoption.feature +++ b/test/e2e/object-controller/features/cos_object_collision_and_adoption.feature @@ -53,6 +53,8 @@ Feature: ClusterObjectSet object collision and adoption """ Cannot take ownership of 1 object(s) in phase "resources" because they are owned by another controller or already exist. """ + And ClusterObjectSet "${COS_NAME}" reports phase "resources" with status ObjectCollision + And ClusterObjectSet "${COS_NAME}" reports phase "resources" object ConfigMap/shared-cm with ownership Colliding And resource "configmap/shared-cm" matches """ data: diff --git a/test/e2e/object-controller/features/cos_preflight.feature b/test/e2e/object-controller/features/cos_preflight.feature index c30b780e53..2255282d15 100644 --- a/test/e2e/object-controller/features/cos_preflight.feature +++ b/test/e2e/object-controller/features/cos_preflight.feature @@ -2,10 +2,10 @@ Feature: ClusterObjectSet preflight dry-run validation As an OLM user applying a ClusterObjectSet directly, I want the revision to be - rejected with an actionable PreconditionsNotMet condition when one of its - objects would be rejected by the API server, and to recover automatically once - the underlying problem is resolved, so that transient or fixable issues do not - require re-creating the revision. + rejected with an actionable condition when one of its objects would be rejected + by the API server: PreconditionsNotMet when the problem can resolve without a + spec change (and the revision recovers automatically once it does), and + InvalidSpecification when the object itself is invalid. Background: Given object-controller is available @@ -39,8 +39,9 @@ Feature: ClusterObjectSet preflight dry-run validation """ check rejected phase "resources": phase "resources": /v1, Kind=ConfigMap ${COS_NAME}-absent/cm-x: namespaces "${COS_NAME}-absent" not found. """ + And ClusterObjectSet "${COS_NAME}" reports phase "resources" with status PreconditionsNotMet - Scenario: ClusterObjectSet reports PreconditionsNotMet when an object has an invalid spec + Scenario: ClusterObjectSet reports InvalidSpecification when an object has an invalid spec Given namespace "${TEST_NAMESPACE}" is available When ClusterObjectSet is applied """ @@ -66,10 +67,11 @@ Feature: ClusterObjectSet preflight dry-run validation containers: [] revision: 1 """ - Then ClusterObjectSet "${COS_NAME}" reports Ready as False with Reason PreconditionsNotMet and Message includes: + Then ClusterObjectSet "${COS_NAME}" reports Ready as False with Reason InvalidSpecification and Message includes: """ check rejected phase "resources": phase "resources": /v1, Kind=Pod ${TEST_NAMESPACE}/bad-pod: Pod "bad-pod" is invalid: spec.containers: Required value. """ + And ClusterObjectSet "${COS_NAME}" reports phase "resources" with status InvalidSpecification Scenario: ClusterObjectSet recovers once a missing target namespace is created When ClusterObjectSet is applied diff --git a/test/e2e/object-controller/features/revision.feature b/test/e2e/object-controller/features/revision.feature index cc4dc1c4fc..805ffca952 100644 --- a/test/e2e/object-controller/features/revision.feature +++ b/test/e2e/object-controller/features/revision.feature @@ -218,6 +218,9 @@ Feature: Install ClusterObjectSet """ 1 object(s) are not yet ready. """ + And ClusterObjectSet "${COS_NAME}" reports phase "cm-1" with status Stabilizing + And ClusterObjectSet "${COS_NAME}" reports phase "cm-1" object ConfigMap/test-configmap-1 with a False probe + And ClusterObjectSet "${COS_NAME}" reports phase "cm-2" with status Pending And resource "configmap/test-configmap-2" is not installed Scenario: Phases progresses when user-provided progressionProbes pass diff --git a/test/internal/e2e/object-controller/steps/steps.go b/test/internal/e2e/object-controller/steps/steps.go index b08b4baa6e..f3e50f0fc2 100644 --- a/test/internal/e2e/object-controller/steps/steps.go +++ b/test/internal/e2e/object-controller/steps/steps.go @@ -37,6 +37,9 @@ func RegisterSteps(sc *godog.ScenarioContext) { sc.Step(`^(?i)ClusterObjectSet "([^"]+)" reconciliation is triggered$`, TriggerClusterObjectSetReconciliation) sc.Step(`^(?i)ClusterObjectSet "([^"]+)" keeps later phase resources absent for "([^"]+)":$`, ClusterObjectSetKeepsLaterPhaseResourcesAbsent) sc.Step(`^(?i)ClusterObjectSet "([^"]+)" has observed phase "([^"]+)" with a non-empty digest$`, ClusterObjectSetHasObservedPhase) + sc.Step(`^(?i)ClusterObjectSet "([^"]+)" reports phase "([^"]+)" with status ([[:alnum:]]+)$`, ClusterObjectSetReportsPhaseStatus) + sc.Step(`^(?i)ClusterObjectSet "([^"]+)" reports phase "([^"]+)" object ([[:alnum:]]+)/(\S+) with ownership ([[:alnum:]]+)$`, ClusterObjectSetReportsPhaseObjectOwnership) + sc.Step(`^(?i)ClusterObjectSet "([^"]+)" reports phase "([^"]+)" object ([[:alnum:]]+)/(\S+) with a (False|Unknown) probe$`, ClusterObjectSetReportsPhaseObjectProbe) sc.Step(`^(?i)ClusterObjectSet "([^"]+)" is archived$`, ClusterObjectSetIsArchived) sc.Step(`^(?i)ClusterObjectSet "([^"]+)" is eventually deleted$`, ClusterObjectSetIsEventuallyDeleted) sc.Step(`^(?i)ClusterObjectSet "([^"]+)" reports aggregate object counts: total=(\d+), present=(\d+), synced=(\d+), ready=(\d+)$`, ClusterObjectSetHasAggregateObjectCounts) @@ -263,6 +266,77 @@ func ClusterObjectSetHasObservedPhase(ctx context.Context, cosName, phaseName st return nil } +// observedPhaseMatches polls the named ClusterObjectSet until the observed phase +// with the given name satisfies match. Polls with timeout. +func observedPhaseMatches(ctx context.Context, cosName, phaseName string, match func(ocv1.ObservedPhase) bool) { + sc := shared.Scenario(ctx) + cosName = shared.SubstituteScenarioVars(cosName, sc) + shared.WaitFor(ctx, func() bool { + out, err := shared.K8sClient(ctx, "get", "clusterobjectset", cosName, "-o", "json") + if err != nil { + return false + } + var cos ocv1.ClusterObjectSet + if err := json.Unmarshal([]byte(out), &cos); err != nil { + return false + } + for _, phase := range cos.Status.ObservedPhases { + if phase.Name == phaseName { + return match(phase) + } + } + return false + }) +} + +// ClusterObjectSetReportsPhaseStatus waits for the named phase of the ClusterObjectSet +// to report the given status. Polls with timeout. +func ClusterObjectSetReportsPhaseStatus(ctx context.Context, cosName, phaseName, phaseStatus string) error { + observedPhaseMatches(ctx, cosName, phaseName, func(phase ocv1.ObservedPhase) bool { + return phase.Status == ocv1.PhaseStatus(phaseStatus) + }) + return nil +} + +// phaseObjectMatches polls the named phase of the ClusterObjectSet until its +// objectDetails entry for the object with the given kind and name satisfies match. +func phaseObjectMatches(ctx context.Context, cosName, phaseName, kind, objName string, match func(ocv1.ObjectStatus) bool) { + objName = shared.SubstituteScenarioVars(objName, shared.Scenario(ctx)) + observedPhaseMatches(ctx, cosName, phaseName, func(phase ocv1.ObservedPhase) bool { + for _, obj := range phase.ObjectDetails { + if obj.Object.Kind == kind && obj.Object.Name == objName { + return match(obj) + } + } + return false + }) +} + +// ClusterObjectSetReportsPhaseObjectOwnership waits for the named phase of the +// ClusterObjectSet to report the object with the given kind and name with the +// given ownership. Polls with timeout. +func ClusterObjectSetReportsPhaseObjectOwnership(ctx context.Context, cosName, phaseName, kind, objName, ownership string) error { + phaseObjectMatches(ctx, cosName, phaseName, kind, objName, func(obj ocv1.ObjectStatus) bool { + return obj.Ownership == ocv1.ObjectOwnership(ownership) + }) + return nil +} + +// ClusterObjectSetReportsPhaseObjectProbe waits for the named phase of the +// ClusterObjectSet to report the object with the given kind and name with a probe +// result of the given status. Polls with timeout. +func ClusterObjectSetReportsPhaseObjectProbe(ctx context.Context, cosName, phaseName, kind, objName, probeStatus string) error { + phaseObjectMatches(ctx, cosName, phaseName, kind, objName, func(obj ocv1.ObjectStatus) bool { + for _, probe := range obj.ProbeResults { + if probe.Status == ocv1.ObjectProbeResultStatus(probeStatus) { + return true + } + } + return false + }) + return nil +} + // ClusterObjectSetIsArchived waits for the named ClusterObjectSet to have Ready=False // with reason Archived. Polls with timeout. func ClusterObjectSetIsArchived(ctx context.Context, revisionName string) error {