From 79e1fb444c301330aef363afae263db36f2dc846 Mon Sep 17 00:00:00 2001 From: 7487 <1042653432@qq.com> Date: Thu, 8 Oct 2026 20:22:39 +0800 Subject: [PATCH 01/14] fix(gateway): copy allowed routes for the edge listener The edge listener retained the renderer's local allowed-routes value, while the apex and child listeners already owned independent copies. Give edge the same ownership so later changes to the local value cannot reach a rendered listener. The rendered Gateway remains unchanged. Fixes #4118 Assisted-by: LLM Signed-off-by: 7487 <1042653432@qq.com> --- internal/controller/tenantgateway/reconciler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/controller/tenantgateway/reconciler.go b/internal/controller/tenantgateway/reconciler.go index b53998051..cedb3732d 100644 --- a/internal/controller/tenantgateway/reconciler.go +++ b/internal/controller/tenantgateway/reconciler.go @@ -1432,7 +1432,7 @@ func (r *Reconciler) renderGateway(tgw *gatewayv1alpha1.TenantGateway, dynHostna Port: 80, Protocol: gatewayv1.HTTPProtocolType, Hostname: &wildcardHost, - AllowedRoutes: edgeAllowedRoutes, + AllowedRoutes: edgeAllowedRoutes.DeepCopy(), }, gatewayv1.Listener{ Name: "edge-apex", From a4cb00e6dd587759f84658dfe3c3ae97da4a41ff Mon Sep 17 00:00:00 2001 From: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:24:49 +0300 Subject: [PATCH 02/14] fix(monitoring): spread monitoring replicas over nodes The VMCluster, VLCluster, VTCluster and VMAlertmanager the chart renders carry no affinity and no topology spread, and vm-operator copies both fields onto the pods as written without adding any of its own. Nothing in those specs kept two replicas of one tier off the same node. With replicationFactor 2 both copies of a series can then sit on one node, and on a node-local class the volumes keep them there, so losing that node loses both copies. A StatefulSet pod on a lost node is not replaced elsewhere until its Pod or Node object is deleted, which holds for the Alertmanager replicas without a volume as well. The tiers that run as StatefulSets, vmstorage, vmselect, vlstorage, vtstorage and the Alertmanager, now get a per-node spread with whenUnsatisfiable DoNotSchedule and nodeTaintsPolicy Ignore. The tiers that run as Deployments, vminsert, vlinsert, vlselect, vtinsert and vtselect, get the same spread with ScheduleAnyway, since their pods are replaced on another node without help. A platform that sets scheduling.globalAppTopologySpreadConstraints gets that policy for every tier instead, with the tier's own selector added to each constraint that has none. vm-operator rolls a changed StatefulSet one pod at a time. A replica on a node-local volume whose peer shares its node cannot be placed again under the new rule, so its new pod stays Pending and the rollout of that cluster stops there until the replica is moved. Assisted-by: LLM Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> --- .../monitoring/templates/_scheduling.tpl | 22 ++ .../monitoring/templates/alerta/alerta.yaml | 1 + .../monitoring/templates/vlogs/vlogs.yaml | 3 + .../monitoring/templates/vm/vmcluster.yaml | 3 + .../monitoring/templates/vtraces/vtraces.yaml | 3 + .../tests/topology_spread_test.yaml | 350 ++++++++++++++++++ 6 files changed, 382 insertions(+) create mode 100644 packages/system/monitoring/templates/_scheduling.tpl create mode 100644 packages/system/monitoring/tests/topology_spread_test.yaml diff --git a/packages/system/monitoring/templates/_scheduling.tpl b/packages/system/monitoring/templates/_scheduling.tpl new file mode 100644 index 000000000..6540d4d84 --- /dev/null +++ b/packages/system/monitoring/templates/_scheduling.tpl @@ -0,0 +1,22 @@ +{{- define "monitoring.topologySpreadConstraints" -}} +{{- $root := index . 0 -}} +{{- $selector := dict "matchLabels" (dict "app.kubernetes.io/name" (index . 1) "app.kubernetes.io/instance" (index . 2)) -}} +{{- $global := list -}} +{{- with ($root.Values._cluster | default dict).scheduling -}} +{{- with get . "globalAppTopologySpreadConstraints" -}} +{{- $global = dig "topologySpreadConstraints" (list) (fromYaml .) -}} +{{- end -}} +{{- end -}} +{{- $constraints := list -}} +{{- range $global -}} +{{- $constraints = append $constraints (ternary . (merge (dict "labelSelector" $selector) .) (hasKey . "labelSelector")) -}} +{{- end -}} +{{- if not $constraints -}} +{{- $default := dict "maxSkew" 1 "topologyKey" "kubernetes.io/hostname" "whenUnsatisfiable" (index . 3) "labelSelector" $selector -}} +{{- if eq (index . 3) "DoNotSchedule" -}} +{{- $_ := set $default "nodeTaintsPolicy" "Ignore" -}} +{{- end -}} +{{- $constraints = list $default -}} +{{- end -}} +{{- toYaml (dict "topologySpreadConstraints" $constraints) -}} +{{- end -}} diff --git a/packages/system/monitoring/templates/alerta/alerta.yaml b/packages/system/monitoring/templates/alerta/alerta.yaml index 6376eaa9e..e5bdda356 100644 --- a/packages/system/monitoring/templates/alerta/alerta.yaml +++ b/packages/system/monitoring/templates/alerta/alerta.yaml @@ -421,6 +421,7 @@ spec: apps.cozystack.io/application.name: {{ $.Release.Name }} replicaCount: {{ include "monitoring.alertmanager.replicas" $ }} configSecret: alertmanager + {{- include "monitoring.topologySpreadConstraints" (list $ "vmalertmanager" "alertmanager" "DoNotSchedule") | nindent 2 }} {{- if and $emailEnabled $email.authUsername }} secrets: - {{ $emailPasswordSecret | quote }} diff --git a/packages/system/monitoring/templates/vlogs/vlogs.yaml b/packages/system/monitoring/templates/vlogs/vlogs.yaml index 0e3d6add1..ed70f3215 100644 --- a/packages/system/monitoring/templates/vlogs/vlogs.yaml +++ b/packages/system/monitoring/templates/vlogs/vlogs.yaml @@ -22,13 +22,16 @@ spec: apps.cozystack.io/application.name: {{ $.Release.Name }} vlinsert: replicaCount: 2 + {{- include "monitoring.topologySpreadConstraints" (list $ "vlinsert" .name "ScheduleAnyway") | nindent 4 }} resources: {} vlselect: replicaCount: 2 + {{- include "monitoring.topologySpreadConstraints" (list $ "vlselect" .name "ScheduleAnyway") | nindent 4 }} resources: {} vlstorage: retentionPeriod: {{ .retentionPeriod | quote }} replicaCount: 2 + {{- include "monitoring.topologySpreadConstraints" (list $ "vlstorage" .name "DoNotSchedule") | nindent 4 }} resources: {} storage: volumeClaimTemplate: diff --git a/packages/system/monitoring/templates/vm/vmcluster.yaml b/packages/system/monitoring/templates/vm/vmcluster.yaml index e2962a12a..a89d410fc 100644 --- a/packages/system/monitoring/templates/vm/vmcluster.yaml +++ b/packages/system/monitoring/templates/vm/vmcluster.yaml @@ -18,9 +18,11 @@ spec: # it's usually more than default 30 maxLabelsPerTimeseries: "60" replicaCount: 2 + {{- include "monitoring.topologySpreadConstraints" (list $ "vminsert" .name "ScheduleAnyway") | nindent 4 }} resources: {} vmselect: replicaCount: 2 + {{- include "monitoring.topologySpreadConstraints" (list $ "vmselect" .name "DoNotSchedule") | nindent 4 }} resources: {} extraArgs: search.maxUniqueTimeseries: "600000" @@ -46,6 +48,7 @@ spec: storage: 2Gi vmstorage: replicaCount: 2 + {{- include "monitoring.topologySpreadConstraints" (list $ "vmstorage" .name "DoNotSchedule") | nindent 4 }} resources: {} storage: volumeClaimTemplate: diff --git a/packages/system/monitoring/templates/vtraces/vtraces.yaml b/packages/system/monitoring/templates/vtraces/vtraces.yaml index c7f3d386f..5c03a9dda 100644 --- a/packages/system/monitoring/templates/vtraces/vtraces.yaml +++ b/packages/system/monitoring/templates/vtraces/vtraces.yaml @@ -71,9 +71,11 @@ spec: apps.cozystack.io/application.name: {{ $.Release.Name }} insert: replicaCount: 2 + {{- include "monitoring.topologySpreadConstraints" (list $ "vtinsert" .name "ScheduleAnyway") | nindent 4 }} resources: {} select: replicaCount: 2 + {{- include "monitoring.topologySpreadConstraints" (list $ "vtselect" .name "ScheduleAnyway") | nindent 4 }} resources: {} storage: retentionPeriod: {{ .retentionPeriod | quote }} @@ -84,6 +86,7 @@ spec: retention.maxDiskUsagePercent: "80" {{- end }} replicaCount: 2 + {{- include "monitoring.topologySpreadConstraints" (list $ "vtstorage" .name "DoNotSchedule") | nindent 4 }} resources: {} storage: volumeClaimTemplate: diff --git a/packages/system/monitoring/tests/topology_spread_test.yaml b/packages/system/monitoring/tests/topology_spread_test.yaml new file mode 100644 index 000000000..dc8273fad --- /dev/null +++ b/packages/system/monitoring/tests/topology_spread_test.yaml @@ -0,0 +1,350 @@ +suite: monitoring replicas spread over nodes +templates: + - templates/vm/vmcluster.yaml + - templates/vlogs/vlogs.yaml + - templates/vtraces/vtraces.yaml + - templates/alerta/alerta.yaml + +release: + name: monitoring-system + namespace: tenant-root + +set: + _cluster: + root-host: example.org + _namespace: + host: tenant-root.example.org + ingress: tenant-root + tracingStorages: + - name: generic + mode: cluster + retentionPeriod: "14d" + storage: 10Gi + +tests: + - it: requires separate nodes for vmstorage and vmselect and prefers them for vminsert + template: templates/vm/vmcluster.yaml + documentSelector: + path: metadata.name + value: shortterm + asserts: + - equal: + path: spec.vmstorage.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: vmstorage + app.kubernetes.io/instance: shortterm + - equal: + path: spec.vmselect.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: vmselect + app.kubernetes.io/instance: shortterm + - equal: + path: spec.vminsert.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vminsert + app.kubernetes.io/instance: shortterm + + - it: keys each VMCluster's constraints to its own name + template: templates/vm/vmcluster.yaml + documentSelector: + path: metadata.name + value: longterm + asserts: + - equal: + path: spec.vmstorage.topologySpreadConstraints[0].labelSelector.matchLabels + value: + app.kubernetes.io/name: vmstorage + app.kubernetes.io/instance: longterm + - equal: + path: spec.vmselect.topologySpreadConstraints[0].labelSelector.matchLabels + value: + app.kubernetes.io/name: vmselect + app.kubernetes.io/instance: longterm + - equal: + path: spec.vminsert.topologySpreadConstraints[0].labelSelector.matchLabels + value: + app.kubernetes.io/name: vminsert + app.kubernetes.io/instance: longterm + + - it: requires separate nodes for vlstorage and prefers them for vlselect and vlinsert + template: templates/vlogs/vlogs.yaml + documentSelector: + path: metadata.name + value: generic + asserts: + - equal: + path: spec.vlstorage.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: vlstorage + app.kubernetes.io/instance: generic + - equal: + path: spec.vlselect.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vlselect + app.kubernetes.io/instance: generic + - equal: + path: spec.vlinsert.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vlinsert + app.kubernetes.io/instance: generic + + - it: requires separate nodes for vtstorage and prefers them for vtselect and vtinsert + template: templates/vtraces/vtraces.yaml + documentSelector: + path: kind + value: VTCluster + asserts: + - equal: + path: spec.storage.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: vtstorage + app.kubernetes.io/instance: generic + - equal: + path: spec.select.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vtselect + app.kubernetes.io/instance: generic + - equal: + path: spec.insert.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vtinsert + app.kubernetes.io/instance: generic + + - it: requires separate nodes for the Alertmanager replicas + template: templates/alerta/alerta.yaml + documentSelector: + path: kind + value: VMAlertmanager + asserts: + - equal: + path: spec.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: vmalertmanager + app.kubernetes.io/instance: alertmanager + + - it: keeps the default when the platform policy is empty + template: templates/vm/vmcluster.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: "" + documentSelector: + path: metadata.name + value: shortterm + asserts: + - equal: + path: spec.vmstorage.topologySpreadConstraints[0].whenUnsatisfiable + value: DoNotSchedule + - equal: + path: spec.vminsert.topologySpreadConstraints[0].whenUnsatisfiable + value: ScheduleAnyway + + - it: renders the platform policy in place of the default for a VMCluster + template: templates/vm/vmcluster.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: metadata.name + value: shortterm + asserts: + - equal: + path: spec.vmstorage.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vmstorage + app.kubernetes.io/instance: shortterm + - equal: + path: spec.vmselect.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vmselect + app.kubernetes.io/instance: shortterm + - equal: + path: spec.vminsert.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vminsert + app.kubernetes.io/instance: shortterm + + - it: renders the platform policy in place of the default for the logs store + template: templates/vlogs/vlogs.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: metadata.name + value: generic + asserts: + - equal: + path: spec.vlstorage.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vlstorage + app.kubernetes.io/instance: generic + + - it: renders the platform policy in place of the default for the traces store + template: templates/vtraces/vtraces.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: kind + value: VTCluster + asserts: + - equal: + path: spec.storage.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vtstorage + app.kubernetes.io/instance: generic + + - it: renders the platform policy in place of the default for the Alertmanager + template: templates/alerta/alerta.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: kind + value: VMAlertmanager + asserts: + - equal: + path: spec.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vmalertmanager + app.kubernetes.io/instance: alertmanager + + - it: gives every constraint of the platform policy the component's selector + template: templates/vm/vmcluster.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: metadata.name + value: shortterm + asserts: + - equal: + path: spec.vmstorage.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + labelSelector: + matchLabels: + app.kubernetes.io/name: vmstorage + app.kubernetes.io/instance: shortterm + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vmstorage + app.kubernetes.io/instance: shortterm From 902051e7806f8205de862c5f1d5986a57bbe8d87 Mon Sep 17 00:00:00 2001 From: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:23:37 +0300 Subject: [PATCH 03/14] fix(redis, valkey, harbor): spread sentinels and data pods over nodes The RedisFailover charts left placement to the operator's default preferred pod anti-affinity. A preference only decides where a pod starts, so a drain or a rollout of the sentinel Deployment can leave two of the three sentinels on one node, and nothing moves them back. Losing that node leaves one sentinel, below the quorum of two, so no failover can happen while it is down. On a node-local StorageClass a data pod that starts next to another one stays there for good. Both now get a hostname spread with whenUnsatisfiable DoNotSchedule and maxSkew 1. An instance with more pods than nodes still starts, because the skew is counted between the nodes that exist. nodeTaintsPolicy is Ignore, so a cordoned node still counts and a pod waits for it instead of starting next to another one. The sentinel constraint also matches on pod-template-hash, because a rollout adds each new sentinel while the old ones still run, and counting those would let two new sentinels share a node once the old ones are gone. A cluster-wide globalAppTopologySpreadConstraints replaces the default, as in the other charts that read it. Assisted-by: LLM Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> --- .../apps/redis/templates/redisfailover.yaml | 37 +++++++ .../redis/tests/topology_spread_test.yaml | 99 +++++++++++++++++++ packages/apps/valkey/Makefile | 4 + .../apps/valkey/templates/valkeyfailover.yaml | 37 +++++++ .../valkey/tests/topology_spread_test.yaml | 80 +++++++++++++++ packages/system/harbor/templates/redis.yaml | 37 +++++++ .../harbor/tests/redis_spread_test.yaml | 81 +++++++++++++++ 7 files changed, 375 insertions(+) create mode 100644 packages/apps/redis/tests/topology_spread_test.yaml create mode 100644 packages/apps/valkey/tests/topology_spread_test.yaml create mode 100644 packages/system/harbor/tests/redis_spread_test.yaml diff --git a/packages/apps/redis/templates/redisfailover.yaml b/packages/apps/redis/templates/redisfailover.yaml index 27c7e9047..f9d679637 100644 --- a/packages/apps/redis/templates/redisfailover.yaml +++ b/packages/apps/redis/templates/redisfailover.yaml @@ -1,6 +1,7 @@ {{- /* One image for the data pods and the Sentinels, resolved once so they cannot drift apart. */}} {{- $redisImage := printf "redis:%s" (include "redis.versionMap" $) }} {{- $tlsEnabled := (include "redis.tls.enabled" .) | eq "true" -}} +{{- $spreadPolicy := dig "scheduling" "globalAppTopologySpreadConstraints" "" (.Values._cluster | default dict) -}} {{- /* A Sentinel holds only its configuration and failover state, so the Redis sizing over-provisions it. An empty sentinel block still falls back to the @@ -66,11 +67,47 @@ spec: # on every start, so a chart rollback to an older engine is safe here. image: {{ $redisImage | quote }} replicas: 3 + {{- if $spreadPolicy }} + {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Release.Name }} + app.kubernetes.io/component: sentinel + {{- else }} + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + matchLabelKeys: + - pod-template-hash + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Release.Name }} + app.kubernetes.io/component: sentinel + {{- end }} resources: {{- include "cozy-lib.resources.defaultingSanitize" (list $sentinelPreset $sentinelResources $) | nindent 6 }} redis: image: {{ $redisImage | quote }} resources: {{- include "cozy-lib.resources.defaultingSanitize" (list .Values.resourcesPreset .Values.resources $) | nindent 6 }} replicas: {{ .Values.replicas }} + {{- if $spreadPolicy }} + {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Release.Name }} + app.kubernetes.io/component: redis + {{- else }} + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Release.Name }} + app.kubernetes.io/component: redis + {{- end }} {{- with .Values.size }} storage: persistentVolumeClaim: diff --git a/packages/apps/redis/tests/topology_spread_test.yaml b/packages/apps/redis/tests/topology_spread_test.yaml new file mode 100644 index 000000000..73d9128f2 --- /dev/null +++ b/packages/apps/redis/tests/topology_spread_test.yaml @@ -0,0 +1,99 @@ +suite: Sentinels and Redis pods spread over nodes + +release: + name: my-redis + namespace: tenant-test + +set: + _cluster: + cluster-domain: cluster.local + _namespace: + host: example.com + +templates: + - templates/redisfailover.yaml + +tests: + - it: requires one sentinel and one Redis pod per node by default + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + matchLabelKeys: + - pod-template-hash + labelSelector: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: sentinel + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: redis + - notExists: + path: spec.sentinel.affinity + - notExists: + path: spec.redis.affinity + + - it: keeps the default when the cluster-wide policy is empty + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: "" + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints[0].whenUnsatisfiable + value: DoNotSchedule + - equal: + path: spec.redis.topologySpreadConstraints[0].whenUnsatisfiable + value: DoNotSchedule + + - it: renders a cluster-wide spread policy as written + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: sentinel + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: redis diff --git a/packages/apps/valkey/Makefile b/packages/apps/valkey/Makefile index 9e0ae15eb..86da36699 100644 --- a/packages/apps/valkey/Makefile +++ b/packages/apps/valkey/Makefile @@ -1,5 +1,9 @@ include ../../../hack/package.mk +.PHONY: test +test: + helm unittest . + generate: cozyvalues-gen -m 'valkey' -v values.yaml -s values.schema.json -r README.md -g ../../../api/apps/v1alpha1/valkey/types.go ../../../hack/update-crd.sh diff --git a/packages/apps/valkey/templates/valkeyfailover.yaml b/packages/apps/valkey/templates/valkeyfailover.yaml index a30382120..636304b23 100644 --- a/packages/apps/valkey/templates/valkeyfailover.yaml +++ b/packages/apps/valkey/templates/valkeyfailover.yaml @@ -1,3 +1,4 @@ +{{- $spreadPolicy := dig "scheduling" "globalAppTopologySpreadConstraints" "" (.Values._cluster | default dict) }} {{- if .Values.authEnabled }} {{- $existingPassword := lookup "v1" "Secret" .Release.Namespace (printf "%s-auth" .Release.Name) }} {{- $password := randAlphaNum 32 | b64enc }} @@ -31,11 +32,47 @@ spec: engine: Valkey sentinel: replicas: 3 + {{- if $spreadPolicy }} + {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Release.Name }} + app.kubernetes.io/component: sentinel + {{- else }} + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + matchLabelKeys: + - pod-template-hash + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Release.Name }} + app.kubernetes.io/component: sentinel + {{- end }} resources: {{- include "cozy-lib.resources.defaultingSanitize" (list .Values.resourcesPreset .Values.resources $) | nindent 6 }} redis: image: "valkey/valkey:{{ include "valkey.versionMap" $ }}" resources: {{- include "cozy-lib.resources.defaultingSanitize" (list .Values.resourcesPreset .Values.resources $) | nindent 6 }} replicas: {{ .Values.replicas }} + {{- if $spreadPolicy }} + {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Release.Name }} + app.kubernetes.io/component: redis + {{- else }} + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Release.Name }} + app.kubernetes.io/component: redis + {{- end }} {{- with .Values.size }} storage: persistentVolumeClaim: diff --git a/packages/apps/valkey/tests/topology_spread_test.yaml b/packages/apps/valkey/tests/topology_spread_test.yaml new file mode 100644 index 000000000..3b249f287 --- /dev/null +++ b/packages/apps/valkey/tests/topology_spread_test.yaml @@ -0,0 +1,80 @@ +suite: Sentinels and Valkey pods spread over nodes + +release: + name: my-valkey + namespace: tenant-test + +set: + _cluster: {} + +templates: + - templates/valkeyfailover.yaml + +tests: + - it: requires one sentinel and one Valkey pod per node by default + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + matchLabelKeys: + - pod-template-hash + labelSelector: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: sentinel + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: redis + - notExists: + path: spec.sentinel.affinity + - notExists: + path: spec.redis.affinity + + - it: renders a cluster-wide spread policy as written + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: sentinel + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: redis diff --git a/packages/system/harbor/templates/redis.yaml b/packages/system/harbor/templates/redis.yaml index b781e42f2..9114ae6f9 100644 --- a/packages/system/harbor/templates/redis.yaml +++ b/packages/system/harbor/templates/redis.yaml @@ -1,3 +1,4 @@ +{{- $spreadPolicy := dig "scheduling" "globalAppTopologySpreadConstraints" "" (.Values._cluster | default dict) }} --- apiVersion: v1 kind: Secret @@ -27,6 +28,25 @@ spec: # bump it as a deliberate, separate change. image: redis:6.2.6-alpine replicas: 3 + {{- if $spreadPolicy }} + {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Values.harbor.fullnameOverride }}-redis + app.kubernetes.io/component: sentinel + {{- else }} + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + matchLabelKeys: + - pod-template-hash + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Values.harbor.fullnameOverride }}-redis + app.kubernetes.io/component: sentinel + {{- end }} resources: limits: cpu: 250m @@ -39,6 +59,23 @@ spec: # Harbor's dump.rdb into a 7.x format a platform rollback can no longer load. image: redis:6.2.6-alpine replicas: {{ .Values.redis.replicas }} + {{- if $spreadPolicy }} + {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Values.harbor.fullnameOverride }}-redis + app.kubernetes.io/component: redis + {{- else }} + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: {{ .Values.harbor.fullnameOverride }}-redis + app.kubernetes.io/component: redis + {{- end }} resources: limits: cpu: "1" diff --git a/packages/system/harbor/tests/redis_spread_test.yaml b/packages/system/harbor/tests/redis_spread_test.yaml new file mode 100644 index 000000000..64015931a --- /dev/null +++ b/packages/system/harbor/tests/redis_spread_test.yaml @@ -0,0 +1,81 @@ +suite: Harbor sentinels and Redis pods spread over nodes + +release: + name: harbor + namespace: tenant-root + +set: + harbor: + fullnameOverride: harbor-test + +templates: + - templates/redis.yaml + +tests: + - it: requires one sentinel and one Redis pod per node by default + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + matchLabelKeys: + - pod-template-hash + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: sentinel + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: redis + - notExists: + path: spec.sentinel.affinity + - notExists: + path: spec.redis.affinity + + - it: renders a cluster-wide spread policy as written + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: sentinel + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: redis From 0dbbb3b157c2e5f3037dccb53b87deba250bc943 Mon Sep 17 00:00:00 2001 From: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:38:25 +0300 Subject: [PATCH 04/14] fix(monitoring): fail the render on a malformed platform spread policy A globalAppTopologySpreadConstraints value that did not parse, or that held no topologySpreadConstraints list, gave every tier the chart default without any sign, so the platform's policy was silently not applied. The render now fails and names the parse error, as the chart already does for an empty logsStorages. The tests also pin that a selector the policy sets itself is kept as written. Assisted-by: LLM Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> --- .../monitoring/templates/_scheduling.tpl | 6 +- .../topology_spread_invalid_policy_test.yaml | 59 +++++++++++++++++++ .../tests/topology_spread_test.yaml | 27 +++++++++ 3 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 packages/system/monitoring/tests/topology_spread_invalid_policy_test.yaml diff --git a/packages/system/monitoring/templates/_scheduling.tpl b/packages/system/monitoring/templates/_scheduling.tpl index 6540d4d84..25ff369ad 100644 --- a/packages/system/monitoring/templates/_scheduling.tpl +++ b/packages/system/monitoring/templates/_scheduling.tpl @@ -4,7 +4,11 @@ {{- $global := list -}} {{- with ($root.Values._cluster | default dict).scheduling -}} {{- with get . "globalAppTopologySpreadConstraints" -}} -{{- $global = dig "topologySpreadConstraints" (list) (fromYaml .) -}} +{{- $parsed := fromYaml . -}} +{{- $global = dig "topologySpreadConstraints" (list) $parsed -}} +{{- if or (not (kindIs "slice" $global)) (not $global) -}} +{{- fail (trim (printf "monitoring: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list. %s" (get $parsed "Error"))) -}} +{{- end -}} {{- end -}} {{- end -}} {{- $constraints := list -}} diff --git a/packages/system/monitoring/tests/topology_spread_invalid_policy_test.yaml b/packages/system/monitoring/tests/topology_spread_invalid_policy_test.yaml new file mode 100644 index 000000000..6558f6764 --- /dev/null +++ b/packages/system/monitoring/tests/topology_spread_invalid_policy_test.yaml @@ -0,0 +1,59 @@ +suite: monitoring refuses a malformed platform spread policy +templates: + - templates/vm/vmcluster.yaml + +release: + name: monitoring-system + namespace: tenant-root + +tests: + - it: fails on a platform policy that does not parse + template: templates/vm/vmcluster.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + asserts: + - failedTemplate: + errorPattern: "globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list\\. error converting YAML to JSON" + + - it: fails on a platform policy without a topologySpreadConstraints list + template: templates/vm/vmcluster.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + asserts: + - failedTemplate: + errorPattern: "globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list" + + - it: fails on a platform policy with an empty topologySpreadConstraints list + template: templates/vm/vmcluster.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: [] + asserts: + - failedTemplate: + errorMessage: "monitoring: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list." + + - it: fails on a platform policy whose topologySpreadConstraints is not a list + template: templates/vm/vmcluster.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + asserts: + - failedTemplate: + errorMessage: "monitoring: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list." diff --git a/packages/system/monitoring/tests/topology_spread_test.yaml b/packages/system/monitoring/tests/topology_spread_test.yaml index dc8273fad..4ede253ea 100644 --- a/packages/system/monitoring/tests/topology_spread_test.yaml +++ b/packages/system/monitoring/tests/topology_spread_test.yaml @@ -348,3 +348,30 @@ tests: matchLabels: app.kubernetes.io/name: vmstorage app.kubernetes.io/instance: shortterm + + - it: keeps a selector the platform policy sets itself + template: templates/vm/vmcluster.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + documentSelector: + path: metadata.name + value: shortterm + asserts: + - equal: + path: spec.vmstorage.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all From 2119b7ac80fb19afd1d9b7b3942bd377c654ad97 Mon Sep 17 00:00:00 2001 From: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:44:09 +0300 Subject: [PATCH 05/14] fix(redis, valkey, harbor): add the selector to every platform spread constraint A globalAppTopologySpreadConstraints policy can hold several constraints, one per zone and one per node for example. The selector was added under the last one only, and kube-scheduler counts no pods for a constraint without a selector, so the earlier constraints did not spread these pods at all. A last constraint with a selector of its own got a second labelSelector key, which a strict YAML parser rejects and Helm resolves to the chart's selector, dropping the policy's. Each constraint without a selector now gets the one of its component, and a constraint with its own keeps it, the rule the keycloak chart already applies to its database constraints. The policy is parsed up front, so one that does not parse or holds no non-empty topologySpreadConstraints list fails the render with a message. Before, such a policy failed only because the appended selector broke the YAML, and a map in place of the list rendered without an error. Assisted-by: LLM Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> --- .../apps/redis/templates/redisfailover.yaml | 31 ++-- .../redis/tests/topology_spread_test.yaml | 150 ++++++++++++++++++ .../apps/valkey/templates/valkeyfailover.yaml | 31 ++-- .../valkey/tests/topology_spread_test.yaml | 113 +++++++++++++ packages/system/harbor/templates/redis.yaml | 31 ++-- .../harbor/tests/redis_spread_test.yaml | 113 +++++++++++++ 6 files changed, 430 insertions(+), 39 deletions(-) diff --git a/packages/apps/redis/templates/redisfailover.yaml b/packages/apps/redis/templates/redisfailover.yaml index f9d679637..ac7c17a9b 100644 --- a/packages/apps/redis/templates/redisfailover.yaml +++ b/packages/apps/redis/templates/redisfailover.yaml @@ -1,7 +1,14 @@ {{- /* One image for the data pods and the Sentinels, resolved once so they cannot drift apart. */}} {{- $redisImage := printf "redis:%s" (include "redis.versionMap" $) }} {{- $tlsEnabled := (include "redis.tls.enabled" .) | eq "true" -}} -{{- $spreadPolicy := dig "scheduling" "globalAppTopologySpreadConstraints" "" (.Values._cluster | default dict) -}} +{{- $spreadConstraints := list -}} +{{- with dig "scheduling" "globalAppTopologySpreadConstraints" "" (.Values._cluster | default dict) -}} +{{- $policy := fromYaml . -}} +{{- $spreadConstraints = dig "topologySpreadConstraints" (list) $policy -}} +{{- if or (not (kindIs "slice" $spreadConstraints)) (not $spreadConstraints) -}} +{{- fail (trim (printf "redis: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list. %s" (get $policy "Error"))) -}} +{{- end -}} +{{- end -}} {{- /* A Sentinel holds only its configuration and failover state, so the Redis sizing over-provisions it. An empty sentinel block still falls back to the @@ -67,12 +74,11 @@ spec: # on every start, so a chart rollback to an older engine is safe here. image: {{ $redisImage | quote }} replicas: 3 - {{- if $spreadPolicy }} - {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} - labelSelector: - matchLabels: - app.kubernetes.io/name: {{ .Release.Name }} - app.kubernetes.io/component: sentinel + {{- if $spreadConstraints }} + topologySpreadConstraints: + {{- range $spreadConstraints }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "sentinel")))) (hasKey . "labelSelector")) | nindent 6 }} + {{- end }} {{- else }} topologySpreadConstraints: - maxSkew: 1 @@ -91,12 +97,11 @@ spec: image: {{ $redisImage | quote }} resources: {{- include "cozy-lib.resources.defaultingSanitize" (list .Values.resourcesPreset .Values.resources $) | nindent 6 }} replicas: {{ .Values.replicas }} - {{- if $spreadPolicy }} - {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} - labelSelector: - matchLabels: - app.kubernetes.io/name: {{ .Release.Name }} - app.kubernetes.io/component: redis + {{- if $spreadConstraints }} + topologySpreadConstraints: + {{- range $spreadConstraints }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "redis")))) (hasKey . "labelSelector")) | nindent 6 }} + {{- end }} {{- else }} topologySpreadConstraints: - maxSkew: 1 diff --git a/packages/apps/redis/tests/topology_spread_test.yaml b/packages/apps/redis/tests/topology_spread_test.yaml index 73d9128f2..c13a99e0d 100644 --- a/packages/apps/redis/tests/topology_spread_test.yaml +++ b/packages/apps/redis/tests/topology_spread_test.yaml @@ -97,3 +97,153 @@ tests: matchLabels: app.kubernetes.io/name: my-redis app.kubernetes.io/component: redis + + - it: gives every constraint of a cluster-wide policy the selector + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + labelSelector: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: sentinel + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: sentinel + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + labelSelector: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: redis + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: redis + + - it: keeps a selector the cluster-wide policy sets itself + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: sentinel + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: redis + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + + - it: fails on a cluster-wide policy that does not parse + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + asserts: + - failedTemplate: + errorPattern: "globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list\\. error converting YAML to JSON" + + - it: fails on a cluster-wide policy without a topologySpreadConstraints key + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + asserts: + - failedTemplate: + errorPattern: "globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list" + + - it: fails on a cluster-wide policy with an empty topologySpreadConstraints list + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: [] + asserts: + - failedTemplate: + errorMessage: "redis: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list." + + - it: fails on a cluster-wide policy whose topologySpreadConstraints is not a list + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + asserts: + - failedTemplate: + errorMessage: "redis: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list." diff --git a/packages/apps/valkey/templates/valkeyfailover.yaml b/packages/apps/valkey/templates/valkeyfailover.yaml index 636304b23..e2fbb4f19 100644 --- a/packages/apps/valkey/templates/valkeyfailover.yaml +++ b/packages/apps/valkey/templates/valkeyfailover.yaml @@ -1,4 +1,11 @@ -{{- $spreadPolicy := dig "scheduling" "globalAppTopologySpreadConstraints" "" (.Values._cluster | default dict) }} +{{- $spreadConstraints := list }} +{{- with dig "scheduling" "globalAppTopologySpreadConstraints" "" (.Values._cluster | default dict) }} +{{- $policy := fromYaml . }} +{{- $spreadConstraints = dig "topologySpreadConstraints" (list) $policy }} +{{- if or (not (kindIs "slice" $spreadConstraints)) (not $spreadConstraints) }} +{{- fail (trim (printf "valkey: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list. %s" (get $policy "Error"))) }} +{{- end }} +{{- end }} {{- if .Values.authEnabled }} {{- $existingPassword := lookup "v1" "Secret" .Release.Namespace (printf "%s-auth" .Release.Name) }} {{- $password := randAlphaNum 32 | b64enc }} @@ -32,12 +39,11 @@ spec: engine: Valkey sentinel: replicas: 3 - {{- if $spreadPolicy }} - {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} - labelSelector: - matchLabels: - app.kubernetes.io/name: {{ .Release.Name }} - app.kubernetes.io/component: sentinel + {{- if $spreadConstraints }} + topologySpreadConstraints: + {{- range $spreadConstraints }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "sentinel")))) (hasKey . "labelSelector")) | nindent 6 }} + {{- end }} {{- else }} topologySpreadConstraints: - maxSkew: 1 @@ -56,12 +62,11 @@ spec: image: "valkey/valkey:{{ include "valkey.versionMap" $ }}" resources: {{- include "cozy-lib.resources.defaultingSanitize" (list .Values.resourcesPreset .Values.resources $) | nindent 6 }} replicas: {{ .Values.replicas }} - {{- if $spreadPolicy }} - {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} - labelSelector: - matchLabels: - app.kubernetes.io/name: {{ .Release.Name }} - app.kubernetes.io/component: redis + {{- if $spreadConstraints }} + topologySpreadConstraints: + {{- range $spreadConstraints }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "redis")))) (hasKey . "labelSelector")) | nindent 6 }} + {{- end }} {{- else }} topologySpreadConstraints: - maxSkew: 1 diff --git a/packages/apps/valkey/tests/topology_spread_test.yaml b/packages/apps/valkey/tests/topology_spread_test.yaml index 3b249f287..ed64e60cf 100644 --- a/packages/apps/valkey/tests/topology_spread_test.yaml +++ b/packages/apps/valkey/tests/topology_spread_test.yaml @@ -78,3 +78,116 @@ tests: matchLabels: app.kubernetes.io/name: my-valkey app.kubernetes.io/component: redis + + - it: gives every constraint of a cluster-wide policy the selector + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + labelSelector: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: sentinel + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: sentinel + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + labelSelector: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: redis + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: redis + + - it: keeps a selector the cluster-wide policy sets itself + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: sentinel + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: redis + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + + - it: fails on a cluster-wide policy with an empty topologySpreadConstraints list + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: [] + asserts: + - failedTemplate: + errorMessage: "valkey: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list." diff --git a/packages/system/harbor/templates/redis.yaml b/packages/system/harbor/templates/redis.yaml index 9114ae6f9..1e4e383fd 100644 --- a/packages/system/harbor/templates/redis.yaml +++ b/packages/system/harbor/templates/redis.yaml @@ -1,4 +1,11 @@ -{{- $spreadPolicy := dig "scheduling" "globalAppTopologySpreadConstraints" "" (.Values._cluster | default dict) }} +{{- $spreadConstraints := list }} +{{- with dig "scheduling" "globalAppTopologySpreadConstraints" "" (.Values._cluster | default dict) }} +{{- $policy := fromYaml . }} +{{- $spreadConstraints = dig "topologySpreadConstraints" (list) $policy }} +{{- if or (not (kindIs "slice" $spreadConstraints)) (not $spreadConstraints) }} +{{- fail (trim (printf "harbor: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list. %s" (get $policy "Error"))) }} +{{- end }} +{{- end }} --- apiVersion: v1 kind: Secret @@ -28,12 +35,11 @@ spec: # bump it as a deliberate, separate change. image: redis:6.2.6-alpine replicas: 3 - {{- if $spreadPolicy }} - {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} - labelSelector: - matchLabels: - app.kubernetes.io/name: {{ .Values.harbor.fullnameOverride }}-redis - app.kubernetes.io/component: sentinel + {{- if $spreadConstraints }} + topologySpreadConstraints: + {{- range $spreadConstraints }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" (printf "%s-redis" $.Values.harbor.fullnameOverride) "app.kubernetes.io/component" "sentinel")))) (hasKey . "labelSelector")) | nindent 6 }} + {{- end }} {{- else }} topologySpreadConstraints: - maxSkew: 1 @@ -59,12 +65,11 @@ spec: # Harbor's dump.rdb into a 7.x format a platform rollback can no longer load. image: redis:6.2.6-alpine replicas: {{ .Values.redis.replicas }} - {{- if $spreadPolicy }} - {{- $spreadPolicy | fromYaml | toYaml | nindent 4 }} - labelSelector: - matchLabels: - app.kubernetes.io/name: {{ .Values.harbor.fullnameOverride }}-redis - app.kubernetes.io/component: redis + {{- if $spreadConstraints }} + topologySpreadConstraints: + {{- range $spreadConstraints }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" (printf "%s-redis" $.Values.harbor.fullnameOverride) "app.kubernetes.io/component" "redis")))) (hasKey . "labelSelector")) | nindent 6 }} + {{- end }} {{- else }} topologySpreadConstraints: - maxSkew: 1 diff --git a/packages/system/harbor/tests/redis_spread_test.yaml b/packages/system/harbor/tests/redis_spread_test.yaml index 64015931a..407e0ee3e 100644 --- a/packages/system/harbor/tests/redis_spread_test.yaml +++ b/packages/system/harbor/tests/redis_spread_test.yaml @@ -79,3 +79,116 @@ tests: matchLabels: app.kubernetes.io/name: harbor-test-redis app.kubernetes.io/component: redis + + - it: gives every constraint of a cluster-wide policy the selector + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: sentinel + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: sentinel + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: redis + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: redis + + - it: keeps a selector the cluster-wide policy sets itself + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: sentinel + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + - equal: + path: spec.redis.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: redis + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + + - it: fails on a cluster-wide policy with an empty topologySpreadConstraints list + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: [] + asserts: + - failedTemplate: + errorMessage: "harbor: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list." From 33783b4c5c84e1ed48df024227192ac330e57605 Mon Sep 17 00:00:00 2001 From: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:15:01 +0300 Subject: [PATCH 06/14] fix(monitoring): stop a policy selector leaking into other constraints The helper gave a platform constraint the tier's selector through a merge inside ternary, and ternary evaluates both branches, so the merge also ran for a constraint that brings a selector of its own. merge writes into its first argument and recurses into the maps both sides hold. The first argument held the shared $selector map, so the labels or matchExpressions of that own selector were written into $selector itself. Every constraint without a selector holds that same map and the list is rendered once at the end, so all of them came out with the foreign terms added, before or after the constraint that brought them. Such a constraint selected only those of the tier's pods that also match the other selector, and on pods without those labels it spread nothing. Only a policy that mixes constraints with and without a selector is affected. The default and other policies render as before. The merge now goes into a deep copy of the constraint, the order the keycloak chart uses for its database constraints, so $selector is never written. Two new cases pin a constraint without a selector after and before one with its own, the first with matchLabels and the second with matchExpressions. Assisted-by: LLM Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> --- .../monitoring/templates/_scheduling.tpl | 2 +- .../tests/topology_spread_test.yaml | 76 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/packages/system/monitoring/templates/_scheduling.tpl b/packages/system/monitoring/templates/_scheduling.tpl index 25ff369ad..e7358c5c6 100644 --- a/packages/system/monitoring/templates/_scheduling.tpl +++ b/packages/system/monitoring/templates/_scheduling.tpl @@ -13,7 +13,7 @@ {{- end -}} {{- $constraints := list -}} {{- range $global -}} -{{- $constraints = append $constraints (ternary . (merge (dict "labelSelector" $selector) .) (hasKey . "labelSelector")) -}} +{{- $constraints = append $constraints (ternary . (merge (deepCopy .) (dict "labelSelector" $selector)) (hasKey . "labelSelector")) -}} {{- end -}} {{- if not $constraints -}} {{- $default := dict "maxSkew" 1 "topologyKey" "kubernetes.io/hostname" "whenUnsatisfiable" (index . 3) "labelSelector" $selector -}} diff --git a/packages/system/monitoring/tests/topology_spread_test.yaml b/packages/system/monitoring/tests/topology_spread_test.yaml index 4ede253ea..14a20da21 100644 --- a/packages/system/monitoring/tests/topology_spread_test.yaml +++ b/packages/system/monitoring/tests/topology_spread_test.yaml @@ -375,3 +375,79 @@ tests: labelSelector: matchLabels: example.org/spread: all + + - it: gives the component's selector to a constraint after one that sets its own + template: templates/vm/vmcluster.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + documentSelector: + path: metadata.name + value: shortterm + asserts: + - equal: + path: spec.vmstorage.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.org/spread: all + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + labelSelector: + matchLabels: + app.kubernetes.io/name: vmstorage + app.kubernetes.io/instance: shortterm + + - it: gives the component's selector to a constraint before one that sets its own + template: templates/vm/vmcluster.yaml + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchExpressions: + - key: example.org/spread + operator: Exists + documentSelector: + path: metadata.name + value: shortterm + asserts: + - equal: + path: spec.vmstorage.topologySpreadConstraints + value: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + labelSelector: + matchLabels: + app.kubernetes.io/name: vmstorage + app.kubernetes.io/instance: shortterm + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchExpressions: + - key: example.org/spread + operator: Exists From a2576bcf782908db92d3d09486e0d41acea735fb Mon Sep 17 00:00:00 2001 From: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:20:28 +0100 Subject: [PATCH 07/14] fix(redis, valkey, harbor): default null topology spread selectors A null selector matches no pods, so the configured policy cannot spread siblings. Treat it as unset while preserving explicit selectors. Assisted-by: LLM Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> --- .../apps/redis/templates/redisfailover.yaml | 4 +- .../redis/tests/topology_spread_test.yaml | 37 +++++++++++++++++++ .../apps/valkey/templates/valkeyfailover.yaml | 4 +- .../valkey/tests/topology_spread_test.yaml | 37 +++++++++++++++++++ packages/system/harbor/templates/redis.yaml | 4 +- .../harbor/tests/redis_spread_test.yaml | 37 +++++++++++++++++++ 6 files changed, 117 insertions(+), 6 deletions(-) diff --git a/packages/apps/redis/templates/redisfailover.yaml b/packages/apps/redis/templates/redisfailover.yaml index 68d39bce9..ec63f9e4b 100644 --- a/packages/apps/redis/templates/redisfailover.yaml +++ b/packages/apps/redis/templates/redisfailover.yaml @@ -90,7 +90,7 @@ spec: {{- if $spreadConstraints }} topologySpreadConstraints: {{- range $spreadConstraints }} - - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "sentinel")))) (hasKey . "labelSelector")) | nindent 6 }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "sentinel")))) (not (kindIs "invalid" .labelSelector))) | nindent 6 }} {{- end }} {{- else }} topologySpreadConstraints: @@ -113,7 +113,7 @@ spec: {{- if $spreadConstraints }} topologySpreadConstraints: {{- range $spreadConstraints }} - - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "redis")))) (hasKey . "labelSelector")) | nindent 6 }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "redis")))) (not (kindIs "invalid" .labelSelector))) | nindent 6 }} {{- end }} {{- else }} topologySpreadConstraints: diff --git a/packages/apps/redis/tests/topology_spread_test.yaml b/packages/apps/redis/tests/topology_spread_test.yaml index c13a99e0d..db6d7b0d2 100644 --- a/packages/apps/redis/tests/topology_spread_test.yaml +++ b/packages/apps/redis/tests/topology_spread_test.yaml @@ -247,3 +247,40 @@ tests: asserts: - failedTemplate: errorMessage: "redis: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list." + + - it: fills null selectors and preserves explicit empty selectors + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + labelSelector: null + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: {} + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints[0].labelSelector + value: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: sentinel + - equal: + path: spec.sentinel.topologySpreadConstraints[1].labelSelector + value: {} + - equal: + path: spec.redis.topologySpreadConstraints[0].labelSelector + value: + matchLabels: + app.kubernetes.io/name: my-redis + app.kubernetes.io/component: redis + - equal: + path: spec.redis.topologySpreadConstraints[1].labelSelector + value: {} diff --git a/packages/apps/valkey/templates/valkeyfailover.yaml b/packages/apps/valkey/templates/valkeyfailover.yaml index e2fbb4f19..e6046162a 100644 --- a/packages/apps/valkey/templates/valkeyfailover.yaml +++ b/packages/apps/valkey/templates/valkeyfailover.yaml @@ -42,7 +42,7 @@ spec: {{- if $spreadConstraints }} topologySpreadConstraints: {{- range $spreadConstraints }} - - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "sentinel")))) (hasKey . "labelSelector")) | nindent 6 }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "sentinel")))) (not (kindIs "invalid" .labelSelector))) | nindent 6 }} {{- end }} {{- else }} topologySpreadConstraints: @@ -65,7 +65,7 @@ spec: {{- if $spreadConstraints }} topologySpreadConstraints: {{- range $spreadConstraints }} - - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "redis")))) (hasKey . "labelSelector")) | nindent 6 }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" $.Release.Name "app.kubernetes.io/component" "redis")))) (not (kindIs "invalid" .labelSelector))) | nindent 6 }} {{- end }} {{- else }} topologySpreadConstraints: diff --git a/packages/apps/valkey/tests/topology_spread_test.yaml b/packages/apps/valkey/tests/topology_spread_test.yaml index ed64e60cf..7ce3f90c0 100644 --- a/packages/apps/valkey/tests/topology_spread_test.yaml +++ b/packages/apps/valkey/tests/topology_spread_test.yaml @@ -191,3 +191,40 @@ tests: asserts: - failedTemplate: errorMessage: "valkey: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list." + + - it: fills null selectors and preserves explicit empty selectors + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + labelSelector: null + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: {} + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints[0].labelSelector + value: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: sentinel + - equal: + path: spec.sentinel.topologySpreadConstraints[1].labelSelector + value: {} + - equal: + path: spec.redis.topologySpreadConstraints[0].labelSelector + value: + matchLabels: + app.kubernetes.io/name: my-valkey + app.kubernetes.io/component: redis + - equal: + path: spec.redis.topologySpreadConstraints[1].labelSelector + value: {} diff --git a/packages/system/harbor/templates/redis.yaml b/packages/system/harbor/templates/redis.yaml index 1e4e383fd..9e7d4062e 100644 --- a/packages/system/harbor/templates/redis.yaml +++ b/packages/system/harbor/templates/redis.yaml @@ -38,7 +38,7 @@ spec: {{- if $spreadConstraints }} topologySpreadConstraints: {{- range $spreadConstraints }} - - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" (printf "%s-redis" $.Values.harbor.fullnameOverride) "app.kubernetes.io/component" "sentinel")))) (hasKey . "labelSelector")) | nindent 6 }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" (printf "%s-redis" $.Values.harbor.fullnameOverride) "app.kubernetes.io/component" "sentinel")))) (not (kindIs "invalid" .labelSelector))) | nindent 6 }} {{- end }} {{- else }} topologySpreadConstraints: @@ -68,7 +68,7 @@ spec: {{- if $spreadConstraints }} topologySpreadConstraints: {{- range $spreadConstraints }} - - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" (printf "%s-redis" $.Values.harbor.fullnameOverride) "app.kubernetes.io/component" "redis")))) (hasKey . "labelSelector")) | nindent 6 }} + - {{- toYaml (ternary . (merge (deepCopy .) (dict "labelSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" (printf "%s-redis" $.Values.harbor.fullnameOverride) "app.kubernetes.io/component" "redis")))) (not (kindIs "invalid" .labelSelector))) | nindent 6 }} {{- end }} {{- else }} topologySpreadConstraints: diff --git a/packages/system/harbor/tests/redis_spread_test.yaml b/packages/system/harbor/tests/redis_spread_test.yaml index 407e0ee3e..c72c012f2 100644 --- a/packages/system/harbor/tests/redis_spread_test.yaml +++ b/packages/system/harbor/tests/redis_spread_test.yaml @@ -192,3 +192,40 @@ tests: asserts: - failedTemplate: errorMessage: "harbor: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list." + + - it: fills null selectors and preserves explicit empty selectors + set: + _cluster: + scheduling: + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + labelSelector: null + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: {} + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.sentinel.topologySpreadConstraints[0].labelSelector + value: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: sentinel + - equal: + path: spec.sentinel.topologySpreadConstraints[1].labelSelector + value: {} + - equal: + path: spec.redis.topologySpreadConstraints[0].labelSelector + value: + matchLabels: + app.kubernetes.io/name: harbor-test-redis + app.kubernetes.io/component: redis + - equal: + path: spec.redis.topologySpreadConstraints[1].labelSelector + value: {} From f13362b0eeff501041eb466edc647d2df0294b18 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Fri, 13 Nov 2026 19:07:44 +0300 Subject: [PATCH 08/14] fix(api): make monitor watch versions usable as delete preconditions A watch event triggered by a WorkloadMonitor carries the monitor's resourceVersion, so a monitor-only status change reaches informer handlers: client-go treats an update with an unchanged resourceVersion as a resync and hides it from them. That version never equals the HelmRelease's, though, so a delete with it as a precondition always failed, and its spec came from the informer cache, which can lag behind the monitor revision. The event now builds the Application from a release no older than the monitor revision and carries the newer of the two versions. HelmReleases and WorkloadMonitors are stored in the same etcd, so their versions are revisions of one sequence, and a value this API hands out that is newer than the live release names the current spec. A resourceVersion precondition on delete is therefore checked against the live release and only an older one is a conflict; the delete itself then carries the live version. The two backing watches are not ordered, so a monitor event can be processed after a release event that is newer than the monitor, and a resumed watch can replay a monitor before the release the client already holds. When the event would carry the version the client may hold, which without anything sent for the object yet means any release version, it falls back to the monitor's own version and the object's version steps back. A delete with that version from the client's cache gets a conflict until the object's next release event or monitor change; no write is lost. The release is read live when the cache does not have it or has one older than the monitor revision; otherwise the cached release already pairs its spec with its own version. A watch start replays every existing monitor as ADDED, so a watch that starts or reconnects reads live once for each monitor written after its release last changed, and each later monitor status change costs at most one read per open watch. Fixes: 1bae0775be19 ("feat(application): add WorkloadsReady condition and Events tab") Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- pkg/registry/apps/application/rest.go | 118 ++++- .../apps/application/rest_watch_rv_test.go | 441 ++++++++++++++++++ .../application/rest_write_options_test.go | 6 +- 3 files changed, 552 insertions(+), 13 deletions(-) create mode 100644 pkg/registry/apps/application/rest_watch_rv_test.go diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index aa0e24a62..817eff526 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -19,6 +19,7 @@ package application import ( "context" "encoding/json" + "errors" "fmt" "maps" "net/http" @@ -673,9 +674,20 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va // Construct HelmRelease name with the configured prefix helmReleaseName := r.releaseConfig.Prefix + name + // A resourceVersion precondition is judged against the live release, so + // read it uncached. + var callerRV *string + if options != nil && options.Preconditions != nil { + callerRV = options.Preconditions.ResourceVersion + } + reader := client.Reader(r.c) + if callerRV != nil { + reader = r.w + } + // Retrieve the HelmRelease before attempting to delete helmRelease := &helmv2.HelmRelease{} - err = r.c.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: &metav1.GetOptions{}}) + err = reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: &metav1.GetOptions{}}) if err != nil { if apierrors.IsNotFound(err) { // If HelmRelease does not exist, return NotFound error for Application @@ -694,6 +706,15 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va return nil, false, apierrors.NewNotFound(r.gvr.GroupResource(), name) } + if callerRV != nil { + if err := r.checkResourceVersion(name, *callerRV, helmRelease.ResourceVersion); err != nil { + return nil, false, err + } + options = options.DeepCopy() + liveRV := helmRelease.ResourceVersion + options.Preconditions.ResourceVersion = &liveRV + } + // Run the genericapiserver-supplied admission chain (validating webhooks // and ValidatingAdmissionPolicies) on the resolved Application before // removing the underlying HelmRelease. Custom REST handlers must invoke @@ -723,6 +744,39 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va return nil, true, nil } +// checkResourceVersion applies a caller's resourceVersion precondition to the +// live HelmRelease. Every resourceVersion is a revision of the same etcd. An +// Application carries the version of the release its spec came from or, on a +// WorkloadMonitor-triggered watch event, a monitor revision, which is newer +// than that release only when the release was read at or after it. A value +// newer than the live release therefore names the current spec, and only an +// older one is a conflict. +func (r *REST) checkResourceVersion(name, callerRV, liveRV string) error { + caller, err := strconv.ParseUint(callerRV, 10, 64) + if err != nil { + return apierrors.NewBadRequest(fmt.Sprintf("invalid resourceVersion %q: %v", callerRV, err)) + } + live, err := strconv.ParseUint(liveRV, 10, 64) + if err != nil { + return fmt.Errorf("HelmRelease for %s has an invalid resourceVersion %q: %w", name, liveRV, err) + } + if caller < live { + return apierrors.NewConflict(r.gvr.GroupResource(), name, errors.New("the object has been modified; please apply your changes to the latest version and try again")) + } + return nil +} + +// newerResourceVersion returns whichever of two numeric resourceVersions is +// higher, preferring b when either does not parse. +func newerResourceVersion(a, b string) string { + av, aErr := strconv.ParseUint(a, 10, 64) + bv, bErr := strconv.ParseUint(b, 10, 64) + if aErr != nil || bErr != nil || bv >= av { + return b + } + return a +} + // Watch sets up a watch on HelmReleases, filters them based on application labels, and converts events to Applications func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) { namespace, err := r.getNamespace(ctx) @@ -871,7 +925,12 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio // workload whose status flips during the snapshot window (after the // Application ADDED but before the bookmark) and then stops changing // would leave the client with a stale WorkloadsReady forever. - var pendingWMEvents []watch.Event + type monitorEvent struct { + event watch.Event + monitorRV string + releaseRV string + } + var pendingWMEvents []monitorEvent // Get the starting resourceVersion from options // If client provides resourceVersion (e.g., from a previous List), we should skip @@ -895,9 +954,38 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio } } + // lastSent holds, per Application, the resourceVersion of the last + // event this watch sent. + lastSent := map[client.ObjectKey]string{} + remember := func(app *appsv1alpha1.Application, eventType watch.EventType) { + key := client.ObjectKey{Namespace: app.Namespace, Name: app.Name} + if eventType == watch.Deleted { + delete(lastSent, key) + return + } + lastSent[key] = app.ResourceVersion + } + + // sendMonitorEvent falls back to the monitor's own resourceVersion + // when the event might repeat the one the client already holds, which + // a shared informer hides from its handlers. Without an entry for the + // object, a client resuming this watch may hold any release version, + // so the release's own version counts as held. The object the client + // caches from a fallback event gets a conflict on a precondition-checked + // delete until its next event. + sendMonitorEvent := func(me monitorEvent) bool { + app := me.event.Object.(*appsv1alpha1.Application) + last, known := lastSent[client.ObjectKey{Namespace: app.Namespace, Name: app.Name}] + if (known && app.ResourceVersion == last) || (!known && app.ResourceVersion == me.releaseRV) { + app.SetResourceVersion(me.monitorRV) + } + remember(app, me.event.Type) + return send(me.event) + } + drainPendingWMEvents := func() bool { for _, ev := range pendingWMEvents { - if !send(ev) { + if !sendMonitorEvent(ev) { return false } } @@ -1012,6 +1100,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio // When startingRV == 0, always send ADDED events (client wants full state) // Send event to custom watcher + remember(&app, event.Type) if !send(watch.Event{Type: event.Type, Object: &app}) { return } @@ -1070,10 +1159,19 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio } else if !fieldFilter.MatchesNamespace(hrNS) { continue } + // The event's resourceVersion may be the monitor's, which a + // Delete precondition accepts as current while the release has + // not moved past it. A cached release older than the monitor + // revision could pair a stale spec with that version, so only + // then is the release read live. + hrKey := client.ObjectKey{Namespace: hrNS, Name: hrName} hr := &helmv2.HelmRelease{} - if err := r.c.Get(ctx, client.ObjectKey{Namespace: hrNS, Name: hrName}, hr); err != nil { - klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, err) - continue + if err := r.c.Get(ctx, hrKey, hr); err != nil || newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion()) != hr.GetResourceVersion() { + hr = &helmv2.HelmRelease{} + if err := r.w.Get(ctx, hrKey, hr); err != nil { + klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, err) + continue + } } // Pass the fresh WorkloadMonitor so conversion uses the latest // operational status even if the cache (r.c) has not yet @@ -1094,10 +1192,8 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio continue } } - // Use the WorkloadMonitor's ResourceVersion for the emitted event - // so clients see a monotonically increasing RV and don't skip this update. - app.SetResourceVersion(wm.GetResourceVersion()) - outEvent := watch.Event{Type: watch.Modified, Object: &app} + app.SetResourceVersion(newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion())) + outEvent := monitorEvent{event: watch.Event{Type: watch.Modified, Object: &app}, monitorRV: wm.GetResourceVersion(), releaseRV: hr.GetResourceVersion()} // Buffer WM-triggered events that arrive before the // initial-events-end bookmark. They will be replayed in order // immediately after the bookmark is emitted. @@ -1106,7 +1202,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio continue } bookmarker.Observe(wm.GetResourceVersion()) - if !send(outEvent) { + if !sendMonitorEvent(outEvent) { return } diff --git a/pkg/registry/apps/application/rest_watch_rv_test.go b/pkg/registry/apps/application/rest_watch_rv_test.go new file mode 100644 index 000000000..a8c141cfc --- /dev/null +++ b/pkg/registry/apps/application/rest_watch_rv_test.go @@ -0,0 +1,441 @@ +package application + +import ( + "context" + "encoding/json" + "strconv" + "testing" + "time" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + "github.com/cozystack/cozystack/pkg/config" + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/apiserver/pkg/endpoints/request" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// rvWatchFixture models the two clients REST uses: c reads from an informer +// cache and writes to the API server, w talks to the API server directly. +// The cache can be left behind the live release, and the HelmRelease and +// WorkloadMonitor watches are fake watchers the test drives. +type rvWatchFixture struct { + rest *REST + cache client.Client + live client.WithWatch + hrW *watch.FakeWatcher + wmW *watch.FakeWatcher + // liveReleaseGets counts HelmRelease reads that bypass the cache. The + // watch goroutine and the test both update it; receiving an event from + // the watch orders the watch's updates before the test's next access. + liveReleaseGets int +} + +var rvReleaseKey = client.ObjectKey{Namespace: "default", Name: "postgresql-mydb"} + +func newRVWatchFixture(t *testing.T) *rvWatchFixture { + t.Helper() + scheme := runtime.NewScheme() + if err := cozyv1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := helmv2.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + release := func() *helmv2.HelmRelease { + return &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{ + Name: rvReleaseKey.Name, + Namespace: rvReleaseKey.Namespace, + Labels: map[string]string{ + ApplicationKindLabel: "PostgreSQL", + ApplicationGroupLabel: appsv1alpha1.GroupName, + ApplicationNameLabel: "mydb", + }, + }, + Spec: helmv2.HelmReleaseSpec{Values: &apiextensionsv1.JSON{Raw: []byte(`{"marker":"cached"}`)}}, + } + } + + f := &rvWatchFixture{hrW: watch.NewFake(), wmW: watch.NewFake()} + liveStore := fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build() + f.live = interceptor.NewClient(liveStore, interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*helmv2.HelmRelease); ok { + f.liveReleaseGets++ + } + return c.Get(ctx, key, obj, opts...) + }, + Watch: func(_ context.Context, _ client.WithWatch, list client.ObjectList, _ ...client.ListOption) (watch.Interface, error) { + if _, ok := list.(*cozyv1alpha1.WorkloadMonitorList); ok { + return f.wmW, nil + } + return f.hrW, nil + }, + }) + f.cache = interceptor.NewClient(fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build(), interceptor.Funcs{ + Delete: func(ctx context.Context, _ client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + return liveStore.Delete(ctx, obj, opts...) + }, + }) + f.rest = NewREST(f.cache, f.live, &config.Resource{ + Application: config.ApplicationConfig{Kind: "PostgreSQL", Plural: "postgresqls", Singular: "postgresql"}, + Release: config.ReleaseConfig{Prefix: "postgresql-"}, + }) + return f +} + +func (f *rvWatchFixture) liveRelease(t *testing.T) *helmv2.HelmRelease { + t.Helper() + hr := &helmv2.HelmRelease{} + if err := f.live.Get(context.Background(), rvReleaseKey, hr); err != nil { + t.Fatal(err) + } + return hr +} + +// advanceLive writes a new spec to the live release only, leaving the cache +// one version behind, and returns the new live release. +func (f *rvWatchFixture) advanceLive(t *testing.T, marker string) *helmv2.HelmRelease { + t.Helper() + hr := f.liveRelease(t) + before := hr.ResourceVersion + hr.Spec.Values = &apiextensionsv1.JSON{Raw: []byte(`{"marker":"` + marker + `"}`)} + if err := f.live.Update(context.Background(), hr); err != nil { + t.Fatal(err) + } + if hr.ResourceVersion == before { + t.Fatal("fake client did not advance the release version") + } + return hr +} + +func (f *rvWatchFixture) monitorEvent(rv string) { + f.wmW.Modify(&cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{ + Name: "mon-1", + Namespace: "default", + ResourceVersion: rv, + Labels: map[string]string{ + appsv1alpha1.ApplicationKindLabel: "PostgreSQL", + appsv1alpha1.ApplicationGroupLabel: appsv1alpha1.GroupName, + appsv1alpha1.ApplicationNameLabel: "mydb", + }, + }, + Status: cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true)}, + }) +} + +func startRVWatch(t *testing.T, f *rvWatchFixture) (context.Context, watch.Interface) { + t.Helper() + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + return ctx, w +} + +func nextApplication(t *testing.T, w watch.Interface) *appsv1alpha1.Application { + t.Helper() + select { + case ev, ok := <-w.ResultChan(): + if !ok { + t.Fatal("watch closed") + } + app, ok := ev.Object.(*appsv1alpha1.Application) + if !ok { + t.Fatalf("got %s %T, want an Application", ev.Type, ev.Object) + } + return app + case <-time.After(5 * time.Second): + t.Fatal("no event") + } + return nil +} + +func specMarker(t *testing.T, app *appsv1alpha1.Application) string { + t.Helper() + var v struct { + Marker string `json:"marker"` + } + if app.Spec == nil { + t.Fatal("application has no spec") + } + if err := json.Unmarshal(app.Spec.Raw, &v); err != nil { + t.Fatal(err) + } + return v.Marker +} + +func rvNumber(t *testing.T, rv string) uint64 { + t.Helper() + n, err := strconv.ParseUint(rv, 10, 64) + if err != nil { + t.Fatalf("resourceVersion %q: %v", rv, err) + } + return n +} + +// The spec in a monitor-triggered event must come from a release read no +// earlier than the monitor revision the event carries, or a precondition on +// that version would accept a write built on a stale spec. +func TestWatchMonitorEventReadsReleaseLive(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + f.advanceLive(t, "live") + + f.monitorEvent("5000") + app := nextApplication(t, w) + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live release's", got) + } + if app.ResourceVersion != "5000" { + t.Fatalf("resourceVersion %q, want the monitor's 5000", app.ResourceVersion) + } + if f.liveReleaseGets != 2 { + t.Fatalf("%d live release reads, want the test's own plus one for the event", f.liveReleaseGets) + } +} + +// A release cached at or past the monitor revision already pairs its spec +// with its own version, so the event uses it without a live read: a watch +// replays every existing monitor as ADDED when it starts. With nothing sent +// for the object yet, the client may hold that release version, so the event +// carries the monitor's. +func TestWatchMonitorEventUsesCacheNotOlderThanMonitor(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + cached := &helmv2.HelmRelease{} + if err := f.cache.Get(context.Background(), rvReleaseKey, cached); err != nil { + t.Fatal(err) + } + f.advanceLive(t, "live") + gets := f.liveReleaseGets + + f.monitorEvent("1") + app := nextApplication(t, w) + if got := specMarker(t, app); got != "cached" { + t.Fatalf("spec marker %q, want the cached release's", got) + } + if app.ResourceVersion != "1" { + t.Fatalf("resourceVersion %q, want the monitor's 1 rather than the cached release's %q", app.ResourceVersion, cached.ResourceVersion) + } + if f.liveReleaseGets != gets { + t.Fatalf("%d live release reads for a monitor older than the cached release, want none", f.liveReleaseGets-gets) + } +} + +// Shared informers deliver an update whose resourceVersion equals the stored +// one only to handlers due for a resync, so each monitor-only change must +// arrive with a resourceVersion different from the previous event's. +func TestWatchMonitorOnlyChangeAdvancesVersion(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + + f.hrW.Modify(live.DeepCopy()) + prev := rvNumber(t, nextApplication(t, w).ResourceVersion) + for _, rv := range []string{"5000", "5001"} { + f.monitorEvent(rv) + got := rvNumber(t, nextApplication(t, w).ResourceVersion) + if got <= prev { + t.Fatalf("monitor event resourceVersion %d, want above the previous event's %d", got, prev) + } + prev = got + } +} + +// A monitor event processed after the release event it predates must not +// repeat the resourceVersion the client already holds, or a shared informer +// hides it from its handlers. It falls back to the monitor's older version, +// and a delete with that version gets a conflict instead of acting on a spec +// the client may not have. +func TestWatchLateMonitorEventDoesNotRepeatVersion(t *testing.T) { + f := newRVWatchFixture(t) + ctx, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.hrW.Modify(live.DeepCopy()) + if got := nextApplication(t, w).ResourceVersion; got != live.ResourceVersion { + t.Fatalf("release event resourceVersion %q, want %q", got, live.ResourceVersion) + } + f.monitorEvent("1") + rv := nextApplication(t, w).ResourceVersion + if rv != "1" { + t.Fatalf("late monitor event resourceVersion %q, want the monitor's 1 rather than the held %q", rv, live.ResourceVersion) + } + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if !apierrors.IsConflict(err) { + t.Fatalf("delete with the monitor's older version: got %v, want Conflict", err) + } +} + +// A release the client already holds is skipped on a resumed watch, so the +// next monitor event must not repeat its version either. +func TestWatchLateMonitorEventAfterSkippedReplay(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + w := startRVWatchFrom(t, f, live.ResourceVersion) + + f.hrW.Add(live.DeepCopy()) + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("monitor event after the skipped replay has resourceVersion %q, want the monitor's 1 rather than the held %q", rv, live.ResourceVersion) + } +} + +// Once this watch has sent the object a monitor version, the release version +// is no longer what the client holds, and the event can carry it. +func TestWatchMonitorEventCarriesReleaseAfterFallback(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("first monitor event resourceVersion %q, want the monitor's 1", rv) + } + f.monitorEvent("2") + if rv := nextApplication(t, w).ResourceVersion; rv != live.ResourceVersion { + t.Fatalf("second monitor event resourceVersion %q, want the release's %q", rv, live.ResourceVersion) + } +} + +// A release event in between makes the release version the held one again. +func TestWatchReleaseEventResetsHeldVersion(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.monitorEvent("1") + nextApplication(t, w) + f.hrW.Modify(live.DeepCopy()) + if rv := nextApplication(t, w).ResourceVersion; rv != live.ResourceVersion { + t.Fatalf("release event resourceVersion %q, want %q", rv, live.ResourceVersion) + } + f.monitorEvent("2") + if rv := nextApplication(t, w).ResourceVersion; rv != "2" { + t.Fatalf("monitor event after the release event has resourceVersion %q, want the monitor's 2 rather than the held %q", rv, live.ResourceVersion) + } +} + +func startRVWatchFrom(t *testing.T, f *rvWatchFixture, resourceVersion string) watch.Interface { + t.Helper() + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{ResourceVersion: resourceVersion}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + return w +} + +// On a resumed watch the replayed monitor can arrive before the replayed +// release, so nothing is known yet about the version the client holds. +func TestWatchResumedMonitorReplayBeforeRelease(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + w := startRVWatchFrom(t, f, live.ResourceVersion) + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("replayed monitor event has resourceVersion %q, want the monitor's 1 rather than the possibly held %q", rv, live.ResourceVersion) + } +} + +// A fallback event steps the client's resume point below versions it holds, +// so a resumed client can hold a release version above the one it resumes +// from. +func TestWatchResumedBelowHeldReleaseVersion(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + if rvNumber(t, live.ResourceVersion) <= 500 { + t.Fatalf("fixture release version %q must be above the resume point", live.ResourceVersion) + } + w := startRVWatchFrom(t, f, "500") + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("replayed monitor event has resourceVersion %q, want the monitor's 1 rather than the possibly held %q", rv, live.ResourceVersion) + } +} + +func TestDeleteWithVersionFromMonitorEvent(t *testing.T) { + f := newRVWatchFixture(t) + ctx, w := startRVWatch(t, f) + f.advanceLive(t, "live") + + f.monitorEvent("5000") + rv := nextApplication(t, w).ResourceVersion + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if err != nil { + t.Fatalf("delete with resourceVersion %q from the watch event: %v", rv, err) + } + if err := f.live.Get(context.Background(), rvReleaseKey, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) { + t.Fatalf("release still present after delete: %v", err) + } +} + +func TestDeleteRejectsVersionOlderThanLive(t *testing.T) { + f := newRVWatchFixture(t) + cached := &helmv2.HelmRelease{} + if err := f.cache.Get(context.Background(), rvReleaseKey, cached); err != nil { + t.Fatal(err) + } + f.advanceLive(t, "live") + + ctx := request.WithNamespace(context.Background(), "default") + rv := cached.ResourceVersion + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if !apierrors.IsConflict(err) { + t.Fatalf("delete with stale resourceVersion %q: got %v, want Conflict", rv, err) + } + if err := f.live.Get(context.Background(), rvReleaseKey, &helmv2.HelmRelease{}); err != nil { + t.Fatalf("release gone after a rejected delete: %v", err) + } +} + +func TestCheckResourceVersion(t *testing.T) { + r := newTestRESTWithSchemesFromClient(nil) + for _, tc := range []struct { + caller string + check func(error) bool + }{ + {"100", func(err error) bool { return err == nil }}, + {"101", func(err error) bool { return err == nil }}, + {"99", apierrors.IsConflict}, + {"0", apierrors.IsConflict}, + {"", apierrors.IsBadRequest}, + {"abc", apierrors.IsBadRequest}, + } { + if err := r.checkResourceVersion("mydb", tc.caller, "100"); !tc.check(err) { + t.Errorf("caller resourceVersion %q against live 100: unexpected result %v", tc.caller, err) + } + } +} + +func TestNewerResourceVersion(t *testing.T) { + for _, tc := range []struct{ a, b, want string }{ + {"7", "5", "7"}, + {"5", "7", "7"}, + {"7", "7", "7"}, + {"x", "5", "5"}, + {"7", "y", "y"}, + } { + if got := newerResourceVersion(tc.a, tc.b); got != tc.want { + t.Errorf("newerResourceVersion(%q, %q) = %q, want %q", tc.a, tc.b, got, tc.want) + } + } +} diff --git a/pkg/registry/apps/application/rest_write_options_test.go b/pkg/registry/apps/application/rest_write_options_test.go index 823a7327c..fd6417c3f 100644 --- a/pkg/registry/apps/application/rest_write_options_test.go +++ b/pkg/registry/apps/application/rest_write_options_test.go @@ -58,7 +58,7 @@ func newOptionsTestREST(t *testing.T, funcs interceptor.Funcs, objects ...client WithObjects(objects...). WithInterceptorFuncs(funcs). Build() - return NewREST(c, nil, &config.Resource{ + return NewREST(c, c, &config.Resource{ Application: config.ApplicationConfig{ Kind: "PostgreSQL", Plural: "postgresqls", @@ -185,7 +185,9 @@ func TestDeletePropagatesWriteOptions(t *testing.T) { grace := int64(3) propagation := metav1.DeletePropagationForeground uid := types.UID("expected-uid") - rv := "17" + // The version the fake client stamps on seeded objects: a resourceVersion + // precondition is checked against the live release. + rv := "999" want := &metav1.DeleteOptions{ GracePeriodSeconds: &grace, Preconditions: &metav1.Preconditions{UID: &uid, ResourceVersion: &rv}, From 0ccb3fead7835fb6aef4022512c089513607ad34 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Mon, 16 Nov 2026 13:10:44 +0300 Subject: [PATCH 09/14] fix(api): retry the live release read behind a monitor event When the cached release is older than the monitor revision, the watch reads the release live so that an event never pairs a stale spec with the monitor's version. A transient error on that read dropped the monitor event. Both streams are plain API watches, so nothing replayed it, and a client kept the old WorkloadsReady state until the next change of either object. Retry the live read a few times before giving the event up. This covers a failure shorter than the retry window; a longer one still drops the event, as a cache miss did before. A release that is gone is not retried: the event is dropped after one read. The live reads run under a context that Stop cancels, so a stopped watch does not wait on the API server. The tests also pin the two paths that were untested: a release the cache has not seen yet is read live and delivered, and a release that is gone everywhere produces no event. Fixes: f13362b0eeff ("fix(api): make monitor watch versions usable as delete preconditions") Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- pkg/registry/apps/application/rest.go | 34 +++- .../apps/application/rest_watch_rv_test.go | 183 +++++++++++++++++- 2 files changed, 214 insertions(+), 3 deletions(-) diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 817eff526..d6c18b410 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -777,6 +777,13 @@ func newerResourceVersion(a, b string) string { return a } +// Bounded so that an apiserver outage drops the monitor event instead of +// holding the watch goroutine. +const ( + liveReleaseReadAttempts = 3 + liveReleaseReadRetryDelay = 100 * time.Millisecond +) + // Watch sets up a watch on HelmReleases, filters them based on application labels, and converts events to Applications func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) { namespace, err := r.getNamespace(ctx) @@ -916,6 +923,17 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio if wmWatcherForCleanup != nil { defer wmWatcherForCleanup.Stop() } + // Live reads use a context that Stop cancels, so a stopped watch + // never waits on the API server. + readCtx, cancelReads := context.WithCancel(ctx) + defer cancelReads() + go func() { + select { + case <-customW.stopChan: + cancelReads() + case <-readCtx.Done(): + } + }() // Buffer of WorkloadMonitor events that arrived before the initial // snapshot finished. The watch-list contract requires the stream to @@ -1168,8 +1186,20 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio hr := &helmv2.HelmRelease{} if err := r.c.Get(ctx, hrKey, hr); err != nil || newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion()) != hr.GetResourceVersion() { hr = &helmv2.HelmRelease{} - if err := r.w.Get(ctx, hrKey, hr); err != nil { - klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, err) + // Nothing replays a monitor event this watch drops, so a + // transient failure of the live read is retried briefly. + // A missing release is final. + liveErr := r.w.Get(readCtx, hrKey, hr) + for attempt := 1; liveErr != nil && !apierrors.IsNotFound(liveErr) && attempt < liveReleaseReadAttempts; attempt++ { + select { + case <-readCtx.Done(): + return + case <-time.After(liveReleaseReadRetryDelay): + } + liveErr = r.w.Get(readCtx, hrKey, hr) + } + if liveErr != nil { + klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, liveErr) continue } } diff --git a/pkg/registry/apps/application/rest_watch_rv_test.go b/pkg/registry/apps/application/rest_watch_rv_test.go index a8c141cfc..f3c30ac38 100644 --- a/pkg/registry/apps/application/rest_watch_rv_test.go +++ b/pkg/registry/apps/application/rest_watch_rv_test.go @@ -3,6 +3,7 @@ package application import ( "context" "encoding/json" + "errors" "strconv" "testing" "time" @@ -37,6 +38,15 @@ type rvWatchFixture struct { // watch goroutine and the test both update it; receiving an event from // the watch orders the watch's updates before the test's next access. liveReleaseGets int + // liveReleaseErrs are returned by the next live HelmRelease reads, one + // per read, before reads reach the store again. + liveReleaseErrs []error + // liveReleaseHang makes live HelmRelease reads block until their context + // ends, like a request to an API server that never answers. + liveReleaseHang bool + // cacheStore is the store behind cache, for tests that leave the cache + // without the release. + cacheStore client.WithWatch } var rvReleaseKey = client.ObjectKey{Namespace: "default", Name: "postgresql-mydb"} @@ -71,6 +81,15 @@ func newRVWatchFixture(t *testing.T) *rvWatchFixture { Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { if _, ok := obj.(*helmv2.HelmRelease); ok { f.liveReleaseGets++ + if f.liveReleaseHang { + <-ctx.Done() + return ctx.Err() + } + if len(f.liveReleaseErrs) > 0 { + err := f.liveReleaseErrs[0] + f.liveReleaseErrs = f.liveReleaseErrs[1:] + return err + } } return c.Get(ctx, key, obj, opts...) }, @@ -81,7 +100,8 @@ func newRVWatchFixture(t *testing.T) *rvWatchFixture { return f.hrW, nil }, }) - f.cache = interceptor.NewClient(fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build(), interceptor.Funcs{ + f.cacheStore = fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build() + f.cache = interceptor.NewClient(f.cacheStore, interceptor.Funcs{ Delete: func(ctx context.Context, _ client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { return liveStore.Delete(ctx, obj, opts...) }, @@ -312,6 +332,167 @@ func TestWatchMonitorEventCarriesReleaseAfterFallback(t *testing.T) { } } +// expectNoApplication fails if the watch delivers anything within the wait, +// then sends a release event and receives it so that the watch goroutine's +// earlier bookkeeping is ordered before the caller's next read of it. +func expectNoApplication(t *testing.T, f *rvWatchFixture, w watch.Interface, release *helmv2.HelmRelease) { + t.Helper() + select { + case ev := <-w.ResultChan(): + t.Fatalf("unexpected %s event", ev.Type) + case <-time.After((liveReleaseReadAttempts + 2) * liveReleaseReadRetryDelay): + } + f.hrW.Modify(release) + nextApplication(t, w) +} + +// A transient failure of the live read must not cost the client the monitor +// change: nothing replays it, so the read is retried. +func TestWatchMonitorEventRetriesLiveRead(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + f.liveReleaseErrs = []error{timeout, timeout} + + f.monitorEvent(live.ResourceVersion) + app := nextApplication(t, w) + if got := f.liveReleaseGets - readsBefore; got != 3 { + t.Fatalf("live release reads %d, want two failed attempts and one success", got) + } + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live spec", got) + } + if app.ResourceVersion != live.ResourceVersion { + t.Fatalf("resourceVersion %q, want the live release's %q", app.ResourceVersion, live.ResourceVersion) + } +} + +// A read that keeps failing is given up after the last attempt, so a broken +// apiserver cannot hold the watch goroutine. +func TestWatchMonitorEventGivesUpAfterRetries(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + for range liveReleaseReadAttempts { + f.liveReleaseErrs = append(f.liveReleaseErrs, timeout) + } + + f.monitorEvent(live.ResourceVersion) + expectNoApplication(t, f, w, live) + if got := f.liveReleaseGets - readsBefore; got != liveReleaseReadAttempts { + t.Fatalf("live release reads %d, want %d attempts and no more", got, liveReleaseReadAttempts) + } +} + +// stopDuringLiveReadRetry queues a failure for every attempt, sends a monitor +// event and calls stop while the watch waits between attempts. The watch must +// close after the one read made before the stop. +func stopDuringLiveReadRetry(t *testing.T, f *rvWatchFixture, w watch.Interface, stop func()) { + t.Helper() + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + for range liveReleaseReadAttempts { + f.liveReleaseErrs = append(f.liveReleaseErrs, timeout) + } + + f.monitorEvent(live.ResourceVersion) + stop() + select { + case ev, ok := <-w.ResultChan(): + if ok { + t.Fatalf("unexpected %s event", ev.Type) + } + case <-time.After(5 * time.Second): + t.Fatal("watch still open") + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want the one before the stop", got) + } +} + +func TestWatchStopEndsLiveReadRetry(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + stopDuringLiveReadRetry(t, f, w, w.Stop) +} + +func TestWatchContextCancelEndsLiveReadRetry(t *testing.T) { + f := newRVWatchFixture(t) + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + stopDuringLiveReadRetry(t, f, w, cancel) +} + +// A live read that never answers must not outlive the watch: Stop cancels +// the read's context, and the watch closes. +func TestWatchStopCancelsHungLiveRead(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + f.liveReleaseHang = true + + f.monitorEvent(live.ResourceVersion) + w.Stop() + select { + case ev, ok := <-w.ResultChan(): + if ok { + t.Fatalf("unexpected %s event", ev.Type) + } + case <-time.After(5 * time.Second): + t.Fatal("watch still open while a live read hangs") + } +} + +// A release that is gone is final: the event is dropped after one read, +// without retries that would delay the next event. +func TestWatchMonitorEventDroppedWhenReleaseIsGone(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + release := f.liveRelease(t) + for _, c := range []client.Client{f.cacheStore, f.live} { + if err := c.Delete(context.Background(), release.DeepCopy()); err != nil { + t.Fatal(err) + } + } + readsBefore := f.liveReleaseGets + + f.monitorEvent(strconv.FormatUint(rvNumber(t, release.ResourceVersion)+1, 10)) + expectNoApplication(t, f, w, release) + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want a single read", got) + } +} + +// A release the cache has not seen yet is read live and delivered. +func TestWatchMonitorEventReadsReleaseMissingFromCache(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + if err := f.cacheStore.Delete(context.Background(), live.DeepCopy()); err != nil { + t.Fatal(err) + } + readsBefore := f.liveReleaseGets + + f.monitorEvent(live.ResourceVersion) + app := nextApplication(t, w) + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want one", got) + } + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live spec", got) + } +} + // A release event in between makes the release version the held one again. func TestWatchReleaseEventResetsHeldVersion(t *testing.T) { f := newRVWatchFixture(t) From 48d83b5f77586fa04680e0f4081b88b8bcbca82b Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Tue, 17 Nov 2026 23:02:58 +0300 Subject: [PATCH 10/14] test(api): cancel monitor live reads before retrying FakeWatcher.Modify synchronizes event receipt, not processing. A test that cancels after sending the event can lose the retry-delay window and observe more reads even when cancellation works correctly. Cancel at the first failed live read and wait for its context to end before returning the error, so the exact read count does not depend on which goroutine runs next. Fixes: 0ccb3fead783 ("fix(api): retry the live release read behind a monitor event") Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- .../apps/application/rest_watch_rv_test.go | 31 +++++++++++++------ 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/pkg/registry/apps/application/rest_watch_rv_test.go b/pkg/registry/apps/application/rest_watch_rv_test.go index f3c30ac38..06640d72e 100644 --- a/pkg/registry/apps/application/rest_watch_rv_test.go +++ b/pkg/registry/apps/application/rest_watch_rv_test.go @@ -40,7 +40,8 @@ type rvWatchFixture struct { liveReleaseGets int // liveReleaseErrs are returned by the next live HelmRelease reads, one // per read, before reads reach the store again. - liveReleaseErrs []error + liveReleaseErrs []error + onLiveReleaseError func(context.Context) // liveReleaseHang makes live HelmRelease reads block until their context // ends, like a request to an API server that never answers. liveReleaseHang bool @@ -88,6 +89,10 @@ func newRVWatchFixture(t *testing.T) *rvWatchFixture { if len(f.liveReleaseErrs) > 0 { err := f.liveReleaseErrs[0] f.liveReleaseErrs = f.liveReleaseErrs[1:] + if hook := f.onLiveReleaseError; hook != nil { + f.onLiveReleaseError = nil + hook(ctx) + } return err } } @@ -388,10 +393,9 @@ func TestWatchMonitorEventGivesUpAfterRetries(t *testing.T) { } } -// stopDuringLiveReadRetry queues a failure for every attempt, sends a monitor -// event and calls stop while the watch waits between attempts. The watch must -// close after the one read made before the stop. -func stopDuringLiveReadRetry(t *testing.T, f *rvWatchFixture, w watch.Interface, stop func()) { +// Cancel before the first failed Get returns: a send to FakeWatcher only +// orders event receipt, so cancelling after the send can lose the retry window. +func stopAtFailedLiveRead(t *testing.T, f *rvWatchFixture, w watch.Interface, stop func()) { t.Helper() live := f.advanceLive(t, "live") readsBefore := f.liveReleaseGets @@ -400,8 +404,15 @@ func stopDuringLiveReadRetry(t *testing.T, f *rvWatchFixture, w watch.Interface, f.liveReleaseErrs = append(f.liveReleaseErrs, timeout) } + f.onLiveReleaseError = func(ctx context.Context) { + stop() + select { + case <-ctx.Done(): + case <-time.After(5 * time.Second): + t.Error("live read context still open after cancellation") + } + } f.monitorEvent(live.ResourceVersion) - stop() select { case ev, ok := <-w.ResultChan(): if ok { @@ -415,13 +426,13 @@ func stopDuringLiveReadRetry(t *testing.T, f *rvWatchFixture, w watch.Interface, } } -func TestWatchStopEndsLiveReadRetry(t *testing.T) { +func TestWatchStopAtFailedLiveReadPreventsRetry(t *testing.T) { f := newRVWatchFixture(t) _, w := startRVWatch(t, f) - stopDuringLiveReadRetry(t, f, w, w.Stop) + stopAtFailedLiveRead(t, f, w, w.Stop) } -func TestWatchContextCancelEndsLiveReadRetry(t *testing.T) { +func TestWatchContextCancelAtFailedLiveReadPreventsRetry(t *testing.T) { f := newRVWatchFixture(t) ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) t.Cleanup(cancel) @@ -430,7 +441,7 @@ func TestWatchContextCancelEndsLiveReadRetry(t *testing.T) { t.Fatal(err) } t.Cleanup(w.Stop) - stopDuringLiveReadRetry(t, f, w, cancel) + stopAtFailedLiveRead(t, f, w, cancel) } // A live read that never answers must not outlive the watch: Stop cancels From dff4553216b99532ac957a75a5b8a37f6cc01a3b Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Wed, 18 Nov 2026 17:29:29 +0300 Subject: [PATCH 11/14] fix(api): bound live release reads in application watches A stalled live release read holds the whole application watch event loop. End the watch when a refresh runs out of time so clients can reconnect without relying on stale cached release data. Fixes: 0ccb3fead783 ("fix(api): retry the live release read behind a monitor event") Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- pkg/registry/apps/application/rest.go | 20 ++- .../application/rest_watch_deadline_test.go | 149 ++++++++++++++++++ 2 files changed, 163 insertions(+), 6 deletions(-) create mode 100644 pkg/registry/apps/application/rest_watch_deadline_test.go diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index d6c18b410..a560cb7fe 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -777,11 +777,11 @@ func newerResourceVersion(a, b string) string { return a } -// Bounded so that an apiserver outage drops the monitor event instead of -// holding the watch goroutine. +// Watches bypass the API server's default one-minute request timeout. const ( liveReleaseReadAttempts = 3 liveReleaseReadRetryDelay = 100 * time.Millisecond + liveReleaseReadTimeout = time.Minute ) // Watch sets up a watch on HelmReleases, filters them based on application labels, and converts events to Applications @@ -1189,14 +1189,22 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio // Nothing replays a monitor event this watch drops, so a // transient failure of the live read is retried briefly. // A missing release is final. - liveErr := r.w.Get(readCtx, hrKey, hr) + liveCtx, cancelLiveRead := context.WithTimeout(readCtx, liveReleaseReadTimeout) + liveErr := r.w.Get(liveCtx, hrKey, hr) for attempt := 1; liveErr != nil && !apierrors.IsNotFound(liveErr) && attempt < liveReleaseReadAttempts; attempt++ { select { - case <-readCtx.Done(): - return + case <-liveCtx.Done(): case <-time.After(liveReleaseReadRetryDelay): } - liveErr = r.w.Get(readCtx, hrKey, hr) + if liveCtx.Err() != nil { + break + } + liveErr = r.w.Get(liveCtx, hrKey, hr) + } + readEnded := liveCtx.Err() != nil + cancelLiveRead() + if readEnded { + return } if liveErr != nil { klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, liveErr) diff --git a/pkg/registry/apps/application/rest_watch_deadline_test.go b/pkg/registry/apps/application/rest_watch_deadline_test.go new file mode 100644 index 000000000..3d4bc68f5 --- /dev/null +++ b/pkg/registry/apps/application/rest_watch_deadline_test.go @@ -0,0 +1,149 @@ +package application + +import ( + "context" + "errors" + "testing" + "testing/synctest" + "time" + + metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/apiserver/pkg/endpoints/request" +) + +func expectLiveReadWatchClosed(t *testing.T, w watch.Interface) { + t.Helper() + select { + case event, open := <-w.ResultChan(): + if open { + t.Fatalf("unexpected %s event instead of watch closure", event.Type) + } + default: + t.Fatal("watch remains open after the live-read deadline") + } +} + +func TestWatchHungLiveReadDeadlineClosesAndReconnects(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + parent, w := startRVWatch(t, f) + cached := f.liveRelease(t) + f.hrW.Modify(cached.DeepCopy()) + resume := nextApplication(t, w).ResourceVersion + live := f.advanceLive(t, "before-timeout") + readsBefore := f.liveReleaseGets + entered := make(chan context.Context, 1) + f.liveReleaseErrs = []error{errors.New("live read failed")} + f.onLiveReleaseError = func(ctx context.Context) { + entered <- ctx + <-ctx.Done() + } + + readStarted := time.Now() + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + var liveCtx context.Context + select { + case liveCtx = <-entered: + default: + t.Fatal("live read did not start") + } + time.Sleep(time.Minute) + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if !errors.Is(liveCtx.Err(), context.DeadlineExceeded) { + t.Fatalf("live read ended with %v, want its own deadline", liveCtx.Err()) + } + deadline, bounded := liveCtx.Deadline() + if !bounded || deadline.Sub(readStarted) != time.Minute { + t.Fatalf("live read budget %v, bounded=%t, want exactly one minute", deadline.Sub(readStarted), bounded) + } + if parent.Err() != nil { + t.Fatalf("watch parent unexpectedly ended: %v", parent.Err()) + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want one bounded hung read", got) + } + + f.hrW, f.wmW = watch.NewFake(), watch.NewFake() + fresh := f.advanceLive(t, "after-reconnect") + reconnected := startRVWatchFrom(t, f, resume) + f.monitorEvent(fresh.ResourceVersion) + app := nextApplication(t, reconnected) + if got := specMarker(t, app); got != "after-reconnect" { + t.Fatalf("reconnected spec marker %q, want fresh live state", got) + } + if app.ResourceVersion != fresh.ResourceVersion { + t.Fatalf("reconnected version %q, want %q", app.ResourceVersion, fresh.ResourceVersion) + } + }) +} + +func TestWatchLiveReadDeadlineIncludesRetries(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + f.liveReleaseErrs = []error{errors.New("temporary live read failure")} + f.onLiveReleaseError = func(context.Context) { + time.Sleep(45 * time.Second) + f.liveReleaseHang = true + } + + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + time.Sleep(time.Minute) + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if got := f.liveReleaseGets - readsBefore; got != 2 { + t.Fatalf("live release reads %d, want one slow failure and one hung retry", got) + } + }) +} + +func TestWatchCancellationEndsHungLiveReadBeforeDeadline(t *testing.T) { + for _, mode := range []string{"stop", "context"} { + t.Run(mode, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + parent, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(parent, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + entered := make(chan context.Context, 1) + f.liveReleaseErrs = []error{errors.New("live read failed")} + f.onLiveReleaseError = func(ctx context.Context) { + entered <- ctx + <-ctx.Done() + } + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + liveCtx := <-entered + before := time.Now() + if mode == "stop" { + w.Stop() + } else { + cancel() + } + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if !errors.Is(liveCtx.Err(), context.Canceled) { + t.Fatalf("live read ended with %v, want cancellation", liveCtx.Err()) + } + if time.Since(before) != 0 { + t.Fatal("cancellation waited for a timer") + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want exactly one", got) + } + }) + }) + } +} From 323bd8bd33647be7cb72b828b07f18d4237b1bc1 Mon Sep 17 00:00:00 2001 From: Adham Kiwan Date: Thu, 19 Nov 2026 14:20:56 +0200 Subject: [PATCH 12/14] fix(linstor): run the NFS server wait init container on the platform CSI image The LinstorCluster set no nfsServer.podTemplate, so the linstor-wait-node-online init container of the NFS server DaemonSet ran piraeus-operator's default CSI image. That image follows the operator release, not linstorCSI.image, so a cluster that pulls only from a mirror of the platform images still needed quay.io for it, and a client behaviour change between the two (as with the certificate variables) would reach this container without the platform choosing it. Pin it to linstorCSI.image like the CSI node and controller pods. nfsServer.enabled is set explicitly, because the operator treats an absent nfsServer as enabled. Closes: #5307 Assisted-by: LLM Signed-off-by: Adham Kiwan --- .../system/linstor/templates/cluster.yaml | 11 ++++++++ .../system/linstor/tests/linstor_test.yaml | 28 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/packages/system/linstor/templates/cluster.yaml b/packages/system/linstor/templates/cluster.yaml index c648c0a8c..2541100f5 100644 --- a/packages/system/linstor/templates/cluster.yaml +++ b/packages/system/linstor/templates/cluster.yaml @@ -128,6 +128,17 @@ spec: containers: - name: linstor-csi image: {{ .Values.linstorCSI.image.repository }}:{{ .Values.linstorCSI.image.tag }} + {{- /* The NFS server DaemonSet runs one init container on the CSI image. + Left unset it follows the operator's default image and tag, not + linstorCSI.image. An absent nfsServer means enabled to the operator, + so enabled is stated explicitly to keep that unchanged. */}} + nfsServer: + enabled: true + podTemplate: + spec: + initContainers: + - name: linstor-wait-node-online + image: {{ .Values.linstorCSI.image.repository }}:{{ .Values.linstorCSI.image.tag }} patches: - target: kind: Deployment diff --git a/packages/system/linstor/tests/linstor_test.yaml b/packages/system/linstor/tests/linstor_test.yaml index 1d0441d46..57b5be514 100644 --- a/packages/system/linstor/tests/linstor_test.yaml +++ b/packages/system/linstor/tests/linstor_test.yaml @@ -16,6 +16,34 @@ tests: path: spec.csiController.podTemplate.spec.containers[0].image pattern: '^ghcr\.io/cozystack/cozystack/linstor-csi:[^@]+@sha256:[0-9a-f]{64}$' + - it: pins the NFS server's wait-node-online init container to the cozystack-built CSI image + template: templates/cluster.yaml + documentSelector: + path: kind + value: LinstorCluster + asserts: + - matchRegex: + path: spec.nfsServer.podTemplate.spec.initContainers[?(@.name=="linstor-wait-node-online")].image + pattern: '^ghcr\.io/cozystack/cozystack/linstor-csi:[^@]+@sha256:[0-9a-f]{64}$' + - equal: + path: spec.nfsServer.enabled + value: true + + - it: the NFS server's wait-node-online init container follows linstorCSI.image + template: templates/cluster.yaml + documentSelector: + path: kind + value: LinstorCluster + set: + linstorCSI: + image: + repository: registry.example/linstor-csi + tag: v0.0.0-test + asserts: + - equal: + path: spec.nfsServer.podTemplate.spec.initContainers[?(@.name=="linstor-wait-node-online")].image + value: registry.example/linstor-csi:v0.0.0-test + - it: pins the satellite to the cozystack-built piraeus-server image template: templates/satellites-cozy.yaml documentSelector: From 8382ed1a92ec40bed270323dba2f8d522c41655d Mon Sep 17 00:00:00 2001 From: somaz Date: Mon, 23 Nov 2026 10:59:26 +0300 Subject: [PATCH 13/14] fix(gateway): skip a child apex the wildcard certificate already covers In DNS-01 mode every inheriting child tenant's apex went into the parent Gateway's wildcard Certificate. When a wildcard in the same Certificate already covers that apex one label up, Let's Encrypt refuses the whole order as redundant and the parent Gateway gets no certificate at all. Skip such a SAN, matching the single-label check Boulder runs in wildcardOverlap. A child may also use a broader custom domain than the gateway. Its wildcard then covers the gateway apex, so the same check drops the gateway SAN too. Closes: #5125 Co-authored-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> Assisted-by: LLM Signed-off-by: somaz Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> --- .../tenantgateway/reconciler_test.go | 10 ++-- .../controller/tenantgateway/renderers.go | 48 +++++++++------ .../tenantgateway/renderers_test.go | 59 +++++++++++++++++++ packages/extra/gateway/README.md | 2 +- 4 files changed, 95 insertions(+), 24 deletions(-) diff --git a/internal/controller/tenantgateway/reconciler_test.go b/internal/controller/tenantgateway/reconciler_test.go index 469af1ccd..1842c22f9 100644 --- a/internal/controller/tenantgateway/reconciler_test.go +++ b/internal/controller/tenantgateway/reconciler_test.go @@ -1814,9 +1814,9 @@ func TestReconcile_HTTP01CollectsHostnamesFromInheritingChildNamespaces(t *testi // the SAN-expansion contract: when a tenant inherits this Gateway's // publishing layer (its namespace is labelled namespace.cozystack. // io/gateway=), the wildcard Certificate that the owner -// issues for DNS-01 mode must also cover the child's apex — -// and *.. Let's Encrypt wildcards are -// single-level, so the parent's `*.` does not match a child +// issues for DNS-01 mode must also cover the child's apex and +// *.. Let's Encrypt wildcards are single-level, so the +// parent's `*.` does not match a child // hostname `harbor.alice.example.com` (two labels deep). Without // SAN expansion the inheritance flow renders Gateway listeners // referencing a cert that fails the SNI handshake — silently in @@ -1883,7 +1883,6 @@ func TestReconcile_DNS01WildcardCertCoversInheritingChildApexes(t *testing.T) { want := map[string]bool{ "example.org": false, "*.example.org": false, - "alice.example.org": false, "*.alice.example.org": false, } for _, n := range cert.Spec.DNSNames { @@ -1896,6 +1895,9 @@ func TestReconcile_DNS01WildcardCertCoversInheritingChildApexes(t *testing.T) { t.Errorf("missing DNS name %q in cert.spec.dnsNames=%v", n, cert.Spec.DNSNames) } } + if containsString(cert.Spec.DNSNames, "alice.example.org") { + t.Errorf("cert.spec.dnsNames=%v lists alice.example.org, which *.example.org already covers; Let's Encrypt refuses such an order", cert.Spec.DNSNames) + } } // TestReconcile_DNS01WildcardCertDeduplicatesChildApexEqualToParent diff --git a/internal/controller/tenantgateway/renderers.go b/internal/controller/tenantgateway/renderers.go index f9886b865..2dfb1407c 100644 --- a/internal/controller/tenantgateway/renderers.go +++ b/internal/controller/tenantgateway/renderers.go @@ -867,7 +867,8 @@ func buildSolver(tgw *gatewayv1alpha1.TenantGateway) (*cmacmev1.ACMEChallengeSol // renderWildcardCertificate builds the cert-manager Certificate that // covers and *., plus per-child-apex SANs for every -// tenant inheriting through this Gateway. Only used in DNS-01 mode; +// tenant inheriting through this Gateway, leaving out any apex that +// another apex's wildcard already covers. Only used in DNS-01 mode; // the listeners rendered by renderGateway reference its secretName. // // childApexes is the deduplicated, sorted list of apex hostnames @@ -878,29 +879,27 @@ func buildSolver(tgw *gatewayv1alpha1.TenantGateway) (*cmacmev1.ACMEChallengeSol // route's hostname (harbor.alice.example.com is two labels deeper // than the wildcard accepts). func (r *Reconciler) renderWildcardCertificate(tgw *gatewayv1alpha1.TenantGateway, childApexes []string) (*cmv1.Certificate, error) { - dnsNames := []string{tgw.Spec.Apex, "*." + tgw.Spec.Apex} - seen := map[string]struct{}{ - tgw.Spec.Apex: {}, - "*." + tgw.Spec.Apex: {}, + apexes := append([]string{tgw.Spec.Apex}, childApexes...) + // A child can use a custom domain whose wildcard covers the gateway apex. + wildcards := make(map[string]struct{}, len(apexes)) + for _, apex := range apexes { + if apex != "" { + wildcards["*."+apex] = struct{}{} + } } - for _, apex := range childApexes { - if apex == "" { + var dnsNames []string + seen := make(map[string]bool, len(apexes)) + for _, apex := range apexes { + if apex == "" || seen[apex] { continue } - // Skip a child whose host label collides with the parent - // apex (mis-labelled namespace, or two tenants briefly - // sharing an apex during a rename). cert-manager rejects - // duplicate dnsNames; the inheriting tenant still attaches - // via the parent SANs already present. - if _, dup := seen[apex]; !dup { + seen[apex] = true + // Let's Encrypt refuses the whole order when it lists a name + // that a wildcard in the same order already covers. + if !coveredByWildcard(wildcards, apex) { dnsNames = append(dnsNames, apex) - seen[apex] = struct{}{} - } - wildcard := "*." + apex - if _, dup := seen[wildcard]; !dup { - dnsNames = append(dnsNames, wildcard) - seen[wildcard] = struct{}{} } + dnsNames = append(dnsNames, "*."+apex) } cert := &cmv1.Certificate{ ObjectMeta: metav1.ObjectMeta{ @@ -925,6 +924,17 @@ func (r *Reconciler) renderWildcardCertificate(tgw *gatewayv1alpha1.TenantGatewa return cert, nil } +// coveredByWildcard mirrors Boulder's wildcardOverlap check. Unlike +// hostnameCovers, a certificate wildcard spans exactly one label. +func coveredByWildcard(wildcards map[string]struct{}, host string) bool { + _, parent, ok := strings.Cut(host, ".") + if !ok { + return false + } + _, covered := wildcards["*."+parent] + return covered +} + func ptrGroup(g string) *gatewayv1.Group { gg := gatewayv1.Group(g) return &gg diff --git a/internal/controller/tenantgateway/renderers_test.go b/internal/controller/tenantgateway/renderers_test.go index d7c60d40a..c0dc69fc0 100644 --- a/internal/controller/tenantgateway/renderers_test.go +++ b/internal/controller/tenantgateway/renderers_test.go @@ -22,6 +22,7 @@ import ( "io" "os" "regexp" + "slices" "testing" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" @@ -203,3 +204,61 @@ func TestPerListenerName_KeepsEveryNameThatWasAlreadyAdmissible(t *testing.T) { } } } + +// TestRenderWildcardCertificate_SkipsChildApexCoveredByWildcard pins the +// dnsNames against Let's Encrypt refusing a whole order that lists a name +// one of its wildcards covers, leaving the Gateway with no certificate. +// A wildcard spans one label, so an apex two labels below stays listed. +func TestRenderWildcardCertificate_SkipsChildApexCoveredByWildcard(t *testing.T) { + cases := []struct { + name string + childApexes []string + want []string + }{ + { + name: "an inheriting tenant uses the parent domain of the gateway apex", + childApexes: []string{"example.com"}, + want: []string{"*.mgmt.example.com", "example.com", "*.example.com"}, + }, + { + name: "child one label below the parent", + childApexes: []string{"ci.mgmt.example.com"}, + want: []string{"mgmt.example.com", "*.mgmt.example.com", "*.ci.mgmt.example.com"}, + }, + { + name: "child two labels below the parent", + childApexes: []string{"b.ci.mgmt.example.com"}, + want: []string{"mgmt.example.com", "*.mgmt.example.com", "b.ci.mgmt.example.com", "*.b.ci.mgmt.example.com"}, + }, + { + name: "covering child wildcard sorts after the apex it covers", + childApexes: []string{"a.z.mgmt.example.com", "z.mgmt.example.com"}, + want: []string{"mgmt.example.com", "*.mgmt.example.com", "*.a.z.mgmt.example.com", "*.z.mgmt.example.com"}, + }, + { + name: "empty apex and apex outside the parent", + childApexes: []string{"", "alice.example.org"}, + want: []string{"mgmt.example.com", "*.mgmt.example.com", "alice.example.org", "*.alice.example.org"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + tgw := &gatewayv1alpha1.TenantGateway{ + ObjectMeta: metav1.ObjectMeta{Name: "cozystack", Namespace: "tenant-management"}, + Spec: gatewayv1alpha1.TenantGatewaySpec{ + Apex: "mgmt.example.com", + CertMode: gatewayv1alpha1.CertModeDNS01, + GatewayClassName: "cilium", + }, + } + r := &Reconciler{Scheme: newScheme(t)} + cert, err := r.renderWildcardCertificate(tgw, tc.childApexes) + if err != nil { + t.Fatalf("renderWildcardCertificate: %v", err) + } + if !slices.Equal(cert.Spec.DNSNames, tc.want) { + t.Errorf("dnsNames = %v, want %v", cert.Spec.DNSNames, tc.want) + } + }) + } +} diff --git a/packages/extra/gateway/README.md b/packages/extra/gateway/README.md index b72dd223b..56b6495bf 100644 --- a/packages/extra/gateway/README.md +++ b/packages/extra/gateway/README.md @@ -44,7 +44,7 @@ The platform chart writes those values into `_cluster.dns01-*` keys consumed by DNS-01 mode renders a single wildcard `Certificate` covering `` and `*.`, plus the corresponding `https` (`*.`) and `https-apex` (``) listeners. New apps published under the apex pick up the existing wildcard cert without per-listener provisioning. -For inheriting child tenants under this Gateway: the controller extends the same wildcard Certificate with `` + `*.` SANs per child, and adds one `*.` listener per child apex referencing the same cert. Child apex SANs are discovered by listing namespaces carrying `namespace.cozystack.io/gateway = ` and reading their `namespace.cozystack.io/host` label. The ACME challenge must succeed for every SAN, which means the DNS provider account configured at the platform layer must be able to write TXT records under each child apex zone — for deeply-nested children that requires either zone delegation or a provider account with apex-spanning permissions. +For inheriting child tenants under this Gateway: the controller extends the same wildcard Certificate with a `*.` SAN per child, plus `` itself unless a wildcard already in the Certificate covers it (Let's Encrypt refuses an order that lists both), and adds one `*.` listener per child apex referencing the same cert. Child apex SANs are discovered by listing namespaces carrying `namespace.cozystack.io/gateway = ` and reading their `namespace.cozystack.io/host` label. The ACME challenge must succeed for every SAN, which means the DNS provider account configured at the platform layer must be able to write TXT records under each child apex zone — for deeply-nested children that requires either zone delegation or a provider account with apex-spanning permissions. Pick DNS-01 when you specifically want a wildcard cert (e.g. a long-lived staging cluster with many short-lived apps and tight LE rate limits). Otherwise stay on HTTP-01. From 46c70422c45f068475c72e17ec15777d4f718131 Mon Sep 17 00:00:00 2001 From: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:33:10 +0300 Subject: [PATCH 14/14] fix(api): validate workload memory before storing an application A memory quantity without a unit is measured in bytes. Reject new values below 1Mi before storing them, while allowing unrelated API edits to applications that already carry a smaller value. The check runs against the live release right before the write, so a stale value read at the start of Update cannot overwrite memory another writer has fixed since. Assisted-by: LLM Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com> --- pkg/registry/apps/application/memory_floor.go | 99 ++++++++++ .../apps/application/memory_floor_test.go | 176 ++++++++++++++++++ pkg/registry/apps/application/rest.go | 18 ++ 3 files changed, 293 insertions(+) create mode 100644 pkg/registry/apps/application/memory_floor.go create mode 100644 pkg/registry/apps/application/memory_floor_test.go diff --git a/pkg/registry/apps/application/memory_floor.go b/pkg/registry/apps/application/memory_floor.go new file mode 100644 index 000000000..32cd3ad2a --- /dev/null +++ b/pkg/registry/apps/application/memory_floor.go @@ -0,0 +1,99 @@ +/* +Copyright 2024 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package application + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" + + apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/apimachinery/pkg/util/validation/field" + + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" +) + +var minimumWorkloadMemory = resource.MustParse("1Mi") + +func workloadValues(values *apiextv1.JSON) (map[string]any, error) { + if values == nil || len(values.Raw) == 0 { + return nil, nil + } + var result map[string]any + decoder := json.NewDecoder(bytes.NewReader(values.Raw)) + decoder.UseNumber() + err := decoder.Decode(&result) + return result, err +} + +func (r *REST) validateWorkloadMemory(app *appsv1alpha1.Application, previous *apiextv1.JSON) error { + if r.specSchema == nil || app.Spec == nil { + return nil + } + values, err := workloadValues(app.Spec) + if err != nil { + return apierrors.NewBadRequest("invalid application spec") + } + old, err := workloadValues(previous) + if err != nil { + return apierrors.NewInternalError(fmt.Errorf("cannot decode stored application spec")) + } + if errs := changedWorkloadMemory(values, old, r.specSchema, field.NewPath("spec")); len(errs) > 0 { + return apierrors.NewInvalid(r.gvk.GroupKind(), app.Name, errs) + } + return nil +} + +// Only walk declared object fields. Arbitrary chart settings and tenant resourceQuotas +// can also contain keys named "memory", with different semantics. +func changedWorkloadMemory(values, old map[string]any, schema *structuralschema.Structural, path *field.Path) field.ErrorList { + var errs field.ErrorList + for _, key := range sortedKeys(values) { + child, declared := schema.Properties[key] + current, ok := values[key].(map[string]any) + if !declared || !ok { + continue + } + previous, _ := old[key].(map[string]any) + where := path.Child(key) + _, preset := schema.Properties["resourcesPreset"] + if key == "resources" && preset && child.Properties["memory"].XIntOrString && child.Properties["cpu"].XIntOrString { + memory := current["memory"] + if memory == nil || reflect.DeepEqual(memory, previous["memory"]) { + continue + } + q, err := resource.ParseQuantity(fmt.Sprint(memory)) + if err != nil { + errs = append(errs, field.Invalid(where.Child("memory"), memory, "expected a Kubernetes quantity")) + continue + } + if q.Cmp(minimumWorkloadMemory) < 0 { + prior, err := resource.ParseQuantity(fmt.Sprint(previous["memory"])) + if err != nil || prior.Cmp(q) != 0 { + errs = append(errs, field.Invalid(where.Child("memory"), memory, "must be at least 1Mi; use a unit such as 512Mi or 8Gi")) + } + } + continue + } + errs = append(errs, changedWorkloadMemory(current, previous, &child, where)...) + } + return errs +} diff --git a/pkg/registry/apps/application/memory_floor_test.go b/pkg/registry/apps/application/memory_floor_test.go new file mode 100644 index 000000000..413afd102 --- /dev/null +++ b/pkg/registry/apps/application/memory_floor_test.go @@ -0,0 +1,176 @@ +/* +Copyright 2024 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package application + +import ( + "context" + "errors" + "testing" + + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apiserver/pkg/endpoints/request" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +func TestWorkloadMemoryAdmission(t *testing.T) { + for _, tc := range []struct { + name, chart, old, next string + upsert, reject bool + }{ + {"new bare bytes", "tcp-balancer", "", `{"resources":{"memory":8}}`, false, true}, + {"upsert respects floor", "tcp-balancer", "", `{"resources":{"memory":"8"}}`, true, true}, + {"new zero", "tcp-balancer", "", `{"resources":{"memory":0}}`, false, true}, + {"minimum", "tcp-balancer", "", `{"resources":{"memory":"1Mi"}}`, false, false}, + {"bytes above minimum", "tcp-balancer", "", `{"resources":{"memory":1048576}}`, false, false}, + {"unchanged scaled to zero", "tcp-balancer", `{"resources":{"memory":8},"replicas":0}`, `{"resources":{"memory":8},"replicas":0,"other":true}`, false, false}, + {"same quantity spelling", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resources":{"memory":"8"}}`, false, false}, + {"changed zero", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resources":{"memory":0}}`, false, true}, + {"repaired", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resources":{"memory":"8Gi"}}`, false, false}, + {"back to preset", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resourcesPreset":"t1.nano"}`, false, false}, + {"nested component", "kubernetes", "", `{"controlPlane":{"apiServer":{"resources":{"memory":"1023Ki"}}}}`, false, true}, + {"quota zero", "tenant", "", `{"resourceQuotas":{"memory":0}}`, false, false}, + {"free form config", "nats", "", `{"config":{"merge":{"resourcesPreset":"example","resources":{"memory":8}}}}`, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + app := &appsv1alpha1.Application{ + TypeMeta: metav1.TypeMeta{Kind: kubernetesKind, APIVersion: "apps.cozystack.io/v1alpha1"}, + ObjectMeta: metav1.ObjectMeta{Name: "good-name", Namespace: "tenant-foo"}, + } + app.Spec = &apiextv1.JSON{Raw: []byte(tc.next)} + var stored []client.Object + if tc.old != "" { + stored = []client.Object{&helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "kubernetes-" + app.Name, Namespace: app.Namespace, Labels: map[string]string{ + ApplicationKindLabel: kubernetesKind, ApplicationGroupLabel: appsv1alpha1.GroupName, ApplicationNameLabel: app.Name, + }}, Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(tc.old)}}}} + } + r := newKubernetesWarnREST(t, stored...) + r.specSchema = chartSpecSchema(t, tc.chart) + ctx := request.WithNamespace(context.Background(), app.Namespace) + var err error + if tc.old != "" || tc.upsert { + _, _, err = r.Update(ctx, app.Name, newDefaultUpdatedObjectInfo(app), nil, nil, tc.upsert, &metav1.UpdateOptions{}) + } else { + _, err = r.Create(ctx, app, nil, &metav1.CreateOptions{}) + } + if tc.reject && !apierrors.IsInvalid(err) || !tc.reject && err != nil { + t.Fatalf("reject=%v, got %v", tc.reject, err) + } + if tc.reject { + list := &helmv2.HelmReleaseList{} + if err := r.c.List(ctx, list); err != nil { + t.Fatal(err) + } + if len(list.Items) != len(stored) || len(stored) > 0 && string(list.Items[0].Spec.Values.Raw) != tc.old { + t.Fatal("a rejected request changed storage") + } + } + }) + } +} + +// A caller that read the app before another writer fixed its memory still +// carries the old value. It must not put that value back, whether the fix lands +// before Update reads the live release or between that read and the write. +func TestWorkloadMemoryRecheckedAgainstLiveRelease(t *testing.T) { + const stale, fixed = `{"resources":{"memory":8}}`, `{"resources":{"memory":"512Mi"}}` + conflict := func(name string) error { + return apierrors.NewConflict(schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, name, errors.New("simulated concurrent write")) + } + setValues := func(ctx context.Context, c client.WithWatch, key client.ObjectKey, values string) error { + live := &helmv2.HelmRelease{} + if err := c.Get(ctx, key, live); err != nil { + return err + } + live.Spec.Values = &apiextv1.JSON{Raw: []byte(values)} + return c.Update(ctx, live) + } + for _, tc := range []struct { + name, next, want string + reject bool + funcs func() interceptor.Funcs + }{ + {"fixed after the first read", `{"resources":{"memory":8},"other":true}`, fixed, true, func() interceptor.Funcs { + gets := 0 + return interceptor.Funcs{Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + err := c.Get(ctx, key, obj, opts...) + if _, ok := obj.(*helmv2.HelmRelease); ok && err == nil { + if gets++; gets == 1 { + return setValues(ctx, c, key, fixed) + } + } + return err + }} + }}, + {"fixed between the live read and the write", `{"resources":{"memory":8},"other":true}`, fixed, true, func() interceptor.Funcs { + writes := 0 + return interceptor.Funcs{Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + if _, ok := obj.(*helmv2.HelmRelease); ok { + if writes++; writes == 1 { + if err := setValues(ctx, c, client.ObjectKeyFromObject(obj), fixed); err != nil { + return err + } + return conflict(obj.GetName()) + } + } + return c.Update(ctx, obj, opts...) + }} + }}, + {"unrelated edit after a conflict", `{"resources":{"memory":8},"other":true}`, `{"resources":{"memory":8},"other":true}`, false, func() interceptor.Funcs { + writes := 0 + return interceptor.Funcs{Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + if _, ok := obj.(*helmv2.HelmRelease); ok { + if writes++; writes == 1 { + return conflict(obj.GetName()) + } + } + return c.Update(ctx, obj, opts...) + }} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + app := &appsv1alpha1.Application{ + TypeMeta: metav1.TypeMeta{Kind: kubernetesKind, APIVersion: "apps.cozystack.io/v1alpha1"}, + ObjectMeta: metav1.ObjectMeta{Name: "good-name", Namespace: "tenant-foo"}, + Spec: &apiextv1.JSON{Raw: []byte(tc.next)}, + } + stored := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "kubernetes-" + app.Name, Namespace: app.Namespace, Labels: map[string]string{ + ApplicationKindLabel: kubernetesKind, ApplicationGroupLabel: appsv1alpha1.GroupName, ApplicationNameLabel: app.Name, + }}, Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(stale)}}} + r := newKubernetesWarnREST(t, stored) + r.specSchema = chartSpecSchema(t, "tcp-balancer") + r.c = interceptor.NewClient(r.w, tc.funcs()) + ctx := request.WithNamespace(context.Background(), app.Namespace) + _, _, err := r.Update(ctx, app.Name, newDefaultUpdatedObjectInfo(app), nil, nil, false, &metav1.UpdateOptions{}) + if tc.reject && !apierrors.IsInvalid(err) || !tc.reject && err != nil { + t.Fatalf("reject=%v, got %v", tc.reject, err) + } + got := &helmv2.HelmRelease{} + if err := r.w.Get(ctx, client.ObjectKeyFromObject(stored), got); err != nil { + t.Fatal(err) + } + if string(got.Spec.Values.Raw) != tc.want { + t.Fatalf("stored values %s, want %s", got.Spec.Values.Raw, tc.want) + } + }) + } +} diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 6cd544994..ca03e255a 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -193,6 +193,10 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation } } + if err := r.validateWorkloadMemory(app, nil); err != nil { + return nil, err + } + // Validate that values don't contain reserved keys (starting with "_") if err := validateNoInternalKeys(app.Spec); err != nil { return nil, apierrors.NewBadRequest(err.Error()) @@ -517,6 +521,7 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje return nil, false, err } + previousValues := oldObj.(*appsv1alpha1.Application).Spec.DeepCopy() previousFinalizers := slices.Clone(oldObj.(*appsv1alpha1.Application).Finalizers) // Update the Application object @@ -539,6 +544,10 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje // Update because Kubernetes names are immutable. Validating here would block // updates to pre-existing resources whose names don't conform to the new rules. + if err := r.validateWorkloadMemory(app, previousValues); err != nil { + return nil, false, err + } + // Validate that values don't contain reserved keys (starting with "_") if err := validateNoInternalKeys(app.Spec); err != nil { return nil, false, apierrors.NewBadRequest(err.Error()) @@ -594,6 +603,12 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje if helmRelease.ResourceVersion == "" { helmRelease.SetResourceVersion(cur.GetResourceVersion()) } + // The memory check above compared against the read at the start of Update. + // Compare again against the live release, so a stale value below 1Mi cannot + // overwrite memory that another writer has fixed since. + if err := r.validateWorkloadMemory(app, cur.Spec.Values); err != nil { + return nil, false, err + } r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers) // Suspension is not part of the Application, so the rebuilt object always @@ -634,6 +649,9 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje if getErr := r.c.Get(ctx, client.ObjectKey{Namespace: helmRelease.Namespace, Name: helmRelease.Name}, cur, &client.GetOptions{Raw: &metav1.GetOptions{}}); getErr != nil { return getErr } + if memErr := r.validateWorkloadMemory(app, cur.Spec.Values); memErr != nil { + return memErr + } helmRelease = converted.DeepCopy() r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers) helmRelease.SetResourceVersion(cur.GetResourceVersion())