From 968d6d14ddfe7b62ebd554735acc79143f186a0c Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Mon, 16 Nov 2026 14:24:02 +0100 Subject: [PATCH] refactor(etcd): render the etcd chart's objects from cozy-lib templates The kubernetes chart is about to render an etcd of its own per cluster, and it needs the same EtcdCluster, PKI, DataStore, defrag, VPA and scrape shapes the etcd chart renders. It cannot take the etcd chart as a subchart: the chart refuses any release not named "etcd", and the names it renders are pinned by the immutable spec.tls of adopted clusters. The shapes therefore move into cozy-lib, parameterised by the cluster name, and the etcd chart calls them with "etcd". Its rendered output is byte-identical before and after. Assisted-by: LLM Signed-off-by: Timofei Larkin --- packages/extra/etcd/templates/datastore.yaml | 32 +- .../extra/etcd/templates/etcd-cluster.yaml | 302 +---------- .../extra/etcd/templates/etcd-defrag.yaml | 66 +-- packages/extra/etcd/templates/podscrape.yaml | 12 +- packages/extra/etcd/templates/vpa.yaml | 28 +- packages/library/cozy-lib/templates/_etcd.tpl | 508 ++++++++++++++++++ .../templates/tests/etcd-cluster.yaml | 3 + .../tests/etcd_cluster_test.yaml | 47 ++ 8 files changed, 566 insertions(+), 432 deletions(-) create mode 100644 packages/library/cozy-lib/templates/_etcd.tpl create mode 100644 packages/tests/cozy-lib-tests/templates/tests/etcd-cluster.yaml create mode 100644 packages/tests/cozy-lib-tests/tests/etcd_cluster_test.yaml diff --git a/packages/extra/etcd/templates/datastore.yaml b/packages/extra/etcd/templates/datastore.yaml index 2a4a9e05a..681fa2a99 100644 --- a/packages/extra/etcd/templates/datastore.yaml +++ b/packages/extra/etcd/templates/datastore.yaml @@ -1,35 +1,5 @@ --- -apiVersion: kamaji.clastix.io/v1alpha1 -kind: DataStore -metadata: - name: {{ .Release.Namespace }} -spec: - driver: etcd - endpoints: - - etcd.{{ $.Release.Namespace }}.svc:2379 - tlsConfig: - certificateAuthority: - certificate: - secretReference: - keyPath: tls.crt - name: etcd-ca-tls - namespace: {{ .Release.Namespace }} - privateKey: - secretReference: - keyPath: tls.key - name: etcd-ca-tls - namespace: {{ .Release.Namespace }} - clientCertificate: - certificate: - secretReference: - keyPath: tls.crt - name: etcd-client-tls - namespace: {{ .Release.Namespace }} - privateKey: - secretReference: - keyPath: tls.key - name: etcd-client-tls - namespace: {{ .Release.Namespace }} +{{ include "cozy-lib.etcd.datastore" (dict "name" "etcd" "dataStoreName" .Release.Namespace "root" $) }} --- apiVersion: v1 kind: Secret diff --git a/packages/extra/etcd/templates/etcd-cluster.yaml b/packages/extra/etcd/templates/etcd-cluster.yaml index 3676f53cb..c0bafb273 100644 --- a/packages/extra/etcd/templates/etcd-cluster.yaml +++ b/packages/extra/etcd/templates/etcd-cluster.yaml @@ -1,304 +1,10 @@ -{{- define "calculateQuotaBackendBytes" -}} -{{- $units := dict "Ki" 1024 "Mi" 1048576 "Gi" 1073741824 -}} -{{- $value := regexFind "[0-9.]+" . -}} -{{- $unit := regexFind "[a-zA-Z]+" . -}} -{{- $numericValue := float64 $value -}} -{{- $bytes := mulf $numericValue (index $units $unit) -}} -{{- $result := mulf $bytes 0.95 -}} -{{- printf "%.0f" $result -}} -{{- end -}} +{{- $etcd := dict "name" "etcd" "values" .Values "root" $ -}} --- -apiVersion: etcd-operator.cozystack.io/v1alpha2 -kind: EtcdCluster -metadata: - name: etcd -spec: - version: {{ .Values.version | quote }} - replicas: {{ .Values.replicas }} - storage: - size: {{ .Values.size }} - {{- with .Values.storageClass }} - storageClassName: {{ . }} - {{- end }} - options: - # quotaBackendBytes/snapshotCount are typed integers in v1alpha2 (no quotes). - quotaBackendBytes: {{ include "calculateQuotaBackendBytes" .Values.size }} - autoCompactionMode: periodic - autoCompactionRetention: "5m" - snapshotCount: 10000 - {{- with .Values.resources }} - resources: {{- include "cozy-lib.resources.sanitize" (list . $) | nindent 4 }} - {{- end }} - additionalMetadata: - labels: - cozystack.io/service: etcd - # TLS uses secretRef mode: the chart issues the server, operator-client and - # peer certs via the cert-manager Certificates rendered below, and the - # EtcdCluster only REFERENCES the resulting Secrets. This is deliberate, not - # cosmetic — spec.tls is immutable in v1alpha2 (CRD CEL: self.tls == - # oldSelf.tls), and `etcd-migrate` adopts legacy clusters into exactly this - # secretRef shape (serverSecretRef/operatorClientSecretRef/peer.secretRef, - # pointing at the legacy etcd-{server,client,peer}-tls Secrets). Rendering - # certManager here would diverge from the adopted object and the API server - # would reject every post-adoption HelmRelease reconcile, leaving migrated - # clusters permanently non-Ready. Providing operatorClientSecretRef keeps etcd - # --client-cert-auth on, so external clients (the Kamaji DataStore) still - # authenticate with a CN=root client cert. ca.crt lives inside each referenced - # Secret (cert-manager writes it), which is what v1alpha2 reads as the trusted - # CA. No spec.auth: cozystack stays cert-only (no etcd password auth). - tls: - client: - serverSecretRef: - name: etcd-server-tls - operatorClientSecretRef: - name: etcd-client-tls - peer: - secretRef: - name: etcd-peer-tls - {{- $rawConstraints := "" }} - {{- if .Values._cluster.scheduling }} - {{- $rawConstraints = get .Values._cluster.scheduling "globalAppTopologySpreadConstraints" }} - {{- end }} - {{- if $rawConstraints }} - {{- /* The raw value already carries its own top-level topologySpreadConstraints: key */}} - {{- $rawConstraints | fromYaml | toYaml | nindent 2 }} - labelSelector: - matchLabels: - app.kubernetes.io/instance: etcd - {{- else }} - topologySpreadConstraints: - - maxSkew: 1 - topologyKey: "kubernetes.io/hostname" - whenUnsatisfiable: DoNotSchedule - nodeTaintsPolicy: Ignore - labelSelector: - matchLabels: - app.kubernetes.io/instance: etcd - {{- end }} - {{- with .Values.affinity }} - affinity: - {{- toYaml . | nindent 4 }} - {{- else }} - # Soft anti-affinity, a preference on top of the spread constraint above, - # which by default is the hard rule that keeps two members off one node - # while another node has none. Preferred, not required, because a required - # rule also forbids two members on one node when every node already has - # one, so an etcd with more members than schedulable nodes could not start - # all of them. With node-local storage a recreated member Pod can only - # return to its own node, and the default spread keeps it Pending there - # while that node holds another member and some other node holds none. - # Override via .Values.affinity for a hard rule. - affinity: - podAntiAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 100 - podAffinityTerm: - labelSelector: - matchLabels: - app.kubernetes.io/instance: etcd - topologyKey: kubernetes.io/hostname - {{- end }} +{{ include "cozy-lib.etcd.cluster" (merge (dict "labels" (dict "cozystack.io/service" "etcd")) $etcd) }} --- -apiVersion: cert-manager.io/v1 -kind: Issuer -metadata: - name: etcd-selfsigning-issuer -spec: - selfSigned: {} +{{ include "cozy-lib.etcd.certificates" (merge (dict "extraDNSNames" (list (printf "*.etcd-headless.%s.svc" .Release.Namespace))) $etcd) }} --- -apiVersion: cert-manager.io/v1 -kind: Certificate -metadata: - name: etcd-peer-ca -spec: - isCA: true - usages: - - "signing" - - "key encipherment" - - "cert sign" - commonName: etcd-peer-ca - duration: 87600h - subject: - organizations: - - {{ .Release.Namespace }} - organizationalUnits: - - {{ .Release.Name }} - secretName: etcd-peer-ca-tls - privateKey: - rotationPolicy: Never - algorithm: RSA - size: 4096 - issuerRef: - name: etcd-selfsigning-issuer - kind: Issuer - group: cert-manager.io ---- -apiVersion: cert-manager.io/v1 -kind: Certificate -metadata: - name: etcd-ca -spec: - isCA: true - usages: - - "signing" - - "key encipherment" - - "cert sign" - commonName: etcd-ca - duration: 87600h - subject: - organizations: - - {{ .Release.Namespace }} - organizationalUnits: - - {{ .Release.Name }} - secretName: etcd-ca-tls - privateKey: - rotationPolicy: Never - algorithm: RSA - size: 4096 - issuerRef: - name: etcd-selfsigning-issuer - kind: Issuer - group: cert-manager.io ---- -apiVersion: cert-manager.io/v1 -kind: Issuer -metadata: - name: etcd-peer-issuer -spec: - ca: - secretName: etcd-peer-ca-tls ---- -apiVersion: cert-manager.io/v1 -kind: Issuer -metadata: - name: etcd-issuer -spec: - ca: - secretName: etcd-ca-tls ---- -# Server certificate, referenced by spec.tls.client.serverSecretRef. The SANs -# must cover every name the operator and clients dial the cluster by. We use -# WILDCARDS (not the legacy chart's enumerated etcd-.etcd-headless SANs) -# because the v1alpha2 operator brings up members — including replacements after -# a failure — under random names in its native domain (.etcd..svc); -# an enumerated list would leave a replacement member's name out of every SAN -# and fail TLS verification forever (a silent one-short-cluster). The legacy -# headless wildcard is kept so adopted members still validate during the -# transition window. cert-manager writes ca.crt into etcd-server-tls, which -# v1alpha2 reads as --trusted-ca-file. -apiVersion: cert-manager.io/v1 -kind: Certificate -metadata: - name: etcd-server -spec: - commonName: etcd-server - secretName: etcd-server-tls - subject: - organizations: - - {{ .Release.Namespace }} - organizationalUnits: - - {{ .Release.Name }} - isCA: false - usages: - - "client auth" - - "server auth" - - "signing" - - "key encipherment" - dnsNames: - - etcd - - etcd.{{ .Release.Namespace }}.svc - - "*.etcd.{{ .Release.Namespace }}.svc" - - "*.etcd-headless.{{ .Release.Namespace }}.svc" - - localhost - ipAddresses: - - "127.0.0.1" - privateKey: - rotationPolicy: Always - algorithm: RSA - size: 4096 - issuerRef: - name: etcd-issuer - kind: Issuer ---- -# Peer certificate, referenced by spec.tls.peer.secretRef. Same wildcard SAN -# rationale as the server cert above. -apiVersion: cert-manager.io/v1 -kind: Certificate -metadata: - name: etcd-peer -spec: - commonName: etcd-peer - secretName: etcd-peer-tls - subject: - organizations: - - {{ .Release.Namespace }} - organizationalUnits: - - {{ .Release.Name }} - isCA: false - usages: - - "server auth" - - "client auth" - - "signing" - - "key encipherment" - dnsNames: - - etcd - - etcd.{{ .Release.Namespace }}.svc - - "*.etcd.{{ .Release.Namespace }}.svc" - - "*.etcd-headless.{{ .Release.Namespace }}.svc" - - localhost - ipAddresses: - - "127.0.0.1" - privateKey: - rotationPolicy: Always - algorithm: RSA - size: 4096 - issuerRef: - name: etcd-peer-issuer - kind: Issuer ---- -# Client certificate, referenced by spec.tls.client.operatorClientSecretRef and -# reused by external consumers of the cluster (the Kamaji DataStore). -# commonName=root identifies the caller as the etcd root user under -# --client-cert-auth. -apiVersion: cert-manager.io/v1 -kind: Certificate -metadata: - name: etcd-client -spec: - commonName: root - secretName: etcd-client-tls - subject: - organizations: - - {{ .Release.Namespace }} - organizationalUnits: - - {{ .Release.Name }} - usages: - - "signing" - - "key encipherment" - - "client auth" - privateKey: - rotationPolicy: Always - algorithm: RSA - size: 4096 - issuerRef: - name: etcd-issuer - kind: Issuer ---- -apiVersion: cozystack.io/v1alpha1 -kind: WorkloadMonitor -metadata: - name: {{ $.Release.Name }} - namespace: {{ $.Release.Namespace }} -spec: - replicas: {{ .Values.replicas }} - minReplicas: {{ div .Values.replicas 2 | add1 }} - kind: etcd - type: etcd - selector: - app.kubernetes.io/instance: etcd - app.kubernetes.io/managed-by: etcd-operator - app.kubernetes.io/name: etcd - version: {{ $.Chart.Version }} +{{ include "cozy-lib.etcd.workloadMonitor" $etcd }} --- # Transitional headless Service backing the LEGACY per-pod DNS names. # diff --git a/packages/extra/etcd/templates/etcd-defrag.yaml b/packages/extra/etcd/templates/etcd-defrag.yaml index c1eefa0db..fbdf49b6e 100644 --- a/packages/extra/etcd/templates/etcd-defrag.yaml +++ b/packages/extra/etcd/templates/etcd-defrag.yaml @@ -1,65 +1 @@ -apiVersion: batch/v1 -kind: CronJob -metadata: - name: {{ .Release.Name }}-defrag -spec: - schedule: "0 * * * *" - concurrencyPolicy: Forbid - startingDeadlineSeconds: 300 - successfulJobsHistoryLimit: 3 - failedJobsHistoryLimit: 1 - jobTemplate: - spec: - activeDeadlineSeconds: 1800 - backoffLimit: 2 - template: - spec: - securityContext: - runAsNonRoot: true - runAsUser: 1001 - seccompProfile: - type: RuntimeDefault - containers: - - name: etcd-defrag - image: ghcr.io/ahrtr/etcd-defrag:v0.13.0 - securityContext: - allowPrivilegeEscalation: false - readOnlyRootFilesystem: true - capabilities: - drop: ["ALL"] - resources: - requests: - cpu: 10m - memory: 32Mi - limits: - cpu: 100m - memory: 64Mi - args: - # The v1alpha2 operator names the headless Service after the - # cluster ({{ $.Release.Name }}) and does not use StatefulSet - # ordinal pod names. Point at the headless Service and let - # --cluster fan the defrag out to every member via member-list. - - --endpoints=https://{{ $.Release.Name }}.{{ $.Release.Namespace }}.svc:2379 - - --cacert=/etc/etcd/pki/client/cert/ca.crt - - --cert=/etc/etcd/pki/client/cert/tls.crt - - --key=/etc/etcd/pki/client/cert/tls.key - - --cluster - # etcd compacts itself (periodic, 5m retention, see etcd-cluster.yaml). - # Compacting again to the latest revision either fails because nothing - # was written since, or drops the history that retention keeps for - # watchers to resume from. - - --compaction=false - # dbQuotaUsage below is dbSize over this value, and the tool assumes - # 2 GiB unless told the quota the cluster actually runs with. - - --etcd-storage-quota-bytes={{ include "calculateQuotaBackendBytes" .Values.size }} - - --defrag-rule - - "dbQuotaUsage > 0.8 || dbSize - dbSizeInUse > 200*1024*1024" - volumeMounts: - - mountPath: /etc/etcd/pki/client/cert - name: client-certificate - readOnly: true - volumes: - - name: client-certificate - secret: - secretName: {{ .Release.Name }}-client-tls - restartPolicy: OnFailure +{{ include "cozy-lib.etcd.defrag" (dict "name" .Release.Name "values" .Values "root" $) }} diff --git a/packages/extra/etcd/templates/podscrape.yaml b/packages/extra/etcd/templates/podscrape.yaml index 8e8df72dc..6acaff0e2 100644 --- a/packages/extra/etcd/templates/podscrape.yaml +++ b/packages/extra/etcd/templates/podscrape.yaml @@ -1,11 +1 @@ -apiVersion: operator.victoriametrics.com/v1beta1 -kind: VMPodScrape -metadata: - name: etcd-pod-scrape -spec: - podMetricsEndpoints: - - port: metrics - scheme: http - selector: - matchLabels: - app.kubernetes.io/name: etcd +{{ include "cozy-lib.etcd.podScrape" (dict "name" "etcd" "selector" (dict "app.kubernetes.io/name" "etcd")) }} diff --git a/packages/extra/etcd/templates/vpa.yaml b/packages/extra/etcd/templates/vpa.yaml index 7be0efbe9..956559ad5 100644 --- a/packages/extra/etcd/templates/vpa.yaml +++ b/packages/extra/etcd/templates/vpa.yaml @@ -1,28 +1,2 @@ --- -apiVersion: autoscaling.k8s.io/v1 -kind: VerticalPodAutoscaler -metadata: - name: etcd -spec: - # The v1alpha2 operator manages member Pods directly (no StatefulSet); the - # EtcdCluster exposes a /scale subresource with status.selector for HPA/VPA. - targetRef: - apiVersion: etcd-operator.cozystack.io/v1alpha2 - kind: EtcdCluster - name: etcd - updatePolicy: - # Initial, not Auto: Auto evicts running etcd members to apply new - # recommendations, churning the StatefulSet (and tripping the Cilium - # IP-reuse leak under load). Evicting an etcd member is also disruptive to - # quorum. Initial sets requests at pod creation without evicting; the - # minAllowed floor below is the safety net since running pods aren't resized. - updateMode: Initial - resourcePolicy: - containerPolicies: - - containerName: etcd - {{- with dict "cpu" "250m" "memory" "256Mi" }} - minAllowed: {{- get (include "cozy-lib.resources.sanitize" (list . $) | fromYaml) "requests" | toYaml | nindent 8 }} - {{- end }} - {{- with dict "cpu" "5000m" "memory" "8Gi" }} - maxAllowed: {{- get (include "cozy-lib.resources.sanitize" (list . $) | fromYaml) "requests" | toYaml | nindent 8 }} - {{- end }} +{{ include "cozy-lib.etcd.vpa" (dict "name" "etcd" "root" $) }} diff --git a/packages/library/cozy-lib/templates/_etcd.tpl b/packages/library/cozy-lib/templates/_etcd.tpl new file mode 100644 index 000000000..2a313bed2 --- /dev/null +++ b/packages/library/cozy-lib/templates/_etcd.tpl @@ -0,0 +1,508 @@ +{{/* +Shapes of a Cozystack etcd: the EtcdCluster, its cert-manager PKI, the Kamaji +DataStore pointing at it and the satellites that keep it healthy. The etcd +chart renders one per tenant under the fixed name "etcd"; the kubernetes chart +renders one per cluster under its own name. Every name below derives from +.name, so the etcd chart's output is unchanged by the extraction. + +Each template takes a dict: + name - EtcdCluster name; the operator names its Services and member Pods + after it, and every Secret, Issuer and Certificate here is + "-". + root - the calling chart's root context ($), for .Release, .Chart and + the _cluster values. + values - (cluster, vpa) version, replicas, size, storageClass, resources, + affinity, in the etcd chart's values shape. + labels, annotations - (cluster) additionalMetadata the operator copies onto + every member Pod and PVC. + extraDNSNames - (certificates) SANs appended to the server and peer + certificates. + dataStoreName - (datastore) name of the cluster-scoped DataStore. + podLabels - (defrag) extra labels on the defrag Job's Pods. + values.size - (defrag) also sizes the quota the defrag rule measures against. +*/}} + +{{- define "cozy-lib.etcd.quotaBackendBytes" -}} +{{- $units := dict "Ki" 1024 "Mi" 1048576 "Gi" 1073741824 -}} +{{- $value := regexFind "[0-9.]+" . -}} +{{- $unit := regexFind "[a-zA-Z]+" . -}} +{{- $numericValue := float64 $value -}} +{{- $bytes := mulf $numericValue (index $units $unit) -}} +{{- $result := mulf $bytes 0.95 -}} +{{- printf "%.0f" $result -}} +{{- end -}} + +{{- define "cozy-lib.etcd.cluster" -}} +{{- $name := .name -}} +{{- $values := .values -}} +{{- $root := .root -}} +apiVersion: etcd-operator.cozystack.io/v1alpha2 +kind: EtcdCluster +metadata: + name: {{ $name }} +spec: + version: {{ $values.version | quote }} + replicas: {{ $values.replicas }} + storage: + size: {{ $values.size }} + {{- with $values.storageClass }} + storageClassName: {{ . }} + {{- end }} + options: + # quotaBackendBytes/snapshotCount are typed integers in v1alpha2 (no quotes). + quotaBackendBytes: {{ include "cozy-lib.etcd.quotaBackendBytes" $values.size }} + autoCompactionMode: periodic + autoCompactionRetention: "5m" + snapshotCount: 10000 + {{- with $values.resources }} + resources: {{- include "cozy-lib.resources.sanitize" (list . $root) | nindent 4 }} + {{- end }} + {{- if or .labels .annotations }} + additionalMetadata: + {{- with .labels }} + labels: + {{- toYaml . | nindent 6 }} + {{- end }} + {{- with .annotations }} + annotations: + {{- toYaml . | nindent 6 }} + {{- end }} + {{- end }} + # TLS uses secretRef mode: the chart issues the server, operator-client and + # peer certs via the cert-manager Certificates rendered below, and the + # EtcdCluster only REFERENCES the resulting Secrets. This is deliberate, not + # cosmetic — spec.tls is immutable in v1alpha2 (CRD CEL: self.tls == + # oldSelf.tls), and `etcd-migrate` adopts legacy clusters into exactly this + # secretRef shape (serverSecretRef/operatorClientSecretRef/peer.secretRef, + # pointing at the legacy etcd-{server,client,peer}-tls Secrets). Rendering + # certManager here would diverge from the adopted object and the API server + # would reject every post-adoption HelmRelease reconcile, leaving migrated + # clusters permanently non-Ready. Providing operatorClientSecretRef keeps etcd + # --client-cert-auth on, so external clients (the Kamaji DataStore) still + # authenticate with a CN=root client cert. ca.crt lives inside each referenced + # Secret (cert-manager writes it), which is what v1alpha2 reads as the trusted + # CA. No spec.auth: cozystack stays cert-only (no etcd password auth). + tls: + client: + serverSecretRef: + name: {{ $name }}-server-tls + operatorClientSecretRef: + name: {{ $name }}-client-tls + peer: + secretRef: + name: {{ $name }}-peer-tls + {{- $rawConstraints := "" }} + {{- with dig "scheduling" "" ($root.Values._cluster | default dict) }} + {{- $rawConstraints = get . "globalAppTopologySpreadConstraints" }} + {{- end }} + {{- if $rawConstraints }} + {{- /* The raw value already carries its own top-level topologySpreadConstraints: key */}} + {{- $rawConstraints | fromYaml | toYaml | nindent 2 }} + labelSelector: + matchLabels: + app.kubernetes.io/instance: {{ $name }} + {{- else }} + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: "kubernetes.io/hostname" + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/instance: {{ $name }} + {{- end }} + {{- with $values.affinity }} + affinity: + {{- toYaml . | nindent 4 }} + {{- else }} + # Soft anti-affinity, a preference on top of the spread constraint above, + # which by default is the hard rule that keeps two members off one node + # while another node has none. Preferred, not required, because a required + # rule also forbids two members on one node when every node already has + # one, so an etcd with more members than schedulable nodes could not start + # all of them. With node-local storage a recreated member Pod can only + # return to its own node, and the default spread keeps it Pending there + # while that node holds another member and some other node holds none. + # Override via .Values.affinity for a hard rule. + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + podAffinityTerm: + labelSelector: + matchLabels: + app.kubernetes.io/instance: {{ $name }} + topologyKey: kubernetes.io/hostname + {{- end }} +{{- end -}} + +{{- define "cozy-lib.etcd.certificates" -}} +{{- $name := .name -}} +{{- $root := .root -}} +{{- $ns := $root.Release.Namespace -}} +{{- $dnsNames := list $name (printf "%s.%s.svc" $name $ns) (printf "*.%s.%s.svc" $name $ns) -}} +{{- $dnsNames = concat $dnsNames (.extraDNSNames | default list) (list "localhost") -}} +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + name: {{ $name }}-selfsigning-issuer +spec: + selfSigned: {} +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: {{ $name }}-peer-ca +spec: + isCA: true + usages: + - "signing" + - "key encipherment" + - "cert sign" + commonName: {{ $name }}-peer-ca + duration: 87600h + subject: + organizations: + - {{ $ns }} + organizationalUnits: + - {{ $root.Release.Name }} + secretName: {{ $name }}-peer-ca-tls + privateKey: + rotationPolicy: Never + algorithm: RSA + size: 4096 + issuerRef: + name: {{ $name }}-selfsigning-issuer + kind: Issuer + group: cert-manager.io +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: {{ $name }}-ca +spec: + isCA: true + usages: + - "signing" + - "key encipherment" + - "cert sign" + commonName: {{ $name }}-ca + duration: 87600h + subject: + organizations: + - {{ $ns }} + organizationalUnits: + - {{ $root.Release.Name }} + secretName: {{ $name }}-ca-tls + privateKey: + rotationPolicy: Never + algorithm: RSA + size: 4096 + issuerRef: + name: {{ $name }}-selfsigning-issuer + kind: Issuer + group: cert-manager.io +--- +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + name: {{ $name }}-peer-issuer +spec: + ca: + secretName: {{ $name }}-peer-ca-tls +--- +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + name: {{ $name }}-issuer +spec: + ca: + secretName: {{ $name }}-ca-tls +--- +# Server certificate, referenced by spec.tls.client.serverSecretRef. The SANs +# must cover every name the operator and clients dial the cluster by. We use +# WILDCARDS (not the legacy chart's enumerated etcd-.etcd-headless SANs) +# because the v1alpha2 operator brings up members — including replacements after +# a failure — under random names in its native domain (.etcd..svc); +# an enumerated list would leave a replacement member's name out of every SAN +# and fail TLS verification forever (a silent one-short-cluster). The legacy +# headless wildcard is kept so adopted members still validate during the +# transition window. cert-manager writes ca.crt into etcd-server-tls, which +# v1alpha2 reads as --trusted-ca-file. +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: {{ $name }}-server +spec: + commonName: {{ $name }}-server + secretName: {{ $name }}-server-tls + subject: + organizations: + - {{ $ns }} + organizationalUnits: + - {{ $root.Release.Name }} + isCA: false + usages: + - "client auth" + - "server auth" + - "signing" + - "key encipherment" + dnsNames: + {{- range $dnsNames }} + - {{ if hasPrefix "*" . }}{{ . | quote }}{{ else }}{{ . }}{{ end }} + {{- end }} + ipAddresses: + - "127.0.0.1" + privateKey: + rotationPolicy: Always + algorithm: RSA + size: 4096 + issuerRef: + name: {{ $name }}-issuer + kind: Issuer +--- +# Peer certificate, referenced by spec.tls.peer.secretRef. Same wildcard SAN +# rationale as the server cert above. +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: {{ $name }}-peer +spec: + commonName: {{ $name }}-peer + secretName: {{ $name }}-peer-tls + subject: + organizations: + - {{ $ns }} + organizationalUnits: + - {{ $root.Release.Name }} + isCA: false + usages: + - "server auth" + - "client auth" + - "signing" + - "key encipherment" + dnsNames: + {{- range $dnsNames }} + - {{ if hasPrefix "*" . }}{{ . | quote }}{{ else }}{{ . }}{{ end }} + {{- end }} + ipAddresses: + - "127.0.0.1" + privateKey: + rotationPolicy: Always + algorithm: RSA + size: 4096 + issuerRef: + name: {{ $name }}-peer-issuer + kind: Issuer +--- +# Client certificate, referenced by spec.tls.client.operatorClientSecretRef and +# reused by external consumers of the cluster (the Kamaji DataStore). +# commonName=root identifies the caller as the etcd root user under +# --client-cert-auth. +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: {{ $name }}-client +spec: + commonName: root + secretName: {{ $name }}-client-tls + subject: + organizations: + - {{ $ns }} + organizationalUnits: + - {{ $root.Release.Name }} + usages: + - "signing" + - "key encipherment" + - "client auth" + privateKey: + rotationPolicy: Always + algorithm: RSA + size: 4096 + issuerRef: + name: {{ $name }}-issuer + kind: Issuer +{{- end -}} + +{{- define "cozy-lib.etcd.workloadMonitor" -}} +{{- $name := .name -}} +{{- $root := .root -}} +apiVersion: cozystack.io/v1alpha1 +kind: WorkloadMonitor +metadata: + name: {{ $name }} + namespace: {{ $root.Release.Namespace }} +spec: + replicas: {{ .values.replicas }} + minReplicas: {{ div .values.replicas 2 | add1 }} + kind: etcd + type: etcd + selector: + app.kubernetes.io/instance: {{ $name }} + app.kubernetes.io/managed-by: etcd-operator + app.kubernetes.io/name: etcd + version: {{ $root.Chart.Version }} +{{- end -}} + +{{- define "cozy-lib.etcd.datastore" -}} +{{- $name := .name -}} +{{- $ns := .root.Release.Namespace -}} +apiVersion: kamaji.clastix.io/v1alpha1 +kind: DataStore +metadata: + name: {{ .dataStoreName }} +spec: + driver: etcd + endpoints: + - {{ $name }}.{{ $ns }}.svc:2379 + tlsConfig: + certificateAuthority: + certificate: + secretReference: + keyPath: tls.crt + name: {{ $name }}-ca-tls + namespace: {{ $ns }} + privateKey: + secretReference: + keyPath: tls.key + name: {{ $name }}-ca-tls + namespace: {{ $ns }} + clientCertificate: + certificate: + secretReference: + keyPath: tls.crt + name: {{ $name }}-client-tls + namespace: {{ $ns }} + privateKey: + secretReference: + keyPath: tls.key + name: {{ $name }}-client-tls + namespace: {{ $ns }} +{{- end -}} + +{{- define "cozy-lib.etcd.defrag" -}} +{{- $name := .name -}} +{{- $root := .root -}} +{{- /* The apiserver refuses a CronJob name over 52 characters, which leaves + room for the 11 its Jobs append. */ -}} +{{- $cronJobName := printf "%s-defrag" $name -}} +{{- if gt (len $cronJobName) 52 -}} +{{- $cronJobName = printf "%s-%s" (trunc 43 $cronJobName | trimSuffix "-") (sha256sum $cronJobName | trunc 8) -}} +{{- end -}} +apiVersion: batch/v1 +kind: CronJob +metadata: + name: {{ $cronJobName }} +spec: + schedule: "0 * * * *" + concurrencyPolicy: Forbid + startingDeadlineSeconds: 300 + successfulJobsHistoryLimit: 3 + failedJobsHistoryLimit: 1 + jobTemplate: + spec: + activeDeadlineSeconds: 1800 + backoffLimit: 2 + template: + {{- with .podLabels }} + metadata: + labels: + {{- toYaml . | nindent 12 }} + {{- end }} + spec: + securityContext: + runAsNonRoot: true + runAsUser: 1001 + seccompProfile: + type: RuntimeDefault + containers: + - name: etcd-defrag + image: ghcr.io/ahrtr/etcd-defrag:v0.13.0 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + resources: + requests: + cpu: 10m + memory: 32Mi + limits: + cpu: 100m + memory: 64Mi + args: + # The v1alpha2 operator names the headless Service after the + # cluster ({{ $name }}) and does not use StatefulSet + # ordinal pod names. Point at the headless Service and let + # --cluster fan the defrag out to every member via member-list. + - --endpoints=https://{{ $name }}.{{ $root.Release.Namespace }}.svc:2379 + - --cacert=/etc/etcd/pki/client/cert/ca.crt + - --cert=/etc/etcd/pki/client/cert/tls.crt + - --key=/etc/etcd/pki/client/cert/tls.key + - --cluster + # etcd compacts itself (periodic, 5m retention, see etcd-cluster.yaml). + # Compacting again to the latest revision either fails because nothing + # was written since, or drops the history that retention keeps for + # watchers to resume from. + - --compaction=false + # dbQuotaUsage below is dbSize over this value, and the tool assumes + # 2 GiB unless told the quota the cluster actually runs with. + - --etcd-storage-quota-bytes={{ include "cozy-lib.etcd.quotaBackendBytes" .values.size }} + - --defrag-rule + - "dbQuotaUsage > 0.8 || dbSize - dbSizeInUse > 200*1024*1024" + volumeMounts: + - mountPath: /etc/etcd/pki/client/cert + name: client-certificate + readOnly: true + volumes: + - name: client-certificate + secret: + secretName: {{ $name }}-client-tls + restartPolicy: OnFailure +{{- end -}} + +{{- define "cozy-lib.etcd.vpa" -}} +{{- $name := .name -}} +{{- $root := .root -}} +apiVersion: autoscaling.k8s.io/v1 +kind: VerticalPodAutoscaler +metadata: + name: {{ $name }} +spec: + # The v1alpha2 operator manages member Pods directly (no StatefulSet); the + # EtcdCluster exposes a /scale subresource with status.selector for HPA/VPA. + targetRef: + apiVersion: etcd-operator.cozystack.io/v1alpha2 + kind: EtcdCluster + name: {{ $name }} + updatePolicy: + # Initial, not Auto: Auto evicts running etcd members to apply new + # recommendations, churning the StatefulSet (and tripping the Cilium + # IP-reuse leak under load). Evicting an etcd member is also disruptive to + # quorum. Initial sets requests at pod creation without evicting; the + # minAllowed floor below is the safety net since running pods aren't resized. + updateMode: Initial + resourcePolicy: + containerPolicies: + - containerName: etcd + {{- with dict "cpu" "250m" "memory" "256Mi" }} + minAllowed: {{- get (include "cozy-lib.resources.sanitize" (list . $root) | fromYaml) "requests" | toYaml | nindent 8 }} + {{- end }} + {{- with dict "cpu" "5000m" "memory" "8Gi" }} + maxAllowed: {{- get (include "cozy-lib.resources.sanitize" (list . $root) | fromYaml) "requests" | toYaml | nindent 8 }} + {{- end }} +{{- end -}} + +{{- define "cozy-lib.etcd.podScrape" -}} +apiVersion: operator.victoriametrics.com/v1beta1 +kind: VMPodScrape +metadata: + name: {{ .name }}-pod-scrape +spec: + podMetricsEndpoints: + - port: metrics + scheme: http + selector: + matchLabels: + {{- toYaml .selector | nindent 6 }} +{{- end -}} diff --git a/packages/tests/cozy-lib-tests/templates/tests/etcd-cluster.yaml b/packages/tests/cozy-lib-tests/templates/tests/etcd-cluster.yaml new file mode 100644 index 000000000..35470ae4d --- /dev/null +++ b/packages/tests/cozy-lib-tests/templates/tests/etcd-cluster.yaml @@ -0,0 +1,3 @@ +{{- with .Values.etcdClusterTest }} +{{ include "cozy-lib.etcd.cluster" (dict "name" "kubernetes-demo-etcd" "values" (dict "version" "3.6.11" "replicas" 3 "size" "4Gi") "root" $ "labels" .labels "annotations" .annotations) }} +{{- end }} diff --git a/packages/tests/cozy-lib-tests/tests/etcd_cluster_test.yaml b/packages/tests/cozy-lib-tests/tests/etcd_cluster_test.yaml new file mode 100644 index 000000000..aa010814f --- /dev/null +++ b/packages/tests/cozy-lib-tests/tests/etcd_cluster_test.yaml @@ -0,0 +1,47 @@ +suite: etcd cluster additionalMetadata + +templates: + - templates/tests/etcd-cluster.yaml + +release: + name: kubernetes-demo + namespace: tenant-demo + +tests: + - it: copies annotations onto the members next to the labels + set: + _cluster: {} + etcdClusterTest: + labels: + cozystack.io/service: kubernetes-etcd + annotations: + sdn.cozystack.io/vpc: virtualprivatecloud-demo + asserts: + - equal: + path: spec.additionalMetadata.labels["cozystack.io/service"] + value: kubernetes-etcd + - equal: + path: spec.additionalMetadata.annotations["sdn.cozystack.io/vpc"] + value: virtualprivatecloud-demo + + - it: renders annotations alone without an empty labels map + set: + _cluster: {} + etcdClusterTest: + annotations: + sdn.cozystack.io/vpc: virtualprivatecloud-demo + asserts: + - equal: + path: spec.additionalMetadata.annotations["sdn.cozystack.io/vpc"] + value: virtualprivatecloud-demo + - notExists: + path: spec.additionalMetadata.labels + + - it: renders no additionalMetadata when given neither + set: + _cluster: {} + etcdClusterTest: + replicas: 3 + asserts: + - notExists: + path: spec.additionalMetadata