From ecd3668b04c7b9fcb9245b2dda9c5fd80dfe3be1 Mon Sep 17 00:00:00 2001 From: Rayhan Hossain Date: Mon, 30 Nov 2026 13:29:12 -0800 Subject: [PATCH 01/10] feat: support declarative products with the shared operator runtime Add an opt-in product definition loader and common startup configuration. Reuse the existing shared API, adapter, controllers and admission; retain zero-value DocumentDB behavior. Add a generic Helm chart backed by canonical shared schemas, automatic schema synchronization and definition/version-policy contract tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 33b3cb3c-1b25-4ffb-bff1-ebf0f3d04058 Signed-off-by: Rayhan Hossain --- operator/product-helm-chart/Chart.yaml | 6 + operator/product-helm-chart/Makefile | 5 + operator/product-helm-chart/README.md | 36 + .../product-helm-chart/schemas/backup.yaml | 248 ++ .../product-helm-chart/schemas/cluster.yaml | 3400 +++++++++++++++++ .../schemas/scheduled-backup.yaml | 182 + .../product-helm-chart/templates/_helpers.tpl | 12 + .../product-helm-chart/templates/crds.yaml | 16 + .../templates/deployment.yaml | 99 + .../templates/injector.yaml | 117 + .../product-helm-chart/templates/role.yaml | 85 + .../product-helm-chart/templates/webhook.yaml | 58 + operator/product-helm-chart/values.yaml | 18 + operator/src/Makefile | 1 + operator/src/cmd/main.go | 44 +- .../internal/controller/backup_controller.go | 18 +- .../controller/certificate_controller.go | 7 +- .../controller/documentdb_controller.go | 22 +- .../src/internal/controller/pv_controller.go | 3 +- .../controller/scheduledbackup_controller.go | 7 +- operator/src/internal/engine/extension.go | 9 + .../internal/engine/extension_policy_test.go | 41 + operator/src/internal/product/definition.go | 226 ++ .../internal/product/definition_chart_test.go | 123 + .../src/internal/product/definition_test.go | 103 + operator/src/internal/product/documentdb.go | 41 +- .../src/internal/product/documentdb_backup.go | 28 +- operator/src/internal/product/profile.go | 8 +- .../src/internal/product/testdata/widget.json | 53 + .../src/internal/webhook/definition_test.go | 81 + .../internal/webhook/documentdb_webhook.go | 88 +- operator/src/internal/webhook/imagevolume.go | 4 +- operator/src/pkg/core/definition.go | 20 + operator/src/pkg/core/engine.go | 4 +- 34 files changed, 5165 insertions(+), 48 deletions(-) create mode 100644 operator/product-helm-chart/Chart.yaml create mode 100644 operator/product-helm-chart/Makefile create mode 100644 operator/product-helm-chart/README.md create mode 100644 operator/product-helm-chart/schemas/backup.yaml create mode 100644 operator/product-helm-chart/schemas/cluster.yaml create mode 100644 operator/product-helm-chart/schemas/scheduled-backup.yaml create mode 100644 operator/product-helm-chart/templates/_helpers.tpl create mode 100644 operator/product-helm-chart/templates/crds.yaml create mode 100644 operator/product-helm-chart/templates/deployment.yaml create mode 100644 operator/product-helm-chart/templates/injector.yaml create mode 100644 operator/product-helm-chart/templates/role.yaml create mode 100644 operator/product-helm-chart/templates/webhook.yaml create mode 100644 operator/product-helm-chart/values.yaml create mode 100644 operator/src/internal/product/definition.go create mode 100644 operator/src/internal/product/definition_chart_test.go create mode 100644 operator/src/internal/product/definition_test.go create mode 100644 operator/src/internal/product/testdata/widget.json create mode 100644 operator/src/internal/webhook/definition_test.go create mode 100644 operator/src/pkg/core/definition.go diff --git a/operator/product-helm-chart/Chart.yaml b/operator/product-helm-chart/Chart.yaml new file mode 100644 index 000000000..ab2cb9946 --- /dev/null +++ b/operator/product-helm-chart/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: product-operator +description: Shared API, admission and controllers configured by a product definition +type: application +version: 0.0.0-dev +appVersion: local-unmerged diff --git a/operator/product-helm-chart/Makefile b/operator/product-helm-chart/Makefile new file mode 100644 index 000000000..edc158806 --- /dev/null +++ b/operator/product-helm-chart/Makefile @@ -0,0 +1,5 @@ +.PHONY: schemas +schemas: + cp ../src/config/crd/bases/documentdb.io_dbs.yaml schemas/cluster.yaml + cp ../src/config/crd/bases/documentdb.io_backups.yaml schemas/backup.yaml + cp ../src/config/crd/bases/documentdb.io_scheduledbackups.yaml schemas/scheduled-backup.yaml diff --git a/operator/product-helm-chart/README.md b/operator/product-helm-chart/README.md new file mode 100644 index 000000000..e4c841fc0 --- /dev/null +++ b/operator/product-helm-chart/README.md @@ -0,0 +1,36 @@ +# Declarative product distribution + +This opt-in chart runs the existing manager with `--product-definition`. +The same API types, adapter mapping, controllers, admission, certificates, +backups and persistent-volume handling serve every definition. The original +DocumentDB chart and no-definition manager startup remain unchanged. + +The definition is data: API identity, product profile, explicit split images, +PostgreSQL defaults, topology policy and endpoint format. It cannot provide Go +callbacks. `operator/src/internal/product/testdata/widget.json` is a synthetic +example. Supply it as the `productDefinition` values object and pin manager +and optional injector images with `image.repository` and `image.digest`. +Install cert-manager and CloudNative-PG first; the injector namespace must +already exist. The bundled injector retains its actual existing RPC identity. + +CRDs are rendered from exact copies of the canonical shared API schemas. +Only group/version/kind/resource metadata changes; there is no product-specific +schema or generated Go API. Run `make schemas` here after regenerating the +canonical CRDs. The chart contract test checks both source equality and rendered +schema equality. CRDs are retained on uninstall. + +For compatibility, the shared Go API and some JSON fields still carry their +original DocumentDB names. A definition changes API identity, not serialization +or schema semantics. Explicit unsupported cross-region/legacy version settings +are rejected, not silently ignored. Local fixed-catalog definitions disable +upgrades and verify the exact available and installed catalog versions without +inventing a semantic version. Co-location requires `localDevelopment`. + +Validate a definition without Kubernetes: + +```sh +go run ./cmd --product-definition=internal/product/testdata/widget.json --check-product-definition +``` + +Run this command from `operator/src`. Fixed-catalog/local-development mode is +not production upgrade, authentication, backup or node-failure HA qualification. diff --git a/operator/product-helm-chart/schemas/backup.yaml b/operator/product-helm-chart/schemas/backup.yaml new file mode 100644 index 000000000..7b3517644 --- /dev/null +++ b/operator/product-helm-chart/schemas/backup.yaml @@ -0,0 +1,248 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + labels: + app: documentdb-operator + name: backups.documentdb.io +spec: + group: documentdb.io + names: + kind: Backup + listKind: BackupList + plural: backups + singular: backup + scope: Namespaced + versions: + - additionalPrinterColumns: + - description: Target DocumentDB cluster + jsonPath: .spec.cluster.name + name: Cluster + type: string + - description: Backup phase + jsonPath: .status.phase + name: Phase + type: string + - description: Backup start time + jsonPath: .status.startedAt + name: StartedAt + type: string + - description: Backup completion time + jsonPath: .status.stoppedAt + name: StoppedAt + type: string + - description: Backup expiration time + jsonPath: .status.expiredAt + name: ExpiredAt + type: string + - description: Backup status message + jsonPath: .status.message + name: Message + type: string + - description: DocumentDB schema version at backup time + jsonPath: .status.schemaVersion + name: SchemaVersion + type: string + deprecated: true + deprecationWarning: documentdb.io/preview is deprecated; use documentdb.io/v1 + name: preview + schema: + openAPIV3Schema: + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: BackupSpec defines the desired state of Backup. + properties: + cluster: + description: |- + Cluster specifies the DocumentDB cluster to backup. + The cluster must exist in the same namespace as the Backup resource. + properties: + name: + description: Name of the referent. + type: string + required: + - name + type: object + retentionDays: + description: |- + RetentionDays specifies how many days the backup should be retained. + If not specified, the default retention period from the cluster's backup retention policy will be used. + type: integer + required: + - cluster + type: object + x-kubernetes-validations: + - message: BackupSpec is immutable once set + rule: oldSelf == self + status: + description: BackupStatus defines the observed state of Backup. + properties: + expiredAt: + description: ExpiredAt is the time when the backup is considered expired + and can be deleted. + format: date-time + type: string + message: + description: |- + Message contains additional information about the backup status. + For failed backups, this contains the error message. + For skipped backups, this explains why the backup was skipped. + type: string + phase: + description: Phase represents the current phase of the backup operation. + type: string + schemaVersion: + description: |- + SchemaVersion is the DocumentDB extension schema version of the source + cluster at backup time, captured from the source DocumentDB's + status.schemaVersion. It is used to validate restore compatibility: + a restore must target a binary version >= this schema version, otherwise + an older binary would run against a newer, irreversible schema. + type: string + startedAt: + description: StartedAt is the time when the backup operation started. + format: date-time + type: string + stoppedAt: + description: StoppedAt is the time when the backup operation completed. + format: date-time + type: string + type: object + type: object + served: true + storage: false + subresources: + status: {} + - additionalPrinterColumns: + - description: Target DocumentDB cluster + jsonPath: .spec.cluster.name + name: Cluster + type: string + - description: Backup phase + jsonPath: .status.phase + name: Phase + type: string + - description: Backup start time + jsonPath: .status.startedAt + name: StartedAt + type: string + - description: Backup completion time + jsonPath: .status.stoppedAt + name: StoppedAt + type: string + - description: Backup expiration time + jsonPath: .status.expiredAt + name: ExpiredAt + type: string + - description: Backup status message + jsonPath: .status.message + name: Message + type: string + - description: DocumentDB schema version at backup time + jsonPath: .status.schemaVersion + name: SchemaVersion + type: string + name: v1 + schema: + openAPIV3Schema: + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: BackupSpec defines the desired state of Backup. + properties: + cluster: + description: |- + Cluster specifies the DocumentDB cluster to backup. + The cluster must exist in the same namespace as the Backup resource. + properties: + name: + description: Name of the referent. + type: string + required: + - name + type: object + retentionDays: + description: |- + RetentionDays specifies how many days the backup should be retained. + If not specified, the default retention period from the cluster's backup retention policy will be used. + type: integer + required: + - cluster + type: object + x-kubernetes-validations: + - message: BackupSpec is immutable once set + rule: oldSelf == self + status: + description: BackupStatus defines the observed state of Backup. + properties: + expiredAt: + description: ExpiredAt is the time when the backup is considered expired + and can be deleted. + format: date-time + type: string + message: + description: |- + Message contains additional information about the backup status. + For failed backups, this contains the error message. + For skipped backups, this explains why the backup was skipped. + type: string + phase: + description: Phase represents the current phase of the backup operation. + type: string + schemaVersion: + description: |- + SchemaVersion is the DocumentDB extension schema version of the source + cluster at backup time, captured from the source DocumentDB's + status.schemaVersion. It is used to validate restore compatibility: + a restore must target a binary version >= this schema version, otherwise + an older binary would run against a newer, irreversible schema. + type: string + startedAt: + description: StartedAt is the time when the backup operation started. + format: date-time + type: string + stoppedAt: + description: StoppedAt is the time when the backup operation completed. + format: date-time + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/operator/product-helm-chart/schemas/cluster.yaml b/operator/product-helm-chart/schemas/cluster.yaml new file mode 100644 index 000000000..6c611e6f9 --- /dev/null +++ b/operator/product-helm-chart/schemas/cluster.yaml @@ -0,0 +1,3400 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + labels: + app: documentdb-operator + name: dbs.documentdb.io +spec: + group: documentdb.io + names: + kind: DocumentDB + listKind: DocumentDBList + plural: dbs + shortNames: + - documentdb + singular: documentdb + scope: Namespaced + versions: + - additionalPrinterColumns: + - description: CNPG Cluster Status + jsonPath: .status.status + name: Status + type: string + - description: DocumentDB Connection String + jsonPath: .status.connectionString + name: Connection String + type: string + deprecated: true + deprecationWarning: documentdb.io/preview is deprecated; use documentdb.io/v1 + name: preview + schema: + openAPIV3Schema: + description: DocumentDB is the Schema for the dbs API. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: DocumentDBSpec defines the desired state of DocumentDB. + properties: + affinity: + description: Affinity/Anti-affinity rules for Pods (cnpg passthrough) + properties: + additionalPodAffinity: + description: AdditionalPodAffinity allows to specify pod affinity + terms to be passed to all the cluster's pods. + properties: + preferredDuringSchedulingIgnoredDuringExecution: + description: |- + The scheduler will prefer to schedule pods to nodes that satisfy + the affinity expressions specified by this field, but it may choose + a node that violates one or more of the expressions. The node that is + most preferred is the one with the greatest sum of weights, i.e. + for each node that meets all of the scheduling requirements (resource + request, requiredDuringScheduling affinity expressions, etc.), + compute a sum by iterating through the elements of this field and adding + "weight" to the sum if the node has pods which matches the corresponding podAffinityTerm; the + node(s) with the highest sum are the most preferred. + items: + description: The weights of all of the matched WeightedPodAffinityTerm + fields are added per-node to find the most preferred node(s) + properties: + podAffinityTerm: + description: Required. A pod affinity term, associated + with the corresponding weight. + properties: + labelSelector: + description: |- + A label query over a set of resources, in this case pods. + If it's null, this PodAffinityTerm matches with no Pods. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are + ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that + the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + matchLabelKeys: + description: |- + MatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both matchLabelKeys and labelSelector. + Also, matchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + mismatchLabelKeys: + description: |- + MismatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. + Also, mismatchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + namespaceSelector: + description: |- + A label query over the set of namespaces that the term applies to. + The term is applied to the union of the namespaces selected by this field + and the ones listed in the namespaces field. + null selector and null or empty namespaces list means "this pod's namespace". + An empty selector ({}) matches all namespaces. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are + ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that + the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + namespaces: + description: |- + namespaces specifies a static list of namespace names that the term applies to. + The term is applied to the union of the namespaces listed in this field + and the ones selected by namespaceSelector. + null or empty namespaces list and null namespaceSelector means "this pod's namespace". + items: + type: string + type: array + x-kubernetes-list-type: atomic + topologyKey: + description: |- + This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching + the labelSelector in the specified namespaces, where co-located is defined as running on a node + whose value of the label with key topologyKey matches that of any node on which any of the + selected pods is running. + Empty topologyKey is not allowed. + type: string + required: + - topologyKey + type: object + weight: + description: |- + weight associated with matching the corresponding podAffinityTerm, + in the range 1-100. + format: int32 + type: integer + required: + - podAffinityTerm + - weight + type: object + type: array + x-kubernetes-list-type: atomic + requiredDuringSchedulingIgnoredDuringExecution: + description: |- + If the affinity requirements specified by this field are not met at + scheduling time, the pod will not be scheduled onto the node. + If the affinity requirements specified by this field cease to be met + at some point during pod execution (e.g. due to a pod label update), the + system may or may not try to eventually evict the pod from its node. + When there are multiple elements, the lists of nodes corresponding to each + podAffinityTerm are intersected, i.e. all terms must be satisfied. + items: + description: |- + Defines a set of pods (namely those matching the labelSelector + relative to the given namespace(s)) that this pod should be + co-located (affinity) or not co-located (anti-affinity) with, + where co-located is defined as running on a node whose value of + the label with key matches that of any node on which + a pod of the set of pods is running + properties: + labelSelector: + description: |- + A label query over a set of resources, in this case pods. + If it's null, this PodAffinityTerm matches with no Pods. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + matchLabelKeys: + description: |- + MatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both matchLabelKeys and labelSelector. + Also, matchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + mismatchLabelKeys: + description: |- + MismatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. + Also, mismatchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + namespaceSelector: + description: |- + A label query over the set of namespaces that the term applies to. + The term is applied to the union of the namespaces selected by this field + and the ones listed in the namespaces field. + null selector and null or empty namespaces list means "this pod's namespace". + An empty selector ({}) matches all namespaces. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + namespaces: + description: |- + namespaces specifies a static list of namespace names that the term applies to. + The term is applied to the union of the namespaces listed in this field + and the ones selected by namespaceSelector. + null or empty namespaces list and null namespaceSelector means "this pod's namespace". + items: + type: string + type: array + x-kubernetes-list-type: atomic + topologyKey: + description: |- + This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching + the labelSelector in the specified namespaces, where co-located is defined as running on a node + whose value of the label with key topologyKey matches that of any node on which any of the + selected pods is running. + Empty topologyKey is not allowed. + type: string + required: + - topologyKey + type: object + type: array + x-kubernetes-list-type: atomic + type: object + additionalPodAntiAffinity: + description: |- + AdditionalPodAntiAffinity allows to specify pod anti-affinity terms to be added to the ones generated + by the operator if EnablePodAntiAffinity is set to true (default) or to be used exclusively if set to false. + properties: + preferredDuringSchedulingIgnoredDuringExecution: + description: |- + The scheduler will prefer to schedule pods to nodes that satisfy + the anti-affinity expressions specified by this field, but it may choose + a node that violates one or more of the expressions. The node that is + most preferred is the one with the greatest sum of weights, i.e. + for each node that meets all of the scheduling requirements (resource + request, requiredDuringScheduling anti-affinity expressions, etc.), + compute a sum by iterating through the elements of this field and subtracting + "weight" from the sum if the node has pods which matches the corresponding podAffinityTerm; the + node(s) with the highest sum are the most preferred. + items: + description: The weights of all of the matched WeightedPodAffinityTerm + fields are added per-node to find the most preferred node(s) + properties: + podAffinityTerm: + description: Required. A pod affinity term, associated + with the corresponding weight. + properties: + labelSelector: + description: |- + A label query over a set of resources, in this case pods. + If it's null, this PodAffinityTerm matches with no Pods. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are + ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that + the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + matchLabelKeys: + description: |- + MatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both matchLabelKeys and labelSelector. + Also, matchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + mismatchLabelKeys: + description: |- + MismatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. + Also, mismatchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + namespaceSelector: + description: |- + A label query over the set of namespaces that the term applies to. + The term is applied to the union of the namespaces selected by this field + and the ones listed in the namespaces field. + null selector and null or empty namespaces list means "this pod's namespace". + An empty selector ({}) matches all namespaces. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are + ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that + the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + namespaces: + description: |- + namespaces specifies a static list of namespace names that the term applies to. + The term is applied to the union of the namespaces listed in this field + and the ones selected by namespaceSelector. + null or empty namespaces list and null namespaceSelector means "this pod's namespace". + items: + type: string + type: array + x-kubernetes-list-type: atomic + topologyKey: + description: |- + This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching + the labelSelector in the specified namespaces, where co-located is defined as running on a node + whose value of the label with key topologyKey matches that of any node on which any of the + selected pods is running. + Empty topologyKey is not allowed. + type: string + required: + - topologyKey + type: object + weight: + description: |- + weight associated with matching the corresponding podAffinityTerm, + in the range 1-100. + format: int32 + type: integer + required: + - podAffinityTerm + - weight + type: object + type: array + x-kubernetes-list-type: atomic + requiredDuringSchedulingIgnoredDuringExecution: + description: |- + If the anti-affinity requirements specified by this field are not met at + scheduling time, the pod will not be scheduled onto the node. + If the anti-affinity requirements specified by this field cease to be met + at some point during pod execution (e.g. due to a pod label update), the + system may or may not try to eventually evict the pod from its node. + When there are multiple elements, the lists of nodes corresponding to each + podAffinityTerm are intersected, i.e. all terms must be satisfied. + items: + description: |- + Defines a set of pods (namely those matching the labelSelector + relative to the given namespace(s)) that this pod should be + co-located (affinity) or not co-located (anti-affinity) with, + where co-located is defined as running on a node whose value of + the label with key matches that of any node on which + a pod of the set of pods is running + properties: + labelSelector: + description: |- + A label query over a set of resources, in this case pods. + If it's null, this PodAffinityTerm matches with no Pods. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + matchLabelKeys: + description: |- + MatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both matchLabelKeys and labelSelector. + Also, matchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + mismatchLabelKeys: + description: |- + MismatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. + Also, mismatchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + namespaceSelector: + description: |- + A label query over the set of namespaces that the term applies to. + The term is applied to the union of the namespaces selected by this field + and the ones listed in the namespaces field. + null selector and null or empty namespaces list means "this pod's namespace". + An empty selector ({}) matches all namespaces. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + namespaces: + description: |- + namespaces specifies a static list of namespace names that the term applies to. + The term is applied to the union of the namespaces listed in this field + and the ones selected by namespaceSelector. + null or empty namespaces list and null namespaceSelector means "this pod's namespace". + items: + type: string + type: array + x-kubernetes-list-type: atomic + topologyKey: + description: |- + This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching + the labelSelector in the specified namespaces, where co-located is defined as running on a node + whose value of the label with key topologyKey matches that of any node on which any of the + selected pods is running. + Empty topologyKey is not allowed. + type: string + required: + - topologyKey + type: object + type: array + x-kubernetes-list-type: atomic + type: object + enablePodAntiAffinity: + description: |- + Activates anti-affinity for the pods. The operator will define pods + anti-affinity unless this field is explicitly set to false + type: boolean + nodeAffinity: + description: |- + NodeAffinity describes node affinity scheduling rules for the pod. + More info: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity + properties: + preferredDuringSchedulingIgnoredDuringExecution: + description: |- + The scheduler will prefer to schedule pods to nodes that satisfy + the affinity expressions specified by this field, but it may choose + a node that violates one or more of the expressions. The node that is + most preferred is the one with the greatest sum of weights, i.e. + for each node that meets all of the scheduling requirements (resource + request, requiredDuringScheduling affinity expressions, etc.), + compute a sum by iterating through the elements of this field and adding + "weight" to the sum if the node matches the corresponding matchExpressions; the + node(s) with the highest sum are the most preferred. + items: + description: |- + An empty preferred scheduling term matches all objects with implicit weight 0 + (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op). + properties: + preference: + description: A node selector term, associated with the + corresponding weight. + properties: + matchExpressions: + description: A list of node selector requirements + by node's labels. + items: + description: |- + A node selector requirement is a selector that contains values, a key, and an operator + that relates the key and values. + properties: + key: + description: The label key that the selector + applies to. + type: string + operator: + description: |- + Represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. + type: string + values: + description: |- + An array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. If the operator is Gt or Lt, the values + array must have a single element, which will be interpreted as an integer. + This array is replaced during a strategic merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchFields: + description: A list of node selector requirements + by node's fields. + items: + description: |- + A node selector requirement is a selector that contains values, a key, and an operator + that relates the key and values. + properties: + key: + description: The label key that the selector + applies to. + type: string + operator: + description: |- + Represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. + type: string + values: + description: |- + An array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. If the operator is Gt or Lt, the values + array must have a single element, which will be interpreted as an integer. + This array is replaced during a strategic merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + type: object + x-kubernetes-map-type: atomic + weight: + description: Weight associated with matching the corresponding + nodeSelectorTerm, in the range 1-100. + format: int32 + type: integer + required: + - preference + - weight + type: object + type: array + x-kubernetes-list-type: atomic + requiredDuringSchedulingIgnoredDuringExecution: + description: |- + If the affinity requirements specified by this field are not met at + scheduling time, the pod will not be scheduled onto the node. + If the affinity requirements specified by this field cease to be met + at some point during pod execution (e.g. due to an update), the system + may or may not try to eventually evict the pod from its node. + properties: + nodeSelectorTerms: + description: Required. A list of node selector terms. + The terms are ORed. + items: + description: |- + A null or empty node selector term matches no objects. The requirements of + them are ANDed. + The TopologySelectorTerm type implements a subset of the NodeSelectorTerm. + properties: + matchExpressions: + description: A list of node selector requirements + by node's labels. + items: + description: |- + A node selector requirement is a selector that contains values, a key, and an operator + that relates the key and values. + properties: + key: + description: The label key that the selector + applies to. + type: string + operator: + description: |- + Represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. + type: string + values: + description: |- + An array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. If the operator is Gt or Lt, the values + array must have a single element, which will be interpreted as an integer. + This array is replaced during a strategic merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchFields: + description: A list of node selector requirements + by node's fields. + items: + description: |- + A node selector requirement is a selector that contains values, a key, and an operator + that relates the key and values. + properties: + key: + description: The label key that the selector + applies to. + type: string + operator: + description: |- + Represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. + type: string + values: + description: |- + An array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. If the operator is Gt or Lt, the values + array must have a single element, which will be interpreted as an integer. + This array is replaced during a strategic merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + type: object + x-kubernetes-map-type: atomic + type: array + x-kubernetes-list-type: atomic + required: + - nodeSelectorTerms + type: object + x-kubernetes-map-type: atomic + type: object + nodeSelector: + additionalProperties: + type: string + description: |- + NodeSelector is map of key-value pairs used to define the nodes on which + the pods can run. + More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/ + type: object + podAntiAffinityType: + description: |- + PodAntiAffinityType allows the user to decide whether pod anti-affinity between cluster instance has to be + considered a strong requirement during scheduling or not. Allowed values are: "preferred" (default if empty) or + "required". Setting it to "required", could lead to instances remaining pending until new kubernetes nodes are + added if all the existing nodes don't match the required pod anti-affinity rule. + More info: + https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#inter-pod-affinity-and-anti-affinity + type: string + tolerations: + description: |- + Tolerations is a list of Tolerations that should be set for all the pods, in order to allow them to run + on tainted nodes. + More info: https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/ + items: + description: |- + The pod this Toleration is attached to tolerates any taint that matches + the triple using the matching operator . + properties: + effect: + description: |- + Effect indicates the taint effect to match. Empty means match all taint effects. + When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute. + type: string + key: + description: |- + Key is the taint key that the toleration applies to. Empty means match all taint keys. + If the key is empty, operator must be Exists; this combination means to match all values and all keys. + type: string + operator: + description: |- + Operator represents a key's relationship to the value. + Valid operators are Exists, Equal, Lt, and Gt. Defaults to Equal. + Exists is equivalent to wildcard for value, so that a pod can + tolerate all taints of a particular category. + Lt and Gt perform numeric comparisons (requires feature gate TaintTolerationComparisonOperators). + type: string + tolerationSeconds: + description: |- + TolerationSeconds represents the period of time the toleration (which must be + of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, + it is not set, which means tolerate the taint forever (do not evict). Zero and + negative values will be treated as 0 (evict immediately) by the system. + format: int64 + type: integer + value: + description: |- + Value is the taint value the toleration matches to. + If the operator is Exists, the value should be empty, otherwise just a regular string. + type: string + type: object + type: array + topologyKey: + description: |- + TopologyKey to use for anti-affinity configuration. See k8s documentation + for more info on that + type: string + type: object + backup: + description: Backup configures backup settings for DocumentDB. + properties: + retentionDays: + default: 30 + description: |- + RetentionDays specifies how many days backups should be retained. + If not specified, the default retention period is 30 days. + maximum: 365 + minimum: 1 + type: integer + type: object + bootstrap: + description: Bootstrap configures the initialization of the DocumentDB + cluster. + properties: + recovery: + description: Recovery configures recovery from a backup. + properties: + backup: + description: Backup specifies the source backup to restore + from. + properties: + name: + description: Name of the referent. + type: string + required: + - name + type: object + persistentVolume: + description: |- + PersistentVolume specifies the PV to restore from. + The operator will create a temporary PVC bound to this PV, use it for CNPG recovery, + and delete the temporary PVC after the cluster is healthy. + Cannot be used together with Backup. + properties: + name: + description: |- + Name is the name of the PersistentVolume to recover from. + The PV must exist and be in Available or Released state. + minLength: 1 + type: string + required: + - name + type: object + type: object + x-kubernetes-validations: + - message: cannot specify both backup and persistentVolume recovery + at the same time + rule: '!(has(self.backup) && size(self.backup.name) > 0 && has(self.persistentVolume) + && size(self.persistentVolume.name) > 0)' + type: object + clusterReplication: + description: ClusterReplication configures cross-cluster replication + for DocumentDB. + properties: + clusterList: + description: ClusterList is the list of clusters participating + in replication. + items: + properties: + environment: + description: |- + EnvironmentOverride is the cloud environment of the member cluster. + Will default to the global setting + enum: + - eks + - aks + - gke + type: string + name: + description: Name is the name of the member cluster. + type: string + storageClass: + description: StorageClassOverride specifies the storage + class for DocumentDB persistent volumes in this member + cluster. + type: string + required: + - name + type: object + type: array + crossCloudNetworkingStrategy: + description: CrossCloudNetworking determines which type of networking + mechanics for the replication + enum: + - AzureFleet + - Istio + - None + type: string + disableTLS: + default: false + description: |- + Disables TLS for replication traffic between clusters. + Only for use when an existing mesh is already providing TLS. + type: boolean + highAvailability: + description: Whether or not to have replicas on the primary cluster. + type: boolean + primary: + description: Primary is the name of the primary cluster for replication. + type: string + required: + - clusterList + - primary + type: object + documentDBVersion: + description: |- + DocumentDBVersion specifies the version for all DocumentDB components (engine, gateway). + When set, this overrides the default versions for image.documentDB and image.gateway. + Individual image fields under spec.image take precedence over this version. + type: string + documentDbCredentialSecret: + description: |- + DocumentDbCredentialSecret is the name of the Kubernetes Secret containing credentials + for the DocumentDB gateway (expects keys `username` and `password`). If omitted, + a default secret name `documentdb-credentials` is used. + + NOTE: Immutable today; will be relaxed in a future release to support credential rotation. + type: string + x-kubernetes-validations: + - message: credential secret cannot be changed after cluster creation + rule: self == oldSelf + environment: + description: |- + Environment specifies the cloud environment for deployment + This determines cloud-specific service annotations for LoadBalancer services + enum: + - eks + - aks + - gke + type: string + exposeViaService: + description: |- + ExposeViaService configures how to expose DocumentDB via a Kubernetes service. + This can be a LoadBalancer or ClusterIP service. + properties: + serviceType: + description: ServiceType determines the type of service to expose + for DocumentDB. + enum: + - LoadBalancer + - ClusterIP + type: string + required: + - serviceType + type: object + featureGates: + additionalProperties: + type: boolean + description: |- + FeatureGates enables or disables optional DocumentDB features. + Keys are PascalCase feature names following the Kubernetes feature gate convention. + Example: {"ChangeStreams": true} + + IMPORTANT: When adding a new feature gate, update ALL of the following: + 1. Add a new FeatureGate* constant in documentdb_types.go + 2. Add the key name to the XValidation CEL rule's allowed list below + 3. Add a default entry in the featureGateDefaults map in documentdb_types.go + type: object + x-kubernetes-validations: + - message: 'unsupported feature gate key; allowed keys: ChangeStreams, + IOUring' + rule: self.all(key, key in ['ChangeStreams', 'IOUring']) + image: + description: |- + Image groups container image settings for the DocumentDB stack + (extension image, gateway image, PostgreSQL image). + All fields are optional; sensible defaults are applied when omitted. + properties: + documentDB: + description: |- + DocumentDB is the container image for the DocumentDB extension layer. + This image is mounted into the PostgreSQL container via CNPG's + ImageVolumeSource so that the extension files are available alongside + an upstream PostgreSQL image. + type: string + gateway: + description: Gateway is the container image for the DocumentDB + Gateway sidecar. + type: string + postgres: + default: ghcr.io/cloudnative-pg/postgresql:18-minimal-trixie + description: |- + Postgres is the container image for the PostgreSQL server. + Must be an upstream CNPG-compatible PostgreSQL image (the operator + adds the DocumentDB extension via an ImageVolume mount), and must + use trixie (Debian 13) base to match the extension's GLIBC + requirements. + + The default floats within PostgreSQL major 18 via CNPG's + "18-minimal-trixie" tag, so deployments pick up new 18.x minors and + Debian/PGDG security rebuilds automatically. + + The floating tag currently resolves to PG 18.6+, which is only safe + for DocumentDB extension >= 0.116.0: older extensions segfault on + insert under PG 18.6 (fixed upstream in documentdb/documentdb 3555c7d, + first released in 0.116.0). Keep the default documentDbVersion, and any + version pair exercised against this default, at >= 0.116.0. + type: string + type: object + imagePullSecrets: + description: |- + ImagePullSecrets is an optional list of references to secrets in the same namespace + to use for pulling any of the images used by this cluster. Passed through to the + underlying CloudNative-PG cluster. + items: + description: |- + LocalObjectReference contains enough information to let you locate the + referenced object inside the same namespace. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + type: array + instancesPerNode: + description: 'InstancesPerNode is the number of DocumentDB instances + per node. Range: 1-3.' + maximum: 3 + minimum: 1 + type: integer + logLevel: + description: Overrides default log level for the DocumentDB cluster. + type: string + monitoring: + description: Monitoring configures observability via an OTel Collector + sidecar. + properties: + enabled: + description: Enabled turns on the OTel Collector sidecar for metrics + collection. + type: boolean + exporter: + description: Exporter configures where metrics are sent. + properties: + otlp: + description: OTLP configures the OpenTelemetry Protocol exporter. + properties: + endpoint: + description: Endpoint is the OTLP gRPC endpoint (e.g., + "otel-collector.monitoring:4317"). + type: string + required: + - endpoint + type: object + prometheus: + description: Prometheus configures a Prometheus scrape endpoint + on the OTel Collector sidecar. + properties: + port: + default: 8888 + description: Port for the Prometheus scrape endpoint. + Defaults to 8888. + format: int32 + maximum: 65535 + minimum: 1024 + type: integer + type: object + type: object + type: object + nodeCount: + description: NodeCount is the number of nodes in the DocumentDB cluster. + Must be 1. + maximum: 1 + minimum: 1 + type: integer + plugins: + description: |- + Plugins groups CNPG plugin configuration (sidecar injector name, WAL replica name). + All fields are optional; defaults are preserved when omitted. + properties: + sidecarInjectorName: + description: |- + SidecarInjectorName is the name of the CNPG sidecar injector plugin + to use for the gateway and other sidecars. Immutable. + type: string + x-kubernetes-validations: + - message: sidecar injector plugin name cannot be changed after + cluster creation + rule: self == oldSelf + walReplicaName: + description: |- + WalReplicaName is the name of the WAL replica plugin to use for + cross-cluster replication. + type: string + type: object + postgres: + description: |- + Postgres groups PostgreSQL process-level tuning (UID/GID, custom post-init SQL). + All fields are optional; defaults are preserved when omitted. + properties: + gid: + description: |- + GID is the numeric group ID under which the PostgreSQL server process runs. + When set, UID must also be set. + format: int64 + type: integer + parameters: + additionalProperties: + type: string + description: |- + Parameters allows users to override PostgreSQL configuration parameters + (postgresql.conf settings) passed through to the underlying CNPG Cluster. + The operator applies memory-aware defaults (shared_buffers, effective_cache_size, + work_mem, maintenance_work_mem) computed from the pod memory limit, plus static + best-practice defaults for autovacuum, IO, WAL, and connection settings. + Values specified here override computed and static defaults. + Protected parameters (cron.database_name, max_replication_slots, max_wal_senders, + max_prepared_transactions) cannot be overridden. + type: object + postInitSQL: + description: |- + PostInitSQL is an ordered list of SQL statements executed after the + cluster is initialized. These statements run AFTER the operator's + mandatory bootstrap (CREATE EXTENSION documentdb, CREATE ROLE + documentdb, ALTER ROLE documentdb), so they can safely reference the + documentdb extension and role. + items: + type: string + type: array + uid: + description: |- + UID is the numeric user ID under which the PostgreSQL server process runs. + When set, GID must also be set. + format: int64 + type: integer + type: object + x-kubernetes-validations: + - message: uid and gid must be set together + rule: has(self.uid) == has(self.gid) + resource: + description: Resource specifies the storage resources for DocumentDB. + properties: + cpu: + description: |- + CPU specifies the total CPU envelope for each DocumentDB instance pod. + The operator divides this envelope across PostgreSQL, the documentdb-gateway + sidecar, and, when monitoring is enabled, the OTel collector sidecar. + PostgreSQL receives the remainder after gateway and OTel CPU reservations; + an explicit per-container CPU override wins over the automatic carve-out. + If not specified or set to "0", no CPU envelope is applied. + Examples: "2", "4", "500m" + type: string + database: + description: |- + Database optionally overrides the resources allocated to the PostgreSQL + container. When unset, PostgreSQL receives the pod memory and CPU envelopes + minus the gateway and (when monitoring is enabled) OTel collector carve-outs. + properties: + cpu: + description: CPU is the CPU request=limit for the container + (e.g. "500m", "2"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + memory: + description: Memory is the memory request=limit for the container + (e.g. "512Mi", "2Gi"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + type: object + gateway: + description: |- + Gateway optionally overrides the resources allocated to the + documentdb-gateway sidecar container. When unset, the operator derives the + gateway's memory as min(gatewayMemoryFraction × memory, gatewayMemoryCap) + and carves it out of the pod memory envelope. The value is applied as both + the request and the limit (Guaranteed-class) so a gateway leak is + OOM-isolated and cannot crowd out PostgreSQL. + properties: + cpu: + description: CPU is the CPU request=limit for the container + (e.g. "500m", "2"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + memory: + description: Memory is the memory request=limit for the container + (e.g. "512Mi", "2Gi"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + type: object + memory: + description: |- + Memory specifies the memory limit for each DocumentDB instance pod. + This value is passed to the CNPG Cluster's spec.resources.limits.memory + and spec.resources.requests.memory (Guaranteed QoS). + Memory-aware PostgreSQL parameters (shared_buffers, effective_cache_size, etc.) + are auto-computed from this value. + If not specified or set to "0", no memory limit is applied and static + defaults are used for memory-aware parameters. + Examples: "2Gi", "4Gi", "8Gi" + type: string + otel: + description: |- + OTel optionally overrides the resources allocated to the otel-collector + sidecar container (only present when spec.monitoring.enabled is true). + When unset, the operator applies built-in defaults: memory request 48Mi / + limit 128Mi and CPU request 50m / limit 200m (Burstable — the requests are + the reserved floor and the limits cap a telemetry burst). Setting otel.cpu + or otel.memory pins that dimension to request == limit (Guaranteed). + properties: + cpu: + description: CPU is the CPU request=limit for the container + (e.g. "500m", "2"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + memory: + description: Memory is the memory request=limit for the container + (e.g. "512Mi", "2Gi"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + type: object + storage: + description: Storage configuration for DocumentDB persistent volumes. + properties: + persistentVolumeReclaimPolicy: + default: Retain + description: |- + PersistentVolumeReclaimPolicy controls what happens to the PersistentVolume when + the DocumentDB cluster is deleted. + + When a DocumentDB cluster is deleted, the following chain of deletions occurs: + DocumentDB deletion → CNPG Cluster deletion → PVC deletion → PV deletion (based on this policy) + + Options: + - Retain (default): The PV is preserved after cluster deletion, allowing manual + data recovery or forensic analysis. Use for production workloads where data + safety is critical. Orphaned PVs must be manually deleted when no longer needed. + - Delete: The PV is automatically deleted when the PVC is deleted. Use for development, + testing, or ephemeral environments where data persistence is not required. + + WARNING: Setting this to "Delete" means all data will be permanently lost when + the DocumentDB cluster is deleted. This cannot be undone. + enum: + - Retain + - Delete + type: string + pvcSize: + description: PvcSize is the size of the persistent volume + claim for DocumentDB storage (e.g., "10Gi"). + minLength: 1 + type: string + storageClass: + description: |- + StorageClass specifies the storage class for DocumentDB persistent volumes. + If not specified, the cluster's default storage class will be used. + type: string + x-kubernetes-validations: + - message: storage class cannot be changed after cluster creation + rule: self == oldSelf + required: + - pvcSize + type: object + required: + - storage + type: object + schemaVersion: + description: |- + SchemaVersion controls the desired schema version for the DocumentDB extension. + + The operator never changes your database schema unless you ask: + - Set schemaVersion → updates the database schema (irreversible) + - Set schemaVersion: "auto" → schema auto-updates with binary + + Once the schema has been updated, the operator blocks image rollback below the + installed schema version to prevent running an untested binary/schema combination. + + Values: + - "" (empty, default): Two-phase mode. Image upgrades happen automatically, + but ALTER EXTENSION UPDATE does NOT run. Users must explicitly set this + field to finalize the schema upgrade. This is the safest option for production + as it allows rollback by reverting the image before committing the schema change. + - "auto": Schema automatically updates to match the binary version whenever + the binary is upgraded. This is the simplest mode but provides no rollback + safety window. Only recommended for single-region clusters. + - "" (e.g. "0.112.0"): Schema updates to exactly this version. + Must be <= the binary version. + pattern: ^(auto|[0-9]+\.[0-9]+\.[0-9]+)?$ + type: string + timeouts: + properties: + stopDelay: + format: int32 + maximum: 1800 + minimum: 0 + type: integer + type: object + tls: + description: TLS configures certificate management for DocumentDB + components. + properties: + gateway: + description: 'Gateway configures TLS for the gateway sidecar (Phase + 1: certificate provisioning only).' + properties: + certManager: + description: CertManager config when Mode=CertManager. + properties: + dnsNames: + description: DNSNames for the certificate SANs. If empty, + operator will add Service DNS names. + items: + type: string + type: array + issuerRef: + description: IssuerRef references a cert-manager Issuer + or ClusterIssuer. + properties: + group: + description: Group defaults to cert-manager.io + type: string + kind: + description: Kind of issuer (Issuer or ClusterIssuer). + Defaults to Issuer. + type: string + name: + type: string + required: + - name + type: object + secretName: + description: SecretName optional explicit name for the + target secret. If empty a default is chosen. + type: string + required: + - issuerRef + type: object + mode: + default: SelfSigned + description: |- + Mode selects the TLS management strategy. + Defaults to SelfSigned if not specified. + enum: + - SelfSigned + - CertManager + - Provided + type: string + provided: + description: Provided secret reference when Mode=Provided. + properties: + secretName: + type: string + required: + - secretName + type: object + type: object + globalEndpoints: + description: GlobalEndpoints configures TLS for global endpoints + (placeholder for future phases). + type: object + postgres: + description: |- + Postgres configures TLS for the Postgres server. + If server side certs are provided alone, the operator will use sslMode=require for cross-regional replication connections. + If replication certs are also provided, the operator will use verify-full, which requires the hostname to be correctly set. + See the multi-region-deployment docs for how to do that. + properties: + clientCASecret: + description: |- + The secret containing the Client CA certificate. If not defined, a new secret will be created + with a self-signed CA and will be used to generate all the client certificates.
+
+ Contains:
+
+ - `ca.crt`: CA that should be used to validate the client certificates, + used as `ssl_ca_file` of all the instances.
+ - `ca.key`: key used to generate client certificates, if ReplicationTLSSecret is provided, + this can be omitted.
+ type: string + replicationTLSSecret: + description: |- + The secret of type kubernetes.io/tls containing the client certificate to authenticate as + the `streaming_replica` user. + If not defined, ClientCASecret must provide also `ca.key`, and a new secret will be + created using the provided CA. + type: string + serverAltDNSNames: + description: The list of the server alternative DNS names + to be added to the generated server TLS certificates, when + required. + items: + type: string + type: array + serverCASecret: + description: |- + The secret containing the Server CA certificate. If not defined, a new secret will be created + with a self-signed CA and will be used to generate the TLS certificate ServerTLSSecret.
+
+ Contains:
+
+ - `ca.crt`: CA that should be used to validate the server certificate, + used as `sslrootcert` in client connection strings.
+ - `ca.key`: key used to generate Server SSL certs, if ServerTLSSecret is provided, + this can be omitted.
+ type: string + serverTLSSecret: + description: |- + The secret of type kubernetes.io/tls containing the server TLS certificate and key that will be set as + `ssl_cert_file` and `ssl_key_file` so that clients can connect to postgres securely. + If not defined, ServerCASecret must provide also `ca.key` and a new secret will be + created using the provided CA. + type: string + type: object + type: object + x-kubernetes-validations: + - message: spec.tls.postgres replicationTLSSecret and clientCASecret + must be provided together; serverTLSSecret and serverCASecret + must be provided together; serverTLSSecret requires replicationTLSSecret + rule: '!has(self.postgres) || (has(self.postgres.replicationTLSSecret) + == has(self.postgres.clientCASecret) && has(self.postgres.serverTLSSecret) + == has(self.postgres.serverCASecret) && (!has(self.postgres.serverTLSSecret) + || has(self.postgres.replicationTLSSecret)))' + required: + - instancesPerNode + - nodeCount + - resource + type: object + x-kubernetes-validations: + - message: when spec.clusterReplication is set, either spec.clusterReplication.disableTLS + must be true or spec.tls.postgres.replicationTLSSecret and spec.tls.postgres.clientCASecret + must be provided + rule: '!has(self.clusterReplication) || ((has(self.clusterReplication.disableTLS) + && self.clusterReplication.disableTLS) || (has(self.tls) && has(self.tls.postgres) + && has(self.tls.postgres.replicationTLSSecret) && has(self.tls.postgres.clientCASecret)))' + status: + description: DocumentDBStatus defines the observed state of DocumentDB. + properties: + connectionString: + type: string + documentDBImage: + description: DocumentDBImage is the extension image URI currently + applied to the cluster. + type: string + gatewayImage: + description: GatewayImage is the gateway sidecar image URI currently + applied to the cluster. + type: string + localPrimary: + type: string + schemaVersion: + description: SchemaVersion is the currently installed schema version + of the DocumentDB extension. + type: string + status: + description: Status reflects the status field from the underlying + CNPG Cluster. + type: string + targetPrimary: + type: string + tls: + description: TLS reports gateway TLS provisioning status (Phase 1). + properties: + message: + type: string + ready: + type: boolean + secretName: + type: string + type: object + type: object + type: object + served: true + storage: false + subresources: + status: {} + - additionalPrinterColumns: + - description: CNPG Cluster Status + jsonPath: .status.status + name: Status + type: string + - description: DocumentDB Connection String + jsonPath: .status.connectionString + name: Connection String + type: string + name: v1 + schema: + openAPIV3Schema: + description: DocumentDB is the Schema for the dbs API. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: DocumentDBSpec defines the desired state of DocumentDB. + properties: + affinity: + description: Affinity/Anti-affinity rules for Pods (cnpg passthrough) + properties: + additionalPodAffinity: + description: AdditionalPodAffinity allows to specify pod affinity + terms to be passed to all the cluster's pods. + properties: + preferredDuringSchedulingIgnoredDuringExecution: + description: |- + The scheduler will prefer to schedule pods to nodes that satisfy + the affinity expressions specified by this field, but it may choose + a node that violates one or more of the expressions. The node that is + most preferred is the one with the greatest sum of weights, i.e. + for each node that meets all of the scheduling requirements (resource + request, requiredDuringScheduling affinity expressions, etc.), + compute a sum by iterating through the elements of this field and adding + "weight" to the sum if the node has pods which matches the corresponding podAffinityTerm; the + node(s) with the highest sum are the most preferred. + items: + description: The weights of all of the matched WeightedPodAffinityTerm + fields are added per-node to find the most preferred node(s) + properties: + podAffinityTerm: + description: Required. A pod affinity term, associated + with the corresponding weight. + properties: + labelSelector: + description: |- + A label query over a set of resources, in this case pods. + If it's null, this PodAffinityTerm matches with no Pods. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are + ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that + the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + matchLabelKeys: + description: |- + MatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both matchLabelKeys and labelSelector. + Also, matchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + mismatchLabelKeys: + description: |- + MismatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. + Also, mismatchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + namespaceSelector: + description: |- + A label query over the set of namespaces that the term applies to. + The term is applied to the union of the namespaces selected by this field + and the ones listed in the namespaces field. + null selector and null or empty namespaces list means "this pod's namespace". + An empty selector ({}) matches all namespaces. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are + ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that + the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + namespaces: + description: |- + namespaces specifies a static list of namespace names that the term applies to. + The term is applied to the union of the namespaces listed in this field + and the ones selected by namespaceSelector. + null or empty namespaces list and null namespaceSelector means "this pod's namespace". + items: + type: string + type: array + x-kubernetes-list-type: atomic + topologyKey: + description: |- + This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching + the labelSelector in the specified namespaces, where co-located is defined as running on a node + whose value of the label with key topologyKey matches that of any node on which any of the + selected pods is running. + Empty topologyKey is not allowed. + type: string + required: + - topologyKey + type: object + weight: + description: |- + weight associated with matching the corresponding podAffinityTerm, + in the range 1-100. + format: int32 + type: integer + required: + - podAffinityTerm + - weight + type: object + type: array + x-kubernetes-list-type: atomic + requiredDuringSchedulingIgnoredDuringExecution: + description: |- + If the affinity requirements specified by this field are not met at + scheduling time, the pod will not be scheduled onto the node. + If the affinity requirements specified by this field cease to be met + at some point during pod execution (e.g. due to a pod label update), the + system may or may not try to eventually evict the pod from its node. + When there are multiple elements, the lists of nodes corresponding to each + podAffinityTerm are intersected, i.e. all terms must be satisfied. + items: + description: |- + Defines a set of pods (namely those matching the labelSelector + relative to the given namespace(s)) that this pod should be + co-located (affinity) or not co-located (anti-affinity) with, + where co-located is defined as running on a node whose value of + the label with key matches that of any node on which + a pod of the set of pods is running + properties: + labelSelector: + description: |- + A label query over a set of resources, in this case pods. + If it's null, this PodAffinityTerm matches with no Pods. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + matchLabelKeys: + description: |- + MatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both matchLabelKeys and labelSelector. + Also, matchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + mismatchLabelKeys: + description: |- + MismatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. + Also, mismatchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + namespaceSelector: + description: |- + A label query over the set of namespaces that the term applies to. + The term is applied to the union of the namespaces selected by this field + and the ones listed in the namespaces field. + null selector and null or empty namespaces list means "this pod's namespace". + An empty selector ({}) matches all namespaces. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + namespaces: + description: |- + namespaces specifies a static list of namespace names that the term applies to. + The term is applied to the union of the namespaces listed in this field + and the ones selected by namespaceSelector. + null or empty namespaces list and null namespaceSelector means "this pod's namespace". + items: + type: string + type: array + x-kubernetes-list-type: atomic + topologyKey: + description: |- + This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching + the labelSelector in the specified namespaces, where co-located is defined as running on a node + whose value of the label with key topologyKey matches that of any node on which any of the + selected pods is running. + Empty topologyKey is not allowed. + type: string + required: + - topologyKey + type: object + type: array + x-kubernetes-list-type: atomic + type: object + additionalPodAntiAffinity: + description: |- + AdditionalPodAntiAffinity allows to specify pod anti-affinity terms to be added to the ones generated + by the operator if EnablePodAntiAffinity is set to true (default) or to be used exclusively if set to false. + properties: + preferredDuringSchedulingIgnoredDuringExecution: + description: |- + The scheduler will prefer to schedule pods to nodes that satisfy + the anti-affinity expressions specified by this field, but it may choose + a node that violates one or more of the expressions. The node that is + most preferred is the one with the greatest sum of weights, i.e. + for each node that meets all of the scheduling requirements (resource + request, requiredDuringScheduling anti-affinity expressions, etc.), + compute a sum by iterating through the elements of this field and subtracting + "weight" from the sum if the node has pods which matches the corresponding podAffinityTerm; the + node(s) with the highest sum are the most preferred. + items: + description: The weights of all of the matched WeightedPodAffinityTerm + fields are added per-node to find the most preferred node(s) + properties: + podAffinityTerm: + description: Required. A pod affinity term, associated + with the corresponding weight. + properties: + labelSelector: + description: |- + A label query over a set of resources, in this case pods. + If it's null, this PodAffinityTerm matches with no Pods. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are + ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that + the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + matchLabelKeys: + description: |- + MatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both matchLabelKeys and labelSelector. + Also, matchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + mismatchLabelKeys: + description: |- + MismatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. + Also, mismatchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + namespaceSelector: + description: |- + A label query over the set of namespaces that the term applies to. + The term is applied to the union of the namespaces selected by this field + and the ones listed in the namespaces field. + null selector and null or empty namespaces list means "this pod's namespace". + An empty selector ({}) matches all namespaces. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are + ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that + the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + namespaces: + description: |- + namespaces specifies a static list of namespace names that the term applies to. + The term is applied to the union of the namespaces listed in this field + and the ones selected by namespaceSelector. + null or empty namespaces list and null namespaceSelector means "this pod's namespace". + items: + type: string + type: array + x-kubernetes-list-type: atomic + topologyKey: + description: |- + This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching + the labelSelector in the specified namespaces, where co-located is defined as running on a node + whose value of the label with key topologyKey matches that of any node on which any of the + selected pods is running. + Empty topologyKey is not allowed. + type: string + required: + - topologyKey + type: object + weight: + description: |- + weight associated with matching the corresponding podAffinityTerm, + in the range 1-100. + format: int32 + type: integer + required: + - podAffinityTerm + - weight + type: object + type: array + x-kubernetes-list-type: atomic + requiredDuringSchedulingIgnoredDuringExecution: + description: |- + If the anti-affinity requirements specified by this field are not met at + scheduling time, the pod will not be scheduled onto the node. + If the anti-affinity requirements specified by this field cease to be met + at some point during pod execution (e.g. due to a pod label update), the + system may or may not try to eventually evict the pod from its node. + When there are multiple elements, the lists of nodes corresponding to each + podAffinityTerm are intersected, i.e. all terms must be satisfied. + items: + description: |- + Defines a set of pods (namely those matching the labelSelector + relative to the given namespace(s)) that this pod should be + co-located (affinity) or not co-located (anti-affinity) with, + where co-located is defined as running on a node whose value of + the label with key matches that of any node on which + a pod of the set of pods is running + properties: + labelSelector: + description: |- + A label query over a set of resources, in this case pods. + If it's null, this PodAffinityTerm matches with no Pods. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + matchLabelKeys: + description: |- + MatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both matchLabelKeys and labelSelector. + Also, matchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + mismatchLabelKeys: + description: |- + MismatchLabelKeys is a set of pod label keys to select which pods will + be taken into consideration. The keys are used to lookup values from the + incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` + to select the group of existing pods which pods will be taken into consideration + for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming + pod labels will be ignored. The default value is empty. + The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. + Also, mismatchLabelKeys cannot be set when labelSelector isn't set. + items: + type: string + type: array + x-kubernetes-list-type: atomic + namespaceSelector: + description: |- + A label query over the set of namespaces that the term applies to. + The term is applied to the union of the namespaces selected by this field + and the ones listed in the namespaces field. + null selector and null or empty namespaces list means "this pod's namespace". + An empty selector ({}) matches all namespaces. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + namespaces: + description: |- + namespaces specifies a static list of namespace names that the term applies to. + The term is applied to the union of the namespaces listed in this field + and the ones selected by namespaceSelector. + null or empty namespaces list and null namespaceSelector means "this pod's namespace". + items: + type: string + type: array + x-kubernetes-list-type: atomic + topologyKey: + description: |- + This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching + the labelSelector in the specified namespaces, where co-located is defined as running on a node + whose value of the label with key topologyKey matches that of any node on which any of the + selected pods is running. + Empty topologyKey is not allowed. + type: string + required: + - topologyKey + type: object + type: array + x-kubernetes-list-type: atomic + type: object + enablePodAntiAffinity: + description: |- + Activates anti-affinity for the pods. The operator will define pods + anti-affinity unless this field is explicitly set to false + type: boolean + nodeAffinity: + description: |- + NodeAffinity describes node affinity scheduling rules for the pod. + More info: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity + properties: + preferredDuringSchedulingIgnoredDuringExecution: + description: |- + The scheduler will prefer to schedule pods to nodes that satisfy + the affinity expressions specified by this field, but it may choose + a node that violates one or more of the expressions. The node that is + most preferred is the one with the greatest sum of weights, i.e. + for each node that meets all of the scheduling requirements (resource + request, requiredDuringScheduling affinity expressions, etc.), + compute a sum by iterating through the elements of this field and adding + "weight" to the sum if the node matches the corresponding matchExpressions; the + node(s) with the highest sum are the most preferred. + items: + description: |- + An empty preferred scheduling term matches all objects with implicit weight 0 + (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op). + properties: + preference: + description: A node selector term, associated with the + corresponding weight. + properties: + matchExpressions: + description: A list of node selector requirements + by node's labels. + items: + description: |- + A node selector requirement is a selector that contains values, a key, and an operator + that relates the key and values. + properties: + key: + description: The label key that the selector + applies to. + type: string + operator: + description: |- + Represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. + type: string + values: + description: |- + An array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. If the operator is Gt or Lt, the values + array must have a single element, which will be interpreted as an integer. + This array is replaced during a strategic merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchFields: + description: A list of node selector requirements + by node's fields. + items: + description: |- + A node selector requirement is a selector that contains values, a key, and an operator + that relates the key and values. + properties: + key: + description: The label key that the selector + applies to. + type: string + operator: + description: |- + Represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. + type: string + values: + description: |- + An array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. If the operator is Gt or Lt, the values + array must have a single element, which will be interpreted as an integer. + This array is replaced during a strategic merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + type: object + x-kubernetes-map-type: atomic + weight: + description: Weight associated with matching the corresponding + nodeSelectorTerm, in the range 1-100. + format: int32 + type: integer + required: + - preference + - weight + type: object + type: array + x-kubernetes-list-type: atomic + requiredDuringSchedulingIgnoredDuringExecution: + description: |- + If the affinity requirements specified by this field are not met at + scheduling time, the pod will not be scheduled onto the node. + If the affinity requirements specified by this field cease to be met + at some point during pod execution (e.g. due to an update), the system + may or may not try to eventually evict the pod from its node. + properties: + nodeSelectorTerms: + description: Required. A list of node selector terms. + The terms are ORed. + items: + description: |- + A null or empty node selector term matches no objects. The requirements of + them are ANDed. + The TopologySelectorTerm type implements a subset of the NodeSelectorTerm. + properties: + matchExpressions: + description: A list of node selector requirements + by node's labels. + items: + description: |- + A node selector requirement is a selector that contains values, a key, and an operator + that relates the key and values. + properties: + key: + description: The label key that the selector + applies to. + type: string + operator: + description: |- + Represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. + type: string + values: + description: |- + An array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. If the operator is Gt or Lt, the values + array must have a single element, which will be interpreted as an integer. + This array is replaced during a strategic merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchFields: + description: A list of node selector requirements + by node's fields. + items: + description: |- + A node selector requirement is a selector that contains values, a key, and an operator + that relates the key and values. + properties: + key: + description: The label key that the selector + applies to. + type: string + operator: + description: |- + Represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. + type: string + values: + description: |- + An array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. If the operator is Gt or Lt, the values + array must have a single element, which will be interpreted as an integer. + This array is replaced during a strategic merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + type: object + x-kubernetes-map-type: atomic + type: array + x-kubernetes-list-type: atomic + required: + - nodeSelectorTerms + type: object + x-kubernetes-map-type: atomic + type: object + nodeSelector: + additionalProperties: + type: string + description: |- + NodeSelector is map of key-value pairs used to define the nodes on which + the pods can run. + More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/ + type: object + podAntiAffinityType: + description: |- + PodAntiAffinityType allows the user to decide whether pod anti-affinity between cluster instance has to be + considered a strong requirement during scheduling or not. Allowed values are: "preferred" (default if empty) or + "required". Setting it to "required", could lead to instances remaining pending until new kubernetes nodes are + added if all the existing nodes don't match the required pod anti-affinity rule. + More info: + https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#inter-pod-affinity-and-anti-affinity + type: string + tolerations: + description: |- + Tolerations is a list of Tolerations that should be set for all the pods, in order to allow them to run + on tainted nodes. + More info: https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/ + items: + description: |- + The pod this Toleration is attached to tolerates any taint that matches + the triple using the matching operator . + properties: + effect: + description: |- + Effect indicates the taint effect to match. Empty means match all taint effects. + When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute. + type: string + key: + description: |- + Key is the taint key that the toleration applies to. Empty means match all taint keys. + If the key is empty, operator must be Exists; this combination means to match all values and all keys. + type: string + operator: + description: |- + Operator represents a key's relationship to the value. + Valid operators are Exists, Equal, Lt, and Gt. Defaults to Equal. + Exists is equivalent to wildcard for value, so that a pod can + tolerate all taints of a particular category. + Lt and Gt perform numeric comparisons (requires feature gate TaintTolerationComparisonOperators). + type: string + tolerationSeconds: + description: |- + TolerationSeconds represents the period of time the toleration (which must be + of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, + it is not set, which means tolerate the taint forever (do not evict). Zero and + negative values will be treated as 0 (evict immediately) by the system. + format: int64 + type: integer + value: + description: |- + Value is the taint value the toleration matches to. + If the operator is Exists, the value should be empty, otherwise just a regular string. + type: string + type: object + type: array + topologyKey: + description: |- + TopologyKey to use for anti-affinity configuration. See k8s documentation + for more info on that + type: string + type: object + backup: + description: Backup configures backup settings for DocumentDB. + properties: + retentionDays: + default: 30 + description: |- + RetentionDays specifies how many days backups should be retained. + If not specified, the default retention period is 30 days. + maximum: 365 + minimum: 1 + type: integer + type: object + bootstrap: + description: Bootstrap configures the initialization of the DocumentDB + cluster. + properties: + recovery: + description: Recovery configures recovery from a backup. + properties: + backup: + description: Backup specifies the source backup to restore + from. + properties: + name: + description: Name of the referent. + type: string + required: + - name + type: object + persistentVolume: + description: |- + PersistentVolume specifies the PV to restore from. + The operator will create a temporary PVC bound to this PV, use it for CNPG recovery, + and delete the temporary PVC after the cluster is healthy. + Cannot be used together with Backup. + properties: + name: + description: |- + Name is the name of the PersistentVolume to recover from. + The PV must exist and be in Available or Released state. + minLength: 1 + type: string + required: + - name + type: object + type: object + x-kubernetes-validations: + - message: cannot specify both backup and persistentVolume recovery + at the same time + rule: '!(has(self.backup) && size(self.backup.name) > 0 && has(self.persistentVolume) + && size(self.persistentVolume.name) > 0)' + type: object + clusterReplication: + description: ClusterReplication configures cross-cluster replication + for DocumentDB. + properties: + clusterList: + description: ClusterList is the list of clusters participating + in replication. + items: + properties: + environment: + description: |- + EnvironmentOverride is the cloud environment of the member cluster. + Will default to the global setting + enum: + - eks + - aks + - gke + type: string + name: + description: Name is the name of the member cluster. + type: string + storageClass: + description: StorageClassOverride specifies the storage + class for DocumentDB persistent volumes in this member + cluster. + type: string + required: + - name + type: object + type: array + crossCloudNetworkingStrategy: + description: CrossCloudNetworking determines which type of networking + mechanics for the replication + enum: + - AzureFleet + - Istio + - None + type: string + disableTLS: + default: false + description: |- + Disables TLS for replication traffic between clusters. + Only for use when an existing mesh is already providing TLS. + type: boolean + highAvailability: + description: Whether or not to have replicas on the primary cluster. + type: boolean + primary: + description: Primary is the name of the primary cluster for replication. + type: string + required: + - clusterList + - primary + type: object + documentDBVersion: + description: |- + DocumentDBVersion specifies the version for all DocumentDB components (engine, gateway). + When set, this overrides the default versions for image.documentDB and image.gateway. + Individual image fields under spec.image take precedence over this version. + type: string + documentDbCredentialSecret: + description: |- + DocumentDbCredentialSecret is the name of the Kubernetes Secret containing credentials + for the DocumentDB gateway (expects keys `username` and `password`). If omitted, + a default secret name `documentdb-credentials` is used. + + NOTE: Immutable today; will be relaxed in a future release to support credential rotation. + type: string + x-kubernetes-validations: + - message: credential secret cannot be changed after cluster creation + rule: self == oldSelf + environment: + description: |- + Environment specifies the cloud environment for deployment + This determines cloud-specific service annotations for LoadBalancer services + enum: + - eks + - aks + - gke + type: string + exposeViaService: + description: |- + ExposeViaService configures how to expose DocumentDB via a Kubernetes service. + This can be a LoadBalancer or ClusterIP service. + properties: + serviceType: + description: ServiceType determines the type of service to expose + for DocumentDB. + enum: + - LoadBalancer + - ClusterIP + type: string + required: + - serviceType + type: object + featureGates: + additionalProperties: + type: boolean + description: |- + FeatureGates enables or disables optional DocumentDB features. + Keys are PascalCase feature names following the Kubernetes feature gate convention. + Example: {"ChangeStreams": true} + + IMPORTANT: When adding a new feature gate, update ALL of the following: + 1. Add a new FeatureGate* constant in documentdb_types.go + 2. Add the key name to the XValidation CEL rule's allowed list below + 3. Add a default entry in the featureGateDefaults map in documentdb_types.go + type: object + x-kubernetes-validations: + - message: 'unsupported feature gate key; allowed keys: ChangeStreams, + IOUring' + rule: self.all(key, key in ['ChangeStreams', 'IOUring']) + image: + description: |- + Image groups container image settings for the DocumentDB stack + (extension image, gateway image, PostgreSQL image). + All fields are optional; sensible defaults are applied when omitted. + properties: + documentDB: + description: |- + DocumentDB is the container image for the DocumentDB extension layer. + This image is mounted into the PostgreSQL container via CNPG's + ImageVolumeSource so that the extension files are available alongside + an upstream PostgreSQL image. + type: string + gateway: + description: Gateway is the container image for the DocumentDB + Gateway sidecar. + type: string + postgres: + default: ghcr.io/cloudnative-pg/postgresql:18-minimal-trixie + description: |- + Postgres is the container image for the PostgreSQL server. + Must be an upstream CNPG-compatible PostgreSQL image (the operator + adds the DocumentDB extension via an ImageVolume mount), and must + use trixie (Debian 13) base to match the extension's GLIBC + requirements. + + The default floats within PostgreSQL major 18 via CNPG's + "18-minimal-trixie" tag, so deployments pick up new 18.x minors and + Debian/PGDG security rebuilds automatically. + + The floating tag currently resolves to PG 18.6+, which is only safe + for DocumentDB extension >= 0.116.0: older extensions segfault on + insert under PG 18.6 (fixed upstream in documentdb/documentdb 3555c7d, + first released in 0.116.0). Keep the default documentDbVersion, and any + version pair exercised against this default, at >= 0.116.0. + type: string + type: object + imagePullSecrets: + description: |- + ImagePullSecrets is an optional list of references to secrets in the same namespace + to use for pulling any of the images used by this cluster. Passed through to the + underlying CloudNative-PG cluster. + items: + description: |- + LocalObjectReference contains enough information to let you locate the + referenced object inside the same namespace. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + type: array + instancesPerNode: + description: 'InstancesPerNode is the number of DocumentDB instances + per node. Range: 1-3.' + maximum: 3 + minimum: 1 + type: integer + logLevel: + description: Overrides default log level for the DocumentDB cluster. + type: string + monitoring: + description: Monitoring configures observability via an OTel Collector + sidecar. + properties: + enabled: + description: Enabled turns on the OTel Collector sidecar for metrics + collection. + type: boolean + exporter: + description: Exporter configures where metrics are sent. + properties: + otlp: + description: OTLP configures the OpenTelemetry Protocol exporter. + properties: + endpoint: + description: Endpoint is the OTLP gRPC endpoint (e.g., + "otel-collector.monitoring:4317"). + type: string + required: + - endpoint + type: object + prometheus: + description: Prometheus configures a Prometheus scrape endpoint + on the OTel Collector sidecar. + properties: + port: + default: 8888 + description: Port for the Prometheus scrape endpoint. + Defaults to 8888. + format: int32 + maximum: 65535 + minimum: 1024 + type: integer + type: object + type: object + type: object + nodeCount: + description: NodeCount is the number of nodes in the DocumentDB cluster. + Must be 1. + maximum: 1 + minimum: 1 + type: integer + plugins: + description: |- + Plugins groups CNPG plugin configuration (sidecar injector name, WAL replica name). + All fields are optional; defaults are preserved when omitted. + properties: + sidecarInjectorName: + description: |- + SidecarInjectorName is the name of the CNPG sidecar injector plugin + to use for the gateway and other sidecars. Immutable. + type: string + x-kubernetes-validations: + - message: sidecar injector plugin name cannot be changed after + cluster creation + rule: self == oldSelf + walReplicaName: + description: |- + WalReplicaName is the name of the WAL replica plugin to use for + cross-cluster replication. + type: string + type: object + postgres: + description: |- + Postgres groups PostgreSQL process-level tuning (UID/GID, custom post-init SQL). + All fields are optional; defaults are preserved when omitted. + properties: + gid: + description: |- + GID is the numeric group ID under which the PostgreSQL server process runs. + When set, UID must also be set. + format: int64 + type: integer + parameters: + additionalProperties: + type: string + description: |- + Parameters allows users to override PostgreSQL configuration parameters + (postgresql.conf settings) passed through to the underlying CNPG Cluster. + The operator applies memory-aware defaults (shared_buffers, effective_cache_size, + work_mem, maintenance_work_mem) computed from the pod memory limit, plus static + best-practice defaults for autovacuum, IO, WAL, and connection settings. + Values specified here override computed and static defaults. + Protected parameters (cron.database_name, max_replication_slots, max_wal_senders, + max_prepared_transactions) cannot be overridden. + type: object + postInitSQL: + description: |- + PostInitSQL is an ordered list of SQL statements executed after the + cluster is initialized. These statements run AFTER the operator's + mandatory bootstrap (CREATE EXTENSION documentdb, CREATE ROLE + documentdb, ALTER ROLE documentdb), so they can safely reference the + documentdb extension and role. + items: + type: string + type: array + uid: + description: |- + UID is the numeric user ID under which the PostgreSQL server process runs. + When set, GID must also be set. + format: int64 + type: integer + type: object + x-kubernetes-validations: + - message: uid and gid must be set together + rule: has(self.uid) == has(self.gid) + resource: + description: Resource specifies the storage resources for DocumentDB. + properties: + cpu: + description: |- + CPU specifies the total CPU envelope for each DocumentDB instance pod. + The operator divides this envelope across PostgreSQL, the documentdb-gateway + sidecar, and, when monitoring is enabled, the OTel collector sidecar. + PostgreSQL receives the remainder after gateway and OTel CPU reservations; + an explicit per-container CPU override wins over the automatic carve-out. + If not specified or set to "0", no CPU envelope is applied. + Examples: "2", "4", "500m" + type: string + database: + description: |- + Database optionally overrides the resources allocated to the PostgreSQL + container. When unset, PostgreSQL receives the pod memory and CPU envelopes + minus the gateway and (when monitoring is enabled) OTel collector carve-outs. + properties: + cpu: + description: CPU is the CPU request=limit for the container + (e.g. "500m", "2"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + memory: + description: Memory is the memory request=limit for the container + (e.g. "512Mi", "2Gi"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + type: object + gateway: + description: |- + Gateway optionally overrides the resources allocated to the + documentdb-gateway sidecar container. When unset, the operator derives the + gateway's memory as min(gatewayMemoryFraction × memory, gatewayMemoryCap) + and carves it out of the pod memory envelope. The value is applied as both + the request and the limit (Guaranteed-class) so a gateway leak is + OOM-isolated and cannot crowd out PostgreSQL. + properties: + cpu: + description: CPU is the CPU request=limit for the container + (e.g. "500m", "2"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + memory: + description: Memory is the memory request=limit for the container + (e.g. "512Mi", "2Gi"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + type: object + memory: + description: |- + Memory specifies the memory limit for each DocumentDB instance pod. + This value is passed to the CNPG Cluster's spec.resources.limits.memory + and spec.resources.requests.memory (Guaranteed QoS). + Memory-aware PostgreSQL parameters (shared_buffers, effective_cache_size, etc.) + are auto-computed from this value. + If not specified or set to "0", no memory limit is applied and static + defaults are used for memory-aware parameters. + Examples: "2Gi", "4Gi", "8Gi" + type: string + otel: + description: |- + OTel optionally overrides the resources allocated to the otel-collector + sidecar container (only present when spec.monitoring.enabled is true). + When unset, the operator applies built-in defaults: memory request 48Mi / + limit 128Mi and CPU request 50m / limit 200m (Burstable — the requests are + the reserved floor and the limits cap a telemetry burst). Setting otel.cpu + or otel.memory pins that dimension to request == limit (Guaranteed). + properties: + cpu: + description: CPU is the CPU request=limit for the container + (e.g. "500m", "2"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + memory: + description: Memory is the memory request=limit for the container + (e.g. "512Mi", "2Gi"). + pattern: ^([0-9]+(\.[0-9]+)?(m|Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?)?$ + type: string + type: object + storage: + description: Storage configuration for DocumentDB persistent volumes. + properties: + persistentVolumeReclaimPolicy: + default: Retain + description: |- + PersistentVolumeReclaimPolicy controls what happens to the PersistentVolume when + the DocumentDB cluster is deleted. + + When a DocumentDB cluster is deleted, the following chain of deletions occurs: + DocumentDB deletion → CNPG Cluster deletion → PVC deletion → PV deletion (based on this policy) + + Options: + - Retain (default): The PV is preserved after cluster deletion, allowing manual + data recovery or forensic analysis. Use for production workloads where data + safety is critical. Orphaned PVs must be manually deleted when no longer needed. + - Delete: The PV is automatically deleted when the PVC is deleted. Use for development, + testing, or ephemeral environments where data persistence is not required. + + WARNING: Setting this to "Delete" means all data will be permanently lost when + the DocumentDB cluster is deleted. This cannot be undone. + enum: + - Retain + - Delete + type: string + pvcSize: + description: PvcSize is the size of the persistent volume + claim for DocumentDB storage (e.g., "10Gi"). + minLength: 1 + type: string + storageClass: + description: |- + StorageClass specifies the storage class for DocumentDB persistent volumes. + If not specified, the cluster's default storage class will be used. + type: string + x-kubernetes-validations: + - message: storage class cannot be changed after cluster creation + rule: self == oldSelf + required: + - pvcSize + type: object + required: + - storage + type: object + schemaVersion: + description: |- + SchemaVersion controls the desired schema version for the DocumentDB extension. + + The operator never changes your database schema unless you ask: + - Set schemaVersion → updates the database schema (irreversible) + - Set schemaVersion: "auto" → schema auto-updates with binary + + Once the schema has been updated, the operator blocks image rollback below the + installed schema version to prevent running an untested binary/schema combination. + + Values: + - "" (empty, default): Two-phase mode. Image upgrades happen automatically, + but ALTER EXTENSION UPDATE does NOT run. Users must explicitly set this + field to finalize the schema upgrade. This is the safest option for production + as it allows rollback by reverting the image before committing the schema change. + - "auto": Schema automatically updates to match the binary version whenever + the binary is upgraded. This is the simplest mode but provides no rollback + safety window. Only recommended for single-region clusters. + - "" (e.g. "0.112.0"): Schema updates to exactly this version. + Must be <= the binary version. + pattern: ^(auto|[0-9]+\.[0-9]+\.[0-9]+)?$ + type: string + timeouts: + properties: + stopDelay: + format: int32 + maximum: 1800 + minimum: 0 + type: integer + type: object + tls: + description: TLS configures certificate management for DocumentDB + components. + properties: + gateway: + description: 'Gateway configures TLS for the gateway sidecar (Phase + 1: certificate provisioning only).' + properties: + certManager: + description: CertManager config when Mode=CertManager. + properties: + dnsNames: + description: DNSNames for the certificate SANs. If empty, + operator will add Service DNS names. + items: + type: string + type: array + issuerRef: + description: IssuerRef references a cert-manager Issuer + or ClusterIssuer. + properties: + group: + description: Group defaults to cert-manager.io + type: string + kind: + description: Kind of issuer (Issuer or ClusterIssuer). + Defaults to Issuer. + type: string + name: + type: string + required: + - name + type: object + secretName: + description: SecretName optional explicit name for the + target secret. If empty a default is chosen. + type: string + required: + - issuerRef + type: object + mode: + default: SelfSigned + description: |- + Mode selects the TLS management strategy. + Defaults to SelfSigned if not specified. + enum: + - SelfSigned + - CertManager + - Provided + type: string + provided: + description: Provided secret reference when Mode=Provided. + properties: + secretName: + type: string + required: + - secretName + type: object + type: object + globalEndpoints: + description: GlobalEndpoints configures TLS for global endpoints + (placeholder for future phases). + type: object + postgres: + description: |- + Postgres configures TLS for the Postgres server. + If server side certs are provided alone, the operator will use sslMode=require for cross-regional replication connections. + If replication certs are also provided, the operator will use verify-full, which requires the hostname to be correctly set. + See the multi-region-deployment docs for how to do that. + properties: + clientCASecret: + description: |- + The secret containing the Client CA certificate. If not defined, a new secret will be created + with a self-signed CA and will be used to generate all the client certificates.
+
+ Contains:
+
+ - `ca.crt`: CA that should be used to validate the client certificates, + used as `ssl_ca_file` of all the instances.
+ - `ca.key`: key used to generate client certificates, if ReplicationTLSSecret is provided, + this can be omitted.
+ type: string + replicationTLSSecret: + description: |- + The secret of type kubernetes.io/tls containing the client certificate to authenticate as + the `streaming_replica` user. + If not defined, ClientCASecret must provide also `ca.key`, and a new secret will be + created using the provided CA. + type: string + serverAltDNSNames: + description: The list of the server alternative DNS names + to be added to the generated server TLS certificates, when + required. + items: + type: string + type: array + serverCASecret: + description: |- + The secret containing the Server CA certificate. If not defined, a new secret will be created + with a self-signed CA and will be used to generate the TLS certificate ServerTLSSecret.
+
+ Contains:
+
+ - `ca.crt`: CA that should be used to validate the server certificate, + used as `sslrootcert` in client connection strings.
+ - `ca.key`: key used to generate Server SSL certs, if ServerTLSSecret is provided, + this can be omitted.
+ type: string + serverTLSSecret: + description: |- + The secret of type kubernetes.io/tls containing the server TLS certificate and key that will be set as + `ssl_cert_file` and `ssl_key_file` so that clients can connect to postgres securely. + If not defined, ServerCASecret must provide also `ca.key` and a new secret will be + created using the provided CA. + type: string + type: object + type: object + x-kubernetes-validations: + - message: spec.tls.postgres replicationTLSSecret and clientCASecret + must be provided together; serverTLSSecret and serverCASecret + must be provided together; serverTLSSecret requires replicationTLSSecret + rule: '!has(self.postgres) || (has(self.postgres.replicationTLSSecret) + == has(self.postgres.clientCASecret) && has(self.postgres.serverTLSSecret) + == has(self.postgres.serverCASecret) && (!has(self.postgres.serverTLSSecret) + || has(self.postgres.replicationTLSSecret)))' + required: + - instancesPerNode + - nodeCount + - resource + type: object + x-kubernetes-validations: + - message: when spec.clusterReplication is set, either spec.clusterReplication.disableTLS + must be true or spec.tls.postgres.replicationTLSSecret and spec.tls.postgres.clientCASecret + must be provided + rule: '!has(self.clusterReplication) || ((has(self.clusterReplication.disableTLS) + && self.clusterReplication.disableTLS) || (has(self.tls) && has(self.tls.postgres) + && has(self.tls.postgres.replicationTLSSecret) && has(self.tls.postgres.clientCASecret)))' + status: + description: DocumentDBStatus defines the observed state of DocumentDB. + properties: + connectionString: + type: string + documentDBImage: + description: DocumentDBImage is the extension image URI currently + applied to the cluster. + type: string + gatewayImage: + description: GatewayImage is the gateway sidecar image URI currently + applied to the cluster. + type: string + localPrimary: + type: string + schemaVersion: + description: SchemaVersion is the currently installed schema version + of the DocumentDB extension. + type: string + status: + description: Status reflects the status field from the underlying + CNPG Cluster. + type: string + targetPrimary: + type: string + tls: + description: TLS reports gateway TLS provisioning status (Phase 1). + properties: + message: + type: string + ready: + type: boolean + secretName: + type: string + type: object + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/operator/product-helm-chart/schemas/scheduled-backup.yaml b/operator/product-helm-chart/schemas/scheduled-backup.yaml new file mode 100644 index 000000000..b1d63e946 --- /dev/null +++ b/operator/product-helm-chart/schemas/scheduled-backup.yaml @@ -0,0 +1,182 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + labels: + app: documentdb-operator + name: scheduledbackups.documentdb.io +spec: + group: documentdb.io + names: + kind: ScheduledBackup + listKind: ScheduledBackupList + plural: scheduledbackups + singular: scheduledbackup + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.cluster.name + name: Cluster + type: string + - jsonPath: .spec.schedule + name: Schedule + type: string + - jsonPath: .spec.retentionDays + name: Retention Days + type: integer + deprecated: true + deprecationWarning: documentdb.io/preview is deprecated; use documentdb.io/v1 + name: preview + schema: + openAPIV3Schema: + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: ScheduledBackupSpec defines the desired state of ScheduledBackup + properties: + cluster: + description: |- + Cluster specifies the DocumentDB cluster to backup. + The cluster must exist in the same namespace as the ScheduledBackup resource. + properties: + name: + description: Name of the referent. + type: string + required: + - name + type: object + retentionDays: + description: |- + RetentionDays specifies how many days the backups should be retained. + If not specified, the default retention period from the cluster's backup retention policy will be used. + type: integer + schedule: + description: |- + Schedule defines when backups should be created using cron expression format. + See https://pkg.go.dev/github.com/robfig/cron#hdr-CRON_Expression_Format + type: string + required: + - cluster + - schedule + type: object + status: + description: ScheduledBackupStatus defines the observed state of ScheduledBackup + properties: + lastScheduledTime: + description: LastScheduledTime is the time when the last backup was + scheduled by this ScheduledBackup. + format: date-time + type: string + nextScheduledTime: + description: NextScheduledTime is the time when the next backup is + scheduled by this ScheduledBackup. + format: date-time + type: string + type: object + required: + - metadata + - spec + type: object + served: true + storage: false + subresources: + status: {} + - additionalPrinterColumns: + - jsonPath: .spec.cluster.name + name: Cluster + type: string + - jsonPath: .spec.schedule + name: Schedule + type: string + - jsonPath: .spec.retentionDays + name: Retention Days + type: integer + name: v1 + schema: + openAPIV3Schema: + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: ScheduledBackupSpec defines the desired state of ScheduledBackup + properties: + cluster: + description: |- + Cluster specifies the DocumentDB cluster to backup. + The cluster must exist in the same namespace as the ScheduledBackup resource. + properties: + name: + description: Name of the referent. + type: string + required: + - name + type: object + retentionDays: + description: |- + RetentionDays specifies how many days the backups should be retained. + If not specified, the default retention period from the cluster's backup retention policy will be used. + type: integer + schedule: + description: |- + Schedule defines when backups should be created using cron expression format. + See https://pkg.go.dev/github.com/robfig/cron#hdr-CRON_Expression_Format + type: string + required: + - cluster + - schedule + type: object + status: + description: ScheduledBackupStatus defines the observed state of ScheduledBackup + properties: + lastScheduledTime: + description: LastScheduledTime is the time when the last backup was + scheduled by this ScheduledBackup. + format: date-time + type: string + nextScheduledTime: + description: NextScheduledTime is the time when the next backup is + scheduled by this ScheduledBackup. + format: date-time + type: string + type: object + required: + - metadata + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/operator/product-helm-chart/templates/_helpers.tpl b/operator/product-helm-chart/templates/_helpers.tpl new file mode 100644 index 000000000..a25acf125 --- /dev/null +++ b/operator/product-helm-chart/templates/_helpers.tpl @@ -0,0 +1,12 @@ +{{- define "product.name" -}} +{{- printf "%s-%s" (.Release.Name | trunc 40 | trimSuffix "-") (printf "%s/%s" .Release.Namespace .Release.Name | sha256sum | trunc 12) -}} +{{- end -}} + +{{- define "product.image" -}} +{{- $repo := required "image.repository is required" .Values.image.repository -}} +{{- $digest := required "image.digest is required; use an approved immutable image" .Values.image.digest -}} +{{- if not (regexMatch "^sha256:[a-f0-9]{64}$" $digest) -}} +{{- fail "image.digest must be a sha256 digest" -}} +{{- end -}} +{{- printf "%s@%s" $repo $digest -}} +{{- end -}} diff --git a/operator/product-helm-chart/templates/crds.yaml b/operator/product-helm-chart/templates/crds.yaml new file mode 100644 index 000000000..74ceba44c --- /dev/null +++ b/operator/product-helm-chart/templates/crds.yaml @@ -0,0 +1,16 @@ +{{- $api := required "productDefinition.api is required" .Values.productDefinition.api -}} +{{- range $entry := list (dict "file" "cluster" "kind" $api.kind "plural" $api.plural) (dict "file" "backup" "kind" "Backup" "plural" "backups") (dict "file" "scheduled-backup" "kind" "ScheduledBackup" "plural" "scheduledbackups") }} +{{- $crd := $.Files.Get (printf "schemas/%s.yaml" $entry.file) | fromYaml }} +{{- $_ := set $crd.metadata "annotations" (merge (dict "helm.sh/resource-policy" "keep") ($crd.metadata.annotations | default dict)) }} +{{- $_ := set $crd.metadata "name" (printf "%s.%s" $entry.plural $api.group) }} +{{- $_ := set $crd.spec "group" $api.group }} +{{- $_ := set $crd.spec "names" (dict "kind" $entry.kind "listKind" (printf "%sList" $entry.kind) "plural" $entry.plural "singular" (lower $entry.kind)) }} +{{- $version := dict }} +{{- range $crd.spec.versions }} +{{- if .storage }}{{- $version = deepCopy . }}{{- end }} +{{- end }} +{{- $_ := set $version "name" $api.version }} +{{- $_ := set $crd.spec "versions" (list $version) }} +--- +{{ toYaml $crd }} +{{- end }} diff --git a/operator/product-helm-chart/templates/deployment.yaml b/operator/product-helm-chart/templates/deployment.yaml new file mode 100644 index 000000000..c7c5de5c5 --- /dev/null +++ b/operator/product-helm-chart/templates/deployment.yaml @@ -0,0 +1,99 @@ +{{- if empty .Values.productDefinition -}} +{{- fail "productDefinition must contain the selected product definition" -}} +{{- end -}} +{{- $runtime := .Values.productDefinition -}} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "product.name" . }}-runtime + namespace: {{ .Release.Namespace }} +data: + runtime.json: {{ $runtime | toJson | quote }} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "product.name" . }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "product.name" . }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "product.name" . }} +subjects: + - kind: ServiceAccount + name: {{ include "product.name" . }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "product.name" . }} + namespace: {{ .Release.Namespace }} +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + app.kubernetes.io/instance: {{ include "product.name" . }} + template: + metadata: + labels: + app.kubernetes.io/instance: {{ include "product.name" . }} + annotations: + checksum/runtime: {{ $runtime | toJson | sha256sum }} + spec: + serviceAccountName: {{ include "product.name" . }} + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + seccompProfile: + type: RuntimeDefault + containers: + - name: manager + image: {{ include "product.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + args: + - --product-definition=/config/runtime.json + ports: + - name: webhook + containerPort: 9443 + - name: health + containerPort: 8081 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + resources: + {{- toYaml .Values.resources | nindent 12 }} + readinessProbe: + httpGet: + path: /readyz + port: health + livenessProbe: + httpGet: + path: /healthz + port: health + volumeMounts: + - name: runtime + mountPath: /config + readOnly: true + - name: webhook-cert + mountPath: /tmp/k8s-webhook-server/serving-certs + readOnly: true + volumes: + - name: runtime + configMap: + name: {{ include "product.name" . }}-runtime + - name: webhook-cert + secret: + secretName: {{ include "product.name" . }}-webhook-tls diff --git a/operator/product-helm-chart/templates/injector.yaml b/operator/product-helm-chart/templates/injector.yaml new file mode 100644 index 000000000..d778fb035 --- /dev/null +++ b/operator/product-helm-chart/templates/injector.yaml @@ -0,0 +1,117 @@ +{{- if .Values.sidecarInjector.enabled }} +{{- if ne .Values.productDefinition.profile.SidecarInjectorPlugin "cnpg-i-sidecar-injector.documentdb.io" }} +{{- fail "the bundled injector implements cnpg-i-sidecar-injector.documentdb.io; use an external plugin for another RPC identity" }} +{{- end }} +{{- $image := required "sidecarInjector.image.repository is required" .Values.sidecarInjector.image.repository }} +{{- $digest := required "sidecarInjector.image.digest is required" .Values.sidecarInjector.image.digest }} +{{- if not (regexMatch "^sha256:[a-f0-9]{64}$" $digest) }} +{{- fail "sidecarInjector.image.digest must be a sha256 digest" }} +{{- end }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "product.name" . }}-injector + namespace: {{ .Values.sidecarInjector.namespace }} + labels: + cnpg.io/pluginName: cnpg-i-sidecar-injector.documentdb.io + annotations: + cnpg.io/pluginClientSecret: {{ include "product.name" . }}-plugin-client-tls + cnpg.io/pluginServerSecret: {{ include "product.name" . }}-plugin-server-tls + cnpg.io/pluginPort: "9090" +spec: + selector: + app.kubernetes.io/instance: {{ include "product.name" . }}-injector + ports: + - port: 9090 + targetPort: 9090 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "product.name" . }}-injector + namespace: {{ .Values.sidecarInjector.namespace }} +spec: + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/instance: {{ include "product.name" . }}-injector + template: + metadata: + labels: + app.kubernetes.io/instance: {{ include "product.name" . }}-injector + spec: + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault + containers: + - name: injector + image: "{{ $image }}@{{ $digest }}" + imagePullPolicy: IfNotPresent + args: + - plugin + - --server-address=:9090 + - --server-cert=/server/tls.crt + - --server-key=/server/tls.key + - --client-cert=/client/tls.crt + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + ports: + - containerPort: 9090 + readinessProbe: + tcpSocket: + port: 9090 + volumeMounts: + - name: server + mountPath: /server + readOnly: true + - name: client + mountPath: /client + readOnly: true + volumes: + - name: server + secret: + secretName: {{ include "product.name" . }}-plugin-server-tls + - name: client + secret: + secretName: {{ include "product.name" . }}-plugin-client-tls +--- +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + name: {{ include "product.name" . }}-plugin-issuer + namespace: {{ .Values.sidecarInjector.namespace }} +spec: + selfSigned: {} +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: {{ include "product.name" . }}-plugin-server + namespace: {{ .Values.sidecarInjector.namespace }} +spec: + secretName: {{ include "product.name" . }}-plugin-server-tls + commonName: {{ include "product.name" . }}-injector + dnsNames: + - {{ include "product.name" . }}-injector + issuerRef: + name: {{ include "product.name" . }}-plugin-issuer + usages: ["server auth"] +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: {{ include "product.name" . }}-plugin-client + namespace: {{ .Values.sidecarInjector.namespace }} +spec: + secretName: {{ include "product.name" . }}-plugin-client-tls + commonName: {{ include "product.name" . }}-client + issuerRef: + name: {{ include "product.name" . }}-plugin-issuer + usages: ["client auth"] +{{- end }} diff --git a/operator/product-helm-chart/templates/role.yaml b/operator/product-helm-chart/templates/role.yaml new file mode 100644 index 000000000..fea130d18 --- /dev/null +++ b/operator/product-helm-chart/templates/role.yaml @@ -0,0 +1,85 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "product.name" . }} + labels: + app.kubernetes.io/name: {{ include "product.name" . }} + app.kubernetes.io/managed-by: "Helm" +rules: +- apiGroups: [{{ .Values.productDefinition.api.group | quote }}] + resources: [{{ .Values.productDefinition.api.plural | quote }}, {{ printf "%s/status" .Values.productDefinition.api.plural | quote }}, {{ printf "%s/finalizers" .Values.productDefinition.api.plural | quote }}] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +# Core API resources the operator creates / reconciles in user namespaces. +# `pods,services,endpoints` need full CRUD because EnsureServiceAccount\ +# RoleAndRoleBinding (documentdb_controller.go) creates per-CR Roles +# granting these to the CNPG cluster's SA. K8s RBAC escalation requires +# the grantor (this operator) to already hold every verb being granted. +- apiGroups: [""] + resources: ["pods", "services", "endpoints", "serviceaccounts", "configmaps", "persistentvolumeclaims"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +# `pods/exec` is a POST-only subresource; only `create` is meaningful. +- apiGroups: [""] + resources: ["pods/exec"] + verbs: ["create"] +- apiGroups: ["rbac.authorization.k8s.io"] # namespaced RBAC created by util.go (Roles/RoleBindings only) + resources: ["roles", "rolebindings"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +- apiGroups: ["coordination.k8s.io"] # leader election + resources: ["leases"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +- apiGroups: ["networking.fleet.azure.com"] # fleet permissions for multi-cluster services + resources: ["serviceexports", "multiclusterservices", "serviceimports", "internalserviceexports"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +# Secrets: certificate_controller reads cert-manager-issued TLS secrets to +# stamp into Cluster spec. No controller writes Secrets. +- apiGroups: [""] + resources: ["secrets"] + verbs: ["get", "list", "watch"] +- apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters", "publications", "subscriptions", "clusters/status"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +# cert-manager: certificate_controller Gets/Creates namespaced Certificates +# and Issuers and Owns() them (which requires watch). It patches only its own +# gateway Certificates, to add gateway Service DNS names they lack. It never +# Deletes or sets Finalizers on cert-manager objects. ClusterIssuer is +# referenced by name in CR spec but resolved by cert-manager itself. +- apiGroups: ["cert-manager.io"] + resources: ["certificates"] + verbs: ["get", "list", "watch", "create", "patch"] +- apiGroups: ["cert-manager.io"] + resources: ["issuers"] + verbs: ["get", "list", "watch", "create"] + +# Backup permissions +- apiGroups: [{{ .Values.productDefinition.api.group | quote }}] + resources: ["backups", "backups/status", "backups/finalizers"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +# ScheduledBackup permissions +- apiGroups: [{{ .Values.productDefinition.api.group | quote }}] + resources: ["scheduledbackups", "scheduledbackups/status", "scheduledbackups/finalizers"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +# CNPG Backup permissions +- apiGroups: ["postgresql.cnpg.io"] + resources: ["backups", "backups/status"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +# VolumeSnapshotClass permissions +- apiGroups: ["snapshot.storage.k8s.io"] + resources: ["volumesnapshotclasses"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +# PersistentVolume permissions for PV controller +- apiGroups: [""] + resources: ["persistentvolumes"] + verbs: ["get", "list", "watch", "update", "patch"] +# Nodes: read container runtime versions to decide whether new clusters can use +# ImageVolume or must fall back to the combined image (imageMode=auto). +- apiGroups: [""] + resources: ["nodes"] + verbs: ["get", "list"] +# StorageClass permissions for PV controller (needed to check provisioner capabilities) +- apiGroups: ["storage.k8s.io"] + resources: ["storageclasses"] + verbs: ["get", "list", "watch"] +# Events permissions for PV retention warnings +- apiGroups: [""] + resources: ["events"] + verbs: ["create", "patch"] diff --git a/operator/product-helm-chart/templates/webhook.yaml b/operator/product-helm-chart/templates/webhook.yaml new file mode 100644 index 000000000..c2bc951a3 --- /dev/null +++ b/operator/product-helm-chart/templates/webhook.yaml @@ -0,0 +1,58 @@ +{{- $api := .Values.productDefinition.api }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "product.name" . }}-webhook + namespace: {{ .Release.Namespace }} +spec: + selector: + app.kubernetes.io/instance: {{ include "product.name" . }} + ports: + - port: 443 + targetPort: webhook +--- +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + name: {{ include "product.name" . }}-issuer + namespace: {{ .Release.Namespace }} +spec: + selfSigned: {} +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: {{ include "product.name" . }}-webhook-cert + namespace: {{ .Release.Namespace }} +spec: + secretName: {{ include "product.name" . }}-webhook-tls + dnsNames: + - {{ include "product.name" . }}-webhook.{{ .Release.Namespace }}.svc + issuerRef: + name: {{ include "product.name" . }}-issuer + kind: Issuer +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: {{ include "product.name" . }} + annotations: + cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/{{ include "product.name" . }}-webhook-cert +webhooks: + - name: {{ printf "validate.%s.%s" (lower $api.kind) $api.group }} + admissionReviewVersions: ["v1"] + sideEffects: None + failurePolicy: Fail + matchPolicy: Equivalent + clientConfig: + service: + name: {{ include "product.name" . }}-webhook + namespace: {{ .Release.Namespace }} + path: {{ printf "/validate-%s-%s-%s" (replace "." "-" $api.group) $api.version (lower $api.kind) }} + port: 443 + rules: + - operations: ["CREATE", "UPDATE"] + apiGroups: [{{ $api.group | quote }}] + apiVersions: [{{ $api.version | quote }}] + resources: [{{ $api.plural | quote }}] + scope: Namespaced diff --git a/operator/product-helm-chart/values.yaml b/operator/product-helm-chart/values.yaml new file mode 100644 index 000000000..8544eadad --- /dev/null +++ b/operator/product-helm-chart/values.yaml @@ -0,0 +1,18 @@ +image: + repository: "" + digest: "" + pullPolicy: IfNotPresent +imagePullSecrets: [] +productDefinition: {} +replicaCount: 1 +resources: + requests: + cpu: 100m + memory: 128Mi +sidecarInjector: + enabled: false + namespace: cnpg-system + namespace: cnpg-system + image: + repository: "" + digest: "" diff --git a/operator/src/Makefile b/operator/src/Makefile index 86aa9ad68..6dcabc5ba 100644 --- a/operator/src/Makefile +++ b/operator/src/Makefile @@ -49,6 +49,7 @@ manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and Cust ./hack/sync-preview-api.sh $(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases cp -f config/crd/bases/*.yaml ../documentdb-helm-chart/crds/ + $(MAKE) -C ../product-helm-chart schemas .PHONY: generate generate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations. diff --git a/operator/src/cmd/main.go b/operator/src/cmd/main.go index 60a183952..91c0be271 100644 --- a/operator/src/cmd/main.go +++ b/operator/src/cmd/main.go @@ -29,6 +29,7 @@ import ( cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" dbv1 "github.com/documentdb/documentdb-operator/api/v1" "github.com/documentdb/documentdb-operator/internal/controller" + "github.com/documentdb/documentdb-operator/internal/product" webhookhandler "github.com/documentdb/documentdb-operator/internal/webhook" fleetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" // +kubebuilder:scaffold:imports @@ -59,6 +60,10 @@ func main() { var secureMetrics bool var enableHTTP2 bool var tlsOpts []func(*tls.Config) + var definitionPath string + var checkDefinition bool + flag.StringVar(&definitionPath, "product-definition", "", "Optional JSON definition for the common API, controllers and admission") + flag.BoolVar(&checkDefinition, "check-product-definition", false, "Validate a product definition without contacting Kubernetes") flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") @@ -83,6 +88,30 @@ func main() { flag.Parse() ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) + adapter := product.DocumentDBAdapter{} + leaderElectionID := "187ffea8.microsoft.com" + if definitionPath != "" { + definition, err := product.LoadDefinition(definitionPath) + if err != nil { + setupLog.Error(err, "invalid product definition") + os.Exit(1) + } + adapter.Definition = definition + scheme = runtime.NewScheme() + utilruntime.Must(clientgoscheme.AddToScheme(scheme)) + utilruntime.Must(cnpgv1.AddToScheme(scheme)) + utilruntime.Must(cmapi.AddToScheme(scheme)) + utilruntime.Must(fleetv1alpha1.AddToScheme(scheme)) + utilruntime.Must(definition.AddToScheme(scheme)) + leaderElectionID = "operator." + definition.API.Group + } else if checkDefinition { + setupLog.Error(nil, "--check-product-definition requires --product-definition") + os.Exit(1) + } + if checkDefinition { + setupLog.Info("product definition validated", "product", adapter.Profile().Name) + return + } // if the enable-http2 flag is false (the default), http/2 should be disabled // due to its vulnerabilities. More specifically, disabling http/2 will @@ -179,7 +208,7 @@ func main() { WebhookServer: webhookServer, HealthProbeBindAddress: probeAddr, LeaderElection: enableLeaderElection, - LeaderElectionID: "187ffea8.microsoft.com", + LeaderElectionID: leaderElectionID, // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily // when the Manager ends. This requires the binary to immediately end when the // Manager is stopped, otherwise, this setting is unsafe. Setting this significantly @@ -198,8 +227,9 @@ func main() { } if err = (&controller.CertificateReconciler{ - Client: mgr.GetClient(), - Scheme: mgr.GetScheme(), + Adapter: adapter, + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "Certificate") os.Exit(1) @@ -213,6 +243,7 @@ func main() { } if err = (&controller.DocumentDBReconciler{ + Adapter: adapter, Client: mgr.GetClient(), Scheme: mgr.GetScheme(), Config: mgr.GetConfig(), @@ -224,6 +255,7 @@ func main() { } if err = (&controller.BackupReconciler{ + Adapter: adapter, Client: mgr.GetClient(), Scheme: mgr.GetScheme(), Recorder: mgr.GetEventRecorderFor("backup-controller"), @@ -233,6 +265,7 @@ func main() { } if err = (&controller.ScheduledBackupReconciler{ + Adapter: adapter, Client: mgr.GetClient(), Scheme: mgr.GetScheme(), Recorder: mgr.GetEventRecorderFor("scheduled-backup-controller"), @@ -242,7 +275,8 @@ func main() { } if err = (&controller.PersistentVolumeReconciler{ - Client: mgr.GetClient(), + Adapter: adapter, + Client: mgr.GetClient(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "PersistentVolume") os.Exit(1) @@ -251,7 +285,7 @@ func main() { // +kubebuilder:scaffold:builder // Register the DocumentDB validating webhook - if err = (&webhookhandler.DocumentDBValidator{}).SetupWebhookWithManager(mgr); err != nil { + if err = (&webhookhandler.DocumentDBValidator{Adapter: adapter}).SetupWebhookWithManager(mgr); err != nil { setupLog.Error(err, "unable to create webhook", "webhook", "DocumentDB") os.Exit(1) } diff --git a/operator/src/internal/controller/backup_controller.go b/operator/src/internal/controller/backup_controller.go index 11518a7f9..2554e6703 100644 --- a/operator/src/internal/controller/backup_controller.go +++ b/operator/src/internal/controller/backup_controller.go @@ -22,19 +22,23 @@ import ( // engine.BackupReconciler. type BackupReconciler struct { client.Client + Adapter product.DocumentDBAdapter Scheme *runtime.Scheme Recorder record.EventRecorder } func (r *BackupReconciler) engine() *engine.BackupReconciler[*dbv1.DocumentDB, *dbv1.Backup] { - return &engine.BackupReconciler[*dbv1.DocumentDB, *dbv1.Backup]{ - Client: r.Client, - Scheme: r.Scheme, - Recorder: r.Recorder, - Cluster: product.DocumentDBAdapter{}, - Backups: product.DocumentDBBackupAdapter{}, - Replication: documentDBReplication{&DocumentDBReconciler{Client: r.Client}}, + reconciler := &engine.BackupReconciler[*dbv1.DocumentDB, *dbv1.Backup]{ + Client: r.Client, + Scheme: r.Scheme, + Recorder: r.Recorder, + Cluster: r.Adapter, + Backups: product.DocumentDBBackupAdapter{Definition: r.Adapter.Definition}, } + if r.Adapter.Definition == nil { + reconciler.Replication = documentDBReplication{&DocumentDBReconciler{Client: r.Client}} + } + return reconciler } // Reconcile handles the reconciliation loop for Backup resources. diff --git a/operator/src/internal/controller/certificate_controller.go b/operator/src/internal/controller/certificate_controller.go index fdd0aa3cc..eb0ccc868 100644 --- a/operator/src/internal/controller/certificate_controller.go +++ b/operator/src/internal/controller/certificate_controller.go @@ -20,7 +20,8 @@ import ( // Today it provisions gateway TLS assets; future work can layer in additional surfaces. type CertificateReconciler struct { client.Client - Scheme *runtime.Scheme + Adapter product.DocumentDBAdapter + Scheme *runtime.Scheme } // +kubebuilder:rbac:groups=documentdb.io,resources=dbs,verbs=get;list;watch;patch @@ -34,7 +35,7 @@ func (r *CertificateReconciler) Reconcile(ctx context.Context, req ctrl.Request) } func (r *CertificateReconciler) engine() *engine.CertificateReconciler[*dbv1.DocumentDB] { - return &engine.CertificateReconciler[*dbv1.DocumentDB]{Client: r.Client, Scheme: r.Scheme, Adapter: product.DocumentDBAdapter{}} + return &engine.CertificateReconciler[*dbv1.DocumentDB]{Client: r.Client, Scheme: r.Scheme, Adapter: r.Adapter} } func (r *CertificateReconciler) reconcileCertificates(ctx context.Context, ddb *dbv1.DocumentDB) (ctrl.Result, error) { @@ -43,7 +44,7 @@ func (r *CertificateReconciler) reconcileCertificates(ctx context.Context, ddb * func (r *CertificateReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). - For(&dbv1.DocumentDB{}). + For(r.Adapter.New()). Owns(&cmapi.Certificate{}). Owns(&cmapi.Issuer{}). Named("certificate-controller"). diff --git a/operator/src/internal/controller/documentdb_controller.go b/operator/src/internal/controller/documentdb_controller.go index 8cd0451c3..1c90ac7b1 100644 --- a/operator/src/internal/controller/documentdb_controller.go +++ b/operator/src/internal/controller/documentdb_controller.go @@ -42,6 +42,7 @@ const ( // this type supplies the DocumentDB adapter and the multi-region hooks. type DocumentDBReconciler struct { client.Client + Adapter product.DocumentDBAdapter Scheme *runtime.Scheme Config *rest.Config Clientset kubernetes.Interface @@ -68,17 +69,20 @@ var reconcileMutex sync.Mutex // clients. It is built per call so struct-literal construction (as in tests) // keeps working. func (r *DocumentDBReconciler) engine() *engine.ClusterReconciler[*dbv1.DocumentDB] { - return &engine.ClusterReconciler[*dbv1.DocumentDB]{ + reconciler := &engine.ClusterReconciler[*dbv1.DocumentDB]{ Client: r.Client, Scheme: r.Scheme, Recorder: r.Recorder, SQLExecutor: r.SQLExecutor, - Adapter: product.DocumentDBAdapter{}, - Replication: documentDBReplication{r}, + Adapter: r.Adapter, Mutex: &reconcileMutex, ImageModeDetector: r.ImageModeDetector, } + if r.Adapter.Definition == nil { + reconciler.Replication = documentDBReplication{r} + } + return reconciler } // +kubebuilder:rbac:groups=documentdb.io,resources=dbs,verbs=get;list;watch;create;update;patch;delete @@ -185,6 +189,18 @@ func (r *DocumentDBReconciler) SetupWithManager(mgr ctrl.Manager) error { if r.ImageModeDetector == nil { detector := &imagemode.Detector{Client: r.Client, Clientset: r.Clientset} r.ImageModeDetector = detector.Detect + if r.Adapter.Definition != nil { + r.ImageModeDetector = func(ctx context.Context, namespace string) (imagemode.Mode, string, error) { + mode, reason, err := detector.Detect(ctx, namespace) + if err != nil { + return mode, reason, err + } + if mode != imagemode.ImageVolume { + return mode, reason, fmt.Errorf("declarative product requires ImageVolume support: %s", reason) + } + return mode, reason, nil + } + } } if r.SQLExecutor == nil { r.SQLExecutor = engine.NewPodSQLExecutor(r.Client, r.Clientset, r.Config) diff --git a/operator/src/internal/controller/pv_controller.go b/operator/src/internal/controller/pv_controller.go index e3762f63f..beb190830 100644 --- a/operator/src/internal/controller/pv_controller.go +++ b/operator/src/internal/controller/pv_controller.go @@ -24,10 +24,11 @@ import ( // The logic lives in engine.PersistentVolumeReconciler. type PersistentVolumeReconciler struct { client.Client + Adapter product.DocumentDBAdapter } func (r *PersistentVolumeReconciler) engine() *engine.PersistentVolumeReconciler[*dbv1.DocumentDB] { - return &engine.PersistentVolumeReconciler[*dbv1.DocumentDB]{Client: r.Client, Adapter: product.DocumentDBAdapter{}} + return &engine.PersistentVolumeReconciler[*dbv1.DocumentDB]{Client: r.Client, Adapter: r.Adapter} } // Package-level RBAC also covers PVC lifecycle operations performed by the diff --git a/operator/src/internal/controller/scheduledbackup_controller.go b/operator/src/internal/controller/scheduledbackup_controller.go index c1ab1527d..ce4ee71b4 100644 --- a/operator/src/internal/controller/scheduledbackup_controller.go +++ b/operator/src/internal/controller/scheduledbackup_controller.go @@ -20,6 +20,7 @@ import ( // lives in engine.ScheduledBackupReconciler. type ScheduledBackupReconciler struct { client.Client + Adapter product.DocumentDBAdapter Scheme *runtime.Scheme Recorder record.EventRecorder } @@ -29,9 +30,9 @@ func (r *ScheduledBackupReconciler) engine() *engine.ScheduledBackupReconciler[* Client: r.Client, Scheme: r.Scheme, Recorder: r.Recorder, - Cluster: product.DocumentDBAdapter{}, - Scheduled: product.DocumentDBScheduledBackupAdapter{}, - Backups: product.DocumentDBBackupAdapter{}, + Cluster: r.Adapter, + Scheduled: product.DocumentDBScheduledBackupAdapter{Definition: r.Adapter.Definition}, + Backups: product.DocumentDBBackupAdapter{Definition: r.Adapter.Definition}, } } diff --git a/operator/src/internal/engine/extension.go b/operator/src/internal/engine/extension.go index 0c794b9c3..10130172a 100644 --- a/operator/src/internal/engine/extension.go +++ b/operator/src/internal/engine/extension.go @@ -55,6 +55,9 @@ func (r *ClusterReconciler[T]) extensionName() string { } func (r *ClusterReconciler[T]) extensionVersionToSemver(v string) string { + if r.profile().Postgres.PinnedCatalogVersion != "" { + return v + } if r.profile().Postgres.ExtensionVersionFormat == product.ExtensionVersionSemver { return v } @@ -131,6 +134,12 @@ func (r *ClusterReconciler[T]) HandleExtensionUpgrade(ctx context.Context, curre } defaultVersion, installedVersion, ok := ParseExtensionVersions(output) + if pinned := r.profile().Postgres.PinnedCatalogVersion; pinned != "" { + if !ok || defaultVersion != pinned || installedVersion != pinned || + r.Adapter.Spec(obj).SchemaVersion != "" { + return fmt.Errorf("non-upgrading product requires binary and installed catalog %q with no schemaVersion override", pinned) + } + } if !ok { logger.Info(name+" extension not found or not installed yet", "output", output) return nil diff --git a/operator/src/internal/engine/extension_policy_test.go b/operator/src/internal/engine/extension_policy_test.go index a3740d1b0..b5c44c2f4 100644 --- a/operator/src/internal/engine/extension_policy_test.go +++ b/operator/src/internal/engine/extension_policy_test.go @@ -16,6 +16,7 @@ import ( type extensionPolicyAdapter struct { product.DocumentDBAdapter format product.ExtensionVersionFormat + pinned string } func (a extensionPolicyAdapter) Profile() product.ProductProfile { @@ -23,9 +24,49 @@ func (a extensionPolicyAdapter) Profile() product.ProductProfile { p.Name = "Widget" p.Postgres.Extension.Name = "widget" p.Postgres.ExtensionVersionFormat = a.format + p.Postgres.PinnedCatalogVersion = a.pinned return p } +func TestPinnedCatalogNeverAltersOrNormalizesVersion(t *testing.T) { + for _, tc := range []struct { + name, binary, installed, requested string + wantError bool + }{ + {name: "exact opaque catalog", binary: "7.4", installed: "7.4"}, + {name: "changed binary", binary: "7.5", installed: "7.4", wantError: true}, + {name: "changed installed catalog", binary: "7.4", installed: "7.3", wantError: true}, + {name: "missing catalog", binary: "7.4", wantError: true}, + {name: "explicit upgrade", binary: "7.4", installed: "7.4", requested: "auto", wantError: true}, + } { + t.Run(tc.name, func(t *testing.T) { + scheme := newTestScheme(t) + db := reconcilableCluster() + db.Spec.SchemaVersion = tc.requested + c := newFakeClient(t, scheme, nil, db) + r, _ := newClusterReconciler(c, scheme, &sqlRecorder{}) + r.Adapter = extensionPolicyAdapter{pinned: "7.4"} + r.SQLExecutor = func(_ context.Context, _ *cnpgv1.Cluster, statement string) (string, error) { + if !strings.Contains(statement, "pg_available_extensions") { + t.Fatalf("pinned product attempted SQL mutation: %s", statement) + } + return "default_version | installed_version\n---+---\n" + tc.binary + " | " + tc.installed + "\n(1 row)", nil + } + cluster := &cnpgv1.Cluster{Status: cnpgv1.ClusterStatus{ + CurrentPrimary: "db-1", + InstancesStatus: map[cnpgv1.PodStatus][]string{cnpgv1.PodHealthy: {"db-1"}}, + }} + err := r.HandleExtensionUpgrade(context.Background(), cluster, db) + if (err != nil) != tc.wantError { + t.Fatalf("catalog verification error: %v, wantError=%v", err, tc.wantError) + } + if !tc.wantError && getDocumentDB(t, c).Status.SchemaVersion != "7.4" { + t.Fatal("opaque catalog version was rewritten") + } + }) + } +} + func TestHandleExtensionUpgradeVersionPolicy(t *testing.T) { for _, tc := range []struct { name string diff --git a/operator/src/internal/product/definition.go b/operator/src/internal/product/definition.go new file mode 100644 index 000000000..3c5546276 --- /dev/null +++ b/operator/src/internal/product/definition.go @@ -0,0 +1,226 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "encoding/json" + "fmt" + "io" + "maps" + "net" + "os" + "reflect" + "strconv" + "strings" + + dbv1 "github.com/documentdb/documentdb-operator/api/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/validation" +) + +// Definition selects data and identity for the common API and adapter. +// A definition never supplies controller, admission or adapter callbacks. +type Definition struct { + APIVersion string `json:"apiVersion"` + API ResourceAPI `json:"api"` + Profile ProductProfile `json:"profile"` + Images Images `json:"images"` + Postgres Postgres `json:"postgres"` + Topology Topology `json:"topology"` + Policy Policy `json:"policy"` + Endpoint EndpointFormat `json:"endpoint"` +} + +type ResourceAPI struct { + Group string `json:"group"` + Version string `json:"version"` + Kind string `json:"kind"` + Plural string `json:"plural"` +} + +type Policy struct { + LocalDevelopment bool `json:"localDevelopment"` + MinimumInstances int `json:"minimumInstances"` + PinnedCatalog string `json:"pinnedCatalog,omitempty"` +} + +type EndpointFormat struct { + Template string `json:"template"` + ServiceDNS bool `json:"serviceDNS"` +} + +func LoadDefinition(path string) (*Definition, error) { + file, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("open product definition: %w", err) + } + defer file.Close() + decoder := json.NewDecoder(file) + decoder.DisallowUnknownFields() + var definition Definition + if err := decoder.Decode(&definition); err != nil { + return nil, fmt.Errorf("decode product definition: %w", err) + } + var extra json.RawMessage + if err := decoder.Decode(&extra); err != io.EOF { + return nil, fmt.Errorf("product definition must contain exactly one JSON object") + } + if err := definition.Validate(); err != nil { + return nil, err + } + return &definition, nil +} + +func (d *Definition) Validate() error { + if d.APIVersion != "operator.documentdb.io/product-definition/v1alpha1" { + return fmt.Errorf("unsupported product-definition apiVersion %q", d.APIVersion) + } + if len(validation.IsDNS1123Subdomain(d.API.Group)) != 0 || + len(validation.IsDNS1035Label(d.API.Version)) != 0 || + len(validation.IsDNS1035Label(d.API.Plural)) != 0 || d.API.Kind == "" || + len(validation.IsCIdentifier(d.API.Kind)) != 0 { + return fmt.Errorf("product definition requires valid group/version/kind/plural") + } + if d.Profile.Naming.Domain != d.API.Group || d.Profile.Naming.Kind != d.API.Kind { + return fmt.Errorf("profile naming must match the shared API identity") + } + if d.API.Kind == "Backup" || d.API.Kind == "ScheduledBackup" || + strings.HasSuffix(d.API.Kind, "List") || d.API.Plural == "backups" || d.API.Plural == "scheduledbackups" { + return fmt.Errorf("cluster identity conflicts with shared backup/list API types") + } + for _, entry := range []struct{ name, value string }{ + {"profile.Name", d.Profile.Name}, + {"profile.Postgres.Extension.Name", d.Profile.Postgres.Extension.Name}, + {"profile.Naming.ServicePrefix", d.Profile.Naming.ServicePrefix}, + {"profile.Naming.OperatorName", d.Profile.Naming.OperatorName}, + {"profile.Naming.MetricClusterAttribute", d.Profile.Naming.MetricClusterAttribute}, + {"profile.Naming.HealthMetricName", d.Profile.Naming.HealthMetricName}, + {"profile.DefaultCredentialSecret", d.Profile.DefaultCredentialSecret}, + {"profile.SidecarInjectorPlugin", d.Profile.SidecarInjectorPlugin}, + {"images.Postgres", d.Images.Postgres}, + {"images.PostgresExtension", d.Images.PostgresExtension}, + {"images.Gateway", d.Images.Gateway}, + {"endpoint.template", d.Endpoint.Template}, + {"profile.Gateway.UsernameEnv", d.Profile.Gateway.UsernameEnv}, + {"profile.Gateway.PasswordEnv", d.Profile.Gateway.PasswordEnv}, + } { + if strings.TrimSpace(entry.value) == "" { + return fmt.Errorf("product definition requires %s", entry.name) + } + } + if len(d.Profile.Naming.ServicePrefix) >= 55 || + len(validation.IsDNS1123Label(d.Profile.Naming.ServicePrefix+"a")) != 0 { + return fmt.Errorf("service prefix must be DNS-safe and shorter than 55 characters") + } + if d.Profile.Gateway.Port < 1 || d.Profile.Gateway.Port > 65535 || + len(validation.IsDNS1123Label(d.Profile.Gateway.ContainerName)) != 0 || + d.Profile.Gateway.Args == nil { + return fmt.Errorf("gateway requires an explicit valid container name, port and argument array") + } + if len(d.Profile.Postgres.PgHBA) == 0 || len(d.Profile.Postgres.BootstrapSQL) == 0 || + len(d.Profile.Postgres.Extension.DynamicLibraryPath) == 0 || + len(d.Profile.Postgres.Extension.ExtensionControlPath) == 0 { + return fmt.Errorf("PostgreSQL HBA, bootstrap and extension paths must be explicit") + } + if d.Policy.MinimumInstances < 1 { + return fmt.Errorf("minimumInstances must be positive") + } + if d.Images.Combined != "" || d.Topology.Instances != 0 { + return fmt.Errorf("definitions require split images; instance counts belong in the shared cluster resource") + } + if d.Policy.PinnedCatalog != "" && !d.Policy.LocalDevelopment { + return fmt.Errorf("non-upgrading pinned catalog policy requires explicit localDevelopment") + } + if (d.Postgres.UID == nil) != (d.Postgres.GID == nil) || + (d.Postgres.UID != nil && (*d.Postgres.UID <= 0 || *d.Postgres.GID <= 0)) { + return fmt.Errorf("PostgreSQL UID/GID must be supplied together and be non-root") + } + if d.Topology.Affinity.PodAntiAffinityType == "preferred" && !d.Policy.LocalDevelopment { + return fmt.Errorf("co-located scheduling requires explicit localDevelopment") + } + if !strings.Contains(d.Endpoint.Template, "{address}") { + return fmt.Errorf("endpoint template must contain {address}") + } + return nil +} + +func (d *Definition) GroupVersion() schema.GroupVersion { + return schema.GroupVersion{Group: d.API.Group, Version: d.API.Version} +} + +// AddToScheme binds the same shared Go API/schema to the selected product identity. +func (d *Definition) AddToScheme(scheme *runtime.Scheme) error { + gv := d.GroupVersion() + for kind, object := range map[string]runtime.Object{ + d.API.Kind: &dbv1.DocumentDB{}, d.API.Kind + "List": &dbv1.DocumentDBList{}, + "Backup": &dbv1.Backup{}, "BackupList": &dbv1.BackupList{}, + "ScheduledBackup": &dbv1.ScheduledBackup{}, "ScheduledBackupList": &dbv1.ScheduledBackupList{}, + } { + scheme.AddKnownTypeWithName(gv.WithKind(kind), object) + } + metav1.AddToGroupVersion(scheme, gv) + return nil +} + +func (a DocumentDBAdapter) applyDefinition(intent ClusterIntent, db *dbv1.DocumentDB) ClusterIntent { + if a.Definition == nil { + return intent + } + d := a.Definition + pg := d.Postgres + if intent.Postgres.UID != nil { + pg.UID = intent.Postgres.UID + } + if intent.Postgres.GID != nil { + pg.GID = intent.Postgres.GID + } + pg.Parameters = maps.Clone(d.Postgres.Parameters) + for key, value := range intent.Postgres.Parameters { + if pg.Parameters == nil { + pg.Parameters = make(map[string]string) + } + pg.Parameters[key] = value + } + pg.PostInitSQL = append(append([]string(nil), d.Postgres.PostInitSQL...), intent.Postgres.PostInitSQL...) + if intent.Postgres.LogLevel != "" { + pg.LogLevel = intent.Postgres.LogLevel + } + if intent.Postgres.StopDelay != 0 { + pg.StopDelay = intent.Postgres.StopDelay + } + intent.Postgres = pg + if reflect.DeepEqual(db.Spec.Affinity, Topology{}.Affinity) { + intent.Topology.Affinity = d.Topology.Affinity + } + intent.Images = d.Images + if db.Spec.Image != nil { + if db.Spec.Image.Postgres != "" { + intent.Images.Postgres = db.Spec.Image.Postgres + } + if db.Spec.Image.DocumentDB != "" { + intent.Images.PostgresExtension = db.Spec.Image.DocumentDB + } + if db.Spec.Image.Gateway != "" { + intent.Images.Gateway = db.Spec.Image.Gateway + } + } + if db.Spec.ImagePullSecrets != nil { + intent.Images.PullSecrets = db.Spec.ImagePullSecrets + } + intent.Images.Combined = "" + return intent +} + +func (d *Definition) endpoint(db *dbv1.DocumentDB, host string, port int32) string { + if d.Endpoint.ServiceDNS && db.Spec.ExposeViaService.ServiceType == "ClusterIP" { + service := db.Annotations[d.Profile.Naming.ServiceNameAnnotation()] + if service == "" { + service = d.Profile.Naming.ServiceName(db.Name) + } + host = service + "." + db.Namespace + ".svc" + } + return strings.ReplaceAll(d.Endpoint.Template, "{address}", net.JoinHostPort(host, strconv.Itoa(int(port)))) +} diff --git a/operator/src/internal/product/definition_chart_test.go b/operator/src/internal/product/definition_chart_test.go new file mode 100644 index 000000000..724141b5b --- /dev/null +++ b/operator/src/internal/product/definition_chart_test.go @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "testing" + + admissionv1 "k8s.io/api/admissionregistration/v1" + apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "sigs.k8s.io/yaml" +) + +func TestDefinitionChartUsesCanonicalSchemaAndAdmissionIdentity(t *testing.T) { + if _, err := exec.LookPath("helm"); err != nil { + t.Skip("Helm is required for the shared product chart contract test") + } + definition, err := LoadDefinition("testdata/widget.json") + if err != nil { + t.Fatal(err) + } + image := map[string]string{ + "repository": "registry.example.invalid/operator", + "digest": "sha256:" + strings.Repeat("a", 64), + } + values, err := json.Marshal(map[string]any{ + "productDefinition": definition, "image": image, + "sidecarInjector": map[string]any{"enabled": true, "image": image}, + }) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "values.json") + if err := os.WriteFile(path, values, 0600); err != nil { + t.Fatal(err) + } + chart := "../../../product-helm-chart" + command := exec.Command("helm", "template", "widget", chart, "-n", "widget-system", "-f", path) + output, err := command.CombinedOutput() + if err != nil { + t.Fatalf("shared chart failed: %v\n%s", err, output) + } + var canonical apiextv1.CustomResourceDefinition + data, err := os.ReadFile("../../config/crd/bases/documentdb.io_dbs.yaml") + if err != nil { + t.Fatal(err) + } + if err := yaml.Unmarshal(data, &canonical); err != nil { + t.Fatal(err) + } + var schema *apiextv1.CustomResourceValidation + for _, version := range canonical.Spec.Versions { + if version.Storage { + schema = version.Schema + } + } + var clusters, backups, webhooks int + for _, document := range strings.Split(string(output), "\n---\n") { + var identity struct{ Kind string } + if err := yaml.Unmarshal([]byte(document), &identity); err != nil { + t.Fatal(err) + } + switch identity.Kind { + case "CustomResourceDefinition": + var crd apiextv1.CustomResourceDefinition + if err := yaml.Unmarshal([]byte(document), &crd); err != nil { + t.Fatal(err) + } + if crd.Spec.Group != definition.API.Group || len(crd.Spec.Versions) != 1 || + crd.Spec.Versions[0].Name != definition.API.Version || crd.Annotations["helm.sh/resource-policy"] != "keep" { + t.Fatalf("incorrect API identity or unsafe CRD lifecycle: %+v", crd.Spec.Names) + } + if crd.Spec.Names.Kind == definition.API.Kind { + clusters++ + if crd.Spec.Names.Plural != definition.API.Plural || !reflect.DeepEqual(crd.Spec.Versions[0].Schema, schema) { + t.Fatal("product forked the shared cluster schema") + } + } else { + backups++ + } + case "ValidatingWebhookConfiguration": + var configuration admissionv1.ValidatingWebhookConfiguration + if err := yaml.Unmarshal([]byte(document), &configuration); err != nil { + t.Fatal(err) + } + webhooks++ + hook := configuration.Webhooks[0] + want := "/validate-widget-example-io-v1alpha1-database" + if *hook.ClientConfig.Service.Path != want || hook.Rules[0].APIGroups[0] != definition.API.Group || + hook.Rules[0].Resources[0] != definition.API.Plural { + t.Fatalf("admission does not match the common runtime registration: %+v", hook) + } + } + } + if clusters != 1 || backups != 2 || webhooks != 1 { + t.Fatalf("missing shared resources: clusters=%d backups=%d webhooks=%d", clusters, backups, webhooks) + } +} + +func TestDefinitionChartSchemaCopiesMatchCanonicalSources(t *testing.T) { + chart := "../../../product-helm-chart" + for _, entry := range []struct{ generated, source string }{ + {"cluster", "dbs"}, {"backup", "backups"}, {"scheduled-backup", "scheduledbackups"}, + } { + generated, err := os.ReadFile(filepath.Join(chart, "schemas", entry.generated+".yaml")) + if err != nil { + t.Fatal(err) + } + source, err := os.ReadFile("../../config/crd/bases/documentdb.io_" + entry.source + ".yaml") + if err != nil { + t.Fatal(err) + } + if string(generated) != string(source) { + t.Fatalf("shared schema copy drifted; run make -C operator/product-helm-chart schemas: %s", entry.generated) + } + } +} diff --git a/operator/src/internal/product/definition_test.go b/operator/src/internal/product/definition_test.go new file mode 100644 index 000000000..7ac92ae4d --- /dev/null +++ b/operator/src/internal/product/definition_test.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "reflect" + "testing" + + dbv1 "github.com/documentdb/documentdb-operator/api/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +func TestDefinitionUsesOneSharedAPIAndAdapter(t *testing.T) { + definition, err := LoadDefinition("testdata/widget.json") + if err != nil { + t.Fatal(err) + } + scheme := runtime.NewScheme() + if err := definition.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + adapter := DocumentDBAdapter{Definition: definition} + db := adapter.New() + db.Name, db.Namespace = "sample", "widgets" + db.Spec.InstancesPerNode = 3 + db.Spec.ExposeViaService.ServiceType = "ClusterIP" + db.Spec.Postgres = &dbv1.PostgresSpec{Parameters: map[string]string{"work_mem": "16MB"}} + gvks, _, err := scheme.ObjectKinds(db) + if err != nil || len(gvks) != 1 || gvks[0] != db.GroupVersionKind() { + t.Fatalf("shared type has ambiguous or incorrect identity: %v, %v", gvks, err) + } + object, err := scheme.New(gvks[0]) + if _, ok := object.(*dbv1.DocumentDB); err != nil || !ok { + t.Fatalf("product must use the existing shared Go API: %T, %v", object, err) + } + intent := adapter.ToClusterIntent(db) + if !reflect.DeepEqual(intent.Images, definition.Images) || + intent.Topology.Instances != 3 || intent.Topology.Affinity.PodAntiAffinityType != "preferred" || + intent.Postgres.UID == nil || *intent.Postgres.UID != 1000 || + intent.Postgres.Parameters["work_mem"] != "16MB" || intent.Postgres.Parameters["maintenance_work_mem"] != "8MB" { + t.Fatalf("definition defaults / CR overrides were lost: %+v", intent) + } + if definition.Postgres.Parameters["work_mem"] != "4MB" { + t.Fatal("mapping mutated the shared definition") + } + if got := adapter.ConnectionString(db, "10.0.0.1", 8443, true); got != "https://widget-sample.widgets.svc:8443/" { + t.Fatalf("endpoint does not use certificate-covered service DNS: %s", got) + } + if !reflect.DeepEqual((DocumentDBAdapter{}).Profile(), DocumentDBProfile()) { + t.Fatal("zero-value adapter changed the existing product") + } +} + +func TestDefinitionFailsClosed(t *testing.T) { + data, err := os.ReadFile("testdata/widget.json") + if err != nil { + t.Fatal(err) + } + for name, mutate := range map[string]func(*Definition){ + "unknown format": func(d *Definition) { d.APIVersion = "unknown" }, + "identity mismatch": func(d *Definition) { d.API.Group = "different.example.io" }, + "missing runtime image": func(d *Definition) { d.Images.Gateway = "" }, + "missing gateway arguments": func(d *Definition) { d.Profile.Gateway.Args = nil }, + "unsafe scheduling policy": func(d *Definition) { d.Policy.LocalDevelopment = false }, + "missing instance policy": func(d *Definition) { d.Policy.MinimumInstances = 0 }, + "reserved kind": func(d *Definition) { + d.API.Kind, d.Profile.Naming.Kind = "Backup", "Backup" + }, + "unpaired process identity": func(d *Definition) { d.Postgres.GID = nil }, + } { + t.Run(name, func(t *testing.T) { + var definition Definition + if err := json.Unmarshal(data, &definition); err != nil { + t.Fatal(err) + } + mutate(&definition) + if err := definition.Validate(); err == nil { + t.Fatal("invalid definition accepted") + } + }) + } + for name, invalid := range map[string][]byte{ + "unknown field": bytes.Replace(data, []byte(`"images"`), []byte(`"typo":true,"images"`), 1), + "trailing object": append(append([]byte(nil), data...), []byte("\n{}")...), + "null": []byte("null"), + "bypassing catalog policy": bytes.Replace(data, []byte(`"Postgres": {`), []byte(`"Postgres":{"PinnedCatalogVersion":"9.9",`), 1), + } { + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "definition.json") + if err := os.WriteFile(path, invalid, 0600); err != nil { + t.Fatal(err) + } + if _, err := LoadDefinition(path); err == nil { + t.Fatal("invalid serialized definition accepted") + } + }) + } +} diff --git a/operator/src/internal/product/documentdb.go b/operator/src/internal/product/documentdb.go index 5a1ec75f4..c324a5266 100644 --- a/operator/src/internal/product/documentdb.go +++ b/operator/src/internal/product/documentdb.go @@ -69,10 +69,17 @@ const DocumentDBCoreExtensionName = "documentdb_core" // DocumentDBAdapter is the first product adapter. It maps the DocumentDB custom // resource onto the product-neutral model consumed by the reconciler. -type DocumentDBAdapter struct{} +type DocumentDBAdapter struct { + Definition *Definition +} // Profile returns the DocumentDB product profile. -func (DocumentDBAdapter) Profile() ProductProfile { +func (a DocumentDBAdapter) Profile() ProductProfile { + if a.Definition != nil { + profile := a.Definition.Profile + profile.Postgres.PinnedCatalogVersion = a.Definition.Policy.PinnedCatalog + return profile + } return DocumentDBProfile() } @@ -80,6 +87,12 @@ func (DocumentDBAdapter) Profile() ProductProfile { // product profile's repo and default. The resolution priority is shared across // products via util.ResolveComponentImage. func (a DocumentDBAdapter) ExtensionImage(db *dbv1.DocumentDB) string { + if a.Definition != nil { + if db.Spec.Image != nil && db.Spec.Image.DocumentDB != "" { + return db.Spec.Image.DocumentDB + } + return a.Definition.Images.PostgresExtension + } p := a.Profile() var explicit string if db.Spec.Image != nil { @@ -100,6 +113,9 @@ func (a DocumentDBAdapter) ExtensionImage(db *dbv1.DocumentDB) string { // the cluster runs in combined image mode. Change-stream images have no // combined counterpart, so the change-stream feature gate does not affect it. func (a DocumentDBAdapter) CombinedImage(db *dbv1.DocumentDB) string { + if a.Definition != nil { + return "" + } var explicit string if db.Spec.Image != nil { explicit = db.Spec.Image.DocumentDB @@ -110,6 +126,12 @@ func (a DocumentDBAdapter) CombinedImage(db *dbv1.DocumentDB) string { // GatewayImage resolves the gateway image for a DocumentDB instance using the // product profile's repo and default. func (a DocumentDBAdapter) GatewayImage(db *dbv1.DocumentDB) string { + if a.Definition != nil { + if db.Spec.Image != nil && db.Spec.Image.Gateway != "" { + return db.Spec.Image.Gateway + } + return a.Definition.Images.Gateway + } p := a.Profile() var explicit string if db.Spec.Image != nil { @@ -202,7 +224,7 @@ func (a DocumentDBAdapter) ToClusterIntent(db *dbv1.DocumentDB) ClusterIntent { bootstrap.Recovery = &r } - return ClusterIntent{ + return a.applyDefinition(ClusterIntent{ Images: Images{ PostgresExtension: a.ExtensionImage(db), PostgresExtensionPullPolicy: ParsePullPolicy(os.Getenv(util.DOCUMENTDB_IMAGE_PULL_POLICY_ENV)), @@ -238,7 +260,7 @@ func (a DocumentDBAdapter) ToClusterIntent(db *dbv1.DocumentDB) ClusterIntent { SidecarInjectorPlugin: sidecarPlugin, WALReplicaPlugin: p.WALReplicaPlugin, Product: p, - } + }, db) } // compile-time assertion that DocumentDBAdapter satisfies the Adapter seam. @@ -248,7 +270,13 @@ var _ Adapter = DocumentDBAdapter{} var _ ClusterAdapter[*dbv1.DocumentDB] = DocumentDBAdapter{} // New returns an empty DocumentDB custom resource. -func (DocumentDBAdapter) New() *dbv1.DocumentDB { return &dbv1.DocumentDB{} } +func (a DocumentDBAdapter) New() *dbv1.DocumentDB { + db := &dbv1.DocumentDB{} + if a.Definition != nil { + db.SetGroupVersionKind(a.Definition.GroupVersion().WithKind(a.Definition.API.Kind)) + } + return db +} // Intent is ToClusterIntent under the ClusterAdapter contract. func (a DocumentDBAdapter) Intent(db *dbv1.DocumentDB) ClusterIntent { @@ -299,6 +327,9 @@ func (DocumentDBAdapter) SetStatus(db *dbv1.DocumentDB, s ClusterStatus) { // ConnectionString builds the MongoDB-protocol connection string for a // DocumentDB gateway. func (a DocumentDBAdapter) ConnectionString(db *dbv1.DocumentDB, host string, port int32, trustTLS bool) string { + if a.Definition != nil { + return a.Definition.endpoint(db, host, port) + } secretName := db.Spec.DocumentDbCredentialSecret if secretName == "" { secretName = a.Profile().DefaultCredentialSecret diff --git a/operator/src/internal/product/documentdb_backup.go b/operator/src/internal/product/documentdb_backup.go index 7c1b9c5ae..f05280dcc 100644 --- a/operator/src/internal/product/documentdb_backup.go +++ b/operator/src/internal/product/documentdb_backup.go @@ -11,10 +11,22 @@ import ( // DocumentDBBackupAdapter maps the documentdb.io Backup custom resource onto // the shared backup spec and status (engine.BackupAdapter). -type DocumentDBBackupAdapter struct{} +type DocumentDBBackupAdapter struct{ Definition *Definition } -func (DocumentDBBackupAdapter) New() *dbv1.Backup { return &dbv1.Backup{} } -func (DocumentDBBackupAdapter) NewList() client.ObjectList { return &dbv1.BackupList{} } +func (a DocumentDBBackupAdapter) New() *dbv1.Backup { + object := &dbv1.Backup{} + if a.Definition != nil { + object.SetGroupVersionKind(a.Definition.GroupVersion().WithKind("Backup")) + } + return object +} +func (a DocumentDBBackupAdapter) NewList() client.ObjectList { + object := &dbv1.BackupList{} + if a.Definition != nil { + object.SetGroupVersionKind(a.Definition.GroupVersion().WithKind("BackupList")) + } + return object +} func (DocumentDBBackupAdapter) Spec(b *dbv1.Backup) *dbv1.BackupSpec { return &b.Spec } @@ -38,10 +50,14 @@ func (DocumentDBBackupAdapter) Items(list client.ObjectList) []*dbv1.Backup { // DocumentDBScheduledBackupAdapter maps the documentdb.io ScheduledBackup // custom resource onto the shared scheduled-backup spec and status // (engine.ScheduledBackupAdapter). -type DocumentDBScheduledBackupAdapter struct{} +type DocumentDBScheduledBackupAdapter struct{ Definition *Definition } -func (DocumentDBScheduledBackupAdapter) New() *dbv1.ScheduledBackup { - return &dbv1.ScheduledBackup{} +func (a DocumentDBScheduledBackupAdapter) New() *dbv1.ScheduledBackup { + object := &dbv1.ScheduledBackup{} + if a.Definition != nil { + object.SetGroupVersionKind(a.Definition.GroupVersion().WithKind("ScheduledBackup")) + } + return object } func (DocumentDBScheduledBackupAdapter) Spec(s *dbv1.ScheduledBackup) *dbv1.ScheduledBackupSpec { return &s.Spec diff --git a/operator/src/internal/product/profile.go b/operator/src/internal/product/profile.go index b62bf226e..acb7df1dd 100644 --- a/operator/src/internal/product/profile.go +++ b/operator/src/internal/product/profile.go @@ -6,8 +6,9 @@ // plugin/secret conventions that vary between operator products, and an Adapter // translates a product-specific custom resource into that neutral model. The // reconciler consumes the profile and a ClusterIntent, so it carries no -// product-branding logic; each product supplies its own adapter without changing -// the reconciler. +// product-branding logic. Products using the shared API configure its existing +// adapter with a declarative Definition; integrations with a different API can +// still provide an adapter without changing the reconciler. package product // ProductProfile captures the product-varying identity and defaults for an @@ -94,6 +95,9 @@ const ( // PostgresProfile captures the product-wide PostgreSQL contract. type PostgresProfile struct { + // PinnedCatalogVersion is an explicit non-upgrading catalog policy. + // The definition loader restricts it to local-development definitions. + PinnedCatalogVersion string `json:"-"` // Extension is the product extension mounted from the extension image. Extension ExtensionSpec // ExtensionVersionFormat controls extension comparison and spec/status diff --git a/operator/src/internal/product/testdata/widget.json b/operator/src/internal/product/testdata/widget.json new file mode 100644 index 000000000..b2d8af0d7 --- /dev/null +++ b/operator/src/internal/product/testdata/widget.json @@ -0,0 +1,53 @@ +{ + "apiVersion": "operator.documentdb.io/product-definition/v1alpha1", + "api": { + "group": "widget.example.io", + "version": "v1alpha1", + "kind": "Database", + "plural": "databases" + }, + "profile": { + "Name": "Widget", + "DefaultCredentialSecret": "widget-credentials", + "SidecarInjectorPlugin": "cnpg-i-sidecar-injector.documentdb.io", + "Postgres": { + "Extension": { + "Name": "widget", + "DynamicLibraryPath": ["lib"], + "ExtensionControlPath": ["share/extension"], + "LdLibraryPath": ["lib"] + }, + "AdditionalLibraries": ["widget"], + "BootstrapSQL": ["CREATE EXTENSION widget"], + "PgHBA": ["host all widget 127.0.0.1/32 trust"] + }, + "Gateway": { + "ContainerName": "widget-gateway", + "Port": 8443, + "Args": ["--config=/etc/widget/config.json"], + "UsernameEnv": "WIDGET_USER", + "PasswordEnv": "WIDGET_PASSWORD" + }, + "Naming": { + "Domain": "widget.example.io", + "Kind": "Database", + "ServicePrefix": "widget-", + "OperatorName": "widget-operator", + "MetricClusterAttribute": "widget.cluster", + "HealthMetricName": "widget.postgres.up" + } + }, + "images": { + "Postgres": "registry.example.invalid/postgres:18", + "PostgresExtension": "registry.example.invalid/widget-extension:proof", + "Gateway": "registry.example.invalid/widget-gateway:proof" + }, + "postgres": { + "UID": 1000, + "GID": 1000, + "Parameters": {"work_mem": "4MB", "maintenance_work_mem": "8MB"} + }, + "topology": {"Affinity": {"enablePodAntiAffinity": true, "podAntiAffinityType": "preferred"}}, + "policy": {"localDevelopment": true, "minimumInstances": 1, "pinnedCatalog": "7.4"}, + "endpoint": {"template": "https://{address}/", "serviceDNS": true} +} diff --git a/operator/src/internal/webhook/definition_test.go b/operator/src/internal/webhook/definition_test.go new file mode 100644 index 000000000..a0b3315f3 --- /dev/null +++ b/operator/src/internal/webhook/definition_test.go @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package webhook + +import ( + "testing" + + dbv1 "github.com/documentdb/documentdb-operator/api/v1" + "github.com/documentdb/documentdb-operator/internal/product" +) + +func TestSharedAdmissionDefinitionPolicy(t *testing.T) { + definition, err := product.LoadDefinition("../product/testdata/widget.json") + if err != nil { + t.Fatal(err) + } + + validator := &DocumentDBValidator{Adapter: product.DocumentDBAdapter{Definition: definition}} + for name, tc := range map[string]struct { + mutate func(*dbv1.DocumentDB) + wantError bool + }{ + "single local primary": {mutate: func(db *dbv1.DocumentDB) { db.Spec.InstancesPerNode = 1 }}, + "three local instances": {mutate: func(db *dbv1.DocumentDB) { db.Spec.InstancesPerNode = 3 }}, + "zero instances": {mutate: func(db *dbv1.DocumentDB) { db.Spec.InstancesPerNode = 0 }, wantError: true}, + "unimplemented multi-region": {mutate: func(db *dbv1.DocumentDB) { + db.Spec.ClusterReplication = &dbv1.ClusterReplication{} + }, wantError: true}, + "ignored legacy version": {mutate: func(db *dbv1.DocumentDB) { + db.Spec.DocumentDBVersion = "1.2.3" + }, wantError: true}, + "catalog upgrade": {mutate: func(db *dbv1.DocumentDB) { + db.Spec.SchemaVersion = "auto" + }, wantError: true}, + "different fixed extension image": {mutate: func(db *dbv1.DocumentDB) { + db.Spec.Image = &dbv1.ImageSpec{DocumentDB: "registry.example.invalid/extension:changed"} + }, wantError: true}, + } { + t.Run(name, func(t *testing.T) { + db := validator.Adapter.New() + db.Spec.InstancesPerNode = 1 + tc.mutate(db) + errors := append(validator.validateDefinitionPolicy(db), validator.validateSchemaVersionNotExceedsBinary(db)...) + if (len(errors) != 0) != tc.wantError { + t.Fatalf("unexpected common admission result: %v", errors) + } + }) + } + if validator.groupKind().Group != definition.API.Group || validator.groupResource().Resource != definition.API.Plural { + t.Fatal("admission errors use the wrong API identity") + } +} + +func TestDefinitionImageParticipatesInCommonVersionGuards(t *testing.T) { + definition, err := product.LoadDefinition("../product/testdata/widget.json") + if err != nil { + t.Fatal(err) + } + definition.Policy.PinnedCatalog = "" + definition.Profile.Postgres.ExtensionVersionFormat = product.ExtensionVersionSemver + definition.Images.PostgresExtension = "registry.example.invalid/widget:1.2.3" + validator := &DocumentDBValidator{Adapter: product.DocumentDBAdapter{Definition: definition}} + db := validator.Adapter.New() + db.Spec.SchemaVersion = "1.2.3" + if errors := validator.validateSchemaVersionNotExceedsBinary(db); len(errors) != 0 { + t.Fatalf("definition-pinned binary was ignored: %v", errors) + } + db.Spec.SchemaVersion = "1.3.0" + if errors := validator.validateSchemaVersionNotExceedsBinary(db); len(errors) == 0 { + t.Fatal("schema newer than the definition's binary was accepted") + } + old := validator.Adapter.New() + old.Status.SchemaVersion = "2.0.0" + old.Spec.Image = &dbv1.ImageSpec{DocumentDB: "registry.example.invalid/widget:2.0.0"} + reverted := old.DeepCopy() + reverted.Spec.Image = nil + if errors := validator.validateImageRollback(reverted, old); len(errors) == 0 { + t.Fatal("removing an override allowed a downgrade to the older definition image") + } +} diff --git a/operator/src/internal/webhook/documentdb_webhook.go b/operator/src/internal/webhook/documentdb_webhook.go index a9d908ec6..6d54b34bb 100644 --- a/operator/src/internal/webhook/documentdb_webhook.go +++ b/operator/src/internal/webhook/documentdb_webhook.go @@ -5,6 +5,7 @@ package webhook import ( "context" + "fmt" "reflect" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -35,6 +36,7 @@ var documentDBTerms = validation.Terms{ // DocumentDBValidator validates DocumentDB resources on create and update. type DocumentDBValidator struct { client.Client + Adapter product.DocumentDBAdapter } var _ admission.Validator[*dbv1.DocumentDB] = &DocumentDBValidator{} @@ -42,7 +44,7 @@ var _ admission.Validator[*dbv1.DocumentDB] = &DocumentDBValidator{} // SetupWebhookWithManager registers the validating webhook with the manager. func (v *DocumentDBValidator) SetupWebhookWithManager(mgr ctrl.Manager) error { v.Client = mgr.GetClient() - return ctrl.NewWebhookManagedBy(mgr, &dbv1.DocumentDB{}). + return ctrl.NewWebhookManagedBy(mgr, v.Adapter.New()). WithValidator(v). Complete() } @@ -62,7 +64,7 @@ func (v *DocumentDBValidator) ValidateCreate(ctx context.Context, documentdb *db // cluster-wide capability, not a per-spec property. if err := v.ensureImageVolumeSupported(ctx, documentdb.Namespace); err != nil { return nil, apierrors.NewForbidden( - schema.GroupResource{Group: "documentdb.io", Resource: "dbs"}, + v.groupResource(), documentdb.Name, err) } @@ -77,7 +79,7 @@ func (v *DocumentDBValidator) ValidateCreate(ctx context.Context, documentdb *db return warnings, nil } return warnings, apierrors.NewInvalid( - schema.GroupKind{Group: "documentdb.io", Kind: "DocumentDB"}, + v.groupKind(), documentdb.Name, allErrs) } @@ -93,7 +95,7 @@ func (v *DocumentDBValidator) ValidateUpdate(_ context.Context, oldDB, newDB *db return nil, nil } return nil, apierrors.NewInvalid( - schema.GroupKind{Group: "documentdb.io", Kind: "DocumentDB"}, + v.groupKind(), newDB.Name, allErrs) } @@ -112,6 +114,7 @@ func (v *DocumentDBValidator) validate(db *dbv1.DocumentDB) (allErrs field.Error validations := []validationFunc{ v.validateSchemaVersionNotExceedsBinary, v.validateResources, + v.validateDefinitionPolicy, // Add new spec-level validations here. } for _, fn := range validations { @@ -130,7 +133,13 @@ func (v *DocumentDBValidator) validateResources(db *dbv1.DocumentDB) field.Error // validateSchemaVersionNotExceedsBinary ensures spec.schemaVersion <= binary version. func (v *DocumentDBValidator) validateSchemaVersionNotExceedsBinary(db *dbv1.DocumentDB) field.ErrorList { - return validation.SchemaVersionNotExceedsBinary(db.Spec.SchemaVersion, resolveBinaryVersion(db), documentDBTerms) + if d := v.Adapter.Definition; d != nil && d.Policy.PinnedCatalog != "" { + if db.Spec.SchemaVersion != "" { + return field.ErrorList{field.Forbidden(field.NewPath("spec", "schemaVersion"), "the selected local product definition disables catalog upgrades")} + } + return nil + } + return validation.SchemaVersionNotExceedsBinary(db.Spec.SchemaVersion, v.binaryVersion(db), documentDBTerms) } // --------------------------------------------------------------------------- @@ -155,6 +164,9 @@ func (v *DocumentDBValidator) validateChanges(newDB, oldDB *dbv1.DocumentDB) (al // Once ALTER EXTENSION UPDATE has run, the schema is irreversible. Running an older // binary against a newer schema is untested and may cause data corruption. func (v *DocumentDBValidator) validateImageRollback(newDB, oldDB *dbv1.DocumentDB) field.ErrorList { + if d := v.Adapter.Definition; d != nil && d.Policy.PinnedCatalog != "" { + return nil // validateDefinitionPolicy fixes the extension image; the engine checks the exact catalog. + } installedSchemaVersion := oldDB.Status.SchemaVersion if installedSchemaVersion == "" { return nil @@ -169,7 +181,14 @@ func (v *DocumentDBValidator) validateImageRollback(newDB, oldDB *dbv1.DocumentD return nil } - return validation.ImageRollback(installedSchemaVersion, resolveBinaryVersion(newDB)) + return validation.ImageRollback(installedSchemaVersion, v.binaryVersion(newDB)) +} + +func (v *DocumentDBValidator) binaryVersion(db *dbv1.DocumentDB) string { + if v.Adapter.Definition != nil { + return validation.ImageTagSemver(v.Adapter.ExtensionImage(db)) + } + return resolveBinaryVersion(db) } // --------------------------------------------------------------------------- @@ -218,7 +237,11 @@ func (v *DocumentDBValidator) validateRestoreSchemaCompatibility(ctx context.Con return warnings, nil } - return validation.CompareBinaryToSchema(resolveEffectiveBinaryVersion(newDB), schemaVersion, src, documentDBTerms) + binaryVersion := resolveEffectiveBinaryVersion(newDB) + if v.Adapter.Definition != nil { + binaryVersion = validation.ImageTagSemver(v.Adapter.ExtensionImage(newDB)) + } + return validation.CompareBinaryToSchema(binaryVersion, schemaVersion, src, documentDBTerms) } // restoreSourceFor identifies the restore source from a recovery configuration, @@ -237,15 +260,62 @@ func restoreSourceFor(recovery *dbv1.RecoveryConfiguration) (validation.RestoreS // resolveSourceSchemaVersion reads the restore source and returns its recorded // schema version. See validation.SourceSchemaVersion. func (v *DocumentDBValidator) resolveSourceSchemaVersion(ctx context.Context, namespace string, src validation.RestoreSource) (string, admission.Warnings) { - return validation.SourceSchemaVersion(ctx, v.Client, src, util.AnnotationSchemaVersion, func() (string, error) { - backup := &dbv1.Backup{} + annotation := util.AnnotationSchemaVersion + if v.Adapter.Definition != nil { + annotation = v.Adapter.Profile().Naming.SchemaVersionAnnotation() + } + return validation.SourceSchemaVersion(ctx, v.Client, src, annotation, func() (string, error) { + backup := (product.DocumentDBBackupAdapter{Definition: v.Adapter.Definition}).New() if err := v.Get(ctx, client.ObjectKey{Name: src.Name, Namespace: namespace}, backup); err != nil { return "", err } + return backup.Status.SchemaVersion, nil }) } +func (v *DocumentDBValidator) groupKind() schema.GroupKind { + p := v.Adapter.Profile() + return schema.GroupKind{Group: p.Naming.Domain, Kind: p.Naming.Kind} +} + +func (v *DocumentDBValidator) groupResource() schema.GroupResource { + if d := v.Adapter.Definition; d != nil { + return schema.GroupResource{Group: d.API.Group, Resource: d.API.Plural} + } + return schema.GroupResource{Group: "documentdb.io", Resource: "dbs"} +} + +func (v *DocumentDBValidator) validateDefinitionPolicy(db *dbv1.DocumentDB) field.ErrorList { + d := v.Adapter.Definition + if d == nil { + return nil + } + var errors field.ErrorList + for name, rejected := range map[string]bool{ + "clusterReplication": db.Spec.ClusterReplication != nil, + "documentDBVersion": db.Spec.DocumentDBVersion != "", + "featureGates": dbv1.IsFeatureGateEnabled(db, dbv1.FeatureGateChangeStreams), + "bootstrap": d.Policy.PinnedCatalog != "" && db.Spec.Bootstrap != nil, + } { + if rejected { + errors = append(errors, field.Forbidden(field.NewPath("spec", name), "not supported by the declarative split-image runtime")) + } + } + if db.Spec.InstancesPerNode < d.Policy.MinimumInstances { + errors = append(errors, field.Invalid(field.NewPath("spec", "instancesPerNode"), + db.Spec.InstancesPerNode, fmt.Sprintf("product definition requires at least %d", d.Policy.MinimumInstances))) + } + if d.Policy.PinnedCatalog != "" && db.Spec.Image != nil && db.Spec.Image.DocumentDB != "" && + db.Spec.Image.DocumentDB != d.Images.PostgresExtension { + errors = append(errors, field.Forbidden(field.NewPath("spec", "image", "documentDB"), "the local non-upgrading definition fixes the extension image")) + } + if !d.Policy.LocalDevelopment && db.Spec.Affinity.PodAntiAffinityType == "preferred" { + errors = append(errors, field.Forbidden(field.NewPath("spec", "affinity"), "co-location requires a localDevelopment definition")) + } + return errors +} + // validateImmutableFields rejects updates to fields that cannot be changed after creation. // Note: credentialSecret, storageClass, and sidecarInjectorPluginName are enforced via // CEL transition rules on the CRD schema (see documentdb_types.go). diff --git a/operator/src/internal/webhook/imagevolume.go b/operator/src/internal/webhook/imagevolume.go index f92aab234..582b7203a 100644 --- a/operator/src/internal/webhook/imagevolume.go +++ b/operator/src/internal/webhook/imagevolume.go @@ -20,7 +20,7 @@ func (v *DocumentDBValidator) imageVolumeProbe() *validation.ImageVolumeProbe { return &validation.ImageVolumeProbe{ Client: v.Client, Confirmed: &imageVolumeConfirmed, - Product: "DocumentDB", + Product: v.Adapter.Profile().Name, Log: documentdbLog, } } @@ -34,7 +34,7 @@ func (v *DocumentDBValidator) imageVolumeProbe() *validation.ImageVolumeProbe { // the controller falls back to the combined PostgreSQL + DocumentDB image when // ImageVolume is unavailable (see docs/designs/combined-image-fallback.md). func (v *DocumentDBValidator) ensureImageVolumeSupported(ctx context.Context, namespace string) error { - if imagemode.ConfiguredMode() != imagemode.ImageVolume { + if v.Adapter.Definition == nil && imagemode.ConfiguredMode() != imagemode.ImageVolume { return nil } if err := v.imageVolumeProbe().Ensure(ctx, namespace); err != nil { diff --git a/operator/src/pkg/core/definition.go b/operator/src/pkg/core/definition.go new file mode 100644 index 000000000..6296a2221 --- /dev/null +++ b/operator/src/pkg/core/definition.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package core + +import "github.com/documentdb/documentdb-operator/internal/product" + +// SharedAPIAdapter and the backup adapters bind the existing shared API to a +// definition, without requiring another API, adapter or controller implementation. +type ( + ProductDefinition = product.Definition + ProductResourceAPI = product.ResourceAPI + SharedAPIAdapter = product.DocumentDBAdapter + SharedAPIBackupAdapter = product.DocumentDBBackupAdapter + SharedAPIScheduledBackupAdapter = product.DocumentDBScheduledBackupAdapter +) + +func LoadProductDefinition(path string) (*ProductDefinition, error) { + return product.LoadDefinition(path) +} diff --git a/operator/src/pkg/core/engine.go b/operator/src/pkg/core/engine.go index 9b1e9308e..8c4fe2d21 100644 --- a/operator/src/pkg/core/engine.go +++ b/operator/src/pkg/core/engine.go @@ -21,8 +21,8 @@ import ( "github.com/documentdb/documentdb-operator/internal/validation" ) -// Adapter contract. A product implements ClusterAdapter for its cluster custom -// resource, and BackupAdapter/ScheduledBackupAdapter when it exposes backups. +// Adapter contract. Declarative products reuse SharedAPIAdapter and the shared +// backup adapters. Integrations with another API can implement these contracts. type ( NamingProfile = product.NamingProfile ClusterSpec = product.ClusterSpec From 19cac960c1f3c9da8ea4cf3670a36677402f6f1b Mon Sep 17 00:00:00 2001 From: Rayhan Hossain Date: Mon, 30 Nov 2026 13:43:53 -0800 Subject: [PATCH 02/10] docs: clarify shared chart schema regeneration Document automatic schema synchronization and the Helm-independent drift guard. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 33b3cb3c-1b25-4ffb-bff1-ebf0f3d04058 Signed-off-by: Rayhan Hossain --- operator/product-helm-chart/README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/operator/product-helm-chart/README.md b/operator/product-helm-chart/README.md index e4c841fc0..548a18a9c 100644 --- a/operator/product-helm-chart/README.md +++ b/operator/product-helm-chart/README.md @@ -15,9 +15,11 @@ already exist. The bundled injector retains its actual existing RPC identity. CRDs are rendered from exact copies of the canonical shared API schemas. Only group/version/kind/resource metadata changes; there is no product-specific -schema or generated Go API. Run `make schemas` here after regenerating the -canonical CRDs. The chart contract test checks both source equality and rendered -schema equality. CRDs are retained on uninstall. +schema or generated Go API. `make manifests` in `operator/src` automatically +synchronizes these copies after regenerating canonical CRDs; `make schemas` +here refreshes only the copies. Source-equality checks run without Helm, while +the Helm contract test also checks rendered schema equality. CRDs are retained +on uninstall. For compatibility, the shared Go API and some JSON fields still carry their original DocumentDB names. A definition changes API identity, not serialization From a580ea1a20520b8646f310bed2b0ec5176e12919 Mon Sep 17 00:00:00 2001 From: Rayhan Hossain Date: Mon, 30 Nov 2026 13:57:56 -0800 Subject: [PATCH 03/10] test: verify startup compatibility and product configuration boundaries Extract startup product selection without changing its default behavior. Exercise the real offline CLI, default scheme isolation, invalid contracts, override/mutation safety, external endpoints, backup identities and restore guards. Meet the existing patch-coverage policy without exclusions or threshold changes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 33b3cb3c-1b25-4ffb-bff1-ebf0f3d04058 Signed-off-by: Rayhan Hossain --- operator/src/cmd/main.go | 45 ++++++---- operator/src/cmd/main_test.go | 86 +++++++++++++++++++ .../src/internal/product/definition_test.go | 84 ++++++++++++++++++ .../src/internal/webhook/definition_test.go | 52 +++++++++++ 4 files changed, 249 insertions(+), 18 deletions(-) create mode 100644 operator/src/cmd/main_test.go diff --git a/operator/src/cmd/main.go b/operator/src/cmd/main.go index 91c0be271..877a9d5b9 100644 --- a/operator/src/cmd/main.go +++ b/operator/src/cmd/main.go @@ -6,6 +6,7 @@ package main import ( "crypto/tls" "flag" + "fmt" "os" "path/filepath" @@ -88,26 +89,12 @@ func main() { flag.Parse() ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) - adapter := product.DocumentDBAdapter{} - leaderElectionID := "187ffea8.microsoft.com" - if definitionPath != "" { - definition, err := product.LoadDefinition(definitionPath) - if err != nil { - setupLog.Error(err, "invalid product definition") - os.Exit(1) - } - adapter.Definition = definition - scheme = runtime.NewScheme() - utilruntime.Must(clientgoscheme.AddToScheme(scheme)) - utilruntime.Must(cnpgv1.AddToScheme(scheme)) - utilruntime.Must(cmapi.AddToScheme(scheme)) - utilruntime.Must(fleetv1alpha1.AddToScheme(scheme)) - utilruntime.Must(definition.AddToScheme(scheme)) - leaderElectionID = "operator." + definition.API.Group - } else if checkDefinition { - setupLog.Error(nil, "--check-product-definition requires --product-definition") + adapter, runtimeScheme, leaderElectionID, err := configureProduct(definitionPath, checkDefinition) + if err != nil { + setupLog.Error(err, "invalid product definition") os.Exit(1) } + scheme = runtimeScheme if checkDefinition { setupLog.Info("product definition validated", "product", adapter.Profile().Name) return @@ -329,3 +316,25 @@ func main() { os.Exit(1) } } + +func configureProduct(path string, checkOnly bool) (product.DocumentDBAdapter, *runtime.Scheme, string, error) { + adapter := product.DocumentDBAdapter{} + if path == "" { + if checkOnly { + return adapter, nil, "", fmt.Errorf("--check-product-definition requires --product-definition") + } + return adapter, scheme, "187ffea8.microsoft.com", nil + } + definition, err := product.LoadDefinition(path) + if err != nil { + return adapter, nil, "", err + } + adapter.Definition = definition + configured := runtime.NewScheme() + utilruntime.Must(clientgoscheme.AddToScheme(configured)) + utilruntime.Must(cnpgv1.AddToScheme(configured)) + utilruntime.Must(cmapi.AddToScheme(configured)) + utilruntime.Must(fleetv1alpha1.AddToScheme(configured)) + utilruntime.Must(definition.AddToScheme(configured)) + return adapter, configured, "operator." + definition.API.Group, nil +} diff --git a/operator/src/cmd/main_test.go b/operator/src/cmd/main_test.go new file mode 100644 index 000000000..c0f515f0b --- /dev/null +++ b/operator/src/cmd/main_test.go @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package main + +import ( + "flag" + "os" + "path/filepath" + "testing" + + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" + dbv1 "github.com/documentdb/documentdb-operator/api/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +func TestDefaultStartupKeepsExistingAPIAndScheme(t *testing.T) { + original := scheme + adapter, configured, election, err := configureProduct("", false) + if err != nil || configured != original || adapter.Definition != nil || election != "187ffea8.microsoft.com" { + t.Fatalf("default startup changed: scheme=%p, definition=%v, election=%q, err=%v", + configured, adapter.Definition, election, err) + } + kinds, _, err := configured.ObjectKinds(adapter.New()) + if err != nil || len(kinds) != 1 || kinds[0] != dbv1.GroupVersion.WithKind("DocumentDB") { + t.Fatalf("existing API registration changed: %v, %v", kinds, err) + } +} + +func TestDefinitionStartupReusesTypesWithoutPollutingDefaultScheme(t *testing.T) { + original := scheme + adapter, configured, election, err := configureProduct("../internal/product/testdata/widget.json", true) + if err != nil { + t.Fatal(err) + } + object := adapter.New() + kinds, _, err := configured.ObjectKinds(object) + if err != nil || len(kinds) != 1 || kinds[0] != object.GroupVersionKind() || kinds[0].Group != "widget.example.io" { + t.Fatalf("ambiguous product API binding: %v, %v", kinds, err) + } + if configured == original || election != "operator.widget.example.io" || scheme != original { + t.Fatal("configured startup mutated the default scheme or election identity") + } + for _, builtIn := range []runtime.Object{&corev1.Pod{}, &cnpgv1.Cluster{}, &cmapi.Certificate{}} { + if _, _, err := configured.ObjectKinds(builtIn); err != nil { + t.Fatalf("product lost built-in registration %T: %v", builtIn, err) + } + } + defaultKinds, _, err := original.ObjectKinds(&dbv1.DocumentDB{}) + if err != nil || len(defaultKinds) != 1 || defaultKinds[0].Group != "documentdb.io" { + t.Fatal("loading another product changed default API discovery") + } +} + +func TestInvalidDefinitionStartupCannotFallBackToDefault(t *testing.T) { + for _, input := range []struct { + path string + check bool + }{ + {"", true}, + {filepath.Join(t.TempDir(), "missing.json"), false}, + } { + adapter, configured, election, err := configureProduct(input.path, input.check) + if err == nil || configured != nil || election != "" || adapter.Definition != nil { + t.Fatalf("invalid startup selected a usable default runtime: %v", err) + } + } + +} + +func TestDefinitionCheckCommandRunsWithoutKubernetes(t *testing.T) { + originalFlags, originalArgs, originalScheme := flag.CommandLine, os.Args, scheme + t.Cleanup(func() { + flag.CommandLine, os.Args, scheme = originalFlags, originalArgs, originalScheme + }) + flag.CommandLine = flag.NewFlagSet("operator", flag.ContinueOnError) + os.Args = []string{"operator", "--product-definition=../internal/product/testdata/widget.json", "--check-product-definition"} + t.Setenv("KUBECONFIG", filepath.Join(t.TempDir(), "no-kubernetes-config")) + main() + kinds, _, err := scheme.ObjectKinds(&dbv1.DocumentDB{}) + if err != nil || len(kinds) != 1 || kinds[0].Group != "widget.example.io" { + t.Fatalf("definition-check command did not configure the selected shared API: %v, %v", kinds, err) + } +} diff --git a/operator/src/internal/product/definition_test.go b/operator/src/internal/product/definition_test.go index 7ac92ae4d..feea32652 100644 --- a/operator/src/internal/product/definition_test.go +++ b/operator/src/internal/product/definition_test.go @@ -11,8 +11,11 @@ import ( "reflect" "testing" + cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" dbv1 "github.com/documentdb/documentdb-operator/api/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" ) func TestDefinitionUsesOneSharedAPIAndAdapter(t *testing.T) { @@ -72,6 +75,17 @@ func TestDefinitionFailsClosed(t *testing.T) { d.API.Kind, d.Profile.Naming.Kind = "Backup", "Backup" }, "unpaired process identity": func(d *Definition) { d.Postgres.GID = nil }, + "invalid API name": func(d *Definition) { d.API.Plural = "not valid" }, + "invalid service prefix": func(d *Definition) { d.Profile.Naming.ServicePrefix = "INVALID_" }, + "invalid gateway port": func(d *Definition) { d.Profile.Gateway.Port = 65536 }, + "missing PostgreSQL paths": func(d *Definition) { d.Profile.Postgres.Extension.DynamicLibraryPath = nil }, + "combined image": func(d *Definition) { d.Images.Combined = "registry.example.invalid/combined:18" }, + "root process identity": func(d *Definition) { d.Postgres.UID = ptr.To(int64(0)) }, + "missing endpoint variable": func(d *Definition) { d.Endpoint.Template = "https://fixed.example.invalid" }, + "nonlocal co-location": func(d *Definition) { + d.Policy.PinnedCatalog = "" + d.Policy.LocalDevelopment = false + }, } { t.Run(name, func(t *testing.T) { var definition Definition @@ -85,6 +99,7 @@ func TestDefinitionFailsClosed(t *testing.T) { }) } for name, invalid := range map[string][]byte{ + "malformed JSON": []byte("{"), "unknown field": bytes.Replace(data, []byte(`"images"`), []byte(`"typo":true,"images"`), 1), "trailing object": append(append([]byte(nil), data...), []byte("\n{}")...), "null": []byte("null"), @@ -101,3 +116,72 @@ func TestDefinitionFailsClosed(t *testing.T) { }) } } + +func TestDefinitionOverridesAreAppliedWithoutSharingMutableState(t *testing.T) { + definition, err := LoadDefinition("testdata/widget.json") + if err != nil { + t.Fatal(err) + } + definition.Postgres.Parameters = nil + definition.Postgres.PostInitSQL = []string{"SELECT 1"} + adapter := DocumentDBAdapter{Definition: definition} + db := adapter.New() + db.Name, db.Namespace = "sample", "widgets" + db.Spec.LogLevel = "debug" + db.Spec.Timeouts.StopDelay = 42 + db.Spec.Postgres = &dbv1.PostgresSpec{ + UID: ptr.To(int64(1200)), GID: ptr.To(int64(1300)), + Parameters: map[string]string{"work_mem": "16MB"}, PostInitSQL: []string{"SELECT 2"}, + } + db.Spec.Image = &dbv1.ImageSpec{ + Postgres: "registry.example.invalid/postgres:18.1", + DocumentDB: "registry.example.invalid/extension:changed", + Gateway: "registry.example.invalid/gateway:changed", + } + db.Spec.ImagePullSecrets = []corev1.LocalObjectReference{{Name: "pull-credentials"}} + db.Spec.Affinity = cnpgv1.AffinityConfiguration{PodAntiAffinityType: "required"} + intent := adapter.ToClusterIntent(db) + if *intent.Postgres.UID != 1200 || *intent.Postgres.GID != 1300 || + intent.Postgres.LogLevel != "debug" || intent.Postgres.StopDelay != 42 || + !reflect.DeepEqual(intent.Postgres.PostInitSQL, []string{"SELECT 1", "SELECT 2"}) || + intent.Postgres.Parameters["work_mem"] != "16MB" { + t.Fatalf("PostgreSQL overrides/defaults were lost: %+v", intent.Postgres) + } + if intent.Images.Postgres != db.Spec.Image.Postgres || intent.Images.PostgresExtension != db.Spec.Image.DocumentDB || + intent.Images.Gateway != db.Spec.Image.Gateway || + !reflect.DeepEqual(intent.Images.PullSecrets, db.Spec.ImagePullSecrets) || intent.Images.Combined != "" || + intent.Topology.Affinity.PodAntiAffinityType != "required" { + t.Fatalf("image/scheduling overrides were lost: %+v", intent) + } + if adapter.ExtensionImage(db) != db.Spec.Image.DocumentDB || adapter.GatewayImage(db) != db.Spec.Image.Gateway || + adapter.CombinedImage(db) != "" { + t.Fatal("effective image helpers disagree with reconciliation") + } + intent.Postgres.PostInitSQL[0] = "SELECT 3" + intent.Postgres.Parameters["work_mem"] = "32MB" + if definition.Postgres.PostInitSQL[0] != "SELECT 1" || definition.Postgres.Parameters != nil || + db.Spec.Postgres.Parameters["work_mem"] != "16MB" { + t.Fatal("mapping leaked mutable state back into definition or CR") + } + db.Annotations = map[string]string{definition.Profile.Naming.ServiceNameAnnotation(): "retained-service"} + db.Spec.ExposeViaService.ServiceType = "ClusterIP" + if endpoint := adapter.ConnectionString(db, "10.0.0.1", 8443, true); endpoint != "https://retained-service.widgets.svc:8443/" { + t.Fatalf("existing gateway service identity was ignored: %s", endpoint) + } + db.Spec.ExposeViaService.ServiceType = "LoadBalancer" + if endpoint := adapter.ConnectionString(db, "2001:db8::1", 8443, true); endpoint != "https://[2001:db8::1]:8443/" { + t.Fatalf("external IPv6 endpoint was not bracketed: %s", endpoint) + } + backups := DocumentDBBackupAdapter{Definition: definition} + scheduled := DocumentDBScheduledBackupAdapter{Definition: definition} + scheme := runtime.NewScheme() + if err := definition.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + for _, object := range []runtime.Object{backups.New(), backups.NewList(), scheduled.New()} { + kinds, _, err := scheme.ObjectKinds(object) + if err != nil || len(kinds) != 1 || kinds[0] != object.GetObjectKind().GroupVersionKind() { + t.Fatalf("shared backup object has an incorrect API identity: %T %v %v", object, kinds, err) + } + } +} diff --git a/operator/src/internal/webhook/definition_test.go b/operator/src/internal/webhook/definition_test.go index a0b3315f3..ad4ed7e5d 100644 --- a/operator/src/internal/webhook/definition_test.go +++ b/operator/src/internal/webhook/definition_test.go @@ -4,10 +4,14 @@ package webhook import ( + "context" + "encoding/json" "testing" dbv1 "github.com/documentdb/documentdb-operator/api/v1" "github.com/documentdb/documentdb-operator/internal/product" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" ) func TestSharedAdmissionDefinitionPolicy(t *testing.T) { @@ -79,3 +83,51 @@ func TestDefinitionImageParticipatesInCommonVersionGuards(t *testing.T) { t.Fatal("removing an override allowed a downgrade to the older definition image") } } + +func TestNonlocalDefinitionCannotBeRelaxedByClusterScheduling(t *testing.T) { + definition, err := product.LoadDefinition("../product/testdata/widget.json") + if err != nil { + t.Fatal(err) + } + definition.Policy.PinnedCatalog = "" + definition.Policy.LocalDevelopment = false + definition.Topology.Affinity.PodAntiAffinityType = "required" + if err := definition.Validate(); err != nil { + t.Fatal(err) + } + validator := &DocumentDBValidator{Adapter: product.DocumentDBAdapter{Definition: definition}} + db := validator.Adapter.New() + db.Spec.InstancesPerNode = 3 + db.Spec.Affinity.PodAntiAffinityType = "preferred" + if errors := validator.validateDefinitionPolicy(db); len(errors) == 0 { + t.Fatal("a cluster override bypassed the definition's local-development scheduling restriction") + } +} + +func TestDefinitionRestoreUsesItsSharedBackupAPIAndConfiguredBinary(t *testing.T) { + definition, err := product.LoadDefinition("../product/testdata/widget.json") + if err != nil { + t.Fatal(err) + } + definition.Policy.PinnedCatalog = "" + definition.Images.PostgresExtension = "registry.example.invalid/widget:1.2.3" + scheme := runtime.NewScheme() + if err := definition.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + backup := (product.DocumentDBBackupAdapter{Definition: definition}).New() + backup.Name, backup.Namespace = "source", "widgets" + backup.Status.SchemaVersion = "2.0.0" + validator := &DocumentDBValidator{ + Adapter: product.DocumentDBAdapter{Definition: definition}, + Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(backup).Build(), + } + db := validator.Adapter.New() + if err := json.Unmarshal([]byte(`{"metadata":{"namespace":"widgets"},"spec":{"bootstrap":{"recovery":{"backup":{"name":"source"}}}}}`), db); err != nil { + t.Fatal(err) + } + warnings, errors := validator.validateRestoreSchemaCompatibility(context.Background(), db) + if len(warnings) != 0 || len(errors) == 0 { + t.Fatalf("restore ignored the product's backup API or effective binary: warnings=%v errors=%v", warnings, errors) + } +} From afaccb32e495e0eefd7497914369799f7d865f5e Mon Sep 17 00:00:00 2001 From: Rayhan Hossain Date: Mon, 30 Nov 2026 14:18:15 -0800 Subject: [PATCH 04/10] fix: enforce declarative product defaults and rollout contracts Preserve definition-owned PostgreSQL images under API-server defaulting of partial image objects. Enable generic manager leader election, propagate injector registry secrets and enforce enabled required anti-affinity on non-local definitions and resolved CR overrides. Add focused schema-defaulting, chart and admission regression tests; preserve the existing DocumentDB chart/schema. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 33b3cb3c-1b25-4ffb-bff1-ebf0f3d04058 Signed-off-by: Rayhan Hossain --- operator/product-helm-chart/README.md | 16 ++-- .../product-helm-chart/templates/crds.yaml | 3 + .../templates/deployment.yaml | 1 + .../templates/injector.yaml | 4 + operator/src/internal/product/definition.go | 14 ++- .../product/definition_affinity_test.go | 45 ++++++++++ .../internal/product/definition_chart_test.go | 85 +++++++++++++++++-- .../src/internal/webhook/definition_test.go | 27 ++++-- .../internal/webhook/documentdb_webhook.go | 4 +- 9 files changed, 180 insertions(+), 19 deletions(-) create mode 100644 operator/src/internal/product/definition_affinity_test.go diff --git a/operator/product-helm-chart/README.md b/operator/product-helm-chart/README.md index 548a18a9c..e16e3dfdd 100644 --- a/operator/product-helm-chart/README.md +++ b/operator/product-helm-chart/README.md @@ -12,21 +12,27 @@ example. Supply it as the `productDefinition` values object and pin manager and optional injector images with `image.repository` and `image.digest`. Install cert-manager and CloudNative-PG first; the injector namespace must already exist. The bundled injector retains its actual existing RPC identity. +`imagePullSecrets` applies to both manager and injector pods; referenced Secrets +must exist in both namespaces. Manager replicas use leader election. CRDs are rendered from exact copies of the canonical shared API schemas. -Only group/version/kind/resource metadata changes; there is no product-specific -schema or generated Go API. `make manifests` in `operator/src` automatically +Rendering changes API identity and removes the legacy PostgreSQL image default, +so partial image objects cannot override the definition's PostgreSQL image. +All other schema properties remain shared; there is no product-specific schema +or generated Go API. `make manifests` in `operator/src` automatically synchronizes these copies after regenerating canonical CRDs; `make schemas` here refreshes only the copies. Source-equality checks run without Helm, while -the Helm contract test also checks rendered schema equality. CRDs are retained -on uninstall. +the Helm contract test also checks the narrowly scoped default overlay and +API-server defaulting behavior. CRDs are retained on uninstall. For compatibility, the shared Go API and some JSON fields still carry their original DocumentDB names. A definition changes API identity, not serialization or schema semantics. Explicit unsupported cross-region/legacy version settings are rejected, not silently ignored. Local fixed-catalog definitions disable upgrades and verify the exact available and installed catalog versions without -inventing a semantic version. Co-location requires `localDevelopment`. +inventing a semantic version. Co-location requires `localDevelopment`; non-local +definitions and effective cluster overrides require explicitly enabled, required +pod anti-affinity. Validate a definition without Kubernetes: diff --git a/operator/product-helm-chart/templates/crds.yaml b/operator/product-helm-chart/templates/crds.yaml index 74ceba44c..cb7319f46 100644 --- a/operator/product-helm-chart/templates/crds.yaml +++ b/operator/product-helm-chart/templates/crds.yaml @@ -10,6 +10,9 @@ {{- if .storage }}{{- $version = deepCopy . }}{{- end }} {{- end }} {{- $_ := set $version "name" $api.version }} +{{- if eq $entry.file "cluster" }} +{{- $_ := unset $version.schema.openAPIV3Schema.properties.spec.properties.image.properties.postgres "default" }} +{{- end }} {{- $_ := set $crd.spec "versions" (list $version) }} --- {{ toYaml $crd }} diff --git a/operator/product-helm-chart/templates/deployment.yaml b/operator/product-helm-chart/templates/deployment.yaml index c7c5de5c5..ee8402e98 100644 --- a/operator/product-helm-chart/templates/deployment.yaml +++ b/operator/product-helm-chart/templates/deployment.yaml @@ -63,6 +63,7 @@ spec: imagePullPolicy: {{ .Values.image.pullPolicy }} args: - --product-definition=/config/runtime.json + - --leader-elect ports: - name: webhook containerPort: 9443 diff --git a/operator/product-helm-chart/templates/injector.yaml b/operator/product-helm-chart/templates/injector.yaml index d778fb035..86b4b7375 100644 --- a/operator/product-helm-chart/templates/injector.yaml +++ b/operator/product-helm-chart/templates/injector.yaml @@ -41,6 +41,10 @@ spec: app.kubernetes.io/instance: {{ include "product.name" . }}-injector spec: automountServiceAccountToken: false + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} securityContext: runAsNonRoot: true runAsUser: 10001 diff --git a/operator/src/internal/product/definition.go b/operator/src/internal/product/definition.go index 3c5546276..2540cf965 100644 --- a/operator/src/internal/product/definition.go +++ b/operator/src/internal/product/definition.go @@ -14,6 +14,7 @@ import ( "strconv" "strings" + cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" dbv1 "github.com/documentdb/documentdb-operator/api/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -138,8 +139,8 @@ func (d *Definition) Validate() error { (d.Postgres.UID != nil && (*d.Postgres.UID <= 0 || *d.Postgres.GID <= 0)) { return fmt.Errorf("PostgreSQL UID/GID must be supplied together and be non-root") } - if d.Topology.Affinity.PodAntiAffinityType == "preferred" && !d.Policy.LocalDevelopment { - return fmt.Errorf("co-located scheduling requires explicit localDevelopment") + if err := d.ValidateAffinity(d.Topology.Affinity); err != nil { + return err } if !strings.Contains(d.Endpoint.Template, "{address}") { return fmt.Errorf("endpoint template must contain {address}") @@ -147,6 +148,15 @@ func (d *Definition) Validate() error { return nil } +// ValidateAffinity checks the effective scheduling contract, not just its type. +func (d *Definition) ValidateAffinity(affinity cnpgv1.AffinityConfiguration) error { + if !d.Policy.LocalDevelopment && + (affinity.EnablePodAntiAffinity == nil || !*affinity.EnablePodAntiAffinity || affinity.PodAntiAffinityType != "required") { + return fmt.Errorf("non-local definitions require explicitly enabled, required pod anti-affinity") + } + return nil +} + func (d *Definition) GroupVersion() schema.GroupVersion { return schema.GroupVersion{Group: d.API.Group, Version: d.API.Version} } diff --git a/operator/src/internal/product/definition_affinity_test.go b/operator/src/internal/product/definition_affinity_test.go new file mode 100644 index 000000000..5defa9a0b --- /dev/null +++ b/operator/src/internal/product/definition_affinity_test.go @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "testing" + + cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" + "k8s.io/utils/ptr" +) + +func TestNonlocalDefinitionRequiresEnabledRequiredAffinity(t *testing.T) { + for name, affinity := range map[string]cnpgv1.AffinityConfiguration{ + "disabled required": {EnablePodAntiAffinity: ptr.To(false), PodAntiAffinityType: "required"}, + "implicit enabled": {PodAntiAffinityType: "required"}, + "implicit type": {EnablePodAntiAffinity: ptr.To(true)}, + "preferred": {EnablePodAntiAffinity: ptr.To(true), PodAntiAffinityType: "preferred"}, + "omitted": {}, + } { + t.Run(name, func(t *testing.T) { + definition, err := LoadDefinition("testdata/widget.json") + if err != nil { + t.Fatal(err) + } + definition.Policy.PinnedCatalog = "" + definition.Policy.LocalDevelopment = false + definition.Topology.Affinity = affinity + if err := definition.Validate(); err == nil { + t.Fatal("non-local definition allowed co-located scheduling") + } + definition.Policy.LocalDevelopment = true + if err := definition.Validate(); err != nil { + t.Fatalf("local development scheduling was rejected: %v", err) + } + definition.Policy.LocalDevelopment = false + definition.Topology.Affinity = cnpgv1.AffinityConfiguration{ + EnablePodAntiAffinity: ptr.To(true), PodAntiAffinityType: "required", + } + if err := definition.Validate(); err != nil { + t.Fatalf("explicit non-local scheduling was rejected: %v", err) + } + }) + } +} diff --git a/operator/src/internal/product/definition_chart_test.go b/operator/src/internal/product/definition_chart_test.go index 724141b5b..d417c3eb1 100644 --- a/operator/src/internal/product/definition_chart_test.go +++ b/operator/src/internal/product/definition_chart_test.go @@ -12,8 +12,14 @@ import ( "strings" "testing" + dbv1 "github.com/documentdb/documentdb-operator/api/v1" admissionv1 "k8s.io/api/admissionregistration/v1" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + structuraldefaulting "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting" "sigs.k8s.io/yaml" ) @@ -31,7 +37,9 @@ func TestDefinitionChartUsesCanonicalSchemaAndAdmissionIdentity(t *testing.T) { } values, err := json.Marshal(map[string]any{ "productDefinition": definition, "image": image, - "sidecarInjector": map[string]any{"enabled": true, "image": image}, + "sidecarInjector": map[string]any{"enabled": true, "image": image}, + "replicaCount": 2, + "imagePullSecrets": []corev1.LocalObjectReference{{Name: "registry-login"}}, }) if err != nil { t.Fatal(err) @@ -57,10 +65,15 @@ func TestDefinitionChartUsesCanonicalSchemaAndAdmissionIdentity(t *testing.T) { var schema *apiextv1.CustomResourceValidation for _, version := range canonical.Spec.Versions { if version.Storage { - schema = version.Schema + schema = version.Schema.DeepCopy() } } - var clusters, backups, webhooks int + spec := schema.OpenAPIV3Schema.Properties["spec"] + imageSchema := spec.Properties["image"] + postgres := imageSchema.Properties["postgres"] + postgres.Default = nil + imageSchema.Properties["postgres"] = postgres + var clusters, backups, webhooks, managers, injectors int for _, document := range strings.Split(string(output), "\n---\n") { var identity struct{ Kind string } if err := yaml.Unmarshal([]byte(document), &identity); err != nil { @@ -81,6 +94,7 @@ func TestDefinitionChartUsesCanonicalSchemaAndAdmissionIdentity(t *testing.T) { if crd.Spec.Names.Plural != definition.API.Plural || !reflect.DeepEqual(crd.Spec.Versions[0].Schema, schema) { t.Fatal("product forked the shared cluster schema") } + assertDefinitionImageDefaulting(t, crd.Spec.Versions[0].Schema.OpenAPIV3Schema, definition) } else { backups++ } @@ -96,10 +110,71 @@ func TestDefinitionChartUsesCanonicalSchemaAndAdmissionIdentity(t *testing.T) { hook.Rules[0].Resources[0] != definition.API.Plural { t.Fatalf("admission does not match the common runtime registration: %+v", hook) } + case "Deployment": + var deployment appsv1.Deployment + if err := yaml.Unmarshal([]byte(document), &deployment); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(deployment.Spec.Template.Spec.ImagePullSecrets, + []corev1.LocalObjectReference{{Name: "registry-login"}}) { + t.Fatalf("private image credentials missing from %s/%s", deployment.Namespace, deployment.Name) + } + if strings.HasSuffix(deployment.Name, "-injector") { + injectors++ + } else { + managers++ + args := deployment.Spec.Template.Spec.Containers[0].Args + if *deployment.Spec.Replicas != 2 || !strings.Contains(strings.Join(args, " "), "--leader-elect") { + t.Fatal("multiple manager replicas can run without leader election") + } + } } } - if clusters != 1 || backups != 2 || webhooks != 1 { - t.Fatalf("missing shared resources: clusters=%d backups=%d webhooks=%d", clusters, backups, webhooks) + if clusters != 1 || backups != 2 || webhooks != 1 || managers != 1 || injectors != 1 { + t.Fatalf("missing shared resources: clusters=%d backups=%d webhooks=%d managers=%d injectors=%d", + clusters, backups, webhooks, managers, injectors) + } +} + +func assertDefinitionImageDefaulting(t *testing.T, schema *apiextv1.JSONSchemaProps, definition *Definition) { + t.Helper() + var internal apiext.JSONSchemaProps + if err := apiextv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(schema, &internal, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&internal) + if err != nil { + t.Fatal(err) + } + for _, input := range []struct { + name, image, postgres string + }{ + {"gateway only", `{"gateway":"registry.example.invalid/gateway:updated"}`, definition.Images.Postgres}, + {"empty image object", `{}`, definition.Images.Postgres}, + {"explicit PostgreSQL override", `{"gateway":"registry.example.invalid/gateway:updated","postgres":"registry.example.invalid/postgres:custom"}`, "registry.example.invalid/postgres:custom"}, + } { + t.Run(input.name, func(t *testing.T) { + var object map[string]any + if err := json.Unmarshal([]byte(`{"spec":{"image":`+input.image+`}}`), &object); err != nil { + t.Fatal(err) + } + structuraldefaulting.Default(object, structural) + data, err := json.Marshal(object) + if err != nil { + t.Fatal(err) + } + var db dbv1.DocumentDB + if err := json.Unmarshal(data, &db); err != nil { + t.Fatal(err) + } + actual := (DocumentDBAdapter{Definition: definition}).ToClusterIntent(&db).Images + if actual.Postgres != input.postgres { + t.Fatalf("API-server defaulting switched PostgreSQL: got %q, want %q", actual.Postgres, input.postgres) + } + if db.Spec.Image.Gateway != "" && actual.Gateway != db.Spec.Image.Gateway { + t.Fatal("gateway override was lost") + } + }) } } diff --git a/operator/src/internal/webhook/definition_test.go b/operator/src/internal/webhook/definition_test.go index ad4ed7e5d..3559e4811 100644 --- a/operator/src/internal/webhook/definition_test.go +++ b/operator/src/internal/webhook/definition_test.go @@ -8,9 +8,11 @@ import ( "encoding/json" "testing" + cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" dbv1 "github.com/documentdb/documentdb-operator/api/v1" "github.com/documentdb/documentdb-operator/internal/product" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client/fake" ) @@ -96,11 +98,26 @@ func TestNonlocalDefinitionCannotBeRelaxedByClusterScheduling(t *testing.T) { t.Fatal(err) } validator := &DocumentDBValidator{Adapter: product.DocumentDBAdapter{Definition: definition}} - db := validator.Adapter.New() - db.Spec.InstancesPerNode = 3 - db.Spec.Affinity.PodAntiAffinityType = "preferred" - if errors := validator.validateDefinitionPolicy(db); len(errors) == 0 { - t.Fatal("a cluster override bypassed the definition's local-development scheduling restriction") + for name, input := range map[string]struct { + affinity cnpgv1.AffinityConfiguration + reject bool + }{ + "inherit definition": {}, + "explicit required": {affinity: definition.Topology.Affinity}, + "disabled required": {affinity: cnpgv1.AffinityConfiguration{EnablePodAntiAffinity: ptr.To(false), PodAntiAffinityType: "required"}, reject: true}, + "missing enable flag": {affinity: cnpgv1.AffinityConfiguration{PodAntiAffinityType: "required"}, reject: true}, + "missing type": {affinity: cnpgv1.AffinityConfiguration{EnablePodAntiAffinity: ptr.To(true)}, reject: true}, + "preferred": {affinity: cnpgv1.AffinityConfiguration{EnablePodAntiAffinity: ptr.To(true), PodAntiAffinityType: "preferred"}, reject: true}, + } { + t.Run(name, func(t *testing.T) { + db := validator.Adapter.New() + db.Spec.InstancesPerNode = 3 + db.Spec.Affinity = input.affinity + errors := validator.validateDefinitionPolicy(db) + if (len(errors) != 0) != input.reject { + t.Fatalf("effective scheduling policy was not enforced: %v", errors) + } + }) } } diff --git a/operator/src/internal/webhook/documentdb_webhook.go b/operator/src/internal/webhook/documentdb_webhook.go index 6d54b34bb..8c2b3eaee 100644 --- a/operator/src/internal/webhook/documentdb_webhook.go +++ b/operator/src/internal/webhook/documentdb_webhook.go @@ -310,8 +310,8 @@ func (v *DocumentDBValidator) validateDefinitionPolicy(db *dbv1.DocumentDB) fiel db.Spec.Image.DocumentDB != d.Images.PostgresExtension { errors = append(errors, field.Forbidden(field.NewPath("spec", "image", "documentDB"), "the local non-upgrading definition fixes the extension image")) } - if !d.Policy.LocalDevelopment && db.Spec.Affinity.PodAntiAffinityType == "preferred" { - errors = append(errors, field.Forbidden(field.NewPath("spec", "affinity"), "co-location requires a localDevelopment definition")) + if err := d.ValidateAffinity(v.Adapter.ToClusterIntent(db).Topology.Affinity); err != nil { + errors = append(errors, field.Forbidden(field.NewPath("spec", "affinity"), err.Error())) } return errors } From 3f2d0ddca9b8dd1b114e99ea4e28a4b95df56057 Mon Sep 17 00:00:00 2001 From: Rayhan Hossain Date: Mon, 30 Nov 2026 14:18:15 -0800 Subject: [PATCH 05/10] ci: verify pinned Helm unittest release before installation Replace the failing install hook checksum fetch with an authenticated release download and strict SHA-256 verification before extraction. Include generic chart changes in unit workflow triggers. Do not disable checksum checks or change the pinned plugin version. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 33b3cb3c-1b25-4ffb-bff1-ebf0f3d04058 Signed-off-by: Rayhan Hossain --- .github/workflows/test-unit.yml | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.yml index d9cedf843..cd22539a2 100644 --- a/.github/workflows/test-unit.yml +++ b/.github/workflows/test-unit.yml @@ -8,6 +8,7 @@ on: - 'operator/src/go.mod' - 'operator/src/go.sum' - 'operator/documentdb-helm-chart/**' + - 'operator/product-helm-chart/**' pull_request: branches: [main] paths: @@ -15,6 +16,7 @@ on: - 'operator/src/go.mod' - 'operator/src/go.sum' - 'operator/documentdb-helm-chart/**' + - 'operator/product-helm-chart/**' permissions: contents: read @@ -67,7 +69,27 @@ jobs: uses: azure/setup-helm@v4 - name: Install helm-unittest plugin - run: helm plugin install --verify=false --version v1.1.0 https://github.com/helm-unittest/helm-unittest + env: + GH_TOKEN: ${{ github.token }} + run: | + version=1.1.0 + archive="helm-unittest-linux-amd64-${version}.tgz" + download_dir="${RUNNER_TEMP}/helm-unittest-download" + mkdir -p "$download_dir" + gh release download "v${version}" --repo helm-unittest/helm-unittest \ + --pattern "$archive" --pattern helm-unittest-checksum.sha \ + --dir "$download_dir" + cd "$download_dir" + checksum=$(awk -v file="*./_dist/${archive}" '$2 == file { print $1 }' helm-unittest-checksum.sha) + if [[ ! "$checksum" =~ ^[[:xdigit:]]{64}$ ]]; then + echo "::error::Missing or invalid checksum for ${archive}" + exit 1 + fi + printf '%s %s\n' "$checksum" "$archive" | sha256sum --check --strict - + plugin_dir="$(helm env HELM_PLUGINS)/unittest" + mkdir -p "$plugin_dir" + tar -xzf "$archive" -C "$plugin_dir" + helm unittest --help > /dev/null - name: Run Helm unit tests run: | From b9f3e9cb5091b7481b8644e62696ecffd9be3c7c Mon Sep 17 00:00:00 2001 From: Rayhan Hossain Date: Mon, 30 Nov 2026 14:55:52 -0800 Subject: [PATCH 06/10] fix: honor product version ordering and shared instance limits Use the selected extension format consistently for image parsing, schema bounds, rollback and restore guards. Preserve semantic prereleases while retaining the legacy DocumentDB policy. Reject definitions whose minimum exceeds the canonical API maximum, with a shared bound checked against both served schemas. Add reviewer reproductions through ValidateUpdate, restore validation and offline definition loading. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 33b3cb3c-1b25-4ffb-bff1-ebf0f3d04058 Signed-off-by: Rayhan Hossain --- operator/src/api/preview/documentdb_types.go | 4 + operator/src/api/v1/documentdb_types.go | 4 + operator/src/internal/product/definition.go | 4 +- .../product/definition_instances_test.go | 55 +++++++++ .../src/internal/validation/validation.go | 70 ++++++++++-- .../validation/version_policy_test.go | 36 ++++++ .../webhook/definition_version_test.go | 104 ++++++++++++++++++ .../internal/webhook/documentdb_webhook.go | 14 ++- 8 files changed, 272 insertions(+), 19 deletions(-) create mode 100644 operator/src/internal/product/definition_instances_test.go create mode 100644 operator/src/internal/validation/version_policy_test.go create mode 100644 operator/src/internal/webhook/definition_version_test.go diff --git a/operator/src/api/preview/documentdb_types.go b/operator/src/api/preview/documentdb_types.go index 75fef30e7..ba87fd17d 100644 --- a/operator/src/api/preview/documentdb_types.go +++ b/operator/src/api/preview/documentdb_types.go @@ -11,6 +11,10 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) +// MaxInstancesPerNode is the upper instance bound supported by the shared API. +// Keep the InstancesPerNode validation marker aligned with this bound. +const MaxInstancesPerNode = 3 + // Feature gate constants. PascalCase names following the Kubernetes feature gate convention. const ( // FeatureGateChangeStreams enables change stream support by setting wal_level=logical. diff --git a/operator/src/api/v1/documentdb_types.go b/operator/src/api/v1/documentdb_types.go index 40a3fbf78..2d58bbdec 100644 --- a/operator/src/api/v1/documentdb_types.go +++ b/operator/src/api/v1/documentdb_types.go @@ -9,6 +9,10 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) +// MaxInstancesPerNode is the upper instance bound supported by the shared API. +// Keep the InstancesPerNode validation marker aligned with this bound. +const MaxInstancesPerNode = 3 + // Feature gate constants. PascalCase names following the Kubernetes feature gate convention. const ( // FeatureGateChangeStreams enables change stream support by setting wal_level=logical. diff --git a/operator/src/internal/product/definition.go b/operator/src/internal/product/definition.go index 2540cf965..2f5dc4aa0 100644 --- a/operator/src/internal/product/definition.go +++ b/operator/src/internal/product/definition.go @@ -126,8 +126,8 @@ func (d *Definition) Validate() error { len(d.Profile.Postgres.Extension.ExtensionControlPath) == 0 { return fmt.Errorf("PostgreSQL HBA, bootstrap and extension paths must be explicit") } - if d.Policy.MinimumInstances < 1 { - return fmt.Errorf("minimumInstances must be positive") + if d.Policy.MinimumInstances < 1 || d.Policy.MinimumInstances > dbv1.MaxInstancesPerNode { + return fmt.Errorf("minimumInstances must be between 1 and %d, matching the shared API", dbv1.MaxInstancesPerNode) } if d.Images.Combined != "" || d.Topology.Instances != 0 { return fmt.Errorf("definitions require split images; instance counts belong in the shared cluster resource") diff --git a/operator/src/internal/product/definition_instances_test.go b/operator/src/internal/product/definition_instances_test.go new file mode 100644 index 000000000..2f61eb809 --- /dev/null +++ b/operator/src/internal/product/definition_instances_test.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "encoding/json" + "os" + "path/filepath" + "strconv" + "testing" + + dbv1 "github.com/documentdb/documentdb-operator/api/v1" + apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "sigs.k8s.io/yaml" +) + +func TestDefinitionMinimumInstancesMustFitSharedSchema(t *testing.T) { + data, err := os.ReadFile("../../config/crd/bases/documentdb.io_dbs.yaml") + if err != nil { + t.Fatal(err) + } + var crd apiextv1.CustomResourceDefinition + if err := yaml.Unmarshal(data, &crd); err != nil { + t.Fatal(err) + } + for _, version := range crd.Spec.Versions { + bound := version.Schema.OpenAPIV3Schema.Properties["spec"].Properties["instancesPerNode"].Maximum + if bound == nil || *bound != float64(dbv1.MaxInstancesPerNode) { + t.Fatalf("shared Go bound drifted from %s schema: %v", version.Name, bound) + } + } + for _, minimum := range []int{0, 1, 2, dbv1.MaxInstancesPerNode, dbv1.MaxInstancesPerNode + 1} { + t.Run(strconv.Itoa(minimum), func(t *testing.T) { + definition, err := LoadDefinition("testdata/widget.json") + if err != nil { + t.Fatal(err) + } + definition.Policy.MinimumInstances = minimum + data, err := json.Marshal(definition) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "definition.json") + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } + _, err = LoadDefinition(path) + reject := minimum < 1 || minimum > dbv1.MaxInstancesPerNode + if (err != nil) != reject { + t.Fatalf("unusable minimumInstances accepted or legal bound rejected: minimum=%d err=%v", minimum, err) + } + }) + } +} diff --git a/operator/src/internal/validation/validation.go b/operator/src/internal/validation/validation.go index 75369aa4a..0f3867dfa 100644 --- a/operator/src/internal/validation/validation.go +++ b/operator/src/internal/validation/validation.go @@ -14,9 +14,11 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apimachinery/pkg/util/version" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "github.com/documentdb/documentdb-operator/internal/product" util "github.com/documentdb/documentdb-operator/internal/utils" ) @@ -33,6 +35,47 @@ type Terms struct { SchemaWithoutBinaryFields string } +// VersionPolicy keeps admission ordering consistent with the product catalog. +// Its zero value preserves DocumentDB's existing normalization and comparison. +type VersionPolicy struct { + Format product.ExtensionVersionFormat +} + +func (p VersionPolicy) ImageVersion(ref string) string { + if p.Format != product.ExtensionVersionSemver { + return ImageTagSemver(ref) + } + tag := util.ReleaseVersionTag(ref) + if _, err := version.ParseSemantic(tag); err != nil { + return "" + } + return tag +} + +func (p VersionPolicy) compare(first, second string) (int, error) { + if p.Format == product.ExtensionVersionDocumentDB { + return util.CompareExtensionVersions(util.SemverToExtensionVersion(first), util.SemverToExtensionVersion(second)) + } + if p.Format != product.ExtensionVersionSemver { + return 0, fmt.Errorf("unsupported extension version format %d", p.Format) + } + a, err := version.ParseSemantic(first) + if err != nil { + return 0, err + } + b, err := version.ParseSemantic(second) + if err != nil { + return 0, err + } + if a.LessThan(b) { + return -1, nil + } + if b.LessThan(a) { + return 1, nil + } + return 0, nil +} + // ExtractSemver returns the leading "X.Y.Z" portion from a tag string, // normalizing "X.Y-RC" tags to the extension version "X.Y.0". // It returns "" when neither version format is recognized. See @@ -60,6 +103,10 @@ func ResolveBinaryVersion(imageRef, version string) string { // SchemaVersionNotExceedsBinary ensures an explicit spec.schemaVersion is <= the binary version. func SchemaVersionNotExceedsBinary(schemaVersion, binaryVersion string, t Terms) field.ErrorList { + return (VersionPolicy{}).SchemaVersionNotExceedsBinary(schemaVersion, binaryVersion, t) +} + +func (p VersionPolicy) SchemaVersionNotExceedsBinary(schemaVersion, binaryVersion string, t Terms) field.ErrorList { if schemaVersion == "" || schemaVersion == "auto" { return nil } @@ -74,10 +121,7 @@ func SchemaVersionNotExceedsBinary(schemaVersion, binaryVersion string, t Terms) )} } - schemaExtensionVersion := util.SemverToExtensionVersion(schemaVersion) - binaryExtensionVersion := util.SemverToExtensionVersion(binaryVersion) - - cmp, err := util.CompareExtensionVersions(schemaExtensionVersion, binaryExtensionVersion) + cmp, err := p.compare(schemaVersion, binaryVersion) if err != nil { return field.ErrorList{field.Invalid( path, @@ -101,14 +145,15 @@ func SchemaVersionNotExceedsBinary(schemaVersion, binaryVersion string, t Terms) // binary against a newer schema is untested and may cause data corruption. // Callers should only invoke it when an image-related field changes. func ImageRollback(installedSchemaVersion, newBinaryVersion string) field.ErrorList { + return (VersionPolicy{}).ImageRollback(installedSchemaVersion, newBinaryVersion) +} + +func (p VersionPolicy) ImageRollback(installedSchemaVersion, newBinaryVersion string) field.ErrorList { if installedSchemaVersion == "" || newBinaryVersion == "" { return nil } - newBinaryExtensionVersion := util.SemverToExtensionVersion(newBinaryVersion) - schemaExtensionVersion := util.SemverToExtensionVersion(installedSchemaVersion) - - cmp, err := util.CompareExtensionVersions(newBinaryExtensionVersion, schemaExtensionVersion) + cmp, err := p.compare(newBinaryVersion, installedSchemaVersion) if err != nil { return field.ErrorList{field.Forbidden( field.NewPath("spec"), @@ -229,6 +274,10 @@ func SourceSchemaVersion(ctx context.Context, c client.Reader, src RestoreSource // unknown, and rejects only a known target version that is older than a known // schema. func CompareBinaryToSchema(binaryVersion, schemaVersion string, src RestoreSource, t Terms) (admission.Warnings, field.ErrorList) { + return (VersionPolicy{}).CompareBinaryToSchema(binaryVersion, schemaVersion, src, t) +} + +func (p VersionPolicy) CompareBinaryToSchema(binaryVersion, schemaVersion string, src RestoreSource, t Terms) (admission.Warnings, field.ErrorList) { target := "the target " + t.Product + " version" if schemaVersion == "" { return admission.Warnings{ @@ -245,10 +294,7 @@ func CompareBinaryToSchema(binaryVersion, schemaVersion string, src RestoreSourc }, nil } - binaryExtensionVersion := util.SemverToExtensionVersion(binaryVersion) - schemaExtensionVersion := util.SemverToExtensionVersion(schemaVersion) - - cmp, err := util.CompareExtensionVersions(binaryExtensionVersion, schemaExtensionVersion) + cmp, err := p.compare(binaryVersion, schemaVersion) if err != nil { return admission.Warnings{ fmt.Sprintf("cannot compare %s %s with the %s's schema version %s: %v; compatibility not verified", diff --git a/operator/src/internal/validation/version_policy_test.go b/operator/src/internal/validation/version_policy_test.go new file mode 100644 index 000000000..7459f91c1 --- /dev/null +++ b/operator/src/internal/validation/version_policy_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package validation + +import ( + "strings" + "testing" + + "github.com/documentdb/documentdb-operator/internal/product" +) + +func TestSemverPolicyDoesNotInventVersionsForOpaqueImages(t *testing.T) { + policy := VersionPolicy{Format: product.ExtensionVersionSemver} + for _, image := range []string{ + "registry.example.invalid/widget:latest", + "registry.example.invalid/widget:1.3.0-rc.1@sha256:0123456789", + "registry.example.invalid/widget", + } { + if version := policy.ImageVersion(image); version != "" { + t.Fatalf("unverifiable image supplied an invented binary version: %s -> %s", image, version) + } + } +} + +func TestSemverPolicyRejectsUnparseableKnownSchemaVersions(t *testing.T) { + policy := VersionPolicy{Format: product.ExtensionVersionSemver} + errors := policy.SchemaVersionNotExceedsBinary("not-semver", "1.3.0", Terms{}) + if len(errors) == 0 || !strings.Contains(errors.ToAggregate().Error(), "cannot validate schemaVersion") { + t.Fatalf("invalid explicit schema version was accepted: %v", errors) + } + errors = policy.ImageRollback("not-semver", "1.3.0") + if len(errors) == 0 || !strings.Contains(errors.ToAggregate().Error(), "cannot validate image rollback") { + t.Fatalf("invalid installed schema silently bypassed rollback protection: %v", errors) + } +} diff --git a/operator/src/internal/webhook/definition_version_test.go b/operator/src/internal/webhook/definition_version_test.go new file mode 100644 index 000000000..dc82f3395 --- /dev/null +++ b/operator/src/internal/webhook/definition_version_test.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package webhook + +import ( + "context" + "encoding/json" + "testing" + + dbv1 "github.com/documentdb/documentdb-operator/api/v1" + "github.com/documentdb/documentdb-operator/internal/product" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func semverValidator(t *testing.T, binary string) *DocumentDBValidator { + t.Helper() + definition, err := product.LoadDefinition("../product/testdata/widget.json") + if err != nil { + t.Fatal(err) + } + definition.Policy.PinnedCatalog = "" + definition.Profile.Postgres.ExtensionVersionFormat = product.ExtensionVersionSemver + definition.Images.PostgresExtension = "registry.example.invalid/widget:" + binary + return &DocumentDBValidator{Adapter: product.DocumentDBAdapter{Definition: definition}} +} + +func validDefinitionCluster(t *testing.T, validator *DocumentDBValidator) *dbv1.DocumentDB { + t.Helper() + db := validator.Adapter.New() + if err := json.Unmarshal([]byte(`{ + "metadata":{"name":"database","namespace":"widgets"}, + "spec":{"nodeCount":1,"instancesPerNode":1,"resource":{"memory":"2Gi","storage":{"pvcSize":"2Gi"}}} + }`), db); err != nil { + t.Fatal(err) + } + return db +} + +func TestSemverDefinitionValidateUpdatePreservesPrereleaseOrdering(t *testing.T) { + for _, input := range []struct { + installed, binary, schema string + reject bool + }{ + {installed: "1.3.0", binary: "1.3.0-rc.1", reject: true}, + {installed: "1.3.0-rc.1", binary: "1.3.0"}, + {installed: "1.3.0-rc.2", binary: "1.3.0-rc.1", reject: true}, + {installed: "1.3.0-rc.2", binary: "1.3.0-rc.10"}, + {installed: "1.3.0+build.2", binary: "1.3.0"}, + {installed: "1.2.0", binary: "1.3.0-rc.1", schema: "1.3.0", reject: true}, + {installed: "1.2.0", binary: "1.3.0", schema: "1.3.0"}, + } { + t.Run(input.installed+"-to-"+input.binary+"-schema-"+input.schema, func(t *testing.T) { + validator := semverValidator(t, input.binary) + old := validDefinitionCluster(t, validator) + old.Status.SchemaVersion = input.installed + old.Spec.Image = &dbv1.ImageSpec{DocumentDB: "registry.example.invalid/widget:previous"} + updated := old.DeepCopy() + updated.Spec.Image.DocumentDB = "registry.example.invalid/widget:" + input.binary + updated.Spec.SchemaVersion = input.schema + warnings, err := validator.ValidateUpdate(context.Background(), old, updated) + if (err != nil) != input.reject || len(warnings) != 0 { + t.Fatalf("semantic ordering not honored: err=%v warnings=%v", err, warnings) + } + if version := validator.binaryVersion(updated); version != input.binary { + t.Fatalf("image prerelease was normalized away: got %q want %q", version, input.binary) + } + }) + } +} + +func TestSemverDefinitionRestorePreservesPrereleaseOrdering(t *testing.T) { + for _, input := range []struct { + catalog, binary string + reject bool + }{ + {"1.3.0-rc.2", "1.3.0-rc.1", true}, + {"1.3.0", "1.3.0-rc.1", true}, + {"1.3.0-rc.1", "1.3.0", false}, + {"1.3.0-rc.2", "1.3.0-rc.10", false}, + {"1.3.0-rc.1", "1.3.0-rc.1", false}, + } { + t.Run(input.catalog+"-onto-"+input.binary, func(t *testing.T) { + validator := semverValidator(t, input.binary) + scheme := runtime.NewScheme() + if err := validator.Adapter.Definition.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + backup := (product.DocumentDBBackupAdapter{Definition: validator.Adapter.Definition}).New() + backup.Name, backup.Namespace = "source", "widgets" + backup.Status.SchemaVersion = input.catalog + validator.Client = fake.NewClientBuilder().WithScheme(scheme).WithObjects(backup).Build() + db := validDefinitionCluster(t, validator) + if err := json.Unmarshal([]byte(`{"spec":{"bootstrap":{"recovery":{"backup":{"name":"source"}}}}}`), db); err != nil { + t.Fatal(err) + } + warnings, errors := validator.validateRestoreSchemaCompatibility(context.Background(), db) + if (len(errors) != 0) != input.reject || len(warnings) != 0 { + t.Fatalf("restore semantic ordering was not enforced: errors=%v warnings=%v", errors, warnings) + } + }) + } +} diff --git a/operator/src/internal/webhook/documentdb_webhook.go b/operator/src/internal/webhook/documentdb_webhook.go index 8c2b3eaee..af744ada2 100644 --- a/operator/src/internal/webhook/documentdb_webhook.go +++ b/operator/src/internal/webhook/documentdb_webhook.go @@ -139,7 +139,7 @@ func (v *DocumentDBValidator) validateSchemaVersionNotExceedsBinary(db *dbv1.Doc } return nil } - return validation.SchemaVersionNotExceedsBinary(db.Spec.SchemaVersion, v.binaryVersion(db), documentDBTerms) + return v.versionPolicy().SchemaVersionNotExceedsBinary(db.Spec.SchemaVersion, v.binaryVersion(db), documentDBTerms) } // --------------------------------------------------------------------------- @@ -181,12 +181,16 @@ func (v *DocumentDBValidator) validateImageRollback(newDB, oldDB *dbv1.DocumentD return nil } - return validation.ImageRollback(installedSchemaVersion, v.binaryVersion(newDB)) + return v.versionPolicy().ImageRollback(installedSchemaVersion, v.binaryVersion(newDB)) +} + +func (v *DocumentDBValidator) versionPolicy() validation.VersionPolicy { + return validation.VersionPolicy{Format: v.Adapter.Profile().Postgres.ExtensionVersionFormat} } func (v *DocumentDBValidator) binaryVersion(db *dbv1.DocumentDB) string { if v.Adapter.Definition != nil { - return validation.ImageTagSemver(v.Adapter.ExtensionImage(db)) + return v.versionPolicy().ImageVersion(v.Adapter.ExtensionImage(db)) } return resolveBinaryVersion(db) } @@ -239,9 +243,9 @@ func (v *DocumentDBValidator) validateRestoreSchemaCompatibility(ctx context.Con binaryVersion := resolveEffectiveBinaryVersion(newDB) if v.Adapter.Definition != nil { - binaryVersion = validation.ImageTagSemver(v.Adapter.ExtensionImage(newDB)) + binaryVersion = v.binaryVersion(newDB) } - return validation.CompareBinaryToSchema(binaryVersion, schemaVersion, src, documentDBTerms) + return v.versionPolicy().CompareBinaryToSchema(binaryVersion, schemaVersion, src, documentDBTerms) } // restoreSourceFor identifies the restore source from a recovery configuration, From ae009e0a54040bab263ec2ae8eab68364beaf153 Mon Sep 17 00:00:00 2001 From: Rayhan Hossain Date: Mon, 30 Nov 2026 15:11:00 -0800 Subject: [PATCH 07/10] fix: guard shared injector ownership and semantic schema targets Reject duplicate plugin identities during server-side install/upgrade while retaining the current release service. Support semantic prerelease/build schema targets only for semver definitions. Add mocked Kubernetes lookup lifecycle tests and real API-schema validation, and run generic chart tests in CI. Preserve canonical schema copies and the existing DocumentDB chart. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 33b3cb3c-1b25-4ffb-bff1-ebf0f3d04058 Signed-off-by: Rayhan Hossain --- .github/workflows/test-unit.yml | 1 + operator/product-helm-chart/README.md | 7 + .../product-helm-chart/templates/crds.yaml | 3 + .../templates/injector.yaml | 10 ++ .../tests/injector_identity_test.yaml | 131 ++++++++++++++++++ operator/product-helm-chart/tests/values.yaml | 18 +++ .../internal/product/definition_chart_test.go | 19 ++- .../product/definition_schema_version_test.go | 73 ++++++++++ 8 files changed, 255 insertions(+), 7 deletions(-) create mode 100644 operator/product-helm-chart/tests/injector_identity_test.yaml create mode 100644 operator/product-helm-chart/tests/values.yaml create mode 100644 operator/src/internal/product/definition_schema_version_test.go diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.yml index cd22539a2..518dae1ad 100644 --- a/.github/workflows/test-unit.yml +++ b/.github/workflows/test-unit.yml @@ -96,6 +96,7 @@ jobs: cd operator/documentdb-helm-chart helm dependency update . helm unittest . + helm unittest ../product-helm-chart - name: Test Summary if: always() diff --git a/operator/product-helm-chart/README.md b/operator/product-helm-chart/README.md index e16e3dfdd..1413e773c 100644 --- a/operator/product-helm-chart/README.md +++ b/operator/product-helm-chart/README.md @@ -12,12 +12,19 @@ example. Supply it as the `productDefinition` values object and pin manager and optional injector images with `image.repository` and `image.digest`. Install cert-manager and CloudNative-PG first; the injector namespace must already exist. The bundled injector retains its actual existing RPC identity. +If another Service in that namespace advertises the same identity, reuse it +with `sidecarInjector.enabled=false`; the chart refuses duplicate registrations. +An upgrade can retain the current release's own Service. This cluster lookup +requires server-side rendering and cannot detect collisions in offline templates +or serialize simultaneous installations. `imagePullSecrets` applies to both manager and injector pods; referenced Secrets must exist in both namespaces. Manager replicas use leader election. CRDs are rendered from exact copies of the canonical shared API schemas. Rendering changes API identity and removes the legacy PostgreSQL image default, so partial image objects cannot override the definition's PostgreSQL image. +Semantic-version definitions also receive a `schemaVersion` pattern accepting +prerelease/build identifiers; the original DocumentDB pattern is unchanged. All other schema properties remain shared; there is no product-specific schema or generated Go API. `make manifests` in `operator/src` automatically synchronizes these copies after regenerating canonical CRDs; `make schemas` diff --git a/operator/product-helm-chart/templates/crds.yaml b/operator/product-helm-chart/templates/crds.yaml index cb7319f46..6c0dfad8c 100644 --- a/operator/product-helm-chart/templates/crds.yaml +++ b/operator/product-helm-chart/templates/crds.yaml @@ -12,6 +12,9 @@ {{- $_ := set $version "name" $api.version }} {{- if eq $entry.file "cluster" }} {{- $_ := unset $version.schema.openAPIV3Schema.properties.spec.properties.image.properties.postgres "default" }} +{{- if eq (int ($.Values.productDefinition.profile.Postgres.ExtensionVersionFormat | default 0)) 1 }} +{{- $_ := set $version.schema.openAPIV3Schema.properties.spec.properties.schemaVersion "pattern" `^(auto|v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)(\.(0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?)?$` }} +{{- end }} {{- end }} {{- $_ := set $crd.spec "versions" (list $version) }} --- diff --git a/operator/product-helm-chart/templates/injector.yaml b/operator/product-helm-chart/templates/injector.yaml index 86b4b7375..84ebccddb 100644 --- a/operator/product-helm-chart/templates/injector.yaml +++ b/operator/product-helm-chart/templates/injector.yaml @@ -1,4 +1,14 @@ {{- if .Values.sidecarInjector.enabled }} +{{- $name := printf "%s-injector" (include "product.name" .) }} +{{- $services := lookup "v1" "Service" .Values.sidecarInjector.namespace "" }} +{{- range $service := $services.items }} +{{- if eq (dig "metadata" "labels" "cnpg.io/pluginName" "" $service) "cnpg-i-sidecar-injector.documentdb.io" }} +{{- $owned := and (eq $service.metadata.name $name) (eq (dig "metadata" "annotations" "meta.helm.sh/release-name" "" $service) $.Release.Name) (eq (dig "metadata" "annotations" "meta.helm.sh/release-namespace" "" $service) $.Release.Namespace) (eq (dig "metadata" "labels" "app.kubernetes.io/managed-by" "" $service) "Helm") }} +{{- if or (not $owned) $service.metadata.deletionTimestamp }} +{{- fail (printf "injector identity already claimed by Service %s/%s; reuse the existing injector with sidecarInjector.enabled=false" $service.metadata.namespace $service.metadata.name) }} +{{- end }} +{{- end }} +{{- end }} {{- if ne .Values.productDefinition.profile.SidecarInjectorPlugin "cnpg-i-sidecar-injector.documentdb.io" }} {{- fail "the bundled injector implements cnpg-i-sidecar-injector.documentdb.io; use an external plugin for another RPC identity" }} {{- end }} diff --git a/operator/product-helm-chart/tests/injector_identity_test.yaml b/operator/product-helm-chart/tests/injector_identity_test.yaml new file mode 100644 index 000000000..112c67eb0 --- /dev/null +++ b/operator/product-helm-chart/tests/injector_identity_test.yaml @@ -0,0 +1,131 @@ +suite: injector plugin identity ownership +templates: + - templates/injector.yaml +values: + - values.yaml +release: + name: widget + namespace: widget-system + upgrade: true +kubernetesProvider: + scheme: + "v1/Service": + gvr: + version: v1 + resource: services + namespaced: true +tests: + - it: retains the current release service during an upgrade + kubernetesProvider: + objects: + - &ownedService + apiVersion: v1 + kind: Service + metadata: &ownedMetadata + name: widget-975f25d2013d-injector + namespace: cnpg-system + labels: + cnpg.io/pluginName: cnpg-i-sidecar-injector.documentdb.io + app.kubernetes.io/managed-by: Helm + annotations: + meta.helm.sh/release-name: widget + meta.helm.sh/release-namespace: widget-system + asserts: + - equal: + path: kind + value: Service + documentIndex: 0 + - equal: + path: metadata.name + value: widget-975f25d2013d-injector + documentIndex: 0 + - it: rejects another release even when its service has the same name + kubernetesProvider: + objects: + - apiVersion: v1 + kind: Service + metadata: + name: widget-975f25d2013d-injector + namespace: cnpg-system + labels: + cnpg.io/pluginName: cnpg-i-sidecar-injector.documentdb.io + app.kubernetes.io/managed-by: Helm + annotations: + meta.helm.sh/release-name: another + meta.helm.sh/release-namespace: widget-system + asserts: + - failedTemplate: + errorPattern: injector identity already claimed + - it: rejects an unmanaged holder with the current release service name + kubernetesProvider: + objects: + - apiVersion: v1 + kind: Service + metadata: + name: widget-975f25d2013d-injector + namespace: cnpg-system + labels: + cnpg.io/pluginName: cnpg-i-sidecar-injector.documentdb.io + asserts: + - failedTemplate: + errorPattern: injector identity already claimed + - it: rejects a duplicate identity even if the current release service is present + kubernetesProvider: + objects: + - *ownedService + - &foreignService + apiVersion: v1 + kind: Service + metadata: + name: documentdb-injector + namespace: cnpg-system + labels: + cnpg.io/pluginName: cnpg-i-sidecar-injector.documentdb.io + asserts: + - failedTemplate: + errorPattern: injector identity already claimed + - it: rejects an unexpected service name even with current release annotations + kubernetesProvider: + objects: + - <<: *ownedService + metadata: + <<: *ownedMetadata + name: another-owned-injector + asserts: + - failedTemplate: + errorPattern: injector identity already claimed + - it: waits for deletion instead of reusing a terminating service + kubernetesProvider: + objects: + - <<: *ownedService + metadata: + <<: *ownedMetadata + deletionTimestamp: "2026-11-30T00:00:00Z" + finalizers: ["example.io/cleanup"] + asserts: + - failedTemplate: + errorPattern: injector identity already claimed + - it: ignores registrations in a different CNPG namespace + kubernetesProvider: + objects: + - apiVersion: v1 + kind: Service + metadata: + name: documentdb-injector + namespace: another-cnpg-system + labels: + cnpg.io/pluginName: cnpg-i-sidecar-injector.documentdb.io + asserts: + - equal: + path: kind + value: Service + documentIndex: 0 + - it: permits reuse of an existing injector when bundling is disabled + set: + sidecarInjector.enabled: false + kubernetesProvider: + objects: + - *foreignService + asserts: + - hasDocuments: + count: 0 diff --git a/operator/product-helm-chart/tests/values.yaml b/operator/product-helm-chart/tests/values.yaml new file mode 100644 index 000000000..9073b5863 --- /dev/null +++ b/operator/product-helm-chart/tests/values.yaml @@ -0,0 +1,18 @@ +productDefinition: + api: + group: widget.example.io + version: v1alpha1 + kind: Database + plural: databases + profile: + SidecarInjectorPlugin: cnpg-i-sidecar-injector.documentdb.io + Postgres: + ExtensionVersionFormat: 0 +image: + repository: registry.example.invalid/operator + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +sidecarInjector: + enabled: true + image: + repository: registry.example.invalid/injector + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa diff --git a/operator/src/internal/product/definition_chart_test.go b/operator/src/internal/product/definition_chart_test.go index d417c3eb1..f9912f0d6 100644 --- a/operator/src/internal/product/definition_chart_test.go +++ b/operator/src/internal/product/definition_chart_test.go @@ -23,14 +23,11 @@ import ( "sigs.k8s.io/yaml" ) -func TestDefinitionChartUsesCanonicalSchemaAndAdmissionIdentity(t *testing.T) { +func renderDefinitionChart(t *testing.T, definition *Definition, extraArgs ...string) ([]byte, error) { + t.Helper() if _, err := exec.LookPath("helm"); err != nil { t.Skip("Helm is required for the shared product chart contract test") } - definition, err := LoadDefinition("testdata/widget.json") - if err != nil { - t.Fatal(err) - } image := map[string]string{ "repository": "registry.example.invalid/operator", "digest": "sha256:" + strings.Repeat("a", 64), @@ -49,8 +46,16 @@ func TestDefinitionChartUsesCanonicalSchemaAndAdmissionIdentity(t *testing.T) { t.Fatal(err) } chart := "../../../product-helm-chart" - command := exec.Command("helm", "template", "widget", chart, "-n", "widget-system", "-f", path) - output, err := command.CombinedOutput() + args := append([]string{"template", "widget", chart, "-n", "widget-system", "-f", path}, extraArgs...) + return exec.Command("helm", args...).CombinedOutput() +} + +func TestDefinitionChartUsesCanonicalSchemaAndAdmissionIdentity(t *testing.T) { + definition, err := LoadDefinition("testdata/widget.json") + if err != nil { + t.Fatal(err) + } + output, err := renderDefinitionChart(t, definition) if err != nil { t.Fatalf("shared chart failed: %v\n%s", err, output) } diff --git a/operator/src/internal/product/definition_schema_version_test.go b/operator/src/internal/product/definition_schema_version_test.go new file mode 100644 index 000000000..648a01f8d --- /dev/null +++ b/operator/src/internal/product/definition_schema_version_test.go @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "strings" + "testing" + + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apiservervalidation "k8s.io/apiextensions-apiserver/pkg/apiserver/validation" + "k8s.io/apimachinery/pkg/util/validation/field" + "sigs.k8s.io/yaml" +) + +func TestRenderedSchemaHonorsSelectedCatalogVersionFormat(t *testing.T) { + for _, format := range []ExtensionVersionFormat{ExtensionVersionDocumentDB, ExtensionVersionSemver} { + t.Run(map[ExtensionVersionFormat]string{ + ExtensionVersionDocumentDB: "legacy", + ExtensionVersionSemver: "semantic", + }[format], func(t *testing.T) { + definition, err := LoadDefinition("testdata/widget.json") + if err != nil { + t.Fatal(err) + } + definition.Policy.PinnedCatalog = "" + definition.Profile.Postgres.ExtensionVersionFormat = format + output, err := renderDefinitionChart(t, definition) + if err != nil { + t.Fatalf("render definition: %v\n%s", err, output) + } + var rendered *apiextv1.JSONSchemaProps + for _, document := range strings.Split(string(output), "\n---\n") { + var crd apiextv1.CustomResourceDefinition + if err := yaml.Unmarshal([]byte(document), &crd); err != nil { + t.Fatal(err) + } + if crd.Kind == "CustomResourceDefinition" && crd.Spec.Names.Kind == definition.API.Kind { + property := crd.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["spec"].Properties["schemaVersion"] + rendered = &property + } + } + if rendered == nil { + t.Fatal("cluster schema missing") + } + var internal apiext.JSONSchemaProps + if err := apiextv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(rendered, &internal, nil); err != nil { + t.Fatal(err) + } + validator, _, err := apiservervalidation.NewSchemaValidator(&internal) + if err != nil { + t.Fatal(err) + } + for _, version := range []string{"", "auto", "1.3.0", "1.3.0-rc.1", "1.3.0-rc.10", "1.3.0+build.2", "1.3.0-rc.1+build.2"} { + errors := apiservervalidation.ValidateCustomResource(field.NewPath("spec", "schemaVersion"), version, validator) + allow := !strings.ContainsAny(version, "-+") || format == ExtensionVersionSemver + if (len(errors) == 0) != allow { + t.Fatalf("format %d schema rejected a supported target or changed legacy semantics: %q, %v", format, version, errors) + } + } + invalidTargets := []string{"latest", "1.3", "1.3.0-", "1.3.0-rc..1", "1.3.0+", " 1.3.0", "1.3.0 "} + if format == ExtensionVersionSemver { + invalidTargets = append(invalidTargets, "01.3.0", "1.3.0-01") + } + for _, invalid := range invalidTargets { + if errors := apiservervalidation.ValidateCustomResource(field.NewPath("spec", "schemaVersion"), invalid, validator); len(errors) == 0 { + t.Fatalf("schema accepted malformed target %q", invalid) + } + } + }) + } +} From 3193702621ca458d4df0adea00e11a369fad61b9 Mon Sep 17 00:00:00 2001 From: Rayhan Hossain Date: Mon, 30 Nov 2026 15:16:57 -0800 Subject: [PATCH 08/10] fix: block incompatible definition updates before database mutation Guard declarative extension image changes before CNPG synchronization. Reject rollback using both status and authoritative installed catalog checks, fail closed when compatibility cannot be verified, and reject extension identity/path/preload changes that cannot be synchronized atomically. Preserve legacy no-definition behavior and unchanged local pinned images. Add 26 guarded-update scenarios and legacy reconciliation coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 33b3cb3c-1b25-4ffb-bff1-ebf0f3d04058 Signed-off-by: Rayhan Hossain --- operator/product-helm-chart/README.md | 7 + .../src/internal/engine/cluster_reconciler.go | 8 + operator/src/internal/engine/image_update.go | 81 +++++++ .../src/internal/engine/image_update_test.go | 204 ++++++++++++++++++ operator/src/internal/product/documentdb.go | 1 + operator/src/internal/product/profile.go | 3 + 6 files changed, 304 insertions(+) create mode 100644 operator/src/internal/engine/image_update.go create mode 100644 operator/src/internal/engine/image_update_test.go diff --git a/operator/product-helm-chart/README.md b/operator/product-helm-chart/README.md index 1413e773c..793c020ae 100644 --- a/operator/product-helm-chart/README.md +++ b/operator/product-helm-chart/README.md @@ -41,6 +41,13 @@ inventing a semantic version. Co-location requires `localDevelopment`; non-local definitions and effective cluster overrides require explicitly enabled, required pod anti-affinity. +For an existing declarative cluster, extension-image changes are checked against +the live installed catalog before CNPG is patched; status alone cannot approve +an update. Changes wait for a healthy primary and reject older or unversioned/ +digest-only target images. Extension identity, library/control paths and preload +libraries cannot change in place. Local pinned-catalog images cannot be replaced. +These guards do not change the legacy no-definition DocumentDB path. + Validate a definition without Kubernetes: ```sh diff --git a/operator/src/internal/engine/cluster_reconciler.go b/operator/src/internal/engine/cluster_reconciler.go index e96ef8c6c..ba6dc8c80 100644 --- a/operator/src/internal/engine/cluster_reconciler.go +++ b/operator/src/internal/engine/cluster_reconciler.go @@ -326,6 +326,14 @@ func (r *ClusterReconciler[T]) Reconcile(ctx context.Context, req ctrl.Request) } } + if err := r.validateImageUpdate(ctx, currentCnpgCluster, desiredCnpgCluster, obj); err != nil { + logger.Error(err, "Blocked incompatible image update") + if r.Recorder != nil { + r.Recorder.Event(obj, corev1.EventTypeWarning, "ImageUpdateBlocked", err.Error()) + } + return ctrl.Result{RequeueAfter: RequeueAfterShort}, nil + } + // otelMonitorPending requeues the reconcile while the OTel monitoring // role's schema grants are not settled, without blocking the steps below. otelMonitorPending := false diff --git a/operator/src/internal/engine/image_update.go b/operator/src/internal/engine/image_update.go new file mode 100644 index 000000000..ff6ac955e --- /dev/null +++ b/operator/src/internal/engine/image_update.go @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package engine + +import ( + "context" + "fmt" + "slices" + + cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" + + "github.com/documentdb/documentdb-operator/internal/cnpg" + "github.com/documentdb/documentdb-operator/internal/validation" +) + +func (r *ClusterReconciler[T]) validateImageUpdate(ctx context.Context, current, desired *cnpgv1.Cluster, obj T) error { + pg := r.profile().Postgres + if !pg.GuardImageUpdates { + return nil + } + + var installed, target *cnpgv1.ExtensionConfiguration + for i := range current.Spec.PostgresConfiguration.Extensions { + extension := ¤t.Spec.PostgresConfiguration.Extensions[i] + if extension.Name == pg.Extension.Name { + installed = extension + } + } + for i := range desired.Spec.PostgresConfiguration.Extensions { + extension := &desired.Spec.PostgresConfiguration.Extensions[i] + if extension.Name == pg.Extension.Name { + target = extension + } + } + if installed == nil || target == nil { + return fmt.Errorf("cannot change the configured extension identity of an existing cluster") + } + // SyncCnpgCluster does not reconcile these fields. Never install an image + // that relies on a layout the existing cluster will not receive. + if !slices.Equal(installed.DynamicLibraryPath, target.DynamicLibraryPath) || + !slices.Equal(installed.ExtensionControlPath, target.ExtensionControlPath) || + !slices.Equal(installed.LdLibraryPath, target.LdLibraryPath) || + !slices.Equal(current.Spec.PostgresConfiguration.AdditionalLibraries, desired.Spec.PostgresConfiguration.AdditionalLibraries) { + return fmt.Errorf("changing extension library/control paths or preload libraries of an existing declarative cluster is unsupported") + } + if installed.ImageVolumeSource.Reference == target.ImageVolumeSource.Reference { + return nil + } + if pg.PinnedCatalogVersion != "" { + return fmt.Errorf("changing the extension image of an existing pinned-catalog cluster is unsupported") + } + + policy := validation.VersionPolicy{Format: pg.ExtensionVersionFormat} + binaryVersion := policy.ImageVersion(target.ImageVolumeSource.Reference) + if binaryVersion == "" { + return fmt.Errorf("cannot verify extension image compatibility: the new image must have a versioned tag without a digest") + } + if errors := policy.ImageRollback(r.Adapter.Status(obj).SchemaVersion, binaryVersion); len(errors) != 0 { + return fmt.Errorf("extension image update blocked: %s", errors.ToAggregate()) + } + // Status may lag an ALTER EXTENSION that committed before its status update + // failed. Only the live catalog can authorize changing the binary. + if r.SQLExecutor == nil || current.Status.CurrentPrimary == "" || + !slices.Contains(current.Status.InstancesStatus[cnpgv1.PodHealthy], current.Status.CurrentPrimary) { + return fmt.Errorf("cannot verify extension image compatibility until the installed schema version is known") + } + output, err := r.SQLExecutor(ctx, current, cnpg.ExtensionVersionSQL(pg.Extension.Name)) + if err != nil { + return fmt.Errorf("read installed schema before changing extension image: %w", err) + } + _, installedVersion, ok := ParseExtensionVersions(output) + if !ok || installedVersion == "" { + return fmt.Errorf("cannot verify extension image compatibility: installed extension catalog is unknown") + } + schemaVersion := r.extensionVersionToSemver(installedVersion) + if errors := policy.ImageRollback(schemaVersion, binaryVersion); len(errors) != 0 { + return fmt.Errorf("extension image update blocked: %s", errors.ToAggregate()) + } + return nil +} diff --git a/operator/src/internal/engine/image_update_test.go b/operator/src/internal/engine/image_update_test.go new file mode 100644 index 000000000..49f277ef7 --- /dev/null +++ b/operator/src/internal/engine/image_update_test.go @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package engine + +import ( + "context" + "fmt" + "reflect" + "strings" + "testing" + + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" + "github.com/go-logr/logr" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + cnpg "github.com/documentdb/documentdb-operator/internal/cnpg" + "github.com/documentdb/documentdb-operator/internal/product" +) + +func TestDefinitionImageUpdatesAreCheckedBeforeCNPGMutation(t *testing.T) { + for _, tc := range []struct { + name, current, target, schema, catalog string + pinned, unhealthy, unknownCatalog bool + queryError bool + documentDBFormat bool + layout string + blocked bool + }{ + {name: "unchanged CR definition rollback", current: "1.3.0", target: "1.2.0", schema: "1.3.0", blocked: true}, + {name: "prerelease rollback", current: "1.3.0", target: "1.3.0-rc.1", schema: "1.3.0", blocked: true}, + {name: "forward image", current: "1.3.0", target: "1.4.0", schema: "1.3.0"}, + {name: "forward prerelease", current: "1.3.0-rc.2", target: "1.3.0-rc.10", schema: "1.3.0-rc.2"}, + {name: "missing status uses installed catalog", current: "1.3.0", target: "1.2.0", catalog: "1.3.0", blocked: true}, + {name: "forward with missing status", current: "1.3.0", target: "1.4.0", catalog: "1.3.0"}, + {name: "stale status cannot authorize catalog rollback", current: "1.4.0", target: "1.2.0", schema: "1.2.0", catalog: "1.3.0", blocked: true}, + {name: "forward image checks catalog despite stale status", current: "1.3.0", target: "1.4.0", schema: "1.2.0", catalog: "1.3.0"}, + {name: "nonempty status cannot replace unavailable primary", current: "1.3.0", target: "1.4.0", schema: "1.3.0", unhealthy: true, blocked: true}, + {name: "nonempty status cannot replace unknown catalog", current: "1.3.0", target: "1.4.0", schema: "1.3.0", unknownCatalog: true, blocked: true}, + {name: "nonempty status cannot replace failed catalog query", current: "1.3.0", target: "1.4.0", schema: "1.3.0", queryError: true, blocked: true}, + {name: "DocumentDB catalog rollback", current: "0.112.0", target: "0.111.0", catalog: "0.112-0", documentDBFormat: true, blocked: true}, + {name: "DocumentDB catalog forward image", current: "0.112.0", target: "0.113.0", catalog: "0.112-0", documentDBFormat: true}, + {name: "unparseable installed schema", current: "1.3.0", target: "1.4.0", schema: "unknown", blocked: true}, + {name: "missing status and unhealthy primary", current: "1.3.0", target: "1.4.0", unhealthy: true, blocked: true}, + {name: "missing catalog", current: "1.3.0", target: "1.4.0", unknownCatalog: true, blocked: true}, + {name: "opaque target", current: "1.3.0", target: "proof-next", schema: "1.3.0", blocked: true}, + {name: "digest target", current: "1.3.0", target: "@sha256:" + strings.Repeat("a", 64), schema: "1.3.0", blocked: true}, + {name: "tagged digest target", current: "1.3.0", target: "1.4.0@sha256:" + strings.Repeat("a", 64), schema: "1.3.0", blocked: true}, + {name: "unchanged local pinned image", current: "proof", target: "proof", schema: "7.4", pinned: true}, + {name: "unchanged local pinned image without healthy primary", current: "proof", target: "proof", schema: "7.4", pinned: true, unhealthy: true}, + {name: "changed local pinned image", current: "proof", target: "proof-next", schema: "7.4", pinned: true, blocked: true}, + {name: "dynamic library layout and image", current: "1.3.0", target: "1.4.0", schema: "1.3.0", layout: "dynamic", blocked: true}, + {name: "control layout and image", current: "1.3.0", target: "1.4.0", schema: "1.3.0", layout: "control", blocked: true}, + {name: "loader layout and image", current: "1.3.0", target: "1.4.0", schema: "1.3.0", layout: "loader", blocked: true}, + {name: "preload libraries and image", current: "1.3.0", target: "1.4.0", schema: "1.3.0", layout: "preload", blocked: true}, + } { + t.Run(tc.name, func(t *testing.T) { + definition, err := product.LoadDefinition("../product/testdata/widget.json") + if err != nil { + t.Fatal(err) + } + definition.Policy.PinnedCatalog = "" + definition.Profile.Postgres.ExtensionVersionFormat = product.ExtensionVersionSemver + if tc.documentDBFormat { + definition.Profile.Postgres.ExtensionVersionFormat = product.ExtensionVersionDocumentDB + } + if tc.pinned { + definition.Policy.PinnedCatalog = "7.4" + } + image := func(tag string) string { + if strings.HasPrefix(tag, "@") { + return "registry.example.invalid/widget" + tag + } + return "registry.example.invalid/widget:" + tag + } + definition.Images.PostgresExtension = image(tc.current) + adapter := product.DocumentDBAdapter{Definition: definition} + db := reconcilableCluster() + db.SetGroupVersionKind(definition.GroupVersion().WithKind(definition.API.Kind)) + db.Finalizers = []string{adapter.Profile().Naming.Finalizer()} + db.Status.SchemaVersion = tc.schema + originalSpec := db.Spec.DeepCopy() + current := cnpg.GetCnpgClusterSpecFromIntent(clusterKey, adapter.Intent(db), db.Name, "", true, logr.Discard()) + current.Status = cnpgv1.ClusterStatus{ + CurrentPrimary: "db-1", + InstancesStatus: map[cnpgv1.PodStatus][]string{cnpgv1.PodHealthy: {"db-1"}}, + } + if tc.unhealthy { + current.Status.InstancesStatus = nil + } + originalCNPGSpec := current.Spec.DeepCopy() + definition.Images.PostgresExtension = image(tc.target) + switch tc.layout { + case "dynamic": + definition.Profile.Postgres.Extension.DynamicLibraryPath = []string{"lib/v2"} + case "control": + definition.Profile.Postgres.Extension.ExtensionControlPath = []string{"share/v2/extension"} + case "loader": + definition.Profile.Postgres.Extension.LdLibraryPath = []string{"lib/v2"} + case "preload": + definition.Profile.Postgres.AdditionalLibraries = []string{"widget_v2"} + } + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{ + clientgoscheme.AddToScheme, cnpgv1.AddToScheme, cmapi.AddToScheme, definition.AddToScheme, + } { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + var patches, queries int + c := newFakeClient(t, scheme, &interceptor.Funcs{ + Patch: func(ctx context.Context, c client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*cnpgv1.Cluster); ok { + patches++ + if queries == 0 { + t.Fatal("extension image was patched before checking the authoritative catalog") + } + } + return c.Patch(ctx, obj, patch, opts...) + }, + }, db, current) + r, recorder := newClusterReconciler(c, scheme, &sqlRecorder{}) + r.Adapter = adapter + r.SQLExecutor = func(_ context.Context, _ *cnpgv1.Cluster, statement string) (string, error) { + if !strings.Contains(statement, "pg_available_extensions") { + t.Fatalf("unexpected SQL mutation: %s", statement) + } + queries++ + if tc.queryError { + return "", errInjected + } + if tc.unknownCatalog { + return "no installed extension", nil + } + catalog := tc.catalog + if catalog == "" { + catalog = tc.schema + } + return fmt.Sprintf("default_version | installed_version\n---+---\n%s | %s\n(1 row)", catalog, catalog), nil + } + result, err := r.Reconcile(context.Background(), clusterKey) + if err != nil { + t.Fatal(err) + } + actual := &cnpgv1.Cluster{} + if err := c.Get(context.Background(), clusterKey.NamespacedName, actual); err != nil { + t.Fatal(err) + } + events := drainEvents(recorder) + if tc.blocked { + if patches != 0 || !reflect.DeepEqual(&actual.Spec, originalCNPGSpec) || + result.RequeueAfter != RequeueAfterShort || !hasEvent(events, "ImageUpdateBlocked") { + t.Fatalf("unsafe update was not blocked before mutation: patches=%d result=%v events=%v", patches, result, events) + } + } else { + wantPatches := 1 + if tc.current == tc.target { + wantPatches = 0 + } + if patches != wantPatches || actual.Spec.PostgresConfiguration.Extensions[0].ImageVolumeSource.Reference != image(tc.target) || + hasEvent(events, "ImageUpdateBlocked") { + t.Fatalf("compatible update did not succeed: patches=%d events=%v", patches, events) + } + } + if tc.catalog != "" && queries == 0 { + t.Fatal("image update did not consult the installed catalog") + } + if err := c.Get(context.Background(), clusterKey.NamespacedName, db); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(&db.Spec, originalSpec) { + t.Fatal("definition-update test changed the cluster CR spec") + } + }) + } +} + +func TestLegacyImageUpdatesKeepExistingBehavior(t *testing.T) { + scheme := newTestScheme(t) + db := reconcilableCluster() + db.Status.SchemaVersion = "1.3.0" + adapter := product.DocumentDBAdapter{} + current := cnpg.GetCnpgClusterSpecFromIntent(clusterKey, adapter.Intent(db), db.Name, "", true, logr.Discard()) + current.Spec.PostgresConfiguration.Extensions[0].ImageVolumeSource.Reference = "registry.example.invalid/documentdb:1.3.0" + c := newFakeClient(t, scheme, nil, db, current) + r, recorder := newClusterReconciler(c, scheme, &sqlRecorder{}) + if _, err := r.Reconcile(context.Background(), clusterKey); err != nil { + t.Fatal(err) + } + actual := &cnpgv1.Cluster{} + if err := c.Get(context.Background(), clusterKey.NamespacedName, actual); err != nil { + t.Fatal(err) + } + expected := adapter.ExtensionImage(db) + if actual.Spec.PostgresConfiguration.Extensions[0].ImageVolumeSource.Reference != expected || + hasEvent(drainEvents(recorder), "ImageUpdateBlocked") { + t.Fatal("no-definition image reconciliation changed") + } +} diff --git a/operator/src/internal/product/documentdb.go b/operator/src/internal/product/documentdb.go index c324a5266..af0feae2c 100644 --- a/operator/src/internal/product/documentdb.go +++ b/operator/src/internal/product/documentdb.go @@ -77,6 +77,7 @@ type DocumentDBAdapter struct { func (a DocumentDBAdapter) Profile() ProductProfile { if a.Definition != nil { profile := a.Definition.Profile + profile.Postgres.GuardImageUpdates = true profile.Postgres.PinnedCatalogVersion = a.Definition.Policy.PinnedCatalog return profile } diff --git a/operator/src/internal/product/profile.go b/operator/src/internal/product/profile.go index acb7df1dd..f4483907e 100644 --- a/operator/src/internal/product/profile.go +++ b/operator/src/internal/product/profile.go @@ -95,6 +95,9 @@ const ( // PostgresProfile captures the product-wide PostgreSQL contract. type PostgresProfile struct { + // GuardImageUpdates requires pre-sync compatibility checks for declarative + // image and extension-layout changes. Legacy adapters retain their behavior. + GuardImageUpdates bool `json:"-"` // PinnedCatalogVersion is an explicit non-upgrading catalog policy. // The definition loader restricts it to local-development definitions. PinnedCatalogVersion string `json:"-"` From 63f2ce6cd814f8b6aa595ed8d1f35c6c8d9a5226 Mon Sep 17 00:00:00 2001 From: Rayhan Hossain Date: Mon, 30 Nov 2026 15:54:08 -0800 Subject: [PATCH 09/10] ci: verify Helm plugin assets using upstream checksum paths Download pinned assets under _dist and use strict GNU checksum verification with ignore-missing, matching upstream release paths. Remove checksum parsing plumbing; verified that valid selected assets pass and missing/corrupt assets still fail. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 33b3cb3c-1b25-4ffb-bff1-ebf0f3d04058 Signed-off-by: Rayhan Hossain --- .github/workflows/test-unit.yml | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.yml index 518dae1ad..e9a3fbbda 100644 --- a/.github/workflows/test-unit.yml +++ b/.github/workflows/test-unit.yml @@ -74,21 +74,16 @@ jobs: run: | version=1.1.0 archive="helm-unittest-linux-amd64-${version}.tgz" - download_dir="${RUNNER_TEMP}/helm-unittest-download" + download_dir="${RUNNER_TEMP}/helm-unittest-download/_dist" mkdir -p "$download_dir" gh release download "v${version}" --repo helm-unittest/helm-unittest \ --pattern "$archive" --pattern helm-unittest-checksum.sha \ --dir "$download_dir" - cd "$download_dir" - checksum=$(awk -v file="*./_dist/${archive}" '$2 == file { print $1 }' helm-unittest-checksum.sha) - if [[ ! "$checksum" =~ ^[[:xdigit:]]{64}$ ]]; then - echo "::error::Missing or invalid checksum for ${archive}" - exit 1 - fi - printf '%s %s\n' "$checksum" "$archive" | sha256sum --check --strict - + cd "${download_dir}/.." + sha256sum --check --strict --ignore-missing _dist/helm-unittest-checksum.sha plugin_dir="$(helm env HELM_PLUGINS)/unittest" mkdir -p "$plugin_dir" - tar -xzf "$archive" -C "$plugin_dir" + tar -xzf "_dist/${archive}" -C "$plugin_dir" helm unittest --help > /dev/null - name: Run Helm unit tests From 1427f0af2ea66f26e73f9e76b59bea19ff3d92d2 Mon Sep 17 00:00:00 2001 From: Rayhan Hossain Date: Mon, 30 Nov 2026 16:14:09 -0800 Subject: [PATCH 10/10] refactor: centralize product resolution and version interpretation Use one adapter-owned image resolver for intent and image accessors. Move image/catalog/schema normalization and ordering to a transport-neutral product policy shared by admission and reconciliation, retaining transport-specific failures and live-catalog checks. Share common scheme registrations and parameterize the existing immutable-image helper for manager/injector. Reuse the semver test fixture and retain all precedence/defaulting regressions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 33b3cb3c-1b25-4ffb-bff1-ebf0f3d04058 Signed-off-by: Rayhan Hossain --- .../product-helm-chart/templates/_helpers.tpl | 6 +- .../templates/deployment.yaml | 2 +- .../templates/injector.yaml | 8 +- operator/src/cmd/main.go | 18 +-- operator/src/internal/engine/extension.go | 35 +----- operator/src/internal/engine/image_update.go | 23 +++- operator/src/internal/product/definition.go | 16 --- .../product/definition_image_helper_test.go | 32 ++++++ operator/src/internal/product/documentdb.go | 103 +++++++----------- operator/src/internal/product/version.go | 72 ++++++++++++ operator/src/internal/product/version_test.go | 30 +++++ .../src/internal/validation/validation.go | 40 +------ .../src/internal/webhook/definition_test.go | 9 +- 13 files changed, 213 insertions(+), 181 deletions(-) create mode 100644 operator/src/internal/product/definition_image_helper_test.go create mode 100644 operator/src/internal/product/version.go create mode 100644 operator/src/internal/product/version_test.go diff --git a/operator/product-helm-chart/templates/_helpers.tpl b/operator/product-helm-chart/templates/_helpers.tpl index a25acf125..e3312c13e 100644 --- a/operator/product-helm-chart/templates/_helpers.tpl +++ b/operator/product-helm-chart/templates/_helpers.tpl @@ -3,10 +3,10 @@ {{- end -}} {{- define "product.image" -}} -{{- $repo := required "image.repository is required" .Values.image.repository -}} -{{- $digest := required "image.digest is required; use an approved immutable image" .Values.image.digest -}} +{{- $repo := required (printf "%s.repository is required" .prefix) .image.repository -}} +{{- $digest := required (printf "%s.digest is required; use an approved immutable image" .prefix) .image.digest -}} {{- if not (regexMatch "^sha256:[a-f0-9]{64}$" $digest) -}} -{{- fail "image.digest must be a sha256 digest" -}} +{{- fail (printf "%s.digest must be a sha256 digest" .prefix) -}} {{- end -}} {{- printf "%s@%s" $repo $digest -}} {{- end -}} diff --git a/operator/product-helm-chart/templates/deployment.yaml b/operator/product-helm-chart/templates/deployment.yaml index ee8402e98..4da56f464 100644 --- a/operator/product-helm-chart/templates/deployment.yaml +++ b/operator/product-helm-chart/templates/deployment.yaml @@ -59,7 +59,7 @@ spec: type: RuntimeDefault containers: - name: manager - image: {{ include "product.image" . | quote }} + image: {{ include "product.image" (dict "image" .Values.image "prefix" "image") | quote }} imagePullPolicy: {{ .Values.image.pullPolicy }} args: - --product-definition=/config/runtime.json diff --git a/operator/product-helm-chart/templates/injector.yaml b/operator/product-helm-chart/templates/injector.yaml index 84ebccddb..94b6d3648 100644 --- a/operator/product-helm-chart/templates/injector.yaml +++ b/operator/product-helm-chart/templates/injector.yaml @@ -12,11 +12,7 @@ {{- if ne .Values.productDefinition.profile.SidecarInjectorPlugin "cnpg-i-sidecar-injector.documentdb.io" }} {{- fail "the bundled injector implements cnpg-i-sidecar-injector.documentdb.io; use an external plugin for another RPC identity" }} {{- end }} -{{- $image := required "sidecarInjector.image.repository is required" .Values.sidecarInjector.image.repository }} -{{- $digest := required "sidecarInjector.image.digest is required" .Values.sidecarInjector.image.digest }} -{{- if not (regexMatch "^sha256:[a-f0-9]{64}$" $digest) }} -{{- fail "sidecarInjector.image.digest must be a sha256 digest" }} -{{- end }} +{{- $image := include "product.image" (dict "image" .Values.sidecarInjector.image "prefix" "sidecarInjector.image") }} apiVersion: v1 kind: Service metadata: @@ -63,7 +59,7 @@ spec: type: RuntimeDefault containers: - name: injector - image: "{{ $image }}@{{ $digest }}" + image: {{ $image | quote }} imagePullPolicy: IfNotPresent args: - plugin diff --git a/operator/src/cmd/main.go b/operator/src/cmd/main.go index 877a9d5b9..e377248f7 100644 --- a/operator/src/cmd/main.go +++ b/operator/src/cmd/main.go @@ -42,15 +42,18 @@ var ( ) func init() { - utilruntime.Must(clientgoscheme.AddToScheme(scheme)) - + registerCommonScheme(scheme) utilruntime.Must(dbv1.AddToScheme(scheme)) - utilruntime.Must(cnpgv1.AddToScheme(scheme)) - utilruntime.Must(cmapi.AddToScheme(scheme)) - utilruntime.Must(fleetv1alpha1.AddToScheme(scheme)) // +kubebuilder:scaffold:scheme } +func registerCommonScheme(target *runtime.Scheme) { + utilruntime.Must(clientgoscheme.AddToScheme(target)) + utilruntime.Must(cnpgv1.AddToScheme(target)) + utilruntime.Must(cmapi.AddToScheme(target)) + utilruntime.Must(fleetv1alpha1.AddToScheme(target)) +} + // nolint:gocyclo func main() { var metricsAddr string @@ -331,10 +334,7 @@ func configureProduct(path string, checkOnly bool) (product.DocumentDBAdapter, * } adapter.Definition = definition configured := runtime.NewScheme() - utilruntime.Must(clientgoscheme.AddToScheme(configured)) - utilruntime.Must(cnpgv1.AddToScheme(configured)) - utilruntime.Must(cmapi.AddToScheme(configured)) - utilruntime.Must(fleetv1alpha1.AddToScheme(configured)) + registerCommonScheme(configured) utilruntime.Must(definition.AddToScheme(configured)) return adapter, configured, "operator." + definition.API.Group, nil } diff --git a/operator/src/internal/engine/extension.go b/operator/src/internal/engine/extension.go index 10130172a..802e6ab2a 100644 --- a/operator/src/internal/engine/extension.go +++ b/operator/src/internal/engine/extension.go @@ -12,12 +12,10 @@ import ( cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/version" "sigs.k8s.io/controller-runtime/pkg/log" cnpg "github.com/documentdb/documentdb-operator/internal/cnpg" "github.com/documentdb/documentdb-operator/internal/product" - util "github.com/documentdb/documentdb-operator/internal/utils" ) // ParseExtensionVersions parses the output of the pg_available_extensions query. @@ -58,42 +56,15 @@ func (r *ClusterReconciler[T]) extensionVersionToSemver(v string) string { if r.profile().Postgres.PinnedCatalogVersion != "" { return v } - if r.profile().Postgres.ExtensionVersionFormat == product.ExtensionVersionSemver { - return v - } - return util.ExtensionVersionToSemver(v) + return (product.VersionPolicy{Format: r.profile().Postgres.ExtensionVersionFormat}).SchemaVersion(v) } func (r *ClusterReconciler[T]) semverToExtensionVersion(v string) string { - if r.profile().Postgres.ExtensionVersionFormat == product.ExtensionVersionSemver { - return v - } - return util.SemverToExtensionVersion(v) + return (product.VersionPolicy{Format: r.profile().Postgres.ExtensionVersionFormat}).CatalogVersion(v) } func (r *ClusterReconciler[T]) compareExtensionVersions(a, b string) (int, error) { - switch format := r.profile().Postgres.ExtensionVersionFormat; format { - case product.ExtensionVersionDocumentDB: - return util.CompareExtensionVersions(a, b) - case product.ExtensionVersionSemver: - first, err := version.ParseSemantic(a) - if err != nil { - return 0, err - } - second, err := version.ParseSemantic(b) - if err != nil { - return 0, err - } - if first.LessThan(second) { - return -1, nil - } - if second.LessThan(first) { - return 1, nil - } - return 0, nil - default: - return 0, fmt.Errorf("unsupported extension version format %d", format) - } + return (product.VersionPolicy{Format: r.profile().Postgres.ExtensionVersionFormat}).CompareCatalogVersions(a, b) } func (r *ClusterReconciler[T]) refetch(ctx context.Context, obj T) error { diff --git a/operator/src/internal/engine/image_update.go b/operator/src/internal/engine/image_update.go index ff6ac955e..b19d2f3c6 100644 --- a/operator/src/internal/engine/image_update.go +++ b/operator/src/internal/engine/image_update.go @@ -11,7 +11,7 @@ import ( cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" "github.com/documentdb/documentdb-operator/internal/cnpg" - "github.com/documentdb/documentdb-operator/internal/validation" + "github.com/documentdb/documentdb-operator/internal/product" ) func (r *ClusterReconciler[T]) validateImageUpdate(ctx context.Context, current, desired *cnpgv1.Cluster, obj T) error { @@ -51,13 +51,13 @@ func (r *ClusterReconciler[T]) validateImageUpdate(ctx context.Context, current, return fmt.Errorf("changing the extension image of an existing pinned-catalog cluster is unsupported") } - policy := validation.VersionPolicy{Format: pg.ExtensionVersionFormat} + policy := product.VersionPolicy{Format: pg.ExtensionVersionFormat} binaryVersion := policy.ImageVersion(target.ImageVolumeSource.Reference) if binaryVersion == "" { return fmt.Errorf("cannot verify extension image compatibility: the new image must have a versioned tag without a digest") } - if errors := policy.ImageRollback(r.Adapter.Status(obj).SchemaVersion, binaryVersion); len(errors) != 0 { - return fmt.Errorf("extension image update blocked: %s", errors.ToAggregate()) + if err := validateImageSchemaCompatibility(policy, binaryVersion, r.Adapter.Status(obj).SchemaVersion); err != nil { + return err } // Status may lag an ALTER EXTENSION that committed before its status update // failed. Only the live catalog can authorize changing the binary. @@ -74,8 +74,19 @@ func (r *ClusterReconciler[T]) validateImageUpdate(ctx context.Context, current, return fmt.Errorf("cannot verify extension image compatibility: installed extension catalog is unknown") } schemaVersion := r.extensionVersionToSemver(installedVersion) - if errors := policy.ImageRollback(schemaVersion, binaryVersion); len(errors) != 0 { - return fmt.Errorf("extension image update blocked: %s", errors.ToAggregate()) + return validateImageSchemaCompatibility(policy, binaryVersion, schemaVersion) +} + +func validateImageSchemaCompatibility(policy product.VersionPolicy, binary, schema string) error { + if schema == "" { + return nil + } + comparison, err := policy.CompareSchemaVersions(binary, schema) + if err != nil { + return fmt.Errorf("cannot verify extension image compatibility: %w", err) + } + if comparison < 0 { + return fmt.Errorf("extension image update blocked: binary version %s is older than installed schema version %s", binary, schema) } return nil } diff --git a/operator/src/internal/product/definition.go b/operator/src/internal/product/definition.go index 2f5dc4aa0..f73600205 100644 --- a/operator/src/internal/product/definition.go +++ b/operator/src/internal/product/definition.go @@ -205,22 +205,6 @@ func (a DocumentDBAdapter) applyDefinition(intent ClusterIntent, db *dbv1.Docume if reflect.DeepEqual(db.Spec.Affinity, Topology{}.Affinity) { intent.Topology.Affinity = d.Topology.Affinity } - intent.Images = d.Images - if db.Spec.Image != nil { - if db.Spec.Image.Postgres != "" { - intent.Images.Postgres = db.Spec.Image.Postgres - } - if db.Spec.Image.DocumentDB != "" { - intent.Images.PostgresExtension = db.Spec.Image.DocumentDB - } - if db.Spec.Image.Gateway != "" { - intent.Images.Gateway = db.Spec.Image.Gateway - } - } - if db.Spec.ImagePullSecrets != nil { - intent.Images.PullSecrets = db.Spec.ImagePullSecrets - } - intent.Images.Combined = "" return intent } diff --git a/operator/src/internal/product/definition_image_helper_test.go b/operator/src/internal/product/definition_image_helper_test.go new file mode 100644 index 000000000..e367e86ec --- /dev/null +++ b/operator/src/internal/product/definition_image_helper_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "strings" + "testing" +) + +func TestChartImageValidationIsSharedAcrossComponents(t *testing.T) { + definition, err := LoadDefinition("testdata/widget.json") + if err != nil { + t.Fatal(err) + } + for _, component := range []string{"image", "sidecarInjector.image"} { + for _, field := range []string{"repository", "digest"} { + t.Run(component+"."+field+" missing", func(t *testing.T) { + output, err := renderDefinitionChart(t, definition, "--set", component+"."+field+"=") + if err == nil || !strings.Contains(string(output), component+"."+field+" is required") { + t.Fatalf("component did not use shared immutable image validation: err=%v output=%s", err, output) + } + }) + } + t.Run(component+" malformed digest", func(t *testing.T) { + output, err := renderDefinitionChart(t, definition, "--set", component+".digest=not-a-digest") + if err == nil || !strings.Contains(string(output), component+".digest must be a sha256 digest") { + t.Fatalf("component accepted an invalid digest or lost its diagnostic prefix: err=%v output=%s", err, output) + } + }) + } +} diff --git a/operator/src/internal/product/documentdb.go b/operator/src/internal/product/documentdb.go index af0feae2c..8661e8f35 100644 --- a/operator/src/internal/product/documentdb.go +++ b/operator/src/internal/product/documentdb.go @@ -88,65 +88,59 @@ func (a DocumentDBAdapter) Profile() ProductProfile { // product profile's repo and default. The resolution priority is shared across // products via util.ResolveComponentImage. func (a DocumentDBAdapter) ExtensionImage(db *dbv1.DocumentDB) string { - if a.Definition != nil { - if db.Spec.Image != nil && db.Spec.Image.DocumentDB != "" { - return db.Spec.Image.DocumentDB - } - return a.Definition.Images.PostgresExtension - } - p := a.Profile() - var explicit string - if db.Spec.Image != nil { - explicit = db.Spec.Image.DocumentDB - } - return util.ResolveComponentImage( - p.ExtensionImageRepo, - p.DefaultTag, - explicit, - db.Spec.DocumentDBVersion, - os.Getenv(util.DOCUMENTDB_VERSION_ENV), - util.CHANGESTREAM_DOCUMENTDB_IMAGE, - dbv1.IsFeatureGateEnabled(db, dbv1.FeatureGateChangeStreams), - ) + return a.resolveImages(db).PostgresExtension } // CombinedImage resolves the combined PostgreSQL + DocumentDB image used when // the cluster runs in combined image mode. Change-stream images have no // combined counterpart, so the change-stream feature gate does not affect it. func (a DocumentDBAdapter) CombinedImage(db *dbv1.DocumentDB) string { - if a.Definition != nil { - return "" - } - var explicit string - if db.Spec.Image != nil { - explicit = db.Spec.Image.DocumentDB - } - return util.CombinedImage(explicit, db.Spec.DocumentDBVersion, os.Getenv(util.DOCUMENTDB_VERSION_ENV)) + return a.resolveImages(db).Combined } // GatewayImage resolves the gateway image for a DocumentDB instance using the // product profile's repo and default. func (a DocumentDBAdapter) GatewayImage(db *dbv1.DocumentDB) string { + return a.resolveImages(db).Gateway +} + +func (a DocumentDBAdapter) resolveImages(db *dbv1.DocumentDB) Images { + var explicit dbv1.ImageSpec + if db.Spec.Image != nil { + explicit = *db.Spec.Image + } + var images Images if a.Definition != nil { - if db.Spec.Image != nil && db.Spec.Image.Gateway != "" { - return db.Spec.Image.Gateway + images = a.Definition.Images + images.Combined = "" + } else { + p := a.Profile() + version := os.Getenv(util.DOCUMENTDB_VERSION_ENV) + changeStreams := dbv1.IsFeatureGateEnabled(db, dbv1.FeatureGateChangeStreams) + images = Images{ + PostgresExtension: util.ResolveComponentImage(p.ExtensionImageRepo, p.DefaultTag, "", db.Spec.DocumentDBVersion, + version, util.CHANGESTREAM_DOCUMENTDB_IMAGE, changeStreams), + Gateway: util.ResolveComponentImage(p.GatewayImageRepo, p.DefaultTag, "", db.Spec.DocumentDBVersion, + version, util.CHANGESTREAM_GATEWAY_IMAGE, changeStreams), + Combined: util.CombinedImage(explicit.DocumentDB, db.Spec.DocumentDBVersion, version), + Postgres: util.PostgresImage(), + PostgresExtensionPullPolicy: ParsePullPolicy(os.Getenv(util.DOCUMENTDB_IMAGE_PULL_POLICY_ENV)), + GatewayPullPolicy: os.Getenv(util.GATEWAY_IMAGE_PULL_POLICY_ENV), } - return a.Definition.Images.Gateway } - p := a.Profile() - var explicit string - if db.Spec.Image != nil { - explicit = db.Spec.Image.Gateway + if explicit.Postgres != "" { + images.Postgres = explicit.Postgres + } + if explicit.DocumentDB != "" { + images.PostgresExtension = explicit.DocumentDB + } + if explicit.Gateway != "" { + images.Gateway = explicit.Gateway } - return util.ResolveComponentImage( - p.GatewayImageRepo, - p.DefaultTag, - explicit, - db.Spec.DocumentDBVersion, - os.Getenv(util.DOCUMENTDB_VERSION_ENV), - util.CHANGESTREAM_GATEWAY_IMAGE, - dbv1.IsFeatureGateEnabled(db, dbv1.FeatureGateChangeStreams), - ) + if a.Definition == nil || db.Spec.ImagePullSecrets != nil { + images.PullSecrets = db.Spec.ImagePullSecrets + } + return images } // DocumentDBResources maps spec.resource of a DocumentDB onto the neutral @@ -185,17 +179,6 @@ func (a DocumentDBAdapter) ToClusterIntent(db *dbv1.DocumentDB) ClusterIntent { sidecarPlugin = db.Spec.Plugins.SidecarInjectorName } - var postgresImage string - if db.Spec.Image != nil && db.Spec.Image.Postgres != "" { - // A CR-pinned operand image wins. - postgresImage = db.Spec.Image.Postgres - } else { - // Otherwise use the operator-level default (POSTGRES_IMAGE env). When that - // is empty the field stays empty and CloudNativePG applies its built-in - // operand default. - postgresImage = util.PostgresImage() - } - pg := Postgres{ LogLevel: db.Spec.LogLevel, StopDelay: db.Spec.Timeouts.StopDelay, @@ -226,15 +209,7 @@ func (a DocumentDBAdapter) ToClusterIntent(db *dbv1.DocumentDB) ClusterIntent { } return a.applyDefinition(ClusterIntent{ - Images: Images{ - PostgresExtension: a.ExtensionImage(db), - PostgresExtensionPullPolicy: ParsePullPolicy(os.Getenv(util.DOCUMENTDB_IMAGE_PULL_POLICY_ENV)), - Combined: a.CombinedImage(db), - Gateway: a.GatewayImage(db), - GatewayPullPolicy: os.Getenv(util.GATEWAY_IMAGE_PULL_POLICY_ENV), - Postgres: postgresImage, - PullSecrets: db.Spec.ImagePullSecrets, - }, + Images: a.resolveImages(db), Topology: Topology{ Instances: db.Spec.InstancesPerNode, Affinity: db.Spec.Affinity, diff --git a/operator/src/internal/product/version.go b/operator/src/internal/product/version.go new file mode 100644 index 000000000..4812c2b6c --- /dev/null +++ b/operator/src/internal/product/version.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "fmt" + + "k8s.io/apimachinery/pkg/util/version" + + util "github.com/documentdb/documentdb-operator/internal/utils" +) + +// VersionPolicy interprets image, catalog and public schema versions without +// imposing admission or reconciliation failure behavior. +type VersionPolicy struct { + Format ExtensionVersionFormat +} + +func (p VersionPolicy) ImageVersion(ref string) string { + tag := util.ReleaseVersionTag(ref) + if p.Format != ExtensionVersionSemver { + return util.ExtractSemver(tag) + } + if _, err := version.ParseSemantic(tag); err != nil { + return "" + } + return tag +} + +func (p VersionPolicy) SchemaVersion(catalog string) string { + if p.Format == ExtensionVersionSemver { + return catalog + } + return util.ExtensionVersionToSemver(catalog) +} + +func (p VersionPolicy) CatalogVersion(schema string) string { + if p.Format == ExtensionVersionSemver { + return schema + } + return util.SemverToExtensionVersion(schema) +} + +func (p VersionPolicy) CompareSchemaVersions(first, second string) (int, error) { + return p.CompareCatalogVersions(p.CatalogVersion(first), p.CatalogVersion(second)) +} + +func (p VersionPolicy) CompareCatalogVersions(first, second string) (int, error) { + switch p.Format { + case ExtensionVersionDocumentDB: + return util.CompareExtensionVersions(first, second) + case ExtensionVersionSemver: + a, err := version.ParseSemantic(first) + if err != nil { + return 0, err + } + b, err := version.ParseSemantic(second) + if err != nil { + return 0, err + } + if a.LessThan(b) { + return -1, nil + } + if b.LessThan(a) { + return 1, nil + } + return 0, nil + default: + return 0, fmt.Errorf("unsupported extension version format %d", p.Format) + } +} diff --git a/operator/src/internal/product/version_test.go b/operator/src/internal/product/version_test.go new file mode 100644 index 000000000..96253e344 --- /dev/null +++ b/operator/src/internal/product/version_test.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import "testing" + +func TestVersionPolicySeparatesCatalogAndPublicRepresentations(t *testing.T) { + for _, input := range []struct { + format ExtensionVersionFormat + catalog, schema string + next string + }{ + {ExtensionVersionDocumentDB, "0.112-0", "0.112.0", "0.113-0"}, + {ExtensionVersionSemver, "1.3.0-rc.2", "1.3.0-rc.2", "1.3.0-rc.10"}, + } { + policy := VersionPolicy{Format: input.format} + if policy.SchemaVersion(input.catalog) != input.schema || policy.CatalogVersion(input.schema) != input.catalog { + t.Fatalf("format %d lost catalog/schema representation: %q %q", input.format, input.catalog, input.schema) + } + catalogOrder, err := policy.CompareCatalogVersions(input.catalog, input.next) + if err != nil { + t.Fatal(err) + } + publicOrder, err := policy.CompareSchemaVersions(input.schema, policy.SchemaVersion(input.next)) + if err != nil || catalogOrder != -1 || publicOrder != catalogOrder { + t.Fatalf("catalog and public guards disagree for format %d: %d %d %v", input.format, catalogOrder, publicOrder, err) + } + } +} diff --git a/operator/src/internal/validation/validation.go b/operator/src/internal/validation/validation.go index 0f3867dfa..fc9b474d6 100644 --- a/operator/src/internal/validation/validation.go +++ b/operator/src/internal/validation/validation.go @@ -14,7 +14,6 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/util/validation/field" - "k8s.io/apimachinery/pkg/util/version" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" @@ -42,38 +41,7 @@ type VersionPolicy struct { } func (p VersionPolicy) ImageVersion(ref string) string { - if p.Format != product.ExtensionVersionSemver { - return ImageTagSemver(ref) - } - tag := util.ReleaseVersionTag(ref) - if _, err := version.ParseSemantic(tag); err != nil { - return "" - } - return tag -} - -func (p VersionPolicy) compare(first, second string) (int, error) { - if p.Format == product.ExtensionVersionDocumentDB { - return util.CompareExtensionVersions(util.SemverToExtensionVersion(first), util.SemverToExtensionVersion(second)) - } - if p.Format != product.ExtensionVersionSemver { - return 0, fmt.Errorf("unsupported extension version format %d", p.Format) - } - a, err := version.ParseSemantic(first) - if err != nil { - return 0, err - } - b, err := version.ParseSemantic(second) - if err != nil { - return 0, err - } - if a.LessThan(b) { - return -1, nil - } - if b.LessThan(a) { - return 1, nil - } - return 0, nil + return (product.VersionPolicy{Format: p.Format}).ImageVersion(ref) } // ExtractSemver returns the leading "X.Y.Z" portion from a tag string, @@ -121,7 +89,7 @@ func (p VersionPolicy) SchemaVersionNotExceedsBinary(schemaVersion, binaryVersio )} } - cmp, err := p.compare(schemaVersion, binaryVersion) + cmp, err := (product.VersionPolicy{Format: p.Format}).CompareSchemaVersions(schemaVersion, binaryVersion) if err != nil { return field.ErrorList{field.Invalid( path, @@ -153,7 +121,7 @@ func (p VersionPolicy) ImageRollback(installedSchemaVersion, newBinaryVersion st return nil } - cmp, err := p.compare(newBinaryVersion, installedSchemaVersion) + cmp, err := (product.VersionPolicy{Format: p.Format}).CompareSchemaVersions(newBinaryVersion, installedSchemaVersion) if err != nil { return field.ErrorList{field.Forbidden( field.NewPath("spec"), @@ -294,7 +262,7 @@ func (p VersionPolicy) CompareBinaryToSchema(binaryVersion, schemaVersion string }, nil } - cmp, err := p.compare(binaryVersion, schemaVersion) + cmp, err := (product.VersionPolicy{Format: p.Format}).CompareSchemaVersions(binaryVersion, schemaVersion) if err != nil { return admission.Warnings{ fmt.Sprintf("cannot compare %s %s with the %s's schema version %s: %v; compatibility not verified", diff --git a/operator/src/internal/webhook/definition_test.go b/operator/src/internal/webhook/definition_test.go index 3559e4811..37085653b 100644 --- a/operator/src/internal/webhook/definition_test.go +++ b/operator/src/internal/webhook/definition_test.go @@ -59,14 +59,7 @@ func TestSharedAdmissionDefinitionPolicy(t *testing.T) { } func TestDefinitionImageParticipatesInCommonVersionGuards(t *testing.T) { - definition, err := product.LoadDefinition("../product/testdata/widget.json") - if err != nil { - t.Fatal(err) - } - definition.Policy.PinnedCatalog = "" - definition.Profile.Postgres.ExtensionVersionFormat = product.ExtensionVersionSemver - definition.Images.PostgresExtension = "registry.example.invalid/widget:1.2.3" - validator := &DocumentDBValidator{Adapter: product.DocumentDBAdapter{Definition: definition}} + validator := semverValidator(t, "1.2.3") db := validator.Adapter.New() db.Spec.SchemaVersion = "1.2.3" if errors := validator.validateSchemaVersionNotExceedsBinary(db); len(errors) != 0 {