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", 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/apps/redis/templates/redisfailover.yaml b/packages/apps/redis/templates/redisfailover.yaml index 417198f59..16732b79c 100644 --- a/packages/apps/redis/templates/redisfailover.yaml +++ b/packages/apps/redis/templates/redisfailover.yaml @@ -1,6 +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" -}} +{{- $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 @@ -79,6 +87,24 @@ spec: {{- if eq $sentinelReplicas 1 }} disablePodDisruptionBudget: true {{- end }} + {{- 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")))) (not (kindIs "invalid" .labelSelector))) | nindent 6 }} + {{- end }} + {{- 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 }} {{- with (.Values.affinity).sentinel }} affinity: {{- toYaml . | nindent 6 }} @@ -90,6 +116,22 @@ spec: affinity: {{- toYaml . | nindent 6 }} {{- end }} replicas: {{ .Values.replicas }} + {{- 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")))) (not (kindIs "invalid" .labelSelector))) | nindent 6 }} + {{- end }} + {{- 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..db6d7b0d2 --- /dev/null +++ b/packages/apps/redis/tests/topology_spread_test.yaml @@ -0,0 +1,286 @@ +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 + + - 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." + + - 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/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..e6046162a 100644 --- a/packages/apps/valkey/templates/valkeyfailover.yaml +++ b/packages/apps/valkey/templates/valkeyfailover.yaml @@ -1,3 +1,11 @@ +{{- $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 }} @@ -31,11 +39,45 @@ spec: engine: Valkey sentinel: replicas: 3 + {{- 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")))) (not (kindIs "invalid" .labelSelector))) | nindent 6 }} + {{- end }} + {{- 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 $spreadConstraints }} + topologySpreadConstraints: + {{- range $spreadConstraints }} + - {{- 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: + - 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..7ce3f90c0 --- /dev/null +++ b/packages/apps/valkey/tests/topology_spread_test.yaml @@ -0,0 +1,230 @@ +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 + + - 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." + + - 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/extra/gateway/README.md b/packages/extra/gateway/README.md index 37105e5ee..5682d2dc0 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. diff --git a/packages/system/harbor/templates/_helpers.tpl b/packages/system/harbor/templates/_helpers.tpl index 111f7585e..7d470bc4d 100644 --- a/packages/system/harbor/templates/_helpers.tpl +++ b/packages/system/harbor/templates/_helpers.tpl @@ -1,29 +1,31 @@ {{- /* Spread for the data tier: the cluster-wide scheduling.globalAppTopologySpreadConstraints when the platform sets one, as - the other applications do, otherwise a soft zone spread. Per-node spreading - is left to the anti-affinity CloudNativePG and the Redis operator apply by - default. Every entry is scoped to the given pod labels. + the other applications do, otherwise the defaults the caller passes. A + constraint without a selector of its own gets the given pod labels, because + kube-scheduler counts no pods for it otherwise; a selector the policy sets is + kept, as in the keycloak chart. - Takes (list ). + Takes (list ). */}} {{- define "harbor.topologySpreadConstraints" -}} {{- $root := index . 0 }} {{- $selector := dict "matchLabels" (index . 1) }} -{{- $raw := dig "scheduling" "globalAppTopologySpreadConstraints" "" ($root.Values._cluster | default dict) }} -{{- $constraints := list }} -{{- if $raw }} -{{- range (get ($raw | fromYaml) "topologySpreadConstraints" | default list) }} -{{- $constraints = append $constraints (omit . "labelSelector") }} -{{- end }} -{{- end }} -{{- if not $constraints }} -{{- $constraints = list (dict "maxSkew" 1 "topologyKey" "topology.kubernetes.io/zone" "whenUnsatisfiable" "ScheduleAnyway") }} +{{- $constraints := index . 2 }} +{{- with dig "scheduling" "globalAppTopologySpreadConstraints" "" ($root.Values._cluster | default dict) }} +{{- $policy := fromYaml . }} +{{- $constraints = dig "topologySpreadConstraints" (list) $policy }} +{{- if or (not (kindIs "slice" $constraints)) (not $constraints) }} +{{- fail (trim (printf "harbor: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list. %s" (get $policy "Error"))) }} +{{- end }} {{- end }} {{- $scoped := list }} {{- range $constraints }} -{{- $scoped = append $scoped (merge (dict "labelSelector" $selector) .) }} +{{- if kindIs "invalid" .labelSelector }} +{{- $scoped = append $scoped (merge (dict "labelSelector" $selector) (omit . "labelSelector")) }} +{{- else }} +{{- $scoped = append $scoped . }} +{{- end }} {{- end }} {{- toYaml $scoped }} {{- end }} - diff --git a/packages/system/harbor/templates/database.yaml b/packages/system/harbor/templates/database.yaml index 8b0c81beb..b985808a6 100644 --- a/packages/system/harbor/templates/database.yaml +++ b/packages/system/harbor/templates/database.yaml @@ -13,7 +13,7 @@ spec: instances off a shared node on a cluster that carries no zone labels. */}} {{- if gt (int .Values.db.replicas) 1 }} topologySpreadConstraints: - {{- include "harbor.topologySpreadConstraints" (list . (dict "cnpg.io/cluster" (printf "%s-db" .Values.harbor.fullnameOverride) "cnpg.io/podRole" "instance")) | nindent 2 }} + {{- include "harbor.topologySpreadConstraints" (list . (dict "cnpg.io/cluster" (printf "%s-db" .Values.harbor.fullnameOverride) "cnpg.io/podRole" "instance") (list (dict "maxSkew" 1 "topologyKey" "topology.kubernetes.io/zone" "whenUnsatisfiable" "ScheduleAnyway"))) | nindent 2 }} {{- end }} storage: size: {{ .Values.db.size }} diff --git a/packages/system/harbor/templates/redis.yaml b/packages/system/harbor/templates/redis.yaml index 217b537f6..3f4dd8167 100644 --- a/packages/system/harbor/templates/redis.yaml +++ b/packages/system/harbor/templates/redis.yaml @@ -27,13 +27,17 @@ spec: # bump it as a deliberate, separate change. image: redis:6.2.6-alpine replicas: 3 - {{- /* Setting affinity would replace the operator's default per-node - anti-affinity, so the zone spread goes through - topologySpreadConstraints instead and the two add up. The selector - leaves out redisfailovers-role, which flips between master and - slave at runtime. */}} + {{- /* Hard per node, because the operator's default anti-affinity is only + a preference and a drain can leave two of three sentinels on one + node, below quorum once it goes. pod-template-hash keeps a rollout's + outgoing sentinels out of the count. Soft across zones on top, so a + cluster without zone labels still schedules. The selector leaves + out redisfailovers-role, which flips between master and slave at + runtime. */}} + {{- $nodeSpread := dict "maxSkew" 1 "topologyKey" "kubernetes.io/hostname" "whenUnsatisfiable" "DoNotSchedule" "nodeTaintsPolicy" "Ignore" }} + {{- $zoneSpread := dict "maxSkew" 1 "topologyKey" "topology.kubernetes.io/zone" "whenUnsatisfiable" "ScheduleAnyway" }} topologySpreadConstraints: - {{- include "harbor.topologySpreadConstraints" (list . (dict "app.kubernetes.io/name" (printf "%s-redis" .Values.harbor.fullnameOverride) "app.kubernetes.io/component" "sentinel")) | nindent 4 }} + {{- include "harbor.topologySpreadConstraints" (list . (dict "app.kubernetes.io/name" (printf "%s-redis" .Values.harbor.fullnameOverride) "app.kubernetes.io/component" "sentinel") (list (merge (dict "matchLabelKeys" (list "pod-template-hash")) $nodeSpread) $zoneSpread)) | nindent 4 }} resources: limits: cpu: 250m @@ -46,10 +50,8 @@ 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 gt (int .Values.redis.replicas) 1 }} topologySpreadConstraints: - {{- include "harbor.topologySpreadConstraints" (list . (dict "app.kubernetes.io/name" (printf "%s-redis" .Values.harbor.fullnameOverride) "app.kubernetes.io/component" "redis")) | nindent 4 }} - {{- end }} + {{- include "harbor.topologySpreadConstraints" (list . (dict "app.kubernetes.io/name" (printf "%s-redis" .Values.harbor.fullnameOverride) "app.kubernetes.io/component" "redis") (list $nodeSpread $zoneSpread)) | nindent 4 }} 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..a57bd9d2d --- /dev/null +++ b/packages/system/harbor/tests/redis_spread_test.yaml @@ -0,0 +1,245 @@ +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, and prefers spreading them across zones + 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 + - 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: kubernetes.io/hostname + whenUnsatisfiable: DoNotSchedule + nodeTaintsPolicy: Ignore + 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: + 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 + + - 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." + + - 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: {} diff --git a/packages/system/harbor/tests/zone_spread_test.yaml b/packages/system/harbor/tests/zone_spread_test.yaml index 74f7922e1..5d33e4751 100644 --- a/packages/system/harbor/tests/zone_spread_test.yaml +++ b/packages/system/harbor/tests/zone_spread_test.yaml @@ -4,12 +4,12 @@ release: name: harbor-system namespace: tenant-test -# Both operators already keep replicas off a shared node. The spread follows -# the platform's globalAppTopologySpreadConstraints when one is set, and is a -# soft zone spread otherwise. It goes through topologySpreadConstraints so the -# operators' per-node default survives: -# overriding affinity on the RedisFailover, or moving CloudNativePG's -# topologyKey to the zone, would drop it on a cluster without zone labels. +# The spread follows the platform's globalAppTopologySpreadConstraints when one +# is set. Otherwise it is a soft zone spread, added through +# topologySpreadConstraints so the per-node placement survives: moving +# CloudNativePG's topologyKey to the zone would drop its per-node anti-affinity +# on a cluster without zone labels, and Redis keeps its hard per-node spread +# (redis_spread_test.yaml) underneath. set: harbor: fullnameOverride: harbor @@ -47,59 +47,34 @@ tests: - notExists: path: spec.topologySpreadConstraints - - it: spreads redis replicas across zones without replacing the operator's affinity + - it: spreads redis pods and sentinels softly across zones on top of the per-node spread template: templates/redis.yaml documentSelector: path: kind value: RedisFailover - set: - redis: - replicas: 3 asserts: - equal: - path: spec.redis.topologySpreadConstraints + path: spec.redis.topologySpreadConstraints[1] value: - - maxSkew: 1 - topologyKey: topology.kubernetes.io/zone - whenUnsatisfiable: ScheduleAnyway - labelSelector: - matchLabels: - app.kubernetes.io/name: harbor-redis - app.kubernetes.io/component: redis + maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-redis + app.kubernetes.io/component: redis + - equal: + path: spec.sentinel.topologySpreadConstraints[1] + value: + maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: harbor-redis + app.kubernetes.io/component: sentinel - notExists: path: spec.redis.affinity - - - it: leaves a single redis replica unconstrained - template: templates/redis.yaml - documentSelector: - path: kind - value: RedisFailover - set: - redis: - replicas: 1 - asserts: - - notExists: - path: spec.redis.topologySpreadConstraints - - - it: always spreads the three sentinels across zones - template: templates/redis.yaml - documentSelector: - path: kind - value: RedisFailover - set: - redis: - replicas: 1 - asserts: - - equal: - path: spec.sentinel.topologySpreadConstraints - value: - - maxSkew: 1 - topologyKey: topology.kubernetes.io/zone - whenUnsatisfiable: ScheduleAnyway - labelSelector: - matchLabels: - app.kubernetes.io/name: harbor-redis - app.kubernetes.io/component: sentinel - notExists: path: spec.sentinel.affinity @@ -137,14 +112,11 @@ tests: cnpg.io/cluster: harbor-db cnpg.io/podRole: instance - # A selector written into the platform-wide policy cannot know this - # release's pods, so it is replaced rather than kept. - - it: scopes the cluster-wide spread policy to the sentinels - template: templates/redis.yaml - documentSelector: - path: kind - value: RedisFailover + - it: keeps a selector the cluster-wide policy sets for the database + template: templates/database.yaml set: + db: + replicas: 3 _cluster: scheduling: globalAppTopologySpreadConstraints: | @@ -154,18 +126,13 @@ tests: whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: - foo: bar + example.org/spread: all asserts: - equal: - path: spec.sentinel.topologySpreadConstraints + path: spec.topologySpreadConstraints[0].labelSelector value: - - maxSkew: 1 - topologyKey: topology.kubernetes.io/zone - whenUnsatisfiable: DoNotSchedule - labelSelector: - matchLabels: - app.kubernetes.io/name: harbor-redis - app.kubernetes.io/component: sentinel + matchLabels: + example.org/spread: all # The values below are what packages/apps/harbor forwards for nginx.replicas: 2. # The API server rejects a PDB that sets both minAvailable and maxUnavailable, diff --git a/packages/system/linstor/templates/cluster.yaml b/packages/system/linstor/templates/cluster.yaml index 8d5eb751d..72ac70493 100644 --- a/packages/system/linstor/templates/cluster.yaml +++ b/packages/system/linstor/templates/cluster.yaml @@ -138,6 +138,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: diff --git a/packages/system/monitoring/templates/_scheduling.tpl b/packages/system/monitoring/templates/_scheduling.tpl new file mode 100644 index 000000000..e7358c5c6 --- /dev/null +++ b/packages/system/monitoring/templates/_scheduling.tpl @@ -0,0 +1,26 @@ +{{- 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" -}} +{{- $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 -}} +{{- range $global -}} +{{- $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 -}} +{{- 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 51dae0411..3199c9b69 100644 --- a/packages/system/monitoring/templates/alerta/alerta.yaml +++ b/packages/system/monitoring/templates/alerta/alerta.yaml @@ -441,6 +441,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_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 new file mode 100644 index 000000000..14a20da21 --- /dev/null +++ b/packages/system/monitoring/tests/topology_spread_test.yaml @@ -0,0 +1,453 @@ +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 + + - 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 + + - 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 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..60816a43d 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" @@ -193,6 +194,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 +522,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 +545,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 +604,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 +650,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()) @@ -673,9 +692,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 +724,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 +762,46 @@ 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 +} + +// 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 func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) { namespace, err := r.getNamespace(ctx) @@ -862,6 +941,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 @@ -871,7 +961,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 +990,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 +1136,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 +1195,39 @@ 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{} + // Nothing replays a monitor event this watch drops, so a + // transient failure of the live read is retried briefly. + // A missing release is final. + 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 <-liveCtx.Done(): + case <-time.After(liveReleaseReadRetryDelay): + } + 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) + continue + } } // Pass the fresh WorkloadMonitor so conversion uses the latest // operational status even if the cache (r.c) has not yet @@ -1094,10 +1248,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 +1258,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_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) + } + }) + }) + } +} 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..06640d72e --- /dev/null +++ b/pkg/registry/apps/application/rest_watch_rv_test.go @@ -0,0 +1,633 @@ +package application + +import ( + "context" + "encoding/json" + "errors" + "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 + // liveReleaseErrs are returned by the next live HelmRelease reads, one + // per read, before reads reach the store again. + 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 + // 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"} + +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++ + if f.liveReleaseHang { + <-ctx.Done() + return ctx.Err() + } + 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 + } + } + 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.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...) + }, + }) + 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) + } +} + +// 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) + } +} + +// 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 + timeout := errors.New("etcdserver: request timed out") + for range liveReleaseReadAttempts { + 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) + 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 TestWatchStopAtFailedLiveReadPreventsRetry(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + stopAtFailedLiveRead(t, f, w, w.Stop) +} + +func TestWatchContextCancelAtFailedLiveReadPreventsRetry(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) + stopAtFailedLiveRead(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) + _, 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},