From e2ee13805e73253ea87f911d92407f1db12b2e22 Mon Sep 17 00:00:00 2001 From: "Per G. da Silva" Date: Thu, 26 Nov 2026 16:22:34 +0100 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=93=96=20Copy=20the=20ClusterExtensio?= =?UTF-8?q?n=20definition=20from=20main=20for=20GA=20shape=20review?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Verbatim copy of api/v1/clusterextension_types.go from main, with deviations decided outside this shape review: .spec.config is moved out of experimental, and the condition constants reflect the Ready condition (ClusterExtensionTypeReady replaces ClusterExtensionTypeAvailable; ClusterExtensionReasonProbesSucceeded and ClusterExtensionReasonProgressDeadlineExceeded are removed). Signed-off-by: Per G. da Silva --- tmp/README.md | 9 + tmp/clusterextension_types.go | 640 ++++++++++++++++++++++++++++++++++ 2 files changed, 649 insertions(+) create mode 100644 tmp/README.md create mode 100644 tmp/clusterextension_types.go diff --git a/tmp/README.md b/tmp/README.md new file mode 100644 index 0000000000..22c2d85fb4 --- /dev/null +++ b/tmp/README.md @@ -0,0 +1,9 @@ +# GA API shape — review copies + +This directory holds Go API type definitions for reviewing the proposed GA +API shape. The first files are verbatim copies of the current definitions +from `api/v1`; subsequent commits apply the proposed GA shape so each kind's +changes can be reviewed as a diff. + +This directory is for review only and will not be merged. The files rely +only on the unchanged `groupversion_info.go` boilerplate. diff --git a/tmp/clusterextension_types.go b/tmp/clusterextension_types.go new file mode 100644 index 0000000000..e38e6bdca4 --- /dev/null +++ b/tmp/clusterextension_types.go @@ -0,0 +1,640 @@ +/* +Copyright 2022. + +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. +*/ + +package v1 + +import ( + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +var ClusterExtensionKind = "ClusterExtension" + +type ( + UpgradeConstraintPolicy string + CRDUpgradeSafetyEnforcement string + + ClusterExtensionConfigType string +) + +const ( + // The extension will only upgrade if the new version satisfies + // the upgrade constraints set by the package author. + UpgradeConstraintPolicyCatalogProvided UpgradeConstraintPolicy = "CatalogProvided" + + // Unsafe option which allows an extension to be + // upgraded or downgraded to any available version of the package and + // ignore the upgrade path designed by package authors. + // This assumes that users independently verify the outcome of the changes. + // Use with caution as this can lead to unknown and potentially + // disastrous results such as data loss. + UpgradeConstraintPolicySelfCertified UpgradeConstraintPolicy = "SelfCertified" + + ClusterExtensionConfigTypeInline ClusterExtensionConfigType = "Inline" +) + +// ClusterExtensionSpec defines the desired state of ClusterExtension +type ClusterExtensionSpec struct { + // namespace specifies a Kubernetes namespace. + // It designates the default namespace where namespace-scoped resources for the extension are applied to the cluster. + // Some extensions may contain namespace-scoped resources to be applied in other namespaces. + // This namespace must exist. + // + // The namespace field is required, immutable, and follows the DNS label standard as defined in [RFC 1123]. + // It must contain only lowercase alphanumeric characters or hyphens (-), start and end with an alphanumeric character, + // and be no longer than 63 characters. + // + // [RFC 1123]: https://tools.ietf.org/html/rfc1123 + // + // + // It designates the default namespace where namespace-scoped resources for the extension + // are applied to. + // + // namespace is optional. When set, it must reference an existing namespace on the cluster. + // When omitted, operator-controller resolves and creates a managed namespace from the + // bundle's metadata. Whether namespace is set or omitted is fixed at creation time and + // cannot be changed afterwards. + // + // The namespace field follows the DNS label standard as defined in [RFC 1123]. + // It must contain only lowercase alphanumeric characters or hyphens (-), start and end with an alphanumeric character, + // and be no longer than 63 characters. + // + // [RFC 1123]: https://tools.ietf.org/html/rfc1123 + // + // + // + // + // + // + // + // + // +kubebuilder:validation:MaxLength:=63 + // +required + Namespace string `json:"namespace,omitzero"` + + // serviceAccount is a deprecated field and is completely ignored. + // OLMv1 is a single-tenant system where users with ClusterExtension write access are + // effectively delegated cluster-admin trust. The operator-controller runs with + // cluster-admin privileges and uses its own service account for all cluster interactions. + // + // Deprecated: serviceAccount is no longer used and will be removed in a future release. + // + // +optional + ServiceAccount ServiceAccountReference `json:"serviceAccount,omitzero"` + + // source is required and selects the installation source of content for this ClusterExtension. + // Set the sourceType field to perform the selection. + // + // Catalog is currently the only implemented sourceType. + // Setting sourceType to "Catalog" requires the catalog field to also be defined. + // + // Below is a minimal example of a source definition (in yaml): + // + // source: + // sourceType: Catalog + // catalog: + // packageName: example-package + // + // +required + Source SourceConfig `json:"source"` + + // install is optional and configures installation options for the ClusterExtension, + // such as the pre-flight check configuration. + // + // +optional + Install *ClusterExtensionInstallConfig `json:"install,omitempty"` + + // config is optional and specifies bundle-specific configuration. + // Configuration is bundle-specific and a bundle may provide a configuration schema. + // When not specified, the default configuration of the resolved bundle is used. + // + // config is validated against a configuration schema provided by the resolved bundle. If the bundle does not provide + // a configuration schema the bundle is deemed to not be configurable. More information on how + // to configure bundles can be found in the OLM documentation associated with your current OLM version. + // + // +optional + Config *ClusterExtensionConfig `json:"config,omitempty"` + + // progressDeadlineMinutes is an optional field that defines the maximum period + // of time in minutes after which an installation should be considered failed and + // require manual intervention. This functionality is disabled when no value + // is provided. The minimum period is 10 minutes, and the maximum is 720 minutes (12 hours). + // + // +kubebuilder:validation:Minimum:=10 + // +kubebuilder:validation:Maximum:=720 + // +optional + // + ProgressDeadlineMinutes int32 `json:"progressDeadlineMinutes,omitempty"` +} + +const SourceTypeCatalog = "Catalog" + +// SourceConfig is a discriminated union which selects the installation source. +// +// +union +// +kubebuilder:validation:XValidation:rule="has(self.sourceType) && self.sourceType == 'Catalog' ? has(self.catalog) : !has(self.catalog)",message="catalog is required when sourceType is Catalog, and forbidden otherwise" +type SourceConfig struct { + // sourceType is required and specifies the type of install source. + // + // The only allowed value is "Catalog". + // + // When set to "Catalog", information for determining the appropriate bundle of content to install + // is fetched from ClusterCatalog resources on the cluster. + // When using the Catalog sourceType, the catalog field must also be set. + // + // +unionDiscriminator + // +kubebuilder:validation:Enum:="Catalog" + // +required + SourceType string `json:"sourceType"` + + // catalog configures how information is sourced from a catalog. + // It is required when sourceType is "Catalog", and forbidden otherwise. + // + // +optional + Catalog *CatalogFilter `json:"catalog,omitempty"` +} + +// ClusterExtensionInstallConfig is a union which selects the clusterExtension installation config. +// +// +kubebuilder:validation:XValidation:rule="has(self.preflight)",message="at least one of [preflight] are required when install is specified" +// +union +type ClusterExtensionInstallConfig struct { + // preflight is optional and configures the checks that run before installation or upgrade + // of the content for the package specified in the packageName field. + // + // When specified, it replaces the default preflight configuration for install/upgrade actions. + // When not specified, the default configuration is used. + // + // +optional + Preflight *PreflightConfig `json:"preflight,omitempty"` +} + +// ClusterExtensionConfig is a discriminated union which selects the source configuration values to be merged into +// the ClusterExtension's rendered manifests. +// +// +kubebuilder:validation:XValidation:rule="has(self.configType) && self.configType == 'Inline' ?has(self.inline) : !has(self.inline)",message="inline is required when configType is Inline, and forbidden otherwise" +// +union +type ClusterExtensionConfig struct { + // configType is required and specifies the type of configuration source. + // + // The only allowed value is "Inline". + // + // When set to "Inline", the cluster extension configuration is defined inline within the ClusterExtension resource. + // + // +unionDiscriminator + // +kubebuilder:validation:Enum:="Inline" + // +required + ConfigType ClusterExtensionConfigType `json:"configType"` + + // inline contains JSON or YAML values specified directly in the ClusterExtension. + // + // It is used to specify arbitrary configuration values for the ClusterExtension. + // It must be set if configType is 'Inline' and must be a valid JSON/YAML object containing at least one property. + // The configuration values are validated at runtime against a JSON schema provided by the bundle. + // + // +kubebuilder:validation:Type=object + // +kubebuilder:validation:MinProperties=1 + // +optional + // +unionMember + Inline *apiextensionsv1.JSON `json:"inline,omitempty"` +} + +// CatalogFilter defines the attributes used to identify and filter content from a catalog. +type CatalogFilter struct { + // packageName specifies the name of the package to be installed and is used to filter + // the content from catalogs. + // + // It is required, immutable, and follows the DNS subdomain standard as defined in [RFC 1123]. + // It must contain only lowercase alphanumeric characters, hyphens (-) or periods (.), + // start and end with an alphanumeric character, and be no longer than 253 characters. + // + // Some examples of valid values are: + // - some-package + // - 123-package + // - 1-package-2 + // - somepackage + // + // Some examples of invalid values are: + // - -some-package + // - some-package- + // - thisisareallylongpackagenamethatisgreaterthanthemaximumlength + // - some.package + // + // [RFC 1123]: https://tools.ietf.org/html/rfc1123 + // + // +kubebuilder:validation.Required + // +kubebuilder:validation:MaxLength:=253 + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="packageName is immutable" + // +kubebuilder:validation:XValidation:rule="self.matches(\"^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$\")",message="packageName must be a valid DNS1123 subdomain. It must contain only lowercase alphanumeric characters, hyphens (-) or periods (.), start and end with an alphanumeric character, and be no longer than 253 characters" + // +required + PackageName string `json:"packageName"` + + // version is an optional semver constraint (a specific version or range of versions). + // When unspecified, the latest version available is installed. + // + // Acceptable version ranges are no longer than 64 characters. + // Version ranges are composed of comma- or space-delimited values and one or more comparison operators, + // known as comparison strings. + // You can add additional comparison strings using the OR operator (||). + // + // # Range Comparisons + // + // To specify a version range, you can use a comparison string like ">=3.0, + // <3.6". When specifying a range, automatic updates will occur within that + // range. The example comparison string means "install any version greater than + // or equal to 3.0.0 but less than 3.6.0.". It also states intent that if any + // upgrades are available within the version range after initial installation, + // those upgrades should be automatically performed. + // + // # Pinned Versions + // + // To specify an exact version to install you can use a version range that + // "pins" to a specific version. When pinning to a specific version, no + // automatic updates will occur. An example of a pinned version range is + // "0.6.0", which means "only install version 0.6.0 and never + // upgrade from this version". + // + // # Basic Comparison Operators + // + // The basic comparison operators and their meanings are: + // - "=", equal (not aliased to an operator) + // - "!=", not equal + // - "<", less than + // - ">", greater than + // - ">=", greater than OR equal to + // - "<=", less than OR equal to + // + // # Wildcard Comparisons + // + // You can use the "x", "X", and "*" characters as wildcard characters in all + // comparison operations. Some examples of using the wildcard characters: + // - "1.2.x", "1.2.X", and "1.2.*" is equivalent to ">=1.2.0, < 1.3.0" + // - ">= 1.2.x", ">= 1.2.X", and ">= 1.2.*" is equivalent to ">= 1.2.0" + // - "<= 2.x", "<= 2.X", and "<= 2.*" is equivalent to "< 3" + // - "x", "X", and "*" is equivalent to ">= 0.0.0" + // + // # Patch Release Comparisons + // + // When you want to specify a minor version up to the next major version you + // can use the "~" character to perform patch comparisons. Some examples: + // - "~1.2.3" is equivalent to ">=1.2.3, <1.3.0" + // - "~1" and "~1.x" is equivalent to ">=1, <2" + // - "~2.3" is equivalent to ">=2.3, <2.4" + // - "~1.2.x" is equivalent to ">=1.2.0, <1.3.0" + // + // # Major Release Comparisons + // + // You can use the "^" character to make major release comparisons after a + // stable 1.0.0 version is published. If there is no stable version published, // minor versions define the stability level. Some examples: + // - "^1.2.3" is equivalent to ">=1.2.3, <2.0.0" + // - "^1.2.x" is equivalent to ">=1.2.0, <2.0.0" + // - "^2.3" is equivalent to ">=2.3, <3" + // - "^2.x" is equivalent to ">=2.0.0, <3" + // - "^0.2.3" is equivalent to ">=0.2.3, <0.3.0" + // - "^0.2" is equivalent to ">=0.2.0, <0.3.0" + // - "^0.0.3" is equvalent to ">=0.0.3, <0.0.4" + // - "^0.0" is equivalent to ">=0.0.0, <0.1.0" + // - "^0" is equivalent to ">=0.0.0, <1.0.0" + // + // # OR Comparisons + // You can use the "||" character to represent an OR operation in the version + // range. Some examples: + // - ">=1.2.3, <2.0.0 || >3.0.0" + // - "^0 || ^3 || ^5" + // + // For more information on semver, please see https://semver.org/ + // + // +kubebuilder:validation:MaxLength:=64 + // +kubebuilder:validation:XValidation:rule="self.matches(\"^(\\\\s*(=||!=|>|<|>=|=>|<=|=<|~|~>|\\\\^)\\\\s*(v?(0|[1-9]\\\\d*|[x|X|\\\\*])(\\\\.(0|[1-9]\\\\d*|x|X|\\\\*]))?(\\\\.(0|[1-9]\\\\d*|x|X|\\\\*))?(-([0-9A-Za-z\\\\-]+(\\\\.[0-9A-Za-z\\\\-]+)*))?(\\\\+([0-9A-Za-z\\\\-]+(\\\\.[0-9A-Za-z\\\\-]+)*))?)\\\\s*)((?:\\\\s+|,\\\\s*|\\\\s*\\\\|\\\\|\\\\s*)(=||!=|>|<|>=|=>|<=|=<|~|~>|\\\\^)\\\\s*(v?(0|[1-9]\\\\d*|x|X|\\\\*])(\\\\.(0|[1-9]\\\\d*|x|X|\\\\*))?(\\\\.(0|[1-9]\\\\d*|x|X|\\\\*]))?(-([0-9A-Za-z\\\\-]+(\\\\.[0-9A-Za-z\\\\-]+)*))?(\\\\+([0-9A-Za-z\\\\-]+(\\\\.[0-9A-Za-z\\\\-]+)*))?)\\\\s*)*$\")",message="invalid version expression" + // +optional + Version string `json:"version,omitempty"` + + // channels is optional and specifies a set of channels belonging to the package + // specified in the packageName field. + // + // A channel is a package-author-defined stream of updates for an extension. + // + // Each channel in the list must follow the DNS subdomain standard as defined in [RFC 1123]. + // It must contain only lowercase alphanumeric characters, hyphens (-) or periods (.), + // start and end with an alphanumeric character, and be no longer than 253 characters. + // You can specify no more than 256 channels. + // + // When specified, it constrains the set of installable bundles and the automated upgrade path. + // This constraint is an AND operation with the version field. For example: + // - Given channel is set to "foo" + // - Given version is set to ">=1.0.0, <1.5.0" + // - Only bundles that exist in channel "foo" AND satisfy the version range comparison are considered installable + // - Automatic upgrades are constrained to upgrade edges defined by the selected channel + // + // When unspecified, upgrade edges across all channels are used to identify valid automatic upgrade paths. + // + // Some examples of valid values are: + // - 1.1.x + // - alpha + // - stable + // - stable-v1 + // - v1-stable + // - dev-preview + // - preview + // - community + // + // Some examples of invalid values are: + // - -some-channel + // - some-channel- + // - thisisareallylongchannelnamethatisgreaterthanthemaximumlength + // - original_40 + // - --default-channel + // + // [RFC 1123]: https://tools.ietf.org/html/rfc1123 + // + // +kubebuilder:validation:items:MaxLength:=253 + // +kubebuilder:validation:MaxItems:=256 + // +kubebuilder:validation:items:XValidation:rule="self.matches(\"^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$\")",message="channels entries must be valid DNS1123 subdomains" + // +optional + Channels []string `json:"channels,omitempty"` + + // selector is optional and filters the set of ClusterCatalogs used in the bundle selection process. + // + // When unspecified, all ClusterCatalogs are used in the bundle selection process. + // + // +optional + Selector *metav1.LabelSelector `json:"selector,omitempty"` + + // upgradeConstraintPolicy is optional and controls whether the upgrade paths defined in the catalog + // are enforced for the package referenced in the packageName field. + // + // Allowed values are "CatalogProvided", "SelfCertified", or omitted. + // + // When set to "CatalogProvided", automatic upgrades only occur when upgrade constraints specified by the package + // author are met. + // + // When set to "SelfCertified", the upgrade constraints specified by the package author are ignored. + // This allows upgrades and downgrades to any version of the package. + // This is considered a dangerous operation as it can lead to unknown and potentially disastrous outcomes, + // such as data loss. + // Use this option only if you have independently verified the changes. + // + // When omitted, the default value is "CatalogProvided". + // + // +kubebuilder:validation:Enum:=CatalogProvided;SelfCertified + // +kubebuilder:default:=CatalogProvided + // +optional + UpgradeConstraintPolicy UpgradeConstraintPolicy `json:"upgradeConstraintPolicy,omitempty"` +} + +// ServiceAccountReference is a deprecated type and is completely ignored. +// +// Deprecated: ServiceAccountReference is no longer used and will be removed in a future release. +// +// +kubebuilder:validation:MinProperties=1 +type ServiceAccountReference struct { + // name is a deprecated field and is completely ignored. + // + // Deprecated: name is no longer used and will be removed in a future release. + // + // The name field follows the DNS subdomain standard as defined in [RFC 1123]. + // It must contain only lowercase alphanumeric characters, hyphens (-) or periods (.), + // start and end with an alphanumeric character, and be no longer than 253 characters. + // + // Some examples of valid values are: + // - some-serviceaccount + // - 123-serviceaccount + // - 1-serviceaccount-2 + // - someserviceaccount + // - some.serviceaccount + // + // Some examples of invalid values are: + // - -some-serviceaccount + // - some-serviceaccount- + // + // [RFC 1123]: https://tools.ietf.org/html/rfc1123 + // + // +kubebuilder:validation:MinLength:=1 + // +kubebuilder:validation:MaxLength:=253 + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="name is immutable once set but may be cleared" + // +kubebuilder:validation:XValidation:rule="self.matches(\"^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$\")",message="name must be a valid DNS1123 subdomain. It must contain only lowercase alphanumeric characters, hyphens (-) or periods (.), start and end with an alphanumeric character, and be no longer than 253 characters" + // +optional + Name string `json:"name,omitempty"` +} + +// PreflightConfig holds the configuration for the preflight checks. If used, at least one preflight check must be non-nil. +// +// +kubebuilder:validation:XValidation:rule="has(self.crdUpgradeSafety)",message="at least one of [crdUpgradeSafety] are required when preflight is specified" +type PreflightConfig struct { + // crdUpgradeSafety configures the CRD Upgrade Safety pre-flight checks that run + // before upgrades of installed content. + // + // The CRD Upgrade Safety pre-flight check safeguards from unintended consequences of upgrading a CRD, + // such as data loss. + CRDUpgradeSafety *CRDUpgradeSafetyPreflightConfig `json:"crdUpgradeSafety"` +} + +// CRDUpgradeSafetyPreflightConfig is the configuration for CRD upgrade safety preflight check. +type CRDUpgradeSafetyPreflightConfig struct { + // enforcement is required and configures the state of the CRD Upgrade Safety pre-flight check. + // + // Allowed values are "None" or "Strict". The default value is "Strict". + // + // When set to "None", the CRD Upgrade Safety pre-flight check is skipped during an upgrade operation. + // Use this option with caution as unintended consequences such as data loss can occur. + // + // When set to "Strict", the CRD Upgrade Safety pre-flight check runs during an upgrade operation. + // + // +kubebuilder:validation:Enum:="None";"Strict" + // +required + Enforcement CRDUpgradeSafetyEnforcement `json:"enforcement"` +} + +const ( + // Condition types + ClusterExtensionTypeInstalled = "Installed" + ClusterExtensionTypeProgressing = "Progressing" + // ClusterExtensionTypeReady is the ClusterExtension condition that reports whether the + // extension's active revision is Ready. It mirrors the Ready condition of + // the managing ClusterObjectDeployment. + ClusterExtensionTypeReady = "Ready" + // ClusterExtensionTypeDeprecated is a rollup condition that is present when + // any of the deprecated conditions are present. + ClusterExtensionTypeDeprecated = "Deprecated" + ClusterExtensionTypePackageDeprecated = "PackageDeprecated" + ClusterExtensionTypeChannelDeprecated = "ChannelDeprecated" + ClusterExtensionTypeBundleDeprecated = "BundleDeprecated" + + // Installed reasons + ClusterExtensionReasonAbsent = "Absent" + + // Progressing reasons + ClusterExtensionReasonRollingOut = "RollingOut" + ClusterExtensionReasonRetrying = "Retrying" + ClusterExtensionReasonBlocked = "Blocked" + ClusterExtensionReasonInvalidConfiguration = "InvalidConfiguration" + + // Deprecation reasons + ClusterExtensionReasonDeprecated = "Deprecated" + ClusterExtensionReasonNotDeprecated = "NotDeprecated" + ClusterExtensionReasonDeprecationStatusUnknown = "DeprecationStatusUnknown" + + // Reasons shared across condition types + ClusterExtensionReasonSucceeded = "Succeeded" + ClusterExtensionReasonFailed = "Failed" + + // None will not perform CRD upgrade safety checks. + CRDUpgradeSafetyEnforcementNone CRDUpgradeSafetyEnforcement = "None" + // Strict will enforce the CRD upgrade safety check and block the upgrade if the CRD would not pass the check. + CRDUpgradeSafetyEnforcementStrict CRDUpgradeSafetyEnforcement = "Strict" +) + +// BundleMetadata is a representation of the identifying attributes of a bundle. +type BundleMetadata struct { + // name is required and follows the DNS subdomain standard as defined in [RFC 1123]. + // It must contain only lowercase alphanumeric characters, hyphens (-) or periods (.), + // start and end with an alphanumeric character, and be no longer than 253 characters. + // + // +required + // +kubebuilder:validation:XValidation:rule="self.matches(\"^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$\")",message="packageName must be a valid DNS1123 subdomain. It must contain only lowercase alphanumeric characters, hyphens (-) or periods (.), start and end with an alphanumeric character, and be no longer than 253 characters" + Name string `json:"name"` + + // version is required and references the version that this bundle represents. + // It follows the semantic versioning standard as defined in https://semver.org/. + // + // +required + // +kubebuilder:validation:XValidation:rule="self.matches(\"^([0-9]+)(\\\\.[0-9]+)?(\\\\.[0-9]+)?(-([-0-9A-Za-z]+(\\\\.[-0-9A-Za-z]+)*))?(\\\\+([-0-9A-Za-z]+(-\\\\.[-0-9A-Za-z]+)*))?\")",message="version must be well-formed semver" + Version string `json:"version"` + + // release is an optional field that identifies a specific release of this bundle's version. + // A release represents a re-publication of the same version, typically used to deliver + // packaging or metadata changes without changing the version number. When multiple + // releases exist for the same version, higher releases are preferred. An unset release + // is less preferred than all other release values. + // + // The value consists of dot-separated identifiers, where each identifier is either a + // numeric value (without leading zeros) or an alphanumeric string (e.g., "2", "1.el9", + // "3.alpha.1"). Releases are compared identifier by identifier: numeric identifiers are + // compared as integers, alphanumeric identifiers are compared lexically, and numeric + // identifiers always sort before alphanumeric identifiers. + // + // For bundles with explicit pkg.Release metadata, this field contains that release value. + // For registry+v1 bundles lacking an explicit release value, this field contains the release + // extracted from version's build metadata (e.g., '2' from '1.0.0+2'). + // This field is omitted when the bundle's release value is unset. + // + // +optional + // + // +kubebuilder:validation:MaxLength=20 + // +kubebuilder:validation:XValidation:rule="self.matches(\"^$|^(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(\\\\.(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*$\")",message="release must be empty or consist of dot-separated identifiers (numeric without leading zeros, or alphanumeric)" + Release *string `json:"release,omitempty"` +} + +// ClusterExtensionStatus defines the observed state of a ClusterExtension. +type ClusterExtensionStatus struct { + // conditions represents the current state of the ClusterExtension. + // + // The set of condition types which apply to all spec.source variations are Installed and Progressing. + // + // The Installed condition represents whether the bundle has been installed for this ClusterExtension: + // - When Installed is True and the Reason is Succeeded, the bundle has been successfully installed. + // - When Installed is False and the Reason is Failed, the bundle has failed to install. + // + // The Progressing condition represents whether or not the ClusterExtension is advancing towards a new state. + // When Progressing is True and the Reason is Succeeded, the ClusterExtension is making progress towards a new state. + // When Progressing is True and the Reason is Retrying, the ClusterExtension has encountered an error that could be resolved on subsequent reconciliation attempts. + // When Progressing is False and the Reason is Blocked, the ClusterExtension has encountered an error that requires manual intervention for recovery. + // + // When Progressing is True and Reason is RollingOut, the ClusterExtension has one or more ClusterObjectSets in active roll out. + // + // + // When the ClusterExtension is sourced from a catalog, it surfaces deprecation conditions based on catalog metadata. + // These are indications from a package owner to guide users away from a particular package, channel, or bundle: + // - BundleDeprecated is True if the installed bundle is marked deprecated, False if not deprecated, or Unknown if no bundle is installed yet or if catalog data is unavailable. + // - ChannelDeprecated is True if any requested channel is marked deprecated, False if not deprecated, or Unknown if catalog data is unavailable. + // - PackageDeprecated is True if the requested package is marked deprecated, False if not deprecated, or Unknown if catalog data is unavailable. + // - Deprecated is a rollup condition that is True when any deprecation exists, False when none exist, or Unknown when catalog data is unavailable. + // + // +listType=map + // +listMapKey=type + // +optional + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // install is a representation of the current installation status for this ClusterExtension. + // + // +optional + Install *ClusterExtensionInstallStatus `json:"install,omitempty"` +} + +// ClusterExtensionInstallStatus is a representation of the status of the identified bundle. +type ClusterExtensionInstallStatus struct { + // bundle is required and represents the identifying attributes of a bundle. + // + // A "bundle" is a versioned set of content that represents the resources that need to be applied + // to a cluster to install a package. + // + // +required + Bundle BundleMetadata `json:"bundle"` +} + +// +genclient +// +genclient:nonNamespaced +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Installed Bundle",type=string,JSONPath=`.status.install.bundle.name` +// +kubebuilder:printcolumn:name=Version,type=string,JSONPath=`.status.install.bundle.version` +// +kubebuilder:printcolumn:name="Installed",type=string,JSONPath=`.status.conditions[?(@.type=='Installed')].status` +// +kubebuilder:printcolumn:name="Progressing",type=string,JSONPath=`.status.conditions[?(@.type=='Progressing')].status` +// +kubebuilder:printcolumn:name=Age,type=date,JSONPath=`.metadata.creationTimestamp` + +// ClusterExtension is the Schema for the clusterextensions API +type ClusterExtension struct { + metav1.TypeMeta `json:",inline"` + + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec is an optional field that defines the desired state of the ClusterExtension. + // + // + // +optional + Spec ClusterExtensionSpec `json:"spec,omitempty"` + + // status is an optional field that defines the observed state of the ClusterExtension. + // +optional + Status ClusterExtensionStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// ClusterExtensionList contains a list of ClusterExtension +type ClusterExtensionList struct { + metav1.TypeMeta `json:",inline"` + + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // items is a required list of ClusterExtension objects. + // + // +required + Items []ClusterExtension `json:"items"` +} + +func init() { + SchemeBuilder.Register(func(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &ClusterExtension{}, &ClusterExtensionList{}) + return nil + }) +} From ddcd681600fb22920f24b4d86b54a9afe362eea8 Mon Sep 17 00:00:00 2001 From: "Per G. da Silva" Date: Thu, 26 Nov 2026 16:37:40 +0100 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=93=96=20Apply=20the=20proposed=20GA?= =?UTF-8?q?=20API=20shape?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ClusterExtension: optional namespace with managed-namespace mode, serviceAccount historic role and fail-open documentation, Ready condition mirroring the managing ClusterObjectDeployment, and experimental retention of spec.progressDeadlineMinutes and status.install.bundle.release. ClusterObjectDeployment (new): condition constants and the Ready condition defined around the active revision's own readiness. ClusterObjectSet (new): grouped objectCounts without health counts, status.phases with pinned contentDigest and sparse per-object diagnostics identified by target identity, objectSliceRef object sources, per-object progressionProbes with ConditionEqual and CEL rules, and experimental phase status fields. ClusterObjectSlice (new): discriminated-union spec with the InlineManifests content type storing embedded manifests inline. Signed-off-by: Per G. da Silva --- tmp/README.md | 93 ++- tmp/clusterextension_types.go | 79 +- tmp/clusterobjectdeployment_types.go | 277 +++++++ tmp/clusterobjectset_types.go | 1013 ++++++++++++++++++++++++++ tmp/clusterobjectslice_types.go | 131 ++++ 5 files changed, 1549 insertions(+), 44 deletions(-) create mode 100644 tmp/clusterobjectdeployment_types.go create mode 100644 tmp/clusterobjectset_types.go create mode 100644 tmp/clusterobjectslice_types.go diff --git a/tmp/README.md b/tmp/README.md index 22c2d85fb4..529f4257a1 100644 --- a/tmp/README.md +++ b/tmp/README.md @@ -1,9 +1,90 @@ # GA API shape — review copies -This directory holds Go API type definitions for reviewing the proposed GA -API shape. The first files are verbatim copies of the current definitions -from `api/v1`; subsequent commits apply the proposed GA shape so each kind's -changes can be reviewed as a diff. +These are the complete Go API type definitions for ClusterObjectDeployment, +ClusterObjectSet, ClusterExtension, and ClusterObjectSlice (with their kind-scoped condition +constants), copied from the `refactor/clusterobjectset-status-api` branch. +They are copied here so the proposed GA shape can be reviewed in its entirety +rather than as a diff against the current types. -This directory is for review only and will not be merged. The files rely -only on the unchanged `groupversion_info.go` boilerplate. +This directory is for review only and will not be merged. The files are otherwise +unmodified; they rely only on the unchanged `groupversion_info.go` boilerplate. +Channel-specific descriptions are marked with `` and +`` directives; CRD schemas, printer columns, and +validation are generated from the kubebuilder markers shown here. + +## Differences from the current upstream/main experimental CRDs + +Note: "removed" below means the field is not part of the proposed standard GA +API, or is not relevant under the `BoxcutterRuntime` feature gate — not +necessarily that the capability is gone from the product. + +### ClusterObjectDeployment (`clusterobjectdeployment_types.go`) + +- `spec.progressDeadlineMinutes` and the `ProgressDeadlineExceeded` Progressing + reason are retained as experimental (omitted from standard-channel CRDs). +- `Available` renamed to `Ready` and redefined around the active revision's own + Ready condition instead of per-object probe health: True when the single + active revision is Ready (`RevisionReady`), False when it is not + (`RevisionNotReady`) or when no active revision is controlled + (`NoActiveRevision`), Unknown while more than one active revision exists + (`MultipleActiveRevisions`) or when its readiness is undetermined + (`Unknown`). +- `status.conditions` documentation restructured per Progressing reason, without + controller internals; `NewClusterObjectSetProgressing` now also covers revision + creation and adoption. +- `spec.template.metadata` documents its reserved labels + (`olm.operatorframework.io/template-hash`, `app.kubernetes.io/managed-by`) and + the label/annotation entry limits and validation. + +### ClusterObjectSet (`clusterobjectset_types.go`) + +- Object sources: `secretRef` (Secret reference) replaced by `objectSliceRef` + (slice name plus the referenced object's target identity — apiVersion, kind, + name, namespace — within a `ClusterObjectSlice`); the object `type` enum is now + `InlineManifest`/`ObjectSliceRef`. +- `ClusterObjectSlice` (started from #3195, reworked here): the spec is a + discriminated union with a single content type, `inlineManifests`, whose + `manifests` list stores embedded Kubernetes manifests inline, each carrying + its own target identity (replacing the encoded-envelope entry design). +- Probes: revision-level `progressionProbes` (selector + + `ConditionEqual`/`FieldsEqual`/`FieldValue` assertions) replaced by per-object + `progressionProbes` supporting `ConditionEqual` and `CEL` rules. +- Status counts: remain grouped under `status.objectCounts`, now with + `{total,present,synced,superseded,colliding}`; `ready` and the health counts + (`healthyObjects`, `unhealthyObjects`) are removed. +- `status.observedPhases` replaced by `status.phases`: pinned `contentDigest`, + lifecycle `status`, machine-readable `reason`, and sparse per-object + `diagnostics` categorized by reason; object entries are identified by + apiVersion, kind, name, and namespace, matching the spec's object + references. +- `spec.lifecycleState` documentation updated to assign archival responsibility: + the owning ClusterObjectDeployment decides when to archive older revisions (on + recorded rollout completion), the ClusterObjectSet controller tears down a + revision once `lifecycleState` is set to `Archived`, and standalone callers + archive explicitly. +- New printer columns: `Superseded` and `Colliding` (counts now served from + `status.objectCounts`). + +### ClusterExtension (`clusterextension_types.go`) + +- `spec.namespace` is optional at GA: when omitted, operator-controller + resolves and creates a managed namespace from the bundle's metadata. Whether + namespace is set or omitted is fixed at creation time; the value itself is + immutable and DNS-label validated. (The standard CRD previously required it.) +- `spec.config` (inline bundle configuration) is part of the standard API. +- Retained as experimental (omitted from standard-channel CRDs): + `spec.progressDeadlineMinutes` and `status.install.bundle.release`. +- Conditions documentation: the `Ready` condition (replacing `Available`) + mirrors the managing ClusterObjectDeployment's `Ready` condition. +- Condition constants are kind-scoped (`ClusterExtensionType*`, + `ClusterExtensionReason*`) and live in `clusterextension_types.go`; + `common_types.go` is removed (see #3205). + +The only other change is the `controller-gen.kubebuilder.io/version` annotation +(v0.21.0 → v0.23.0), from regenerating with the current toolchain. + +To reproduce a full diff for a kind: + +```console +git diff upstream/main:api/v1/_types.go tmp/_types.go +``` diff --git a/tmp/clusterextension_types.go b/tmp/clusterextension_types.go index e38e6bdca4..95dcb313f1 100644 --- a/tmp/clusterextension_types.go +++ b/tmp/clusterextension_types.go @@ -50,23 +50,12 @@ const ( // ClusterExtensionSpec defines the desired state of ClusterExtension type ClusterExtensionSpec struct { // namespace specifies a Kubernetes namespace. - // It designates the default namespace where namespace-scoped resources for the extension are applied to the cluster. - // Some extensions may contain namespace-scoped resources to be applied in other namespaces. - // This namespace must exist. - // - // The namespace field is required, immutable, and follows the DNS label standard as defined in [RFC 1123]. - // It must contain only lowercase alphanumeric characters or hyphens (-), start and end with an alphanumeric character, - // and be no longer than 63 characters. - // - // [RFC 1123]: https://tools.ietf.org/html/rfc1123 - // - // // It designates the default namespace where namespace-scoped resources for the extension - // are applied to. + // are applied. // - // namespace is optional. When set, it must reference an existing namespace on the cluster. + // namespace is optional. When set, it must reference an existing namespace on the cluster. This namespace is unmanaged and will not be affected by deleting the ClusterExtension. // When omitted, operator-controller resolves and creates a managed namespace from the - // bundle's metadata. Whether namespace is set or omitted is fixed at creation time and + // bundle's metadata. This namespace will be deleted if the ClusterExtension is deleted. Whether namespace is set or omitted is fixed at creation time and // cannot be changed afterwards. // // The namespace field follows the DNS label standard as defined in [RFC 1123]. @@ -74,22 +63,23 @@ type ClusterExtensionSpec struct { // and be no longer than 63 characters. // // [RFC 1123]: https://tools.ietf.org/html/rfc1123 - // - // - // - // - // - // - // // + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="namespace is immutable" + // +kubebuilder:validation:XValidation:rule="self.matches(\"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$\")",message="namespace must be a valid DNS1123 label" // +kubebuilder:validation:MaxLength:=63 - // +required + // +optional Namespace string `json:"namespace,omitzero"` // serviceAccount is a deprecated field and is completely ignored. - // OLMv1 is a single-tenant system where users with ClusterExtension write access are - // effectively delegated cluster-admin trust. The operator-controller runs with - // cluster-admin privileges and uses its own service account for all cluster interactions. + // Historically, serviceAccount specified the service account used to apply + // this extension's content, letting adopters scope installation privileges. + // It has no effect: ClusterExtension is a cluster-scoped resource where + // users with write access are effectively delegated cluster-admin trust, + // and the operator-controller runs with cluster-admin privileges and uses + // its own service account for all cluster interactions. + // Because the field is silently accepted, its presence must not be read as + // confirmation that an extension's content requires no additional + // privileges; it provides no signal either way. // // Deprecated: serviceAccount is no longer used and will be removed in a future release. // @@ -397,6 +387,8 @@ type CatalogFilter struct { } // ServiceAccountReference is a deprecated type and is completely ignored. +// Historically, it selected the service account used to apply a +// ClusterExtension's content. // // Deprecated: ServiceAccountReference is no longer used and will be removed in a future release. // @@ -478,10 +470,10 @@ const ( ClusterExtensionReasonAbsent = "Absent" // Progressing reasons - ClusterExtensionReasonRollingOut = "RollingOut" - ClusterExtensionReasonRetrying = "Retrying" - ClusterExtensionReasonBlocked = "Blocked" - ClusterExtensionReasonInvalidConfiguration = "InvalidConfiguration" + ClusterExtensionReasonNewRevisionRollingOut = "NewRevisionRollingOut" + ClusterExtensionReasonRetrying = "Retrying" + ClusterExtensionReasonBlocked = "Blocked" + ClusterExtensionReasonInvalidConfiguration = "InvalidConfiguration" // Deprecation reasons ClusterExtensionReasonDeprecated = "Deprecated" @@ -549,13 +541,25 @@ type ClusterExtensionStatus struct { // - When Installed is True and the Reason is Succeeded, the bundle has been successfully installed. // - When Installed is False and the Reason is Failed, the bundle has failed to install. // - // The Progressing condition represents whether or not the ClusterExtension is advancing towards a new state. - // When Progressing is True and the Reason is Succeeded, the ClusterExtension is making progress towards a new state. - // When Progressing is True and the Reason is Retrying, the ClusterExtension has encountered an error that could be resolved on subsequent reconciliation attempts. - // When Progressing is False and the Reason is Blocked, the ClusterExtension has encountered an error that requires manual intervention for recovery. - // - // When Progressing is True and Reason is RollingOut, the ClusterExtension has one or more ClusterObjectSets in active roll out. - // + // The Progressing condition represents whether or not the ClusterExtension is advancing towards a new state: + // - When Progressing is True and the Reason is Succeeded, the ClusterExtension is making progress towards a new state. + // - When Progressing is True and the Reason is NewRevisionRollingOut, a new revision of the + // ClusterExtension's content has been determined, for example for an initial installation, + // upgrade, or reconfiguration, and that revision is actively rolling out. + // - When Progressing is True and the Reason is Retrying, the ClusterExtension has encountered an error that could be resolved on subsequent reconciliation attempts. + // - When Progressing is False and the Reason is Blocked, the ClusterExtension has encountered an error that requires manual intervention for recovery. + // + // The Ready condition reports whether the objects of the ClusterExtension's + // latest completed rollout are at the desired state: + // - When Ready is True and the Reason is AllObjectsReady, the ClusterExtension's + // objects are rolled out and at the desired state. + // - When Ready is False and the Reason is NewRevisionPending, a rollout of a new + // revision is in progress, or no rollout has completed yet; see the Progressing + // condition for detail. + // - When Ready is False and the Reason is ObjectsNotReady, one or more of the + // ClusterExtension's objects are not at the desired state. + // - When Ready is False and the Reason is ObjectCollision, one or more objects are + // controlled by another owner. // // When the ClusterExtension is sourced from a catalog, it surfaces deprecation conditions based on catalog metadata. // These are indications from a package owner to guide users away from a particular package, channel, or bundle: @@ -607,8 +611,7 @@ type ClusterExtension struct { metav1.ObjectMeta `json:"metadata,omitempty"` // spec is an optional field that defines the desired state of the ClusterExtension. - // - // + // +kubebuilder:validation:XValidation:rule="has(oldSelf.namespace) == has(self.namespace)",message="namespace presence is immutable; it cannot be added or removed after creation" // +optional Spec ClusterExtensionSpec `json:"spec,omitempty"` diff --git a/tmp/clusterobjectdeployment_types.go b/tmp/clusterobjectdeployment_types.go new file mode 100644 index 0000000000..628e99cc90 --- /dev/null +++ b/tmp/clusterobjectdeployment_types.go @@ -0,0 +1,277 @@ +/* +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. +*/ + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +const ( + // ClusterObjectDeploymentKind is the kind of the ClusterObjectDeployment API. + ClusterObjectDeploymentKind = "ClusterObjectDeployment" + + // ClusterObjectDeploymentTypeProgressing is the condition type that reports the + // rollout of the latest revision. + ClusterObjectDeploymentTypeProgressing = "Progressing" + // ClusterObjectDeploymentTypeReady is the condition type that reports whether + // the latest revision's objects are at the desired state. + ClusterObjectDeploymentTypeReady = "Ready" + + // ClusterObjectDeploymentReasonNewRevisionProgressing reports that a new + // revision is being created or adopted, or that the latest revision is + // rolling out. + ClusterObjectDeploymentReasonNewRevisionProgressing = "NewRevisionProgressing" + // ClusterObjectDeploymentReasonNewRevisionCompleted reports that the latest + // revision has completed its rollout. + ClusterObjectDeploymentReasonNewRevisionCompleted = "NewRevisionCompleted" + // ClusterObjectDeploymentReasonProgressDeadlineExceeded reports that the latest + // revision did not complete its rollout within spec.progressDeadlineMinutes. + ClusterObjectDeploymentReasonProgressDeadlineExceeded = "ProgressDeadlineExceeded" + // ClusterObjectDeploymentReasonPreconditionsNotMet reports that the latest + // revision is waiting on preconditions that are not yet met. + ClusterObjectDeploymentReasonPreconditionsNotMet = "PreconditionsNotMet" + // ClusterObjectDeploymentReasonObjectCollision reports that objects in the + // latest revision are owned by another controller or already exist. + ClusterObjectDeploymentReasonObjectCollision = "ObjectCollision" + // ClusterObjectDeploymentReasonInvalidSpecification reports that the revision + // content is invalid: either spec.template.metadata contains labels or + // annotations that are not valid on a ClusterObjectSet, or objects in the + // latest revision are invalid. In both cases, correct spec.template to resume. + ClusterObjectDeploymentReasonInvalidSpecification = "InvalidSpecification" + // ClusterObjectDeploymentReasonNewRevisionPending reports that the latest + // revision has not yet completed its rollout, so the deployment's objects + // are not yet at the desired state. + ClusterObjectDeploymentReasonNewRevisionPending = "NewRevisionPending" + // ClusterObjectDeploymentReasonOwnerConflict reports that the newest active revision + // in the deployment's group is controlled by another controller. + ClusterObjectDeploymentReasonOwnerConflict = "OwnerConflict" + // ClusterObjectDeploymentReasonUnmanagedRevision reports that the newest active + // revision in the deployment's group has no controller owner and was not created by + // this controller. + ClusterObjectDeploymentReasonUnmanagedRevision = "UnmanagedRevision" +) + +// ClusterObjectDeploymentSpec defines the mutable desired state of a deployment: +// a rollout policy and the template for new revisions. +type ClusterObjectDeploymentSpec struct { + // revisionHistoryLimit is the maximum number of archived revisions to + // retain for inspecting rollout history. Active revisions are never + // deleted and do not count against this limit. When more archived revisions exist + // than this limit, the oldest ones are deleted once they have finished tearing + // down. Archived revisions cannot be reactivated; to return to earlier content, + // set spec.template to that content, which creates a new revision. + // + // A value of 0 retains no archived revisions. The minimum is 0, the maximum + // is 50, and the default is 5. + // + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=50 + // +kubebuilder:default=5 + // +optional + RevisionHistoryLimit *int32 `json:"revisionHistoryLimit,omitempty"` + + // progressDeadlineMinutes is the maximum number of minutes a revision may take + // to roll out, measured from the ClusterObjectSet's creation timestamp. Time + // spent waiting for the ClusterObjectSet to be created is not counted. The + // deadline covers all phases together; completing a phase does not reset it. + // Once a revision has completed, the deadline no longer applies, even if it + // later becomes unhealthy. When omitted, no deadline is enforced. The minimum + // period is 1 minute, and the maximum is 720 minutes (12 hours). + // + // The deadline is rollout policy, not revision content: changing it does not + // create a new revision and applies immediately to the latest active revision. + // + // +kubebuilder:validation:Minimum:=1 + // +kubebuilder:validation:Maximum:=720 + // +optional + // + ProgressDeadlineMinutes int32 `json:"progressDeadlineMinutes,omitempty"` + + // template is the desired content of each new revision (a revision is a + // ClusterObjectSet object). Changes to template create a new revision; + // existing revisions remain immutable. + // +required + Template ClusterObjectDeploymentTemplate `json:"template,omitzero"` +} + +// ClusterObjectDeploymentTemplate describes the caller-controlled part of a revision. +type ClusterObjectDeploymentTemplate struct { + // metadata contains labels and annotations propagated to each revision + // created from this template. The labels + // olm.operatorframework.io/template-hash and app.kubernetes.io/managed-by are + // reserved; the controller always sets their values on each revision. Changes to + // metadata create a new revision. + // +optional + Metadata ClusterObjectDeploymentTemplateMetadata `json:"metadata,omitzero"` + + // spec contains the desired revision content. Group, revision, lifecycle state, + // and ownership are assigned by the controller and cannot be set here. + // +required + Spec ClusterObjectDeploymentTemplateSpec `json:"spec,omitzero"` +} + +// ClusterObjectDeploymentTemplateMetadata contains labels and annotations +// propagated to each ClusterObjectSet revision created from the template. +// At least one of labels or annotations must be set. +// +kubebuilder:validation:MinProperties=1 +type ClusterObjectDeploymentTemplateMetadata struct { + // labels is an optional set of key/value pairs propagated to each revision's + // metadata. When set, it must contain between 1 and 32 entries. Keys and values + // must be valid Kubernetes labels; invalid labels are reported on the Progressing + // condition with reason InvalidSpecification and block new revisions until + // corrected. The labels olm.operatorframework.io/template-hash and + // app.kubernetes.io/managed-by are reserved; values set for them are ignored + // and the controller's values are always used. + // +optional + // +kubebuilder:validation:MinProperties=1 + // +kubebuilder:validation:MaxProperties=32 + Labels map[string]string `json:"labels,omitempty"` + + // annotations is an optional set of key/value pairs propagated to each + // revision's metadata. When set, it must contain between 1 and 32 entries. Keys + // and the total size must satisfy the Kubernetes annotation rules; invalid + // annotations are reported on the Progressing condition with reason + // InvalidSpecification and block new revisions until corrected. + // +optional + // +kubebuilder:validation:MinProperties=1 + // +kubebuilder:validation:MaxProperties=32 + Annotations map[string]string `json:"annotations,omitempty"` +} + +// ClusterObjectDeploymentTemplateSpec contains mutable ClusterObjectSet content. +type ClusterObjectDeploymentTemplateSpec struct { + // ClusterObjectSetContent holds the mutable revision content that is + // propagated to each ClusterObjectSet created from this template. Changes + // to these fields create a new revision; existing revisions remain immutable. + ClusterObjectSetContent `json:",inline"` +} + +// ClusterObjectDeploymentStatus reports rollout progress. +type ClusterObjectDeploymentStatus struct { + // conditions describes the rollout state and readiness of the deployment. + // + // Progressing reports the rollout of the latest revision. Once the + // latest revision has recorded completion in its status.completedAt, + // Progressing is no longer updated: + // - True, NewRevisionProgressing: a new revision is being created or + // adopted, or the latest revision is rolling out. The message says which. If + // creating or adopting a revision fails, the controller keeps retrying. + // - False, NewRevisionCompleted: the latest revision has completed its + // rollout. Completion remains recorded even if the revision later + // becomes unhealthy. + // + // - False, ProgressDeadlineExceeded: the latest revision did not complete its + // rollout within spec.progressDeadlineMinutes. + // + // - True, PreconditionsNotMet: the latest revision is waiting on + // preconditions that are not yet met, such as required RBAC permissions + // that do not exist yet, or a custom resource definition that has not + // finished registering with the API server. The controller keeps retrying. + // - False, ObjectCollision: objects in the latest revision are owned by + // another controller or already exist. The collision must be resolved. + // - False, InvalidSpecification: the revision content is invalid, either + // because spec.template.metadata contains labels or annotations that are + // not valid on a ClusterObjectSet, or because one or more objects in the + // latest revision are invalid, for example a Deployment with an invalid + // selector. In both cases, correct spec.template to resume. + // - False, OwnerConflict: the newest active ClusterObjectSet in this deployment's + // group is controlled by another controller. No new revision is created while + // the conflict persists. + // - False, UnmanagedRevision: the newest active ClusterObjectSet in this + // deployment's group has no controller owner and was not created by this + // controller. Remove it, or restore its + // app.kubernetes.io/managed-by=object-controller label, to resume. + // + // Ready reports whether the latest revision's objects are at the desired state. + // It mirrors the Ready condition of the latest non-deleting revision in the + // deployment's group once that revision has recorded completion in its + // status.completedAt; until then, Ready is False with reason + // NewRevisionPending: + // - False, NewRevisionPending: the latest revision has not yet completed + // its rollout, or no revision has been created; see the Progressing + // condition for detail. + // - True, AllObjectsReady: the revision has rolled out and all objects are + // at the desired state. + // - False, ObjectsNotReady: one or more objects are not at the desired + // state or have not passed their progression probes. + // - False, ObjectCollision: one or more objects are controlled by another + // owner. + // + // +optional + // +listType=map + // +listMapKey=type + // +patchStrategy=merge + // +patchMergeKey=type + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` //nolint:kubeapilinter // This CRD uses structural list-map validation, not protobuf serialization. +} + +// +genclient +// +genclient:nonNamespaced +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster,shortName=cod +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name=Ready,type=string,JSONPath=`.status.conditions[?(@.type=='Ready')].status` +// +kubebuilder:printcolumn:name=Progressing,type=string,JSONPath=`.status.conditions[?(@.type=='Progressing')].status` +// +kubebuilder:printcolumn:name=Age,type=date,JSONPath=`.metadata.creationTimestamp` +// +kubebuilder:validation:XValidation:rule="size(self.metadata.name) <= 52 && self.metadata.name.matches('^[a-z]([a-z0-9-]*[a-z0-9])?$')",message="name must be 1 to 52 lowercase alphanumeric or hyphen characters, starting with a letter and ending with an alphanumeric character" + +// ClusterObjectDeployment is a cluster-scoped API that manages mutable desired +// content as an ordered sequence of immutable revisions. Each revision is a +// ClusterObjectSet object, created from the deployment's template; changing the +// template creates a new revision that replaces the previous one. +type ClusterObjectDeployment struct { + metav1.TypeMeta `json:",inline"` + + // metadata is the standard object's metadata. The name must be 1 to 52 lowercase + // alphanumeric or hyphen characters, start with a letter, and end with an + // alphanumeric character. It is used as the group of each ClusterObjectSet + // revision, whose names are -. + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec defines the desired state of the deployment: the revision template and + // the rollout policy. + // +required + Spec ClusterObjectDeploymentSpec `json:"spec,omitzero"` + + // status is the most recently observed state of the deployment. + // +optional + Status ClusterObjectDeploymentStatus `json:"status,omitzero"` //nolint:kubeapilinter // OpenShift APIs use value structs with omitzero for optional status. +} + +// +kubebuilder:object:root=true + +// ClusterObjectDeploymentList contains ClusterObjectDeployment objects. +type ClusterObjectDeploymentList struct { + metav1.TypeMeta `json:",inline"` + + // metadata is the standard list metadata. + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // items is the list of deployments. + // +required + Items []ClusterObjectDeployment `json:"items"` +} + +func init() { + SchemeBuilder.Register(func(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &ClusterObjectDeployment{}, &ClusterObjectDeploymentList{}) + return nil + }) +} diff --git a/tmp/clusterobjectset_types.go b/tmp/clusterobjectset_types.go new file mode 100644 index 0000000000..120905a4d5 --- /dev/null +++ b/tmp/clusterobjectset_types.go @@ -0,0 +1,1013 @@ +/* +Copyright 2024. + +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. +*/ + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" +) + +const ( + ClusterObjectSetKind = "ClusterObjectSet" + + // ClusterObjectSetMaxRevision is the largest revision whose canonical name fits + // in a 63-character label value with a 52-character group and a separating hyphen. + // Keep the revision validation maximum below in sync with this value. + ClusterObjectSetMaxRevision int64 = 9999999999 + + // Condition Types + ClusterObjectSetTypeReady = "Ready" + + // Condition Reasons + ClusterObjectSetReasonPending = "Pending" + ClusterObjectSetReasonArchived = "Archived" + ClusterObjectSetReasonArchiving = "Archiving" + ClusterObjectSetReasonObjectsNotReady = "ObjectsNotReady" + ClusterObjectSetReasonSuperseded = "Superseded" + ClusterObjectSetReasonObjectCollision = "ObjectCollision" + ClusterObjectSetReasonPreconditionsNotMet = "PreconditionsNotMet" + ClusterObjectSetReasonInvalidSpecification = "InvalidSpecification" + ClusterObjectSetReasonAllObjectsReady = "AllObjectsReady" +) + +// ClusterObjectSetSpec defines the desired state of ClusterObjectSet. +// The content fields (phases, collisionProtection) are +// immutable from creation and may only be changed by creating a replacement +// ClusterObjectSet. +// +kubebuilder:validation:XValidation:rule="self.phases == oldSelf.phases",message="phases is immutable" +// +kubebuilder:validation:XValidation:rule="self.collisionProtection == oldSelf.collisionProtection",message="collisionProtection is immutable" +type ClusterObjectSetSpec struct { + // group is a required, immutable identifier that links related + // ClusterObjectSets together. All ClusterObjectSets sharing the same group + // form a sequence ordered by their .spec.revision, regardless of owner + // references. + // The value must be 1 to 52 characters long, start with a lowercase letter, + // contain only lowercase letters, digits or hyphens, and end with a letter or digit. + // + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=52 + // +kubebuilder:validation:XValidation:rule=`self.matches('^[a-z]([a-z0-9-]*[a-z0-9])?$')`,message="group must start with a lowercase letter, contain only lowercase letters, digits or hyphens, and end with a letter or digit" + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="group is immutable" + Group string `json:"group,omitempty"` + + // lifecycleState specifies the lifecycle state of the ClusterObjectSet. + // + // When set to "Active", the ClusterObjectSet is actively managed and reconciled. + // When set to "Archived", the ClusterObjectSet is inactive and any resources not managed by a subsequent ClusterObjectSet are deleted. + // The ClusterObjectSet is removed from the owner list of all objects previously under management. + // All objects that did not transition to a succeeding ClusterObjectSet are deleted. + // + // Once a ClusterObjectSet is set to "Archived", it cannot be un-archived. + // + // More than one ClusterObjectSet may be "Active" during a rollout. For ClusterObjectSets owned + // by a ClusterObjectDeployment, its controller requests archival of older + // active ClusterObjectSets based on a newer owned, active ClusterObjectSet's recorded rollout + // completion, even if that newer ClusterObjectSet is no longer Ready. + // Standalone callers are responsible for setting lifecycleState to "Archived". + // + // +required + // +kubebuilder:validation:XValidation:rule="oldSelf == 'Active' || oldSelf == 'Archived' && oldSelf == self", message="cannot un-archive" + LifecycleState ClusterObjectSetLifecycleState `json:"lifecycleState,omitempty"` + + // revision is a required, immutable sequence number identifying a specific + // ClusterObjectSet within a sequence of related ClusterObjectSets. + // + // The revision field must be an integer from 1 to 9999999999, inclusive. + // Each ClusterObjectSet in the same group must have a unique revision number. + // + // +required + // +kubebuilder:validation:Minimum:=1 + // +kubebuilder:validation:Maximum:=9999999999 + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="revision is immutable" + Revision int64 `json:"revision,omitempty"` + + ClusterObjectSetContent `json:",inline"` +} + +// ClusterObjectSetContent holds the object set's content: its phases and the +// default collision protection. +type ClusterObjectSetContent struct { + // phases is a required list of phases that group objects to be applied together. + // + // All objects in a phase are applied in no particular order. + // The ClusterObjectSet progresses to the next phase only after all objects + // in the current phase pass their progression probes, if any are defined. + // + // Each phase in the list must have a unique name. The maximum number of phases is 20. + // + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=20 + // +listType=map + // +listMapKey=name + // +required + Phases []ClusterObjectSetPhase `json:"phases,omitempty"` + + // collisionProtection is a required field that specifies the default collision protection + // strategy for all objects in this content. Individual phases or objects can override this value. + // + // This value is used as the default for any phase or object that does not explicitly specify + // its own collisionProtection. The resolution order is object, then phase, then content. + // + // +required + CollisionProtection CollisionProtection `json:"collisionProtection,omitempty"` +} + +// ProbeType defines the type of object probe. +// +enum +type ProbeType string + +const ( + ProbeTypeConditionEqual ProbeType = "ConditionEqual" + ProbeTypeCEL ProbeType = "CEL" +) + +// Probe is a discriminated union defining a check for an object, for example +// that the object reports a desired status. +// +union +// +kubebuilder:validation:XValidation:rule="self.type == 'ConditionEqual' ?has(self.conditionEqual) : !has(self.conditionEqual)",message="conditionEqual is required when type is ConditionEqual, and forbidden otherwise" +// +kubebuilder:validation:XValidation:rule="self.type == 'CEL' ?has(self.cel) : !has(self.cel)",message="cel is required when type is CEL, and forbidden otherwise" +type Probe struct { + // type is a required field which specifies the type of object probe to use. + // + // The allowed probe types are "ConditionEqual" and "CEL". + // + // When set to "ConditionEqual", the probe checks objects that have reached a condition of specified type and status. + // When set to "CEL", the probe evaluates a boolean CEL rule against the object. + // + // +unionDiscriminator + // +kubebuilder:validation:Enum=ConditionEqual;CEL + // +required + Type ProbeType `json:"type,omitempty"` + + // conditionEqual checks the requested condition in the object's status.conditions. + // The probe result is True when the matching condition's status equals the + // configured status, and False when it does not. Missing or malformed condition + // lists, unreadable condition entries, or a missing requested condition produce + // Unknown. If the matching condition has an integer observedGeneration that + // differs from metadata.generation, the result is Unknown. An absent + // observedGeneration does not by itself prevent the probe from passing. + // Required when type is "ConditionEqual", and forbidden otherwise. + // + // +unionMember + // +optional + ConditionEqual ConditionEqualProbe `json:"conditionEqual,omitzero"` + + // cel contains a boolean CEL rule evaluated against the object's live state. + // A False result reports the configured message; an evaluation error produces + // Unknown and reports the error instead. Compilation and boolean result-type + // checking occur before evaluation, not during CR admission. + // Required when type is "CEL", and forbidden otherwise. + // +unionMember + // +optional + CEL ProbeCELSpec `json:"cel,omitzero"` +} + +// ProbeCELSpec uses Common Expression Language (CEL) to probe an object. +// CEL rules must evaluate to a boolean to be valid. The variable self refers to +// the live Kubernetes resource described by the enclosing phase-object entry, +// including its status. +// See: +// https://kubernetes.io/docs/reference/using-api/cel +// https://github.com/google/cel-go +type ProbeCELSpec struct { + // rule is the CEL expression to evaluate. The dynamically typed variable self + // refers to the live Kubernetes resource described by the enclosing phase-object + // entry, including its status, regardless of the desired manifest's source. + // + // The controller compiles and type-checks rule before evaluation. Its inferred + // result type must be boolean; compilation failures and non-boolean result types + // are invalid configuration. CR admission validates only the configuration's + // structure and string bounds, not CEL syntax or types. + // + // True passes the probe. False fails it and reports message. An evaluation + // error, such as an unguarded missing-field access, produces Unknown and reports + // the error instead of message. + // + // See https://kubernetes.io/docs/reference/using-api/cel and + // https://github.com/google/cel-go. + // +kubebuilder:example="self.metadata.name == \"Hans\"" + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=1024 + // +required + Rule string `json:"rule,omitempty"` + + // message is the human-readable explanation reported only when rule evaluates + // to False. Evaluation errors produce Unknown and report the error instead. + // Consumers must not parse this message. + // +kubebuilder:example="Object must be named Hans" + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=1024 + // +required + Message string `json:"message,omitempty"` +} + +// ConditionEqualProbe defines the condition type and status required for the probe to succeed. +type ConditionEqualProbe struct { + // type sets the expected condition type, i.e. "Ready". + // + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=200 + // +required + Type string `json:"type,omitempty"` + + // status sets the expected condition status. + // + // Allowed values are "True" and "False". + // + // +kubebuilder:validation:Enum=True;False + // +required + Status string `json:"status,omitempty"` +} + +// ClusterObjectSetLifecycleState specifies the lifecycle state of the ClusterObjectSet. +// +kubebuilder:validation:Enum=Active;Archived +type ClusterObjectSetLifecycleState string + +const ( + // ClusterObjectSetLifecycleStateActive / "Active" is the default lifecycle state. + ClusterObjectSetLifecycleStateActive ClusterObjectSetLifecycleState = "Active" + // ClusterObjectSetLifecycleStateArchived / "Archived" archives the ClusterObjectSet for historical or auditing purposes. + // The ClusterObjectSet is removed from the owner list of all other objects previously under management and all objects + // that did not transition to a succeeding ClusterObjectSet are deleted. + ClusterObjectSetLifecycleStateArchived ClusterObjectSetLifecycleState = "Archived" +) + +// ClusterObjectSetPhase represents a group of objects that are applied together. The phase is considered +// complete only after all objects pass their progression probes. +type ClusterObjectSetPhase struct { + // name is a required identifier for this phase. + // + // phase names must follow the DNS label standard as defined in [RFC 1123]. + // They must contain only lowercase alphanumeric characters or hyphens (-), + // start and end with an alphanumeric character, and be no longer than 63 characters. + // + // Common phase names include: namespaces, policies, rbac, crds, storage, deploy, publish. + // + // [RFC 1123]: https://tools.ietf.org/html/rfc1123 + // + // +required + // +kubebuilder:validation:MinLength=1 + // +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." + Name string `json:"name,omitempty"` + + // objects is a required list of all Kubernetes objects that belong to this phase. + // + // All objects in this list are applied to the cluster in no particular order. The maximum number of objects per phase is 50. + // +required + // +listType=atomic + // +kubebuilder:validation:MaxItems=50 + Objects []ClusterObjectSetObject `json:"objects"` + + // collisionProtection specifies the default collision protection strategy for all objects + // in this phase. Individual objects can override this value. + // + // When set, this value is used as the default for any object in this phase that does not + // explicitly specify its own collisionProtection. + // + // When omitted, objects in this phase that do not specify their own collisionProtection inherit the + // enclosing spec default: the ClusterObjectSet's .spec.collisionProtection or, for a + // ClusterObjectDeployment, the .spec.template.spec.collisionProtection. + // + // +optional + CollisionProtection CollisionProtection `json:"collisionProtection,omitempty"` +} + +// ObjectType defines the type of objects provided in the Objects set. +// +kubebuilder:validation:Enum=InlineManifest;ObjectSliceRef +type ObjectType string + +const ( + ObjectTypeInlineManifest ObjectType = "InlineManifest" + ObjectTypeObjectSliceRef ObjectType = "ObjectSliceRef" +) + +// ClusterObjectSetObject represents a Kubernetes object to be applied as part +// of a phase, along with its progression probes and collision protection settings. +// +// Exactly one of inlineManifest or objectSliceRef must be set. +// +// +union +// +kubebuilder:validation:XValidation:rule="self.type == 'InlineManifest' ?has(self.inlineManifest) : !has(self.inlineManifest)",message="inlineManifest is required when type is InlineManifest, and forbidden otherwise" +// +kubebuilder:validation:XValidation:rule="self.type == 'ObjectSliceRef' ?has(self.objectSliceRef) : !has(self.objectSliceRef)",message="objectSliceRef is required when type is ObjectSliceRef, and forbidden otherwise" +type ClusterObjectSetObject struct { + // type is a required field which specifies the type of object to use. + // + // The allowed object types are "InlineManifest" and "ObjectSliceRef". + // + // When set to "InlineManifest", object manifests are supplied inline, as valid Kubernetes resources with apiVersion, kind, and metadata fields. + // When set to "ObjectSliceRef", a slice name and entry identity identify an object manifest in a cluster-scoped ClusterObjectSlice. + // + // +unionDiscriminator + // +required + Type ObjectType `json:"type,omitempty"` + + // inlineManifest is an optional embedded Kubernetes object to be applied. + // + // Exactly one of inlineManifest or objectSliceRef must be set. + // + // This object must be a valid Kubernetes resource with apiVersion, kind, and metadata fields. + // + // +kubebuilder:validation:EmbeddedResource + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:XValidation:rule="has(self.apiVersion) && has(self.kind) && has(self.metadata)",message="inlineManifest must be a valid Kubernetes resource with apiVersion, kind, and metadata" + // +kubebuilder:validation:XValidation:rule="self.apiVersion != '' && self.kind != ''",message="apiVersion and kind must be non-empty" + // +kubebuilder:validation:XValidation:rule="has(self.metadata.name) && self.metadata.name != ''",message="metadata.name is required" + // +unionMember + // +optional + InlineManifest unstructured.Unstructured `json:"inlineManifest,omitempty,omitzero"` + + // objectSliceRef is an optional reference to an object manifest within a + // ClusterObjectSlice. + // + // Exactly one of inlineManifest or objectSliceRef must be set. + // + // +unionMember + // +optional + ObjectSliceRef ObjectSliceSourceRef `json:"objectSliceRef,omitzero"` + + // progressionProbes is an optional list of checks evaluated against this + // object's live state, whether the object was provided inline or referenced + // from a ClusterObjectSlice. All configured probes must pass for the object + // to satisfy its progression requirements. Failed or unknown results block + // advancement to later phases. When omitted, the object has no progression + // checks; this does not establish application availability. Each object may + // specify at most 20 probes. + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=20 + // +listType=atomic + // +optional + ProgressionProbes []Probe `json:"progressionProbes,omitempty"` + + // collisionProtection controls whether the operator can adopt and modify objects + // that already exist on the cluster. + // + // Allowed values are: "Prevent", "IfNoController", and "None". + // + // When set to "Prevent", the operator only manages objects it created itself. + // This prevents ownership collisions. + // + // When set to "IfNoController", the operator can adopt and modify pre-existing objects + // that are not owned by another controller. + // This is useful for taking over management of manually-created resources. + // + // When set to "None", the operator can adopt and modify any pre-existing object, even if + // owned by another controller. + // Use this setting with extreme caution as it may cause multiple controllers to fight over + // the same resource, resulting in increased load on the API server and etcd. + // + // When omitted, the value is inherited from the phase, then spec. + // + // +optional + CollisionProtection CollisionProtection `json:"collisionProtection,omitempty"` +} + +// ObjectSliceSourceRef identifies one object manifest within a +// ClusterObjectSlice by the slice's name and the manifest's target identity. +type ObjectSliceSourceRef struct { + // name is the name of the referenced ClusterObjectSlice. + // + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:XValidation:rule=`!format.dns1123Subdomain().validate(self).hasValue()`,message="the value must consist of only lowercase alphanumeric characters, hyphens, and dots, and must start and end with an alphanumeric character." + Name string `json:"name,omitempty"` + + // objectRef identifies the desired object manifest within the referenced + // ClusterObjectSlice by its target identity: apiVersion, kind, name, and + // namespace. The identity must match the selected slice entry's key + // exactly. Omitted and empty namespaces identify the same cluster-scoped + // entry. The slice entry's content is not validated against this identity + // at admission. + // + // +required + ObjectRef ObjectRef `json:"objectRef,omitzero"` +} + +// ObjectRef identifies an object manifest within a referenced +// ClusterObjectSlice by its target identity: apiVersion, kind, name, and +// namespace. Field names and validation mirror the target-identity fields +// of the slice's stored manifests. +type ObjectRef struct { + // apiVersion is the required API version of the referenced object + // manifest, for example "v1" or "apps/v1". It must match the apiVersion + // of the selected slice entry. + // + // +required + // +kubebuilder:validation:MinLength=1 + // +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 required kind of the referenced object manifest, for + // example "ConfigMap". It must match the kind of the selected slice entry. + // + // +required + // +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"` + + // name is the required metadata.name of the referenced object manifest. + // It must match the name of the selected slice entry. + // + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:XValidation:rule=`self != "." && self != ".." && !self.contains("/") && !self.contains("%")`,message="name must not be '.', '..', or contain '/' or '%'" + Name string `json:"name,omitempty"` + + // namespace is the metadata.namespace of the referenced object manifest. + // When omitted, it identifies a cluster-scoped entry; omitted and empty + // namespaces identify the same entry. Nonempty values must be lowercase + // DNS labels of at most 63 characters. Namespaced objects must declare + // their namespace explicitly. + // + // +optional + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:XValidation:rule=`self == "" || !format.dns1123Label().validate(self).hasValue()`,message="namespace must be empty or a valid lowercase DNS label" + Namespace string `json:"namespace,omitempty"` +} + +// CollisionProtection specifies if and how ownership collisions are prevented. +// +kubebuilder:validation:Enum=Prevent;IfNoController;None +type CollisionProtection string + +const ( + // CollisionProtectionPrevent prevents owner collisions entirely + // by only allowing to work with objects itself has created. + CollisionProtectionPrevent CollisionProtection = "Prevent" + // CollisionProtectionIfNoController allows to patch and override + // objects already present if they are not owned by another controller. + CollisionProtectionIfNoController CollisionProtection = "IfNoController" + // CollisionProtectionNone allows to patch and override objects + // already present and owned by other controllers. + // Be careful! This setting may cause multiple controllers to fight over a resource, + // causing load on the API server and etcd. + CollisionProtectionNone CollisionProtection = "None" +) + +// ClusterObjectSetStatus defines the observed state of a ClusterObjectSet. +// +// The completedAt removal guard lives here at the parent level because a +// field-level transition rule is skipped when the field is absent from an +// update, which would otherwise allow the timestamp to be cleared and re-set. +// +// +kubebuilder:validation:XValidation:rule="!has(oldSelf.completedAt) || has(self.completedAt)",message="completedAt cannot be removed once set" +// +kubebuilder:validation:XValidation:rule="!has(oldSelf.phases) || oldSelf.phases.all(p, (!has(p.contentDigest) && !has(p.completedAt)) || (has(self.phases) && self.phases.exists(n, n.name == p.name)))",message="phases with recorded contentDigest or completedAt cannot be removed" +type ClusterObjectSetStatus struct { + // conditions is an optional list of status conditions describing the state of the + // ClusterObjectSet. + // + // The Ready condition represents the state of the ClusterObjectSet. + // True means all objects declared by this ClusterObjectSet are managed by + // it, are at the desired state defined in its spec, and pass their + // progression probes, if any are defined. False means the ClusterObjectSet + // does not currently satisfy its readiness requirements; the reason explains + // why. Unknown is the initial state, before the first reconciliation has + // evaluated the ClusterObjectSet. + // - Unknown with reason Pending: the ClusterObjectSet has not yet been evaluated (initial state, set when the condition is first created). + // - True with reason AllObjectsReady: the ClusterObjectSet has rolled out and all objects are at the desired state. + // - False with reason ObjectsNotReady: one or more objects are still being applied or have not yet passed their progression probes during rollout. + // - False with reason Superseded: one or more objects have been adopted by a newer ClusterObjectSet in the same group. + // - False with reason 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. + // - False with reason PreconditionsNotMet: a precondition for applying the ClusterObjectSet is not yet satisfied (referenced object content is unavailable, invalid, or changed, or a preflight dry-run was rejected, for example due to an immutable field, a conflicting object, or required RBAC or custom resource definitions that do not exist yet); the ClusterObjectSet keeps retrying and recovers once the precondition is met. + // - False with reason InvalidSpecification: the ClusterObjectSet spec is invalid (a malformed phase object or progression probe); correcting the configuration requires creating a replacement ClusterObjectSet. + // - False with reason Archiving: the ClusterObjectSet is being archived and its owned objects are still being torn down. + // - False with reason Archived: the ClusterObjectSet has been archived and its objects have been torn down. + // + // Rollout completion is recorded separately by status.completedAt. + // + // +listType=map + // +listMapKey=type + // +optional + // +patchStrategy=merge + // +patchMergeKey=type + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` //nolint:kubeapilinter // This CRD uses structural list-map validation, not protobuf serialization. + + // objectCounts reports counts of the ClusterObjectSet's objects by state. + // total is reported after every reconciliation; all other counts are + // best-effort summaries of the observations available, not an atomic + // inventory of live objects, and may be older than conditions. + // Omitted before the first reconciliation. + // +optional + ObjectCounts ObjectCounts `json:"objectCounts,omitzero"` + + // phases reports lifecycle state and sparse diagnostics for phases in + // spec.phases, correlated by name. The content digest pins the initially + // resolved desired content; it does not describe live cluster state. + // +kubebuilder:validation:MaxItems=20 + // +listType=map + // +listMapKey=name + // +optional + Phases []ClusterObjectSetPhaseStatus `json:"phases,omitempty"` + + // completedAt is the timestamp at which the ClusterObjectSet was first observed to be + // ready, meaning it had successfully rolled out and all of its objects passed + // their probes. It is set once and is immutable thereafter. + // + // +kubebuilder:validation:XValidation:rule="self == oldSelf || oldSelf == null",message="completedAt is immutable, once set" + // +optional + CompletedAt metav1.Time `json:"completedAt,omitempty,omitzero"` +} + +// ObjectCounts reports counts of a ClusterObjectSet's objects by state. +// All counts are best-effort summaries of the observations available, not an +// atomic inventory of live objects. Revision- or phase-level errors may leave +// them unavailable, incomplete, or unchanged from earlier observations. +// A recognized sibling is another active, non-deleting ClusterObjectSet with +// the same spec.group. +type ObjectCounts struct { + // total is the number of object declarations across all phases, including + // phases that fail validation. It remains the declared total during archival + // and does not decrease as objects are removed. It is reported after every + // reconciliation, even when errors prevent observation of the objects. + // Omitted before the first reconciliation; an explicit zero is a reported count. + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=1000 + // +optional + Total *int64 `json:"total,omitempty"` + + // present is the number of declared objects reported as present. + // During reconciliation, this includes objects controlled by this + // ClusterObjectSet or a recognized sibling. Dry-run creations + // and objects with ownership collisions are excluded. + // During archival, this counts objects still owned by this ClusterObjectSet and + // awaiting teardown, including objects in phases waiting for their turn. + // Objects controlled by another owner are excluded during archival, even if + // they still exist on the cluster. + // A reported zero does not establish that every declared object is absent. + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=1000 + // +optional + Present *int64 `json:"present,omitempty"` + + // synced is the number of objects controlled by this ClusterObjectSet whose + // observed state matches the desired state declared in this ClusterObjectSet's + // spec. Passing progression probes is not required for an object to be synced. + // Objects adopted by newer ClusterObjectSets are excluded, even if their + // content matches this ClusterObjectSet. + // Omitted until observed and during archival, when synchronization is not + // evaluated. Omission does not imply a zero count. + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=1000 + // +optional + Synced *int64 `json:"synced,omitempty"` + + // superseded is the number of objects observed under the control of a + // recognized sibling with a higher .spec.revision. During reconciliation, + // these objects also count as present, but are not synced. This describes + // observed ownership, not a cumulative count of transfers. + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=1000 + // +optional + Superseded *int64 `json:"superseded,omitempty"` + + // colliding is the number of desired objects whose adoption is refused by + // the configured collision-protection policy. The conflicting resources + // exist but do not count as present, synced, or superseded. + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=1000 + // +optional + Colliding *int64 `json:"colliding,omitempty"` +} + +// ClusterObjectSetPhaseStatus 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" +// +kubebuilder:validation:XValidation:rule="!has(oldSelf.contentDigest) || has(self.contentDigest)",message="contentDigest cannot be removed once set" +type ClusterObjectSetPhaseStatus struct { + // name is the phase name matching a phase in spec.phases. + // + // +required + // +kubebuilder:validation:MinLength=1 + // +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." + Name string `json:"name,omitempty"` + + // 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 referenced object content that is unavailable + // or changed, or a rejected preflight dry-run; the ClusterObjectSet + // keeps retrying and recovers once the precondition is met. + // - InvalidSpecification: the phase's declared content or progression + // probes are 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 a recognized sibling + // 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. + // +required + Status PhaseStatus `json:"status,omitempty"` + + // reason is a machine-readable explanation of status: + // - NotEvaluated: no usable evaluation of the phase exists yet (status Unknown). + // - WaitingForPreviousPhase: application is waiting for an earlier phase to + // complete its rollout (status Pending). + // - WaitingForLaterPhase: teardown is waiting for a later phase to complete + // its teardown (status Pending). + // - ProgressionProbesPending: all objects are synced to this ClusterObjectSet, but at + // least one progression-probe result is false or unknown (status Stabilizing). + // - AllObjectsReady: all objects are synced to this ClusterObjectSet and pass their + // progression probes (status Ready). + // - ContentUnavailable: referenced object content is unavailable or invalid + // (status PreconditionsNotMet). + // - ContentChanged: referenced object content changed after this phase's + // content was initially resolved, violating the pinned content digest + // (status PreconditionsNotMet). + // - ObjectsAdoptedByNewerRevision: at least one object is controlled by a + // recognized sibling ClusterObjectSet with a higher + // .spec.revision (status Superseded). + // - RemovingOwnedObjects: this is the active teardown phase and owned + // objects remain to be removed (status Archiving). + // - TeardownComplete: this ClusterObjectSet's teardown responsibility for the phase + // is complete; objects adopted by newer ClusterObjectSets may still exist + // (status Archived). + // + // PreconditionsNotMet, InvalidSpecification, and ObjectCollision statuses + // do not imply a terminal failure or a fixed retry policy. + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=1024 + // +kubebuilder:validation:Pattern=`^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$` + // +required + Reason string `json:"reason,omitempty"` + + // 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 provides human-readable context, such as a phase-wide validation + // failure, content mismatch, or the name of another phase blocking progress. + // 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 + Message string `json:"message,omitempty"` + + // contentDigest pins the phase's initially resolved desired object content, + // before controller mutations, in the format ":". Currently + // sha256 is the only supported algorithm. Omitted until content is resolved; + // once recorded, it cannot change or be removed. Matching content permits + // reconciliation but does not establish live-object synchronization or health. + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="contentDigest cannot change once set" + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + // +kubebuilder:validation:Pattern=`^[a-z0-9]+:[a-f0-9]+$` + // +optional + ContentDigest string `json:"contentDigest,omitempty"` + + // lastTransitionTime is the timestamp when the current status was first + // reported or last changed. Changes to reason or 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 contains sparse current diagnostics, not a full object + // inventory. Include failed or unknown progression probes, ownership + // collisions (including independently actionable collisions in paused phases), + // and objects awaiting deletion in the active teardown phase. Superseded + // objects remain eligible for probe diagnostics when they block progression. + // Omit objects with no reportable diagnostics, expected pending work in paused + // phases, and copies of phase-wide failures. Entries are removed when their + // diagnostics resolve. + // At most 50 entries, matching the maximum number of objects per phase. + // +kubebuilder:validation:MaxItems=50 + // +listType=atomic + // +optional + ObjectDetails []ObjectStatus `json:"objectDetails,omitempty"` +} + +// ObjectStatus identifies an object with current diagnostics, using the same +// target identity fields as the spec's object references (see +// ObjectRef), so status entries correlate directly with the +// declared objects. The object may be missing or controlled by a conflicting +// owner; it is not necessarily managed. +type ObjectStatus 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=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 + // +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. Omitted for cluster-scoped + // resources. At most 63 characters (DNS label max). + // +kubebuilder:validation:MinLength=1 + // +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"` + + // name is the name of the object. Must be between 1 and 253 + // characters (DNS subdomain max). + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +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"` + + // diagnostics categorizes current object-specific problems. InvalidSpecification + // and PreconditionsNotMet are classified at phase level only. Diagnostics are + // not an event history or individual assertion results. Messages sharing a + // reason are grouped into one entry. + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=18 + // +listType=map + // +listMapKey=reason + // +required + Diagnostics []ObjectDiagnostic `json:"diagnostics,omitempty"` +} + +// ObjectDiagnosticReasons are the known reason values for ObjectDiagnostic.reason. +const ( + // ObjectDiagnosticReasonProgressionProbeFailed indicates the object's + // aggregate progression probes evaluated to false. + ObjectDiagnosticReasonProgressionProbeFailed = "ProgressionProbeFailed" + + // ObjectDiagnosticReasonProgressionProbeUnknown indicates the object's + // aggregate progression probes could not be determined, for example because + // the object's status has not yet been reported or is outdated. + ObjectDiagnosticReasonProgressionProbeUnknown = "ProgressionProbeUnknown" + + // ObjectDiagnosticReasonObjectCollision indicates the object exists but + // this ClusterObjectSet cannot take ownership of it under the configured collision + // protection policy. + ObjectDiagnosticReasonObjectCollision = "ObjectCollision" + + // ObjectDiagnosticReasonAwaitingDeletion indicates the object is owned by + // this ClusterObjectSet, has been requested for deletion, and is not yet gone from + // the cluster. + ObjectDiagnosticReasonAwaitingDeletion = "AwaitingDeletion" +) + +// ObjectDiagnostic categorizes an observed object problem without exposing +// implementation-specific actions or claiming individual assertion outcomes. +type ObjectDiagnostic struct { + // reason identifies the diagnostic category: + // - ProgressionProbeFailed: the object's aggregate progression probes + // evaluated to false. + // - ProgressionProbeUnknown: the object's aggregate progression probes + // could not be determined, for example because the object's status has + // not yet been reported or is outdated. + // - ObjectCollision: the object exists but this ClusterObjectSet cannot take + // ownership of it under the configured collision protection policy. + // - AwaitingDeletion: the object is owned by this ClusterObjectSet, has been + // requested for deletion, and is not yet gone from the cluster. + // + // Retryability and terminality must not be inferred from the presence of a + // diagnostic alone. + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=1024 + // +kubebuilder:validation:Pattern=`^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$` + // +required + Reason string `json:"reason,omitempty"` + + // messages provides bounded human-readable explanations of this diagnostic. + // Consumers must not parse these messages. Probe messages describe an aggregate + // result; their number is not the number of failed assertions. AwaitingDeletion + // establishes that teardown is incomplete, not necessarily its underlying cause. + // +kubebuilder:validation:MaxItems=18 + // +kubebuilder:validation:items:MinLength=1 + // +kubebuilder:validation:items:MaxLength=1024 + // +listType=atomic + // +optional + Messages []string `json:"messages,omitempty"` +} + +// PhaseStatus describes the current state of a phase in the rollout. +// +// +kubebuilder:validation:Enum=Unknown;Pending;Stabilizing;Ready;PreconditionsNotMet;InvalidSpecification;ObjectCollision;Superseded;Archiving;Archived +type PhaseStatus string + +const ( + // 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" + + // PhaseStatusPending indicates writes are waiting for an earlier application + // phase or a later teardown phase, as identified by the reason. + PhaseStatusPending PhaseStatus = "Pending" + + // 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 to this + // ClusterObjectSet and pass their progression probes, if any are defined. + PhaseStatusReady PhaseStatus = "Ready" + + // 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 or + // progression probes are 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 at least one object in this phase has been + // adopted by a recognized newer ClusterObjectSet. Failing or unknown progression + // probes may still prevent later phases from advancing and remain visible + // in objectDetails. + PhaseStatusSuperseded PhaseStatus = "Superseded" + + // PhaseStatusArchiving indicates this is the active teardown phase and + // owned objects remain to be removed. + PhaseStatusArchiving PhaseStatus = "Archiving" + + // PhaseStatusArchived indicates this ClusterObjectSet's teardown responsibility for + // the phase is complete. Objects adopted by newer ClusterObjectSets may still exist. + PhaseStatusArchived PhaseStatus = "Archived" +) + +// Phase status reasons are the known reason values for +// ClusterObjectSetPhaseStatus.reason. +const ( + // PhaseStatusReasonNotEvaluated indicates no usable evaluation of the phase + // exists yet (status Unknown). + PhaseStatusReasonNotEvaluated = "NotEvaluated" + + // PhaseStatusReasonWaitingForPreviousPhase indicates application is waiting + // for an earlier phase to complete its rollout (status Pending). + PhaseStatusReasonWaitingForPreviousPhase = "WaitingForPreviousPhase" + + // PhaseStatusReasonWaitingForLaterPhase indicates teardown is waiting for a + // later phase to complete its teardown (status Pending). + PhaseStatusReasonWaitingForLaterPhase = "WaitingForLaterPhase" + + // PhaseStatusReasonProgressionProbesPending indicates all objects are synced + // to this ClusterObjectSet, but at least one progression-probe result is false or + // unknown (status Stabilizing). + PhaseStatusReasonProgressionProbesPending = "ProgressionProbesPending" + + // PhaseStatusReasonAllObjectsReady indicates all objects are synced to this + // ClusterObjectSet and pass their progression probes (status Ready). + PhaseStatusReasonAllObjectsReady = "AllObjectsReady" + + // PhaseStatusReasonContentUnavailable indicates referenced object content is + // unavailable or invalid (status PreconditionsNotMet). + PhaseStatusReasonContentUnavailable = "ContentUnavailable" + + // PhaseStatusReasonContentChanged indicates referenced object content changed + // after this phase's content was initially resolved, violating the pinned + // content digest (status PreconditionsNotMet). + PhaseStatusReasonContentChanged = "ContentChanged" + + // PhaseStatusReasonObjectsAdoptedByNewerRevision indicates at least one object + // is controlled by a recognized sibling ClusterObjectSet with a higher .spec.revision + // number (status Superseded). + PhaseStatusReasonObjectsAdoptedByNewerRevision = "ObjectsAdoptedByNewerRevision" + + // PhaseStatusReasonRemovingOwnedObjects indicates this is the active teardown + // phase and owned objects remain to be removed (status Archiving). + PhaseStatusReasonRemovingOwnedObjects = "RemovingOwnedObjects" + + // PhaseStatusReasonTeardownComplete indicates this ClusterObjectSet's teardown + // responsibility for the phase is complete; objects adopted by newer + // ClusterObjectSets may still exist (status Archived). + PhaseStatusReasonTeardownComplete = "TeardownComplete" +) + +// +genclient +// +genclient:nonNamespaced +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster +// +kubebuilder:subresource:status +// +kubebuilder:validation:XValidation:rule="self.metadata.name == '%s-%d'.format([self.spec.group, self.spec.revision])",message="metadata.name must be -" +// +kubebuilder:selectablefield:JSONPath=`.spec.group` +// +kubebuilder:printcolumn:name="Group",type=string,JSONPath=`.spec.group` +// +kubebuilder:printcolumn:name="Revision",type=integer,JSONPath=`.spec.revision` +// +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=='Ready')].status` +// +kubebuilder:printcolumn:name="Reason",type=string,JSONPath=`.status.conditions[?(@.type=='Ready')].reason` +// +kubebuilder:printcolumn:name="Total",type=integer,JSONPath=`.status.objectCounts.total` +// +kubebuilder:printcolumn:name="Present",type=integer,JSONPath=`.status.objectCounts.present` +// +kubebuilder:printcolumn:name="Synced",type=integer,JSONPath=`.status.objectCounts.synced` +// +kubebuilder:printcolumn:name="Superseded",type=integer,JSONPath=`.status.objectCounts.superseded`,priority=1 +// +kubebuilder:printcolumn:name="Colliding",type=integer,JSONPath=`.status.objectCounts.colliding`,priority=1 +// +kubebuilder:printcolumn:name=Age,type=date,JSONPath=`.metadata.creationTimestamp` + +// ClusterObjectSet is a cluster-scoped API that holds an immutable set of +// Kubernetes objects, organized into phases that roll out sequentially. It is +// created standalone, or by a ClusterObjectDeployment controller, which cuts a +// new ClusterObjectSet from its template whenever the template changes; +// ClusterObjectSets sharing a group form the deployment's revision sequence, +// ordered by .spec.revision. The same object can only be managed by a single +// ClusterObjectSet at a time. Ownership of objects is transitioned from one +// ClusterObjectSet to the next as new ones roll out. +// +// For ClusterObjectSets owned by a ClusterObjectDeployment, that deployment's +// controller requests archival of older active ClusterObjectSets once a newer +// owned, non-deleting, active ClusterObjectSet has recorded rollout completion +// in status.completedAt. This decision uses historical completion, not current +// readiness, and does not require the newest ClusterObjectSet to have completed. +// The ClusterObjectSet controller performs teardown when spec.lifecycleState is +// set to "Archived"; it does not request archival of sibling ClusterObjectSets. +// Standalone callers manage archival explicitly. Archived ClusterObjectSets +// owned by a ClusterObjectDeployment may be pruned after teardown according to +// its spec.revisionHistoryLimit. +// +// Set metadata.name explicitly to -, using decimal +// notation without leading zeros. This ensures revision uniqueness within a group. +// Name generation through metadata.generateName is not supported. +// +kubebuilder:validation:XValidation:rule="!has(oldSelf.status) || has(self.status)",message="status cannot be removed once set" +type ClusterObjectSet struct { + metav1.TypeMeta `json:",inline"` + + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec defines the desired state of the ClusterObjectSet. + // +required + Spec ClusterObjectSetSpec `json:"spec,omitzero"` + + // status is optional and defines the observed state of the ClusterObjectSet. + // objectCounts.total is reported after every reconciliation. All other object + // counts are best-effort summaries of the observations available, not an + // atomic inventory of live objects. Revision- or phase-level errors may leave + // those counts unavailable, incomplete, or unchanged from earlier observations, + // so they may be older than conditions. A reported zero is not proof that all + // objects were evaluated. + // During archival, objectCounts.synced is omitted. + // Cannot be removed once set; this is to prevent immutable fields such as completedAt + // from being cleared by an update which omits the status. + // +optional + Status ClusterObjectSetStatus `json:"status,omitzero"` +} + +// +kubebuilder:object:root=true + +// ClusterObjectSetList contains a list of ClusterObjectSet +type ClusterObjectSetList struct { + metav1.TypeMeta `json:",inline"` + + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // items is a required list of ClusterObjectSet objects. + // + // +required + Items []ClusterObjectSet `json:"items"` +} + +func init() { + SchemeBuilder.Register(func(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &ClusterObjectSet{}, &ClusterObjectSetList{}) + return nil + }) +} diff --git a/tmp/clusterobjectslice_types.go b/tmp/clusterobjectslice_types.go new file mode 100644 index 0000000000..c330f9c4e8 --- /dev/null +++ b/tmp/clusterobjectslice_types.go @@ -0,0 +1,131 @@ +/* +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. +*/ + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" +) + +const ClusterObjectSliceKind = "ClusterObjectSlice" + +// ClusterObjectSliceType defines the type of content stored in a ClusterObjectSlice. +// +kubebuilder:validation:Enum=InlineManifests +type ClusterObjectSliceType string + +const ( + // ClusterObjectSliceTypeInlineManifests stores Kubernetes object manifests + // inline in the slice. + ClusterObjectSliceTypeInlineManifests ClusterObjectSliceType = "InlineManifests" +) + +// ClusterObjectSliceSpec defines an immutable group of stored manifests. +// At least one manifest must be set. Once created, the slice content cannot +// be changed: manifests cannot be added, removed, or reordered, and the +// content of each manifest cannot be modified. Create a new slice to change +// content. List order has no meaning. +// +// +union +// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="spec is immutable: manifests cannot be added, removed, reordered, or modified; create a new ClusterObjectSlice instead" +// +kubebuilder:validation:XValidation:rule="self.type == 'InlineManifests' ? has(self.manifests) : !has(self.manifests)",message="manifests is required when type is InlineManifests, and forbidden otherwise" +type ClusterObjectSliceSpec struct { + // type is a required field which specifies the type of content stored in + // the slice. + // + // The allowed content type is "InlineManifests". + // + // When set to "InlineManifests", the slice stores Kubernetes object + // manifests inline in spec.manifests. + // + // +unionDiscriminator + // +kubebuilder:validation:Enum=InlineManifests + // +required + Type ClusterObjectSliceType `json:"type,omitempty"` + + // manifests is a required list of 1 to 256 Kubernetes object manifests + // stored inline in the slice. The list is immutable: manifests cannot be + // added, removed, or reordered, and the content of each manifest cannot be + // modified. Each manifest must be a valid Kubernetes + // resource with a non-empty apiVersion, kind, and metadata.name. Admission + // validates only this structure; it does not validate a manifest against + // the schema of its apiVersion and kind, does not verify resource scope or + // namespace correctness, and does not enforce uniqueness of the manifests' + // target identities (apiVersion, kind, name, and namespace). + // + // Each manifest is identified by its own target identity: apiVersion, + // kind, metadata.name, and metadata.namespace. Consumers select a manifest + // by that identity. + // + // List order has no rollout meaning. + // + // +unionMember + // +optional + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=256 + // +listType=atomic + // +kubebuilder:validation:items:XEmbeddedResource + // +kubebuilder:validation:items:XPreserveUnknownFields + // +kubebuilder:validation:items:XValidation:rule="has(self.apiVersion) && has(self.kind) && has(self.metadata)",message="manifests items must be a valid Kubernetes resource with apiVersion, kind, and metadata" + // +kubebuilder:validation:items:XValidation:rule="self.apiVersion != '' && self.kind != ''",message="apiVersion and kind must be non-empty" + // +kubebuilder:validation:items:XValidation:rule="has(self.metadata.name) && self.metadata.name != ''",message="metadata.name is required" + Manifests []unstructured.Unstructured `json:"manifests,omitzero"` +} + +// +genclient +// +genclient:nonNamespaced +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster,shortName=cosl +// +kubebuilder:printcolumn:name=Age,type=date,JSONPath=`.metadata.creationTimestamp` + +// ClusterObjectSlice stores immutable Kubernetes object manifests independently +// of rollout intent. It is an experimental, cluster-scoped API. Creating a slice +// stores content only; it does not apply objects or report rollout readiness. +type ClusterObjectSlice struct { + metav1.TypeMeta `json:",inline"` + + // metadata is the standard object's metadata. Labels, annotations, and + // owner references can change independently of the immutable content. + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec defines the required, immutable content of the slice. + // +required + Spec ClusterObjectSliceSpec `json:"spec,omitzero"` +} + +// +kubebuilder:object:root=true + +// ClusterObjectSliceList contains ClusterObjectSlice objects. +type ClusterObjectSliceList struct { + metav1.TypeMeta `json:",inline"` + + // metadata is the standard list metadata. + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // items is the list of slices. + // +required + Items []ClusterObjectSlice `json:"items"` +} + +func init() { + SchemeBuilder.Register(func(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &ClusterObjectSlice{}, &ClusterObjectSliceList{}) + return nil + }) +}