mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-05 14:42:05 +09:00
fix(redis): let the operator delete a disabled Sentinel PDB instead of a per-upgrade hook (#5429)
## What this PR does When a Redis instance runs a single pod, the chart runs one Sentinel and sets `disablePodDisruptionBudget` on it. The redis-operator stops ensuring the Sentinel PDB once that flag is set, but never deletes the PDB it created earlier, and the PDB's owner reference only removes it together with the RedisFailover. An instance scaled down from three pods therefore keeps a `minAvailable: 1` PDB on its only Sentinel, and every node drain blocks on it. The chart worked around this with a post-upgrade Helm hook: a ServiceAccount, a Role, a RoleBinding and a kubectl Job, rendered on every upgrade of every single-replica instance, to delete a PDB the operator should have removed itself. The operator image is already built in this repository with carried patches, so I fixed it there instead. - `redis-operator`: a new source patch makes the operator look the Sentinel or Redis PDB up on reconcile while its `disablePodDisruptionBudget` is set, and delete it only when the RedisFailover is its controller. A PDB without that owner is left alone, no delete is sent when there is no PDB, and one that disappears between the lookup and the delete counts as done. It has a unit test next to the operator's own `EnsureSentinelDeployment` tests, which the image build runs for every package a patch touches. The patch header says it is carried until an upstream release includes the change. - `redis`: the hook, its RBAC, its chart tests and the `redis.sentinelReplicas` helper extracted for it are removed. The single-Sentinel change and its tests stay as they were. - e2e: the base Redis case now scales its instance from two replicas to one and asserts that `rfs-<name>` existed before and is gone after, and that the data pods' PDB stays. Upgrade: an instance that still has the stale PDB loses it on the first reconcile by the updated operator, which resyncs every RedisFailover every 30 seconds. Until the operator Deployment rolls, the PDB stays, so drains on such an instance can block for that window. Hook objects from earlier upgrades are not release resources, so Helm does not touch them; the successful runs already deleted theirs through `hook-succeeded`. A run that failed leaves its ServiceAccount, Role and RoleBinding named `<release>-sentinel-pdb` behind (its Job goes after an hour through `ttlSecondsAfterFinished`). They grant only get and delete on one PDB and can be removed by hand. Cost: while a PDB is disabled, every reconcile (on each RedisFailover change and on the 30-second resync) reads it once from the API server; a delete is sent only when an owned PDB is still there. I have not run the image build or the e2e suite. The patch series applies on the v3.3.5 tarball, alone and together with the operator patch of the open draft #5382, and every package it touches passes `go test` and `go vet -tags integration`. `helm unittest packages/apps/redis` passes. Upstream v3.3.5 is the latest release and its master still has the same code, so there is no version to bump to; a version of the patch rebased onto upstream master, without the `tlsHash` parameter the carried TLS patch adds, is open as freshworks-oss/redis-operator#93, and the patch header links to it. ### Screenshots Not a UI change. ### Downstream repositories - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: No values key, schema, README or version enum changes; the diff touches an image patch, chart templates and tests, and the Redis e2e suite only. ### Release note ```release-note fix(redis): the redis-operator now deletes the Sentinel or Redis PodDisruptionBudget it created once that budget is disabled, so a Redis scaled down to one replica no longer keeps the Sentinel PDB that blocks node drains, and the chart no longer runs a cleanup Job with its own RBAC on every upgrade of a single-replica instance. ``` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Redis and Sentinel PodDisruptionBudgets are removed when their respective settings disable management, provided they are owned by the RedisFailover. Missing or unrelated budgets are left unchanged. * Sentinel replica counts remain at one when Redis is configured with one replica, and three otherwise. * When switching to one Sentinel replica with PDB management disabled, the Sentinel budget is removed while the data-pod budget remains. The Helm release is then verified as ready. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
7 files changed
+365
-284
No files matched your search
@@ -13,6 +13,12 @@ spec:
|
||||
- podLogs:
|
||||
selector: app.kubernetes.io/instance=redis-test
|
||||
tail: 50
|
||||
# The scale-down step waits on the operator deleting a PDB, which leaves its
|
||||
# trace in the operator's log and nowhere in the tenant namespace.
|
||||
- podLogs:
|
||||
namespace: cozy-redis-operator
|
||||
selector: app.kubernetes.io/name=redis-operator
|
||||
tail: 100
|
||||
steps:
|
||||
- name: create-redis
|
||||
try:
|
||||
@@ -74,6 +80,68 @@ spec:
|
||||
name: rfr-redis-test
|
||||
status:
|
||||
readyReplicas: 2
|
||||
|
||||
# One replica runs one Sentinel with its PDB disabled. The PDB the operator
|
||||
# created for the three Sentinels of two replicas has to go with it, or its
|
||||
# minAvailable: 1 pins the only Sentinel against every eviction.
|
||||
- name: scale-down-drops-sentinel-pdb
|
||||
try:
|
||||
# Positive control: the absence asserted below is also what an operator
|
||||
# that never created the PDB looks like.
|
||||
- assert:
|
||||
timeout: 2m
|
||||
resource:
|
||||
apiVersion: policy/v1
|
||||
kind: PodDisruptionBudget
|
||||
metadata:
|
||||
name: rfs-redis-test
|
||||
- apply:
|
||||
file: redis-single.yaml
|
||||
# The upgraded chart reaching the RedisFailover is what starts the
|
||||
# operator's part; asserting it first tells a chart that never disabled
|
||||
# the PDB apart from an operator that left it behind.
|
||||
- assert:
|
||||
timeout: 5m
|
||||
resource:
|
||||
apiVersion: databases.spotahome.com/v1
|
||||
kind: RedisFailover
|
||||
metadata:
|
||||
name: redis-test
|
||||
spec:
|
||||
sentinel:
|
||||
replicas: 1
|
||||
disablePodDisruptionBudget: true
|
||||
# 2m: a RedisFailover change triggers a reconcile, and the operator
|
||||
# resyncs every 30s besides.
|
||||
- error:
|
||||
timeout: 2m
|
||||
resource:
|
||||
apiVersion: policy/v1
|
||||
kind: PodDisruptionBudget
|
||||
metadata:
|
||||
name: rfs-redis-test
|
||||
# The data pods' PDB is still enabled and must stay.
|
||||
- assert:
|
||||
timeout: 1m
|
||||
resource:
|
||||
apiVersion: policy/v1
|
||||
kind: PodDisruptionBudget
|
||||
metadata:
|
||||
name: rfr-redis-test
|
||||
# The upgrade holds the release until the StatefulSet has scaled, and
|
||||
# cleanup cannot uninstall it before then. Same 11m as the install wait;
|
||||
# matching generations keep the Ready left from the install from passing.
|
||||
- assert:
|
||||
timeout: 11m
|
||||
resource:
|
||||
apiVersion: helm.toolkit.fluxcd.io/v2
|
||||
kind: HelmRelease
|
||||
metadata:
|
||||
name: redis-test
|
||||
(status.observedGeneration == metadata.generation): true
|
||||
status:
|
||||
(conditions[?type == 'Ready']):
|
||||
- status: "True"
|
||||
---
|
||||
# TLS on. Everything the unit tests can only render runs live here: the
|
||||
# rebuilt operator with the TLS patch, the CRD and ClusterRole patches on its
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
apiVersion: apps.cozystack.io/v1alpha1
|
||||
kind: Redis
|
||||
metadata:
|
||||
name: test
|
||||
spec:
|
||||
external: false
|
||||
size: 1Gi
|
||||
replicas: 1
|
||||
storageClass: ""
|
||||
authEnabled: true
|
||||
resources: {}
|
||||
resourcesPreset: "nano"
|
||||
@@ -47,7 +47,3 @@ These presets are for basic testing and not meant to be used in production
|
||||
{{- printf "ERROR: Preset key '%s' invalid. Allowed values are %s" .type (join "," (keys $presets)) | fail -}}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "redis.sentinelReplicas" -}}
|
||||
{{- ternary 1 3 (eq (int .Values.replicas) 1) -}}
|
||||
{{- end -}}
|
||||
@@ -1,122 +0,0 @@
|
||||
{{- /*
|
||||
An instance scaled down to one Redis pod keeps the Sentinel PDB the operator
|
||||
created while it ran three Sentinels: setting disablePodDisruptionBudget only
|
||||
stops the operator from ensuring it, never deletes it, and minAvailable 1 on
|
||||
a single Sentinel refuses every eviction. A fresh install with one replica
|
||||
never gets that PDB, so this runs on upgrade only.
|
||||
*/}}
|
||||
{{- if and .Release.IsUpgrade (eq (include "redis.sentinelReplicas" . | int) 1) }}
|
||||
{{- $name := printf "%s-sentinel-pdb" .Release.Name }}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: {{ $name }}
|
||||
labels:
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
annotations:
|
||||
helm.sh/hook: post-upgrade
|
||||
helm.sh/hook-weight: "0"
|
||||
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: Role
|
||||
metadata:
|
||||
name: {{ $name }}
|
||||
labels:
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
annotations:
|
||||
helm.sh/hook: post-upgrade
|
||||
helm.sh/hook-weight: "0"
|
||||
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
|
||||
rules:
|
||||
- apiGroups: ["policy"]
|
||||
resources: ["poddisruptionbudgets"]
|
||||
resourceNames: ["rfs-{{ .Release.Name }}"]
|
||||
verbs: ["get", "delete"]
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: {{ $name }}
|
||||
labels:
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
annotations:
|
||||
helm.sh/hook: post-upgrade
|
||||
helm.sh/hook-weight: "0"
|
||||
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: Role
|
||||
name: {{ $name }}
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: {{ $name }}
|
||||
namespace: {{ .Release.Namespace }}
|
||||
---
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
{{- /* The API server copies a Job's name into its pods' job-name label,
|
||||
which takes 63 characters at most, while a release name may take 53.
|
||||
The objects above have no such limit and keep the full name. */}}
|
||||
name: {{ $name | trunc 63 | trimSuffix "-" }}
|
||||
labels:
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
annotations:
|
||||
helm.sh/hook: post-upgrade
|
||||
helm.sh/hook-weight: "5"
|
||||
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
|
||||
spec:
|
||||
ttlSecondsAfterFinished: 3600
|
||||
# Bounds the kubectl call too: a --request-timeout would make kubectl skip
|
||||
# its in-cluster credentials (hack/check-hook-request-timeout.bats).
|
||||
activeDeadlineSeconds: 120
|
||||
backoffLimit: 2
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
policy.cozystack.io/allow-to-apiserver: "true"
|
||||
spec:
|
||||
serviceAccountName: {{ $name }}
|
||||
restartPolicy: Never
|
||||
terminationGracePeriodSeconds: 10
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 65534
|
||||
runAsGroup: 65534
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: delete-pdb
|
||||
image: '{{ include "cozy-lib.image" (list "clastix/kubectl:v1.32@sha256:b9ef7d8dbe65bcc81a46c09b8dc7543103055021c4f43287bf59e92a8f4fe05c" $) }}'
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
resources:
|
||||
requests:
|
||||
cpu: 10m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 200m
|
||||
memory: 128Mi
|
||||
env:
|
||||
- name: HOME
|
||||
value: /tmp
|
||||
command:
|
||||
- kubectl
|
||||
- --namespace={{ .Release.Namespace }}
|
||||
- delete
|
||||
- poddisruptionbudget
|
||||
- rfs-{{ .Release.Name }}
|
||||
- --ignore-not-found=true
|
||||
volumeMounts:
|
||||
- name: tmp
|
||||
mountPath: /tmp
|
||||
volumes:
|
||||
- name: tmp
|
||||
emptyDir: {}
|
||||
{{- end }}
|
||||
@@ -22,11 +22,9 @@
|
||||
watch it. One Sentinel still lets the operator find the master (its quorum is
|
||||
replicas/2+1, so 1). The operator gives the Sentinel Deployment a PDB with
|
||||
minAvailable 1 whenever Redis has two replicas or fewer, which on a single
|
||||
Sentinel would block every node drain, so that PDB is dropped with it; the
|
||||
operator does not delete a PDB it stops managing, hence
|
||||
hooks/sentinel-pdb.yaml.
|
||||
Sentinel would block every node drain, so that PDB is dropped with it.
|
||||
*/}}
|
||||
{{- $sentinelReplicas := include "redis.sentinelReplicas" . | int -}}
|
||||
{{- $sentinelReplicas := ternary 1 3 (eq (int .Values.replicas) 1) -}}
|
||||
{{- $sentinelPreset := $sentinel.resourcesPreset | default .Values.resourcesPreset -}}
|
||||
{{- $sentinelResources := .Values.resources -}}
|
||||
{{- if or $sentinel.resources $sentinel.resourcesPreset -}}
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
suite: stale Sentinel PDB removed on scale-down to one Redis pod
|
||||
|
||||
# The operator only stops ensuring the Sentinel PDB once
|
||||
# disablePodDisruptionBudget is set; it never deletes the one it created while
|
||||
# three Sentinels ran. Left in place, its minAvailable 1 refuses every eviction
|
||||
# of the single Sentinel and blocks node drains.
|
||||
|
||||
templates:
|
||||
- templates/hooks/sentinel-pdb.yaml
|
||||
|
||||
release:
|
||||
name: my-redis
|
||||
namespace: tenant-test
|
||||
|
||||
set:
|
||||
_cluster:
|
||||
cluster-domain: cluster.local
|
||||
_namespace:
|
||||
host: example.com
|
||||
|
||||
tests:
|
||||
- it: deletes the operator's Sentinel PDB on an upgrade to one replica
|
||||
release:
|
||||
upgrade: true
|
||||
set:
|
||||
replicas: 1
|
||||
documentSelector:
|
||||
path: kind
|
||||
value: Job
|
||||
asserts:
|
||||
- equal:
|
||||
path: metadata.annotations["helm.sh/hook"]
|
||||
value: post-upgrade
|
||||
- equal:
|
||||
path: spec.template.spec.containers[0].command
|
||||
value:
|
||||
- kubectl
|
||||
- --namespace=tenant-test
|
||||
- delete
|
||||
- poddisruptionbudget
|
||||
- rfs-my-redis
|
||||
- --ignore-not-found=true
|
||||
- notMatchRegex:
|
||||
path: spec.template.spec.containers[0].command[4]
|
||||
pattern: request-timeout
|
||||
|
||||
- it: lets the hook delete only that PDB
|
||||
release:
|
||||
upgrade: true
|
||||
set:
|
||||
replicas: 1
|
||||
documentSelector:
|
||||
path: kind
|
||||
value: Role
|
||||
asserts:
|
||||
- equal:
|
||||
path: rules
|
||||
value:
|
||||
- apiGroups: ["policy"]
|
||||
resources: ["poddisruptionbudgets"]
|
||||
resourceNames: ["rfs-my-redis"]
|
||||
verbs: ["get", "delete"]
|
||||
|
||||
- it: renders nothing on install, where no such PDB exists
|
||||
set:
|
||||
replicas: 1
|
||||
asserts:
|
||||
- hasDocuments:
|
||||
count: 0
|
||||
|
||||
- it: renders nothing while three Sentinels run
|
||||
release:
|
||||
upgrade: true
|
||||
set:
|
||||
replicas: 2
|
||||
asserts:
|
||||
- hasDocuments:
|
||||
count: 0
|
||||
|
||||
# The operator runs three Redis pods for a zero or negative count, so their
|
||||
# Sentinel PDB stays.
|
||||
- it: renders nothing for a zero replica count
|
||||
release:
|
||||
upgrade: true
|
||||
set:
|
||||
replicas: 0
|
||||
asserts:
|
||||
- hasDocuments:
|
||||
count: 0
|
||||
|
||||
- it: renders nothing for a negative replica count
|
||||
release:
|
||||
upgrade: true
|
||||
set:
|
||||
replicas: -1
|
||||
asserts:
|
||||
- hasDocuments:
|
||||
count: 0
|
||||
|
||||
# The pods' job-name label takes 63 characters at most; a 53-character
|
||||
# release name plus -sentinel-pdb would pass it and Kubernetes would refuse
|
||||
# the Job, leaving the stale PDB in place.
|
||||
- it: keeps the Job name within 63 characters for the longest release name
|
||||
release:
|
||||
name: redis-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
upgrade: true
|
||||
set:
|
||||
replicas: 1
|
||||
documentSelector:
|
||||
path: kind
|
||||
value: Job
|
||||
asserts:
|
||||
- matchRegex:
|
||||
path: metadata.name
|
||||
pattern: ^[a-z0-9-]{1,63}$
|
||||
- matchRegex:
|
||||
path: metadata.name
|
||||
pattern: '[a-z0-9]$'
|
||||
# The full release name stays in the Job name, so the hooks of two
|
||||
# releases in one namespace never replace each other's Job.
|
||||
- matchRegex:
|
||||
path: metadata.name
|
||||
pattern: ^redis-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-
|
||||
- equal:
|
||||
path: spec.template.spec.containers[0].command[4]
|
||||
value: rfs-redis-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
|
||||
- it: lets the hook delete the Sentinel PDB of the longest release name
|
||||
release:
|
||||
name: redis-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
upgrade: true
|
||||
set:
|
||||
replicas: 1
|
||||
documentSelector:
|
||||
path: kind
|
||||
value: Role
|
||||
asserts:
|
||||
- equal:
|
||||
path: rules[0].resourceNames
|
||||
value:
|
||||
- rfs-redis-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
|
||||
- it: keeps the full Job name for a short release name
|
||||
release:
|
||||
upgrade: true
|
||||
set:
|
||||
replicas: 1
|
||||
documentSelector:
|
||||
path: kind
|
||||
value: Job
|
||||
asserts:
|
||||
- equal:
|
||||
path: metadata.name
|
||||
value: my-redis-sentinel-pdb
|
||||
@@ -0,0 +1,283 @@
|
||||
# Downstream carry: the operator deletes the Sentinel or Redis PDB it created
|
||||
# once disablePodDisruptionBudget is set for that component. v3.3.5 only stops
|
||||
# ensuring the PDB, and its owner reference removes it only together with the
|
||||
# RedisFailover, so an instance scaled down to one Sentinel keeps a
|
||||
# minAvailable: 1 PDB that blocks every drain. A PDB this RedisFailover does
|
||||
# not control is left alone, and no delete is sent when there is no PDB.
|
||||
#
|
||||
# Its context includes the tlsHash parameter tls.diff adds, so it applies
|
||||
# after that patch. Retire it when a release carrying the upstream pull
|
||||
# request lands.
|
||||
#
|
||||
# Upstream: https://github.com/freshworks-oss/redis-operator/pull/93
|
||||
diff --git a/mocks/service/k8s/Services.go b/mocks/service/k8s/Services.go
|
||||
index 142eaeef44d0..8162d06b9c8a 100644
|
||||
--- a/mocks/service/k8s/Services.go
|
||||
+++ b/mocks/service/k8s/Services.go
|
||||
@@ -431,17 +431,17 @@ func (_m *Services) DeletePod(namespace string, name string) error {
|
||||
return r0
|
||||
}
|
||||
|
||||
-// DeletePodDisruptionBudget provides a mock function with given fields: namespace, name
|
||||
-func (_m *Services) DeletePodDisruptionBudget(namespace string, name string) error {
|
||||
- ret := _m.Called(namespace, name)
|
||||
+// DeletePodDisruptionBudget provides a mock function with given fields: namespace, name, options
|
||||
+func (_m *Services) DeletePodDisruptionBudget(namespace string, name string, options metav1.DeleteOptions) error {
|
||||
+ ret := _m.Called(namespace, name, options)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for DeletePodDisruptionBudget")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
- if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
- r0 = rf(namespace, name)
|
||||
+ if rf, ok := ret.Get(0).(func(string, string, metav1.DeleteOptions) error); ok {
|
||||
+ r0 = rf(namespace, name, options)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
diff --git a/operator/redisfailover/service/client.go b/operator/redisfailover/service/client.go
|
||||
index b83ba64e1151..50638f81fe61 100644
|
||||
--- a/operator/redisfailover/service/client.go
|
||||
+++ b/operator/redisfailover/service/client.go
|
||||
@@ -116,10 +116,12 @@ func (r *RedisFailoverKubeClient) EnsureSentinelConfigMap(rf *redisfailoverv1.Re
|
||||
// EnsureSentinelDeployment makes sure the sentinel deployment exists in the desired state.
|
||||
// tlsHash is stamped on the pod template so a renewed TLS Secret rolls the pods.
|
||||
func (r *RedisFailoverKubeClient) EnsureSentinelDeployment(rf *redisfailoverv1.RedisFailover, labels map[string]string, ownerRefs []metav1.OwnerReference, tlsHash string) error {
|
||||
- if !rf.Spec.Sentinel.DisablePodDisruptionBudget {
|
||||
- if err := r.ensurePodDisruptionBudget(rf, sentinelName, sentinelRoleName, labels, ownerRefs); err != nil {
|
||||
+ if rf.Spec.Sentinel.DisablePodDisruptionBudget {
|
||||
+ if err := r.ensureNotPresentPodDisruptionBudget(rf, sentinelName); err != nil {
|
||||
return err
|
||||
}
|
||||
+ } else if err := r.ensurePodDisruptionBudget(rf, sentinelName, sentinelRoleName, labels, ownerRefs); err != nil {
|
||||
+ return err
|
||||
}
|
||||
d := generateSentinelDeployment(rf, labels, ownerRefs, tlsHash)
|
||||
err := r.K8SService.CreateOrUpdateDeployment(rf.Namespace, d)
|
||||
@@ -131,10 +133,12 @@ func (r *RedisFailoverKubeClient) EnsureSentinelDeployment(rf *redisfailoverv1.R
|
||||
// EnsureRedisStatefulset makes sure the redis statefulset exists in the desired state.
|
||||
// tlsHash is stamped on the pod template so a renewed TLS Secret rolls the pods.
|
||||
func (r *RedisFailoverKubeClient) EnsureRedisStatefulset(rf *redisfailoverv1.RedisFailover, labels map[string]string, ownerRefs []metav1.OwnerReference, tlsHash string) error {
|
||||
- if !rf.Spec.Redis.DisablePodDisruptionBudget {
|
||||
- if err := r.ensurePodDisruptionBudget(rf, redisName, redisRoleName, labels, ownerRefs); err != nil {
|
||||
+ if rf.Spec.Redis.DisablePodDisruptionBudget {
|
||||
+ if err := r.ensureNotPresentPodDisruptionBudget(rf, redisName); err != nil {
|
||||
return err
|
||||
}
|
||||
+ } else if err := r.ensurePodDisruptionBudget(rf, redisName, redisRoleName, labels, ownerRefs); err != nil {
|
||||
+ return err
|
||||
}
|
||||
|
||||
// Check and validate StatefulSet before creation/update
|
||||
@@ -412,6 +416,31 @@ func (r *RedisFailoverKubeClient) ensurePodDisruptionBudget(rf *redisfailoverv1.
|
||||
return err
|
||||
}
|
||||
|
||||
+// ensureNotPresentPodDisruptionBudget deletes the PDB a previous reconcile
|
||||
+// created: its owner reference removes it only with the RedisFailover, so
|
||||
+// disabling the PDB would otherwise leave the last one in force. A PDB this
|
||||
+// RedisFailover does not control was not created by the operator and stays.
|
||||
+func (r *RedisFailoverKubeClient) ensureNotPresentPodDisruptionBudget(rf *redisfailoverv1.RedisFailover, name string) error {
|
||||
+ name = generateName(name, rf.Name)
|
||||
+ pdb, err := r.K8SService.GetPodDisruptionBudget(rf.Namespace, name)
|
||||
+ if apierrors.IsNotFound(err) {
|
||||
+ return nil
|
||||
+ }
|
||||
+ if err != nil {
|
||||
+ return err
|
||||
+ }
|
||||
+ if !metav1.IsControlledBy(pdb, rf) {
|
||||
+ return nil
|
||||
+ }
|
||||
+ err = r.K8SService.DeletePodDisruptionBudget(rf.Namespace, name, metav1.DeleteOptions{
|
||||
+ Preconditions: &metav1.Preconditions{UID: &pdb.UID, ResourceVersion: &pdb.ResourceVersion},
|
||||
+ })
|
||||
+ if apierrors.IsNotFound(err) {
|
||||
+ return nil
|
||||
+ }
|
||||
+ return err
|
||||
+}
|
||||
+
|
||||
func (r *RedisFailoverKubeClient) setEnsureOperationMetrics(objectNamespace string, objectName string, objectKind string, ownerName string, err error) {
|
||||
if nil != err {
|
||||
r.metricsClient.RecordEnsureOperation(objectNamespace, objectName, objectKind, ownerName, metrics.FAIL)
|
||||
diff --git a/operator/redisfailover/service/generator_test.go b/operator/redisfailover/service/generator_test.go
|
||||
index 39bbcfdd6f02..173a5f68f8cb 100644
|
||||
--- a/operator/redisfailover/service/generator_test.go
|
||||
+++ b/operator/redisfailover/service/generator_test.go
|
||||
@@ -8,10 +8,12 @@ import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
appsv1 "k8s.io/api/apps/v1"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
+ policyv1 "k8s.io/api/policy/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
"k8s.io/apimachinery/pkg/api/resource"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
+ "k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/intstr"
|
||||
|
||||
redisfailoverv1 "github.com/freshworks/redis-operator/api/redisfailover/v1"
|
||||
@@ -2926,3 +2928,85 @@ func TestDisableMyMaster(t *testing.T) {
|
||||
assert.Equal(test.expectedRedisShutdownSHScriptConfigMap.Data, generatedRedisConfigMap.Data)
|
||||
}
|
||||
}
|
||||
+
|
||||
+func TestDisabledPodDisruptionBudgetIsDeleted(t *testing.T) {
|
||||
+ notFound := errors.NewNotFound(schema.GroupResource{}, "")
|
||||
+ isController := true
|
||||
+ pdbOwnedBy := func(uid string) *policyv1.PodDisruptionBudget {
|
||||
+ return &policyv1.PodDisruptionBudget{ObjectMeta: metav1.ObjectMeta{
|
||||
+ UID: "pdb-uid", ResourceVersion: "42",
|
||||
+ OwnerReferences: []metav1.OwnerReference{{UID: types.UID(uid), Controller: &isController}},
|
||||
+ }}
|
||||
+ }
|
||||
+ tests := []struct {
|
||||
+ name string
|
||||
+ stored *policyv1.PodDisruptionBudget
|
||||
+ getErr error
|
||||
+ wantDelete bool
|
||||
+ deleteErr error
|
||||
+ wantErr bool
|
||||
+ }{
|
||||
+ {name: "owned PDB is deleted", stored: pdbOwnedBy("rf-uid"), wantDelete: true},
|
||||
+ {name: "PDB without an owner is kept", stored: &policyv1.PodDisruptionBudget{}},
|
||||
+ {name: "PDB with a foreign owner is kept", stored: pdbOwnedBy("other-uid")},
|
||||
+ {name: "absent PDB is not deleted", getErr: notFound},
|
||||
+ {name: "PDB gone before the delete is not an error", stored: pdbOwnedBy("rf-uid"), wantDelete: true, deleteErr: notFound},
|
||||
+ {name: "changed PDB returns a conflict", stored: pdbOwnedBy("rf-uid"), wantDelete: true, deleteErr: errors.NewConflict(schema.GroupResource{Resource: "poddisruptionbudgets"}, "rfs-test", fmt.Errorf("precondition failed")), wantErr: true},
|
||||
+ }
|
||||
+
|
||||
+ for _, test := range tests {
|
||||
+ t.Run(test.name, func(t *testing.T) {
|
||||
+ rf := generateRF()
|
||||
+ rf.UID = "rf-uid"
|
||||
+ rf.Spec.Sentinel.DisablePodDisruptionBudget = true
|
||||
+ rf.Spec.Redis.DisablePodDisruptionBudget = true
|
||||
+
|
||||
+ ms := &mK8SService.Services{}
|
||||
+ for _, pdbName := range []string{sentinelName, redisName} {
|
||||
+ ms.On("GetPodDisruptionBudget", namespace, pdbName).Once().Return(test.stored, test.getErr)
|
||||
+ if test.wantDelete {
|
||||
+ ms.On("DeletePodDisruptionBudget", namespace, pdbName, metav1.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &test.stored.UID, ResourceVersion: &test.stored.ResourceVersion}}).Once().Return(test.deleteErr)
|
||||
+ }
|
||||
+ }
|
||||
+ if !test.wantErr {
|
||||
+ ms.On("GetStatefulSet", namespace, mock.Anything).Once().Return(nil, notFound)
|
||||
+ ms.On("CreateOrUpdateDeployment", namespace, mock.Anything).Once().Return(nil)
|
||||
+ ms.On("CreateOrUpdateStatefulSet", namespace, mock.Anything).Once().Return(nil)
|
||||
+ }
|
||||
+
|
||||
+ client := rfservice.NewRedisFailoverKubeClient(ms, log.Dummy, metrics.Dummy, "cluster.local")
|
||||
+ sentinelErr := client.EnsureSentinelDeployment(rf, nil, []metav1.OwnerReference{}, "")
|
||||
+ redisErr := client.EnsureRedisStatefulset(rf, nil, []metav1.OwnerReference{}, "")
|
||||
+ if test.wantErr {
|
||||
+ assert.ErrorIs(t, sentinelErr, test.deleteErr)
|
||||
+ assert.ErrorIs(t, redisErr, test.deleteErr)
|
||||
+ } else {
|
||||
+ assert.NoError(t, sentinelErr)
|
||||
+ assert.NoError(t, redisErr)
|
||||
+ }
|
||||
+ ms.AssertExpectations(t)
|
||||
+ if !test.wantDelete {
|
||||
+ ms.AssertNotCalled(t, "DeletePodDisruptionBudget", mock.Anything, mock.Anything, mock.Anything)
|
||||
+ }
|
||||
+ })
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+func TestDisabledPodDisruptionBudgetLookupErrorIsReturned(t *testing.T) {
|
||||
+ forbidden := errors.NewForbidden(schema.GroupResource{Resource: "poddisruptionbudgets"}, "rfs-test", fmt.Errorf("denied"))
|
||||
+ rf := generateRF()
|
||||
+ rf.Spec.Sentinel.DisablePodDisruptionBudget = true
|
||||
+ rf.Spec.Redis.DisablePodDisruptionBudget = true
|
||||
+
|
||||
+ ms := &mK8SService.Services{}
|
||||
+ ms.On("GetPodDisruptionBudget", namespace, sentinelName).Once().Return(nil, forbidden)
|
||||
+ ms.On("GetPodDisruptionBudget", namespace, redisName).Once().Return(nil, forbidden)
|
||||
+
|
||||
+ client := rfservice.NewRedisFailoverKubeClient(ms, log.Dummy, metrics.Dummy, "cluster.local")
|
||||
+ assert.ErrorIs(t, client.EnsureSentinelDeployment(rf, nil, []metav1.OwnerReference{}, ""), forbidden)
|
||||
+ assert.ErrorIs(t, client.EnsureRedisStatefulset(rf, nil, []metav1.OwnerReference{}, ""), forbidden)
|
||||
+ ms.AssertExpectations(t)
|
||||
+ ms.AssertNotCalled(t, "DeletePodDisruptionBudget", mock.Anything, mock.Anything, mock.Anything)
|
||||
+ ms.AssertNotCalled(t, "CreateOrUpdateDeployment", mock.Anything, mock.Anything)
|
||||
+ ms.AssertNotCalled(t, "CreateOrUpdateStatefulSet", mock.Anything, mock.Anything)
|
||||
+}
|
||||
diff --git a/service/k8s/poddisruptionbudget.go b/service/k8s/poddisruptionbudget.go
|
||||
index 7aff70708946..e9592405ed3c 100644
|
||||
--- a/service/k8s/poddisruptionbudget.go
|
||||
+++ b/service/k8s/poddisruptionbudget.go
|
||||
@@ -18,7 +18,7 @@ type PodDisruptionBudget interface {
|
||||
CreatePodDisruptionBudget(namespace string, podDisruptionBudget *policyv1.PodDisruptionBudget) error
|
||||
UpdatePodDisruptionBudget(namespace string, podDisruptionBudget *policyv1.PodDisruptionBudget) error
|
||||
CreateOrUpdatePodDisruptionBudget(namespace string, podDisruptionBudget *policyv1.PodDisruptionBudget) error
|
||||
- DeletePodDisruptionBudget(namespace string, name string) error
|
||||
+ DeletePodDisruptionBudget(namespace string, name string, options metav1.DeleteOptions) error
|
||||
}
|
||||
|
||||
// PodDisruptionBudgetService is the podDisruptionBudget service implementation using API calls to kubernetes.
|
||||
@@ -85,8 +85,8 @@ func (p *PodDisruptionBudgetService) CreateOrUpdatePodDisruptionBudget(namespace
|
||||
return p.UpdatePodDisruptionBudget(namespace, podDisruptionBudget)
|
||||
}
|
||||
|
||||
-func (p *PodDisruptionBudgetService) DeletePodDisruptionBudget(namespace string, name string) error {
|
||||
- err := p.kubeClient.PolicyV1().PodDisruptionBudgets(namespace).Delete(context.TODO(), name, metav1.DeleteOptions{})
|
||||
+func (p *PodDisruptionBudgetService) DeletePodDisruptionBudget(namespace string, name string, options metav1.DeleteOptions) error {
|
||||
+ err := p.kubeClient.PolicyV1().PodDisruptionBudgets(namespace).Delete(context.TODO(), name, options)
|
||||
recordMetrics(namespace, "PodDisruptionBudget", name, "DELETE", err, p.metricsRecorder)
|
||||
return err
|
||||
}
|
||||
diff --git a/service/k8s/poddisruptionbudget_test.go b/service/k8s/poddisruptionbudget_test.go
|
||||
index 8d8de2e9f7df..d16a0745a0e0 100644
|
||||
--- a/service/k8s/poddisruptionbudget_test.go
|
||||
+++ b/service/k8s/poddisruptionbudget_test.go
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
+ "k8s.io/apimachinery/pkg/types"
|
||||
kubernetes "k8s.io/client-go/kubernetes/fake"
|
||||
kubetesting "k8s.io/client-go/testing"
|
||||
|
||||
@@ -115,3 +116,38 @@ func TestPodDisruptionBudgetServiceGetCreateOrUpdate(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
+
|
||||
+func TestPodDisruptionBudgetDeletePreconditions(t *testing.T) {
|
||||
+ uid := types.UID("pdb-uid")
|
||||
+ version := "42"
|
||||
+ options := metav1.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &uid, ResourceVersion: &version}}
|
||||
+ for _, test := range []struct {
|
||||
+ name string
|
||||
+ currentUID types.UID
|
||||
+ currentVersion string
|
||||
+ wantConflict bool
|
||||
+ }{
|
||||
+ {name: "unchanged object is deleted", currentUID: uid, currentVersion: version},
|
||||
+ {name: "replacement object is kept", currentUID: "replacement-uid", currentVersion: version, wantConflict: true},
|
||||
+ {name: "same object with a changed owner is kept", currentUID: uid, currentVersion: "43", wantConflict: true},
|
||||
+ } {
|
||||
+ t.Run(test.name, func(t *testing.T) {
|
||||
+ client := &kubernetes.Clientset{}
|
||||
+ deleted := false
|
||||
+ client.AddReactor("delete", "poddisruptionbudgets", func(action kubetesting.Action) (bool, runtime.Object, error) {
|
||||
+ preconditions := action.(kubetesting.DeleteAction).GetDeleteOptions().Preconditions
|
||||
+ if preconditions != nil && ((preconditions.UID != nil && *preconditions.UID != test.currentUID) ||
|
||||
+ (preconditions.ResourceVersion != nil && *preconditions.ResourceVersion != test.currentVersion)) {
|
||||
+ return true, nil, kubeerrors.NewConflict(schema.GroupResource{Resource: "poddisruptionbudgets"}, "test-pdb", errors.New("precondition failed"))
|
||||
+ }
|
||||
+ deleted = true
|
||||
+ return true, nil, nil
|
||||
+ })
|
||||
+ service := k8s.NewPodDisruptionBudgetService(client, log.Dummy, metrics.Dummy)
|
||||
+ err := service.DeletePodDisruptionBudget("testns", "test-pdb", options)
|
||||
+ assert.Equal(t, test.wantConflict, kubeerrors.IsConflict(err))
|
||||
+ assert.Equal(t, !test.wantConflict, deleted)
|
||||
+ assert.Len(t, client.Actions(), 1)
|
||||
+ })
|
||||
+ }
|
||||
+}
|
||||
Reference in new issue
Block a user