diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.yml index d9cedf843..e9a3fbbda 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,13 +69,29 @@ 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/_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}/.." + sha256sum --check --strict --ignore-missing _dist/helm-unittest-checksum.sha + plugin_dir="$(helm env HELM_PLUGINS)/unittest" + mkdir -p "$plugin_dir" + tar -xzf "_dist/${archive}" -C "$plugin_dir" + helm unittest --help > /dev/null - name: Run Helm unit tests run: | 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/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..793c020ae --- /dev/null +++ b/operator/product-helm-chart/README.md @@ -0,0 +1,58 @@ +# 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. +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` +here refreshes only the copies. Source-equality checks run without Helm, while +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`; 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 +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..e3312c13e --- /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 (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 (printf "%s.digest must be a sha256 digest" .prefix) -}} +{{- 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..6c0dfad8c --- /dev/null +++ b/operator/product-helm-chart/templates/crds.yaml @@ -0,0 +1,22 @@ +{{- $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 }} +{{- 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) }} +--- +{{ 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..4da56f464 --- /dev/null +++ b/operator/product-helm-chart/templates/deployment.yaml @@ -0,0 +1,100 @@ +{{- 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" (dict "image" .Values.image "prefix" "image") | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + args: + - --product-definition=/config/runtime.json + - --leader-elect + 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..94b6d3648 --- /dev/null +++ b/operator/product-helm-chart/templates/injector.yaml @@ -0,0 +1,127 @@ +{{- 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 }} +{{- $image := include "product.image" (dict "image" .Values.sidecarInjector.image "prefix" "sidecarInjector.image") }} +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 + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault + containers: + - name: injector + image: {{ $image | quote }} + 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/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/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/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/cmd/main.go b/operator/src/cmd/main.go index 60a183952..e377248f7 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" @@ -29,6 +30,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 @@ -40,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 @@ -59,6 +64,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 +92,16 @@ func main() { flag.Parse() ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) + 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 + } // 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 +198,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 +217,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 +233,7 @@ func main() { } if err = (&controller.DocumentDBReconciler{ + Adapter: adapter, Client: mgr.GetClient(), Scheme: mgr.GetScheme(), Config: mgr.GetConfig(), @@ -224,6 +245,7 @@ func main() { } if err = (&controller.BackupReconciler{ + Adapter: adapter, Client: mgr.GetClient(), Scheme: mgr.GetScheme(), Recorder: mgr.GetEventRecorderFor("backup-controller"), @@ -233,6 +255,7 @@ func main() { } if err = (&controller.ScheduledBackupReconciler{ + Adapter: adapter, Client: mgr.GetClient(), Scheme: mgr.GetScheme(), Recorder: mgr.GetEventRecorderFor("scheduled-backup-controller"), @@ -242,7 +265,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 +275,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) } @@ -295,3 +319,22 @@ 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() + registerCommonScheme(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/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/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/extension.go b/operator/src/internal/engine/extension.go index 0c794b9c3..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. @@ -55,42 +53,18 @@ func (r *ClusterReconciler[T]) extensionName() string { } func (r *ClusterReconciler[T]) extensionVersionToSemver(v string) string { - if r.profile().Postgres.ExtensionVersionFormat == product.ExtensionVersionSemver { + if r.profile().Postgres.PinnedCatalogVersion != "" { 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 { @@ -131,6 +105,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/engine/image_update.go b/operator/src/internal/engine/image_update.go new file mode 100644 index 000000000..b19d2f3c6 --- /dev/null +++ b/operator/src/internal/engine/image_update.go @@ -0,0 +1,92 @@ +// 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/product" +) + +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 := 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 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. + 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) + 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/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/definition.go b/operator/src/internal/product/definition.go new file mode 100644 index 000000000..f73600205 --- /dev/null +++ b/operator/src/internal/product/definition.go @@ -0,0 +1,220 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "encoding/json" + "fmt" + "io" + "maps" + "net" + "os" + "reflect" + "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" + "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 || 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") + } + 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 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}") + } + 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} +} + +// 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 + } + 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_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 new file mode 100644 index 000000000..f9912f0d6 --- /dev/null +++ b/operator/src/internal/product/definition_chart_test.go @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "reflect" + "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" +) + +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") + } + 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}, + "replicaCount": 2, + "imagePullSecrets": []corev1.LocalObjectReference{{Name: "registry-login"}}, + }) + 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" + 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) + } + 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.DeepCopy() + } + } + 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 { + 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") + } + assertDefinitionImageDefaulting(t, crd.Spec.Versions[0].Schema.OpenAPIV3Schema, definition) + } 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) + } + 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 || 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") + } + }) + } +} + +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_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/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/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) + } + } + }) + } +} diff --git a/operator/src/internal/product/definition_test.go b/operator/src/internal/product/definition_test.go new file mode 100644 index 000000000..feea32652 --- /dev/null +++ b/operator/src/internal/product/definition_test.go @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package product + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "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) { + 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 }, + "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 + 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{ + "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"), + "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") + } + }) + } +} + +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/product/documentdb.go b/operator/src/internal/product/documentdb.go index 5a1ec75f4..8661e8f35 100644 --- a/operator/src/internal/product/documentdb.go +++ b/operator/src/internal/product/documentdb.go @@ -69,10 +69,18 @@ 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.GuardImageUpdates = true + profile.Postgres.PinnedCatalogVersion = a.Definition.Policy.PinnedCatalog + return profile + } return DocumentDBProfile() } @@ -80,50 +88,59 @@ 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 { - 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 { - 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 { - p := a.Profile() - var explicit 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.Gateway + explicit = *db.Spec.Image + } + var images Images + if a.Definition != nil { + 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 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 explicit.Postgres != "" { + images.Postgres = explicit.Postgres + } + if explicit.DocumentDB != "" { + images.PostgresExtension = explicit.DocumentDB + } + if explicit.Gateway != "" { + images.Gateway = explicit.Gateway + } + 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 @@ -162,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, @@ -202,16 +208,8 @@ func (a DocumentDBAdapter) ToClusterIntent(db *dbv1.DocumentDB) ClusterIntent { bootstrap.Recovery = &r } - return 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, - }, + return a.applyDefinition(ClusterIntent{ + Images: a.resolveImages(db), Topology: Topology{ Instances: db.Spec.InstancesPerNode, Affinity: db.Spec.Affinity, @@ -238,7 +236,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 +246,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 +303,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..f4483907e 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,12 @@ 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:"-"` // 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/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 75369aa4a..fc9b474d6 100644 --- a/operator/src/internal/validation/validation.go +++ b/operator/src/internal/validation/validation.go @@ -17,6 +17,7 @@ import ( "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 +34,16 @@ 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 { + return (product.VersionPolicy{Format: p.Format}).ImageVersion(ref) +} + // 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 +71,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 +89,7 @@ func SchemaVersionNotExceedsBinary(schemaVersion, binaryVersion string, t Terms) )} } - schemaExtensionVersion := util.SemverToExtensionVersion(schemaVersion) - binaryExtensionVersion := util.SemverToExtensionVersion(binaryVersion) - - cmp, err := util.CompareExtensionVersions(schemaExtensionVersion, binaryExtensionVersion) + cmp, err := (product.VersionPolicy{Format: p.Format}).CompareSchemaVersions(schemaVersion, binaryVersion) if err != nil { return field.ErrorList{field.Invalid( path, @@ -101,14 +113,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 := (product.VersionPolicy{Format: p.Format}).CompareSchemaVersions(newBinaryVersion, installedSchemaVersion) if err != nil { return field.ErrorList{field.Forbidden( field.NewPath("spec"), @@ -229,6 +242,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 +262,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 := (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/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_test.go b/operator/src/internal/webhook/definition_test.go new file mode 100644 index 000000000..37085653b --- /dev/null +++ b/operator/src/internal/webhook/definition_test.go @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package webhook + +import ( + "context" + "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" +) + +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) { + validator := semverValidator(t, "1.2.3") + 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") + } +} + +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}} + 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) + } + }) + } +} + +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) + } +} 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 a9d908ec6..af744ada2 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 v.versionPolicy().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,18 @@ func (v *DocumentDBValidator) validateImageRollback(newDB, oldDB *dbv1.DocumentD return nil } - return validation.ImageRollback(installedSchemaVersion, resolveBinaryVersion(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 v.versionPolicy().ImageVersion(v.Adapter.ExtensionImage(db)) + } + return resolveBinaryVersion(db) } // --------------------------------------------------------------------------- @@ -218,7 +241,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 = v.binaryVersion(newDB) + } + return v.versionPolicy().CompareBinaryToSchema(binaryVersion, schemaVersion, src, documentDBTerms) } // restoreSourceFor identifies the restore source from a recovery configuration, @@ -237,15 +264,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 err := d.ValidateAffinity(v.Adapter.ToClusterIntent(db).Topology.Affinity); err != nil { + errors = append(errors, field.Forbidden(field.NewPath("spec", "affinity"), err.Error())) + } + 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