-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathvalkeycluster_controller.go
More file actions
1667 lines (1536 loc) · 76.1 KB
/
Copy pathvalkeycluster_controller.go
File metadata and controls
1667 lines (1536 loc) · 76.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2025 Valkey Contributors.
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 controller
import (
"context"
"crypto/tls"
"errors"
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"time"
valkeyiov1alpha1 "github.com/valkey-io/valkey-operator/api/v1alpha1"
"github.com/valkey-io/valkey-operator/internal/valkey"
corev1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/tools/events"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
logf "sigs.k8s.io/controller-runtime/pkg/log"
)
const (
DefaultPort = 6379
DefaultClusterBusPort = 16379
DefaultImage = "valkey/valkey:9.0.0"
DefaultExporterImage = "oliver006/redis_exporter:v1.80.0"
DefaultExporterPort = 9121
// AclSecretType is the Secret type used for operator-managed ACL Secrets.
AclSecretType = corev1.SecretType("valkey.io/acl")
// Error messages
statusUpdateFailedMsg = "failed to update status"
)
// ValkeyClusterReconciler reconciles a ValkeyCluster object
type ValkeyClusterReconciler struct {
client.Client
APIReader client.Reader
Scheme *runtime.Scheme
Recorder events.EventRecorder
}
// +kubebuilder:rbac:groups=valkey.io,resources=valkeyclusters,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=valkey.io,resources=valkeyclusters/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=valkey.io,resources=valkeyclusters/finalizers,verbs=update
// +kubebuilder:rbac:groups=valkey.io,resources=valkeynodes,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch
// +kubebuilder:rbac:groups="apps",resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch
// +kubebuilder:rbac:groups=policy,resources=poddisruptionbudgets,verbs=get;list;watch;create;update;patch;delete
// Reconcile is the main reconciliation loop. On each invocation it drives the
// cluster one step closer to the desired state described by the ValkeyCluster
// spec. The pipeline runs in the following order:
//
// - Ensure the headless Service exists (upsertService).
// - Ensure PodDisruptionBudget exists (reconcilePodDisruptionBudget).
// - Ensure internal ACL users are configured (reconcileUsersAcl).
// - Ensure the ConfigMap with valkey.conf and health-check scripts exists
// (upsertConfigMap).
// - Ensure one ValkeyNode per (shard, node) pair exists, creating missing
// nodes and propagating spec changes one at a time in shard order with
// replicas updated before the primary (reconcileValkeyNodes).
// - Build the Valkey cluster state by connecting to each node and scraping
// CLUSTER INFO / CLUSTER NODES.
// - Promote orphaned replicas via CLUSTER FAILOVER TAKEOVER when quorum
// is lost (promoteOrphanedReplicas).
// - Forget stale nodes that no longer have a backing ValkeyNode.
// - MEET: batch-introduce all isolated pending nodes to the cluster via
// CLUSTER MEET. Requeue to let gossip propagate.
// - Assign slots: batch-assign hash-slot ranges to all primary-labeled
// pending nodes via CLUSTER ADDSLOTSRANGE.
// - Replicate: batch-attach all replica-labeled pending nodes to their
// matching primaries via CLUSTER REPLICATE.
// - Scale-in: if the cluster has more shards than desired, drain slots
// from excess shards via CLUSTER MIGRATESLOTS and delete their
// ValkeyNodes once fully drained.
// - Verify that the expected number of shards and replicas exist.
// - Verify that all 16384 hash slots are assigned.
// - If everything is healthy, mark the cluster Ready and requeue after 30s
// for periodic health checks.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.23.3/pkg/reconcile
func (r *ValkeyClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { //nolint:gocyclo
log := logf.FromContext(ctx)
log.V(1).Info("reconcile...")
cluster := &valkeyiov1alpha1.ValkeyCluster{}
if err := r.Get(ctx, req.NamespacedName, cluster); err != nil {
if apierrors.IsNotFound(err) {
deleteClusterMetrics(req.Name, req.Namespace)
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
initClusterMetrics(req.Name, req.Namespace)
if err := r.upsertService(ctx, cluster); err != nil {
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonServiceError, err.Error(), metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, nil)
return ctrl.Result{}, err
}
if err := r.reconcilePodDisruptionBudget(ctx, cluster); err != nil {
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonPodDisruptionBudgetError, err.Error(), metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, nil)
return ctrl.Result{}, err
}
if err := r.reconcileUsersAcl(ctx, cluster); err != nil {
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonUsersAclError, err.Error(), metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, nil)
return ctrl.Result{}, err
}
if err := r.upsertConfigMap(ctx, cluster); err != nil {
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonConfigMapError, err.Error(), metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, nil)
return ctrl.Result{}, err
}
// Roll hash ignores live-settable keys, so a change confined to those keys
// does not roll the pods (they are applied live by the ValkeyNode controller).
// Computed directly from cluster.Spec rather than reading back from the
// ConfigMap to avoid a race condition where the cache does not have the ConfigMap
configHash := serverConfigRollHash(cluster)
// Surface a ConfigurationWarning condition when an explicit
// terminationGracePeriodSeconds is too short for the graceful failover on
// SIGTERM to finish before SIGKILL. The value is honoured; the operator does
// not silently override it. The condition is idempotent, so the event fires
// only when the cluster first enters the warning state.
rec := recommendedGracePeriodSeconds(cluster)
if g := cluster.Spec.TerminationGracePeriodSeconds; g != nil && *g < rec {
msg := fmt.Sprintf("spec.terminationGracePeriodSeconds (%ds) is below the recommended %ds for cluster-manual-failover-timeout; SIGKILL may interrupt the graceful failover on shutdown", *g, rec)
if !meta.IsStatusConditionTrue(cluster.Status.Conditions, valkeyiov1alpha1.ConditionConfigurationWarning) {
log.Info("terminationGracePeriodSeconds is below the recommended minimum for graceful failover",
"requested", *g, "recommended", rec)
r.Recorder.Eventf(cluster, nil, corev1.EventTypeWarning, valkeyiov1alpha1.ReasonGracePeriodTooShort, "ReconcileValkeyCluster", "%s", msg)
}
setCondition(cluster, valkeyiov1alpha1.ConditionConfigurationWarning, valkeyiov1alpha1.ReasonGracePeriodTooShort, msg, metav1.ConditionTrue)
} else {
removeConditionIfReason(&cluster.Status.Conditions, valkeyiov1alpha1.ConditionConfigurationWarning, valkeyiov1alpha1.ReasonGracePeriodTooShort)
}
nodes := &valkeyiov1alpha1.ValkeyNodeList{}
if err := r.List(ctx, nodes, client.InNamespace(cluster.Namespace), client.MatchingLabels(map[string]string{LabelCluster: cluster.Name})); err != nil {
log.Error(err, "failed to list ValkeyNodes")
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonValkeyNodeListError, err.Error(), metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, nil)
return ctrl.Result{}, err
}
if requeue, err := r.reconcileValkeyNodes(ctx, cluster, nodes, configHash); err != nil {
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonValkeyNodeError, err.Error(), metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, nil)
return ctrl.Result{}, err
} else if requeue {
if result, handled, err := r.handlePodSchedulingIssues(ctx, cluster); err != nil {
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonValkeyNodeError, err.Error(), metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, nil)
return ctrl.Result{}, err
} else if handled {
return result, nil
}
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonUpdatingNodes, "Updating ValkeyNodes", metav1.ConditionFalse)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonUpdatingNodes, "Updating ValkeyNodes", metav1.ConditionTrue)
_ = r.updateStatus(ctx, cluster, nil)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
operatorPassword, err := fetchSystemUserPassword(ctx, operatorUser, r.Client, cluster.Name, cluster.Namespace)
if err != nil {
log.Error(err, "failed to retrieve system user password")
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonSystemUsersAclError, err.Error(), metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, nil)
return ctrl.Result{}, nil
}
state := r.getValkeyClusterState(ctx, cluster, nodes, operatorUser, operatorPassword)
defer state.CloseClients()
// Promote replicas of dead primaries when quorum is lost.
// TAKEOVER before FORGET so slots remain continuously owned.
if result, handled := r.promoteOrphanedReplicas(ctx, cluster, state); handled {
return result, nil
}
r.forgetStaleNodes(ctx, cluster, state, nodes)
// --- Phase 1: MEET all isolated nodes in one batch ---
// A node with cluster_known_nodes <= 1 hasn't been introduced to the
// cluster yet. CLUSTER MEET is idempotent and has no ordering
// dependencies, so we issue it for every isolated pending node in a
// single reconcile pass. Phase 2 refuses to assign slots to isolated
// nodes, so every node is guaranteed to pass through here first.
// After MEET, we requeue to let gossip propagate before proceeding
// to slot assignment or replication.
{
met, err := r.meetIsolatedNodes(ctx, cluster, state)
if err != nil {
setCondition(cluster, valkeyiov1alpha1.ConditionDegraded, valkeyiov1alpha1.ReasonNodeAddFailed, err.Error(), metav1.ConditionTrue)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
if met > 0 {
r.Recorder.Eventf(cluster, nil, corev1.EventTypeNormal, "ClusterMeetBatch", "ClusterMeet", "Introduced %d isolated node(s) to the cluster", met)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonAddingNodes, "Introducing nodes to cluster", metav1.ConditionTrue)
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonReconciling, "Cluster is Reconciling", metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
}
// --- Phase 2: Assign slots to all primary-labeled pending nodes ---
// Slot assignment (CLUSTER ADDSLOTSRANGE) makes a pending node a
// slot-owning primary. During scale-out (no unassigned slots), this
// is a no-op; new primaries stay in PendingNodes until the rebalancer
// migrates slots to them.
if len(state.PendingNodes) > 0 {
assigned, err := r.assignSlotsToPendingPrimaries(ctx, cluster, state, nodes)
if err != nil {
setCondition(cluster, valkeyiov1alpha1.ConditionDegraded, valkeyiov1alpha1.ReasonNodeAddFailed, err.Error(), metav1.ConditionTrue)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
if assigned > 0 {
r.Recorder.Eventf(cluster, nil, corev1.EventTypeNormal, "PrimariesCreated", "AssignSlots", "Assigned slots to %d new primary node(s)", assigned)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonAddingNodes, "Assigning slots to primaries", metav1.ConditionTrue)
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonReconciling, "Cluster is Reconciling", metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, state)
// Requeue so that the next reconcile sees the newly-created shards
// in state.Shards, which replicas need for their lookup.
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
}
// --- Phase 3: REPLICATE all replica-labeled pending nodes ---
// By this point all currently known primaries have slots and appear in state.Shards.
// CLUSTER REPLICATE for different replicas targets different primaries,
// so they can all be issued in one pass.
if len(state.PendingNodes) > 0 {
replicated, err := r.replicatePendingReplicas(ctx, cluster, state, nodes)
if err != nil {
setCondition(cluster, valkeyiov1alpha1.ConditionDegraded, valkeyiov1alpha1.ReasonNodeAddFailed, err.Error(), metav1.ConditionTrue)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
if replicated > 0 {
r.Recorder.Eventf(cluster, nil, corev1.EventTypeNormal, "ReplicasAttached", "CreateReplica", "Attached %d replica node(s)", replicated)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonAddingNodes, "Attaching replicas", metav1.ConditionTrue)
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonReconciling, "Cluster is Reconciling", metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
}
// Build the effective shard list: state.Shards plus any pending primaries
// that are scale-out leaders. During scale-out, GetClusterState places
// new slot-less primaries in PendingNodes because it can't distinguish
// them from unreplicated replicas. We use pod labels to identify them
// and include them as empty shards for health checks and rebalancing.
allShards := effectiveShards(state, nodes)
// Handle scale-in: drain excess shards and clean up leftover ValkeyNodes.
// This runs before pod scheduling checks so that excess shard pods from a
// prior scale-up don't block scale-down when they can't be scheduled.
if result, requeue := r.handleScaleIn(ctx, cluster, state, nodes); requeue {
return result, nil
}
if result, handled, err := r.handlePodSchedulingIssues(ctx, cluster); err != nil {
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonValkeyNodeError, err.Error(), metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{}, err
} else if handled {
return result, nil
}
// Check cluster status
if len(allShards) < int(cluster.Spec.Shards) {
log.V(1).Info("missing shards, requeue..")
r.Recorder.Eventf(cluster, nil, corev1.EventTypeNormal, "WaitingForShards", "CheckShards", "%d of %d shards exist", len(allShards), cluster.Spec.Shards)
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonMissingShards, "Waiting for all shards to be created", metav1.ConditionFalse)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonReconciling, "Creating shards", metav1.ConditionTrue)
setCondition(cluster, valkeyiov1alpha1.ConditionClusterFormed, valkeyiov1alpha1.ReasonMissingShards, "Waiting for shards", metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
for _, shard := range allShards {
if countSlots(shard.Slots) == 0 {
continue
}
if len(shard.Nodes) < (1 + int(cluster.Spec.Replicas)) {
log.V(1).Info("missing replicas, requeue..")
r.Recorder.Eventf(cluster, nil, corev1.EventTypeNormal, "WaitingForReplicas", "CheckReplicas", "Shard has %d of %d nodes", len(shard.Nodes), 1+int(cluster.Spec.Replicas))
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonMissingReplicas, "Waiting for all replicas to be created", metav1.ConditionFalse)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonReconciling, "Creating replicas", metav1.ConditionTrue)
setCondition(cluster, valkeyiov1alpha1.ConditionClusterFormed, valkeyiov1alpha1.ReasonMissingReplicas, "Waiting for replicas", metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
}
// Check if all slots are assigned
unassignedSlots := state.GetUnassignedSlots()
allSlotsAssigned := len(unassignedSlots) == 0
if !allSlotsAssigned {
log.V(1).Info("slots are not assigned, requeue..", "unassignedSlots", unassignedSlots)
setCondition(cluster, valkeyiov1alpha1.ConditionSlotsAssigned, valkeyiov1alpha1.ReasonSlotsUnassigned, "Waiting for slots to be assigned", metav1.ConditionFalse)
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonReconciling, "Waiting for all slots to be assigned", metav1.ConditionFalse)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonReconciling, "Waiting for slots to be assigned", metav1.ConditionTrue)
setCondition(cluster, valkeyiov1alpha1.ConditionClusterFormed, valkeyiov1alpha1.ReasonSlotsUnassigned, "Waiting for slots to be assigned", metav1.ConditionFalse)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
// Check that all replicas have their replication link up (master_link_status:up).
// before marking the cluster Ready, we need to make sure all replicas are in sync with their primary.
for _, shard := range allShards {
for _, node := range shard.Nodes {
if !node.IsReplicationInSync() {
log.V(1).Info("replica not yet in sync, requeue..", "address", node.Address)
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonReconciling, "Waiting for replicas to sync with primary", metav1.ConditionFalse)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonReconciling, "Waiting for replica sync", metav1.ConditionTrue)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
}
}
// --- Rebalance slots across primaries (scale-out) ---
// After all shards are healthy and all slots are assigned, check if
// the slot distribution is uneven (e.g. a new shard was added with
// zero slots). rebalanceSlots picks a single src→dst move per
// reconcile and migrates up to rebalanceSlotBatchSize slots at a
// time using CLUSTER MIGRATESLOTS (atomic migration, requires
// Valkey >= 9.0). Each pass requeues so the next reconcile
// re-evaluates cluster state with fresh topology before continuing.
rebalanced, err := r.rebalanceSlots(ctx, cluster, allShards)
if err != nil {
log.Error(err, "slot rebalancing failed")
r.Recorder.Eventf(cluster, nil, corev1.EventTypeWarning, "SlotRebalanceFailed", "RebalanceSlots", "Slot rebalancing failed: %v", err)
setCondition(cluster, valkeyiov1alpha1.ConditionDegraded, valkeyiov1alpha1.ReasonRebalanceFailed, err.Error(), metav1.ConditionTrue)
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonReconciling, "Cluster is Reconciling", metav1.ConditionFalse)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonRebalancingSlots, "Rebalancing slots across primaries", metav1.ConditionTrue)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
if rebalanced {
// Clear any stale Degraded condition from earlier phases (e.g.
// NodeAddFailed set when replicas couldn't attach to primaries
// that hadn't received slots yet during scale-out).
meta.RemoveStatusCondition(&cluster.Status.Conditions, valkeyiov1alpha1.ConditionDegraded)
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonReconciling, "Cluster is Reconciling", metav1.ConditionFalse)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonRebalancingSlots, "Rebalancing slots across primaries", metav1.ConditionTrue)
_ = r.updateStatus(ctx, cluster, state)
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
// Cluster is healthy - set all positive conditions
r.Recorder.Eventf(cluster, nil, corev1.EventTypeNormal, "ClusterReady", "ReconcileCluster", "Cluster ready with %d shards and %d replicas", cluster.Spec.Shards, cluster.Spec.Replicas)
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonClusterHealthy, "Cluster is healthy", metav1.ConditionTrue)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonReconcileComplete, "No changes needed", metav1.ConditionFalse)
meta.RemoveStatusCondition(&cluster.Status.Conditions, valkeyiov1alpha1.ConditionDegraded)
setCondition(cluster, valkeyiov1alpha1.ConditionClusterFormed, valkeyiov1alpha1.ReasonTopologyComplete, "All nodes joined cluster", metav1.ConditionTrue)
setCondition(cluster, valkeyiov1alpha1.ConditionSlotsAssigned, valkeyiov1alpha1.ReasonAllSlotsAssigned, "All slots assigned", metav1.ConditionTrue)
if err := r.updateStatus(ctx, cluster, state); err != nil {
log.Error(err, statusUpdateFailedMsg)
return ctrl.Result{}, err
}
log.V(1).Info("reconcile done")
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
type podSchedulingIssue struct {
podName string
message string
}
func (r *ValkeyClusterReconciler) handlePodSchedulingIssues(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster) (ctrl.Result, bool, error) {
issue, err := r.findPodSchedulingIssue(ctx, cluster)
if err != nil {
return ctrl.Result{}, false, err
}
if issue == nil {
removeConditionIfReason(&cluster.Status.Conditions, valkeyiov1alpha1.ConditionDegraded, valkeyiov1alpha1.ReasonPodUnschedulable)
removeConditionIfReason(&cluster.Status.Conditions, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonPodUnschedulable)
return ctrl.Result{}, false, nil
}
message := fmt.Sprintf("Pod %s is unschedulable", issue.podName)
if issue.message != "" {
message = fmt.Sprintf("%s: %s", message, issue.message)
}
r.Recorder.Eventf(cluster, nil, corev1.EventTypeWarning, "PodUnschedulable", "SchedulePod", "%s", message)
setCondition(cluster, valkeyiov1alpha1.ConditionDegraded, valkeyiov1alpha1.ReasonPodUnschedulable, message, metav1.ConditionTrue)
setCondition(cluster, valkeyiov1alpha1.ConditionReady, valkeyiov1alpha1.ReasonPodUnschedulable, message, metav1.ConditionFalse)
setCondition(cluster, valkeyiov1alpha1.ConditionProgressing, valkeyiov1alpha1.ReasonReconciling, "Waiting for unschedulable pods to be scheduled", metav1.ConditionTrue)
if err := r.updateStatus(ctx, cluster, nil); err != nil {
return ctrl.Result{}, false, err
}
return ctrl.Result{RequeueAfter: 10 * time.Second}, true, nil
}
func (r *ValkeyClusterReconciler) findPodSchedulingIssue(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster) (*podSchedulingIssue, error) {
pods := &corev1.PodList{}
if err := r.List(ctx, pods, client.InNamespace(cluster.Namespace), client.MatchingLabels(map[string]string{LabelCluster: cluster.Name})); err != nil {
return nil, fmt.Errorf("list Valkey pods: %w", err)
}
desiredShards := int(cluster.Spec.Shards)
for i := range pods.Items {
if label, ok := pods.Items[i].Labels[LabelShardIndex]; ok {
si, err := strconv.Atoi(label)
if err == nil && si >= desiredShards {
continue
}
}
if issue := podSchedulingIssueForPod(&pods.Items[i]); issue != nil {
return issue, nil
}
}
return nil, nil
}
func podSchedulingIssueForPod(pod *corev1.Pod) *podSchedulingIssue {
if pod.DeletionTimestamp != nil {
return nil
}
for _, condition := range pod.Status.Conditions {
if condition.Type == corev1.PodScheduled &&
condition.Status == corev1.ConditionFalse &&
condition.Reason == corev1.PodReasonUnschedulable {
return &podSchedulingIssue{
podName: pod.Name,
message: condition.Message,
}
}
}
return nil
}
func headlessServiceName(clusterName string) string {
return resourcePrefix + clusterName
}
// Create or update a headless service (client connects to pods directly)
func (r *ValkeyClusterReconciler) upsertService(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster) error {
svc := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: headlessServiceName(cluster.Name),
Namespace: cluster.Namespace,
},
}
result, err := controllerutil.CreateOrUpdate(ctx, r.Client, svc, func() error {
svc.Labels = labels(cluster)
svc.Spec.Type = corev1.ServiceTypeClusterIP
// ClusterIP is immutable after creation; preserve the existing value on updates.
if svc.Spec.ClusterIP == "" {
svc.Spec.ClusterIP = "None"
}
svc.Spec.Selector = map[string]string{LabelCluster: cluster.Name}
// Protocol and TargetPort are API-server defaults; set them explicitly
// so the rebuilt slice deep-equals the stored one and CreateOrUpdate
// stops updating the Service on every reconcile (#315).
svc.Spec.Ports = []corev1.ServicePort{{
Name: appName,
Port: DefaultPort,
Protocol: corev1.ProtocolTCP,
TargetPort: intstr.FromInt32(DefaultPort),
}}
return controllerutil.SetControllerReference(cluster, svc, r.Scheme)
})
if err != nil {
r.Recorder.Eventf(cluster, svc, corev1.EventTypeWarning, "ServiceUpdateFailed", "UpdateService", "Failed to upsert Service: %v", err)
return err
}
if result == controllerutil.OperationResultCreated {
r.Recorder.Eventf(cluster, svc, corev1.EventTypeNormal, "ServiceCreated", "CreateService", "Created headless Service")
}
return nil
}
// reconcileValkeyNodes ensures every (shard, nodeIndex) pair has a ValkeyNode CR.
// Each ValkeyNode manages exactly one Pod (Replicas=1) and is named
// deterministically:
//
// <cluster>-<N>-<M>
//
// where N is the shard index and M is the node index (0 = initial primary,
// 1+ = replicas). It iterates shards in ascending order and nodes replica-first within each
// shard, using live cluster state to identify the actual primary. At most one spec update is issued per reconcile.
// Once a node is updated or found not-ready after a prior update,
// the function returns (true, nil) so the caller requeues before advancing to the next node.
//
// For a 3-shard cluster with 2 replicas per shard, this produces 9 ValkeyNodes:
//
// mycluster-0-0, mycluster-0-1, mycluster-0-2,
// mycluster-1-0, mycluster-1-1, mycluster-1-2,
// mycluster-2-0, mycluster-2-1, mycluster-2-2.
func (r *ValkeyClusterReconciler) reconcileValkeyNodes(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster, nodes *valkeyiov1alpha1.ValkeyNodeList, configHash string) (bool, error) {
log := logf.FromContext(ctx)
nodesPerShard := 1 + int(cluster.Spec.Replicas)
totalCreated := 0
// Scrape cluster state once for proactive failover decisions, but only
// when at least one node actually needs a roll. During initial bootstrap
// no nodes exist, so state stays nil. The snapshot is safe to reuse
// across the loop: replicaFirstNodeOrder uses it to place the actual
// primary last within each shard, and after an update we requeue
// immediately, re-scraping fresh state before any further rolls.
var clusterState *valkey.ClusterState
// Scrape topology for Spec rolls and for workload-template rolls (operator
// builder drift) so proactive failover still runs before killing a primary.
if anyNodeRequiresRoll(cluster, nodes, configHash) || anyNodeRequiresWorkloadRoll(nodes) {
operatorPassword, err := fetchSystemUserPassword(ctx, operatorUser, r.Client, cluster.Name, cluster.Namespace)
if err != nil {
return false, fmt.Errorf("failed to fetch operator password for proactive failover: %w", err)
}
clusterState = r.getValkeyClusterState(ctx, cluster, nodes, operatorUser, operatorPassword)
defer clusterState.CloseClients()
}
for shardIndex := range int(cluster.Spec.Shards) {
// If rolls are in progress but the primary of an active shard cannot be
// identified from cluster state, defer rather than roll in an unknown order.
// New shards (not yet in the topology) are exempt — they need creation, not rolling.
if clusterState != nil && shardExistsInTopology(clusterState, shardIndex, nodes) &&
primaryNodeIndexForShard(shardIndex, nodesPerShard, nodes, clusterState) < 0 {
log.Info("cannot identify primary for shard, deferring roll", "shardIndex", shardIndex)
return true, nil
}
// Iterate nodes replica-first: use live cluster state to identify the
// actual primary (which may differ from node-index=0 after a failover)
// and place it last.
for _, nodeIndex := range replicaFirstNodeOrder(shardIndex, nodesPerShard, nodes, clusterState) {
result, err := r.reconcileValkeyNode(ctx, cluster, shardIndex, nodeIndex, clusterState, configHash)
if err != nil {
return false, err
}
switch result {
case nodeDeferred:
// Roll deferred; MEET and REPLICATE isolated nodes so they
// rejoin the shard before next reconcile.
if _, meetErr := r.meetIsolatedNodes(ctx, cluster, clusterState); meetErr != nil {
log.Error(meetErr, "meetIsolatedNodes failed during deferred roll")
}
if _, replErr := r.replicatePendingReplicas(ctx, cluster, clusterState, nodes); replErr != nil {
log.Error(replErr, "replicatePendingReplicas failed during deferred roll")
}
return true, nil
case nodeRequeued:
return true, nil
case nodeCreated:
totalCreated++
}
}
}
if totalCreated > 0 {
log.V(1).Info("created ValkeyNodes", "count", totalCreated)
}
return false, nil
}
// nodeResult describes the outcome of reconciling a single ValkeyNode.
type nodeResult int
const (
nodeUnchanged nodeResult = iota // no spec change, node is ready
nodeRequeued // spec updated or not ready, caller should requeue
nodeCreated // new ValkeyNode was created
nodeDeferred // primary roll deferred, waiting for synced replica
)
// reconcileValkeyNode reconciles a single ValkeyNode for (shardIndex, nodeIndex).
// Returns a nodeResult signaling the outcome or required next action.
func (r *ValkeyClusterReconciler) reconcileValkeyNode(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster, shardIndex, nodeIndex int, clusterState *valkey.ClusterState, configHash string) (nodeResult, error) {
log := logf.FromContext(ctx)
desired := buildClusterValkeyNode(cluster, shardIndex, nodeIndex)
desired.Spec.ServerConfigHash = configHash
node := &valkeyiov1alpha1.ValkeyNode{
ObjectMeta: metav1.ObjectMeta{
Name: desired.Name,
Namespace: desired.Namespace,
},
}
// Load current node (if any) for failover + workload-drift decisions.
current := &valkeyiov1alpha1.ValkeyNode{}
currentExists := true
if err := r.Get(ctx, client.ObjectKeyFromObject(node), current); err != nil {
if !apierrors.IsNotFound(err) {
return nodeUnchanged, err
}
currentExists = false
}
needsSpecRoll := currentExists && nodeRequiresRoll(current, desired)
needsWorkloadPermit := currentExists && nodeNeedsWorkloadPermit(current)
inFlightWorkloadRoll := currentExists && nodeHasInFlightWorkloadRoll(current)
// Failover / ordered roll applies to Spec changes and workload template rolls.
needsWorkloadRoll := needsWorkloadPermit || inFlightWorkloadRoll
if deferred := r.maybeProactiveFailoverBeforeRoll(ctx, cluster, clusterState, current, needsSpecRoll || needsWorkloadRoll); deferred {
return nodeDeferred, nil
}
// One-at-a-time for Spec and workload rolls: never grant a new permit or
// Spec update while another node still holds an in-flight allow annotation.
if needsSpecRoll || needsWorkloadPermit {
if other, err := r.otherNodeHasInFlightWorkloadRoll(ctx, cluster, node.Name); err != nil {
return nodeUnchanged, err
} else if other {
log.V(1).Info("another ValkeyNode already holds a workload roll permit, waiting", "name", node.Name)
return nodeRequeued, nil
}
}
result, err := controllerutil.CreateOrUpdate(ctx, r.Client, node, func() error {
node.Labels = desired.Labels
node.Spec = desired.Spec
// Spec-driven rolls: grant a one-shot permit so the node controller may
// apply the new pod template. Workload-only drift uses the desired hash
// path below (CreateOrUpdate result None).
if needsSpecRoll {
setNodeAnnotation(node, allowWorkloadRevisionAnnotation, allowWorkloadRevisionAny)
}
return controllerutil.SetControllerReference(cluster, node, r.Scheme)
})
if err != nil {
r.Recorder.Eventf(cluster, node, corev1.EventTypeWarning, "ValkeyNodeFailed", "ReconcileValkeyNode", "Failed to reconcile ValkeyNode: %v", err)
return nodeUnchanged, err
}
switch result {
case controllerutil.OperationResultCreated:
r.Recorder.Eventf(cluster, node, corev1.EventTypeNormal, "ValkeyNodeCreated", "CreateValkeyNode", "Created ValkeyNode for shard %d node %d", shardIndex, nodeIndex)
return nodeCreated, nil
case controllerutil.OperationResultUpdated:
// A spec change was applied. Requeue unconditionally so the node has
// time to settle before we advance to the next one (one-at-a-time
// rolling update).
log.V(1).Info("updated ValkeyNode, waiting for it to become ready", "name", node.Name)
r.Recorder.Eventf(cluster, node, corev1.EventTypeNormal, "ValkeyNodeUpdated", "UpdateValkeyNode", "Updated ValkeyNode %s", node.Name)
return nodeRequeued, nil
case controllerutil.OperationResultNone:
return r.handleUnchangedValkeyNode(ctx, cluster, node, inFlightWorkloadRoll, needsWorkloadPermit)
default:
log.V(1).Info("unexpected CreateOrUpdate result", "result", result, "name", node.Name)
}
return nodeUnchanged, nil
}
// maybeProactiveFailoverBeforeRoll runs proactive failover when rolling a
// primary. Returns true when the primary has no synced replica yet (defer).
func (r *ValkeyClusterReconciler) maybeProactiveFailoverBeforeRoll(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster, clusterState *valkey.ClusterState, current *valkeyiov1alpha1.ValkeyNode, rolling bool) bool {
log := logf.FromContext(ctx)
if clusterState == nil || !rolling {
return false
}
shard, replicas := findFailoverShard(clusterState, current.Status.PodIP)
if shard != nil {
log.Info("proactive failover before rolling primary",
"name", current.Name, "address", current.Status.PodIP,
"syncedReplicas", len(replicas))
if err := proactiveFailover(ctx, r.Recorder, cluster, shard, replicas); err != nil {
log.Info("proactive failover did not complete, proceeding with roll",
"name", current.Name, "err", err)
}
return false
}
if cluster.Spec.Replicas == 0 {
return false
}
// findFailoverShard returned nil for one of three reasons:
// 1. Node is the shard primary but has no synced replicas: wait for replica to rejoin
// 2. Node is in a shard but is a replica: safe to roll
// 3. Node isn't in any shard (isolated): safe to roll
// Only case 1 requires waiting; identify it's the actual primary of its shard.
shardInState := clusterState.FindShardForAddress(current.Status.PodIP)
if shardInState != nil && shardInState.GetPrimaryNode() != nil && shardInState.GetPrimaryNode().Address == current.Status.PodIP {
log.Info("primary has no synced replicas, deferring roll",
"name", current.Name, "address", current.Status.PodIP,
"shardNodes", len(shardInState.Nodes),
"shardId", shardInState.Id)
return true
}
return false
}
// handleUnchangedValkeyNode handles CreateOrUpdate OperationResultNone: grant
// a workload permit if needed, or wait until the node is settled and Ready.
func (r *ValkeyClusterReconciler) handleUnchangedValkeyNode(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster, node *valkeyiov1alpha1.ValkeyNode, inFlightWorkloadRoll, needsWorkloadPermit bool) (nodeResult, error) {
log := logf.FromContext(ctx)
// In-flight permitted roll: wait until the node clears the permit
// (after the workload revision is live) and is Ready.
if inFlightWorkloadRoll {
log.V(1).Info("ValkeyNode workload roll in flight, waiting", "name", node.Name)
return nodeRequeued, nil
}
// Builder/template drift without Spec change: grant permit for this node.
// Sibling in-flight was already checked by the caller.
if needsWorkloadPermit {
return r.grantWorkloadRollPermit(ctx, cluster, node)
}
if node.Status.ObservedGeneration > 0 && node.Generation != node.Status.ObservedGeneration {
log.V(1).Info("ValkeyNode spec not yet observed by controller, waiting",
"name", node.Name,
"generation", node.Generation,
"observedGeneration", node.Status.ObservedGeneration)
return nodeRequeued, nil
}
if !node.Status.Ready {
// No spec change, but the node hasn't reached Ready yet (e.g.
// still starting after a prior update). Unlike Updated above, we
// only wait when not-ready; a ready unchanged node is safe to
// advance past.
log.V(1).Info("ValkeyNode not yet ready, waiting", "name", node.Name)
return nodeRequeued, nil
}
if c := meta.FindStatusCondition(node.Status.Conditions, valkeyiov1alpha1.ValkeyNodeConditionLiveConfigApplied); c != nil && c.Status == metav1.ConditionFalse {
log.V(1).Info("ValkeyNode live config not yet applied, waiting", "name", node.Name)
return nodeRequeued, nil
}
return nodeUnchanged, nil
}
// grantWorkloadRollPermit writes allow-workload-revision for a node waiting on
// builder/template drift. Always requeues so the node controller can apply.
func (r *ValkeyClusterReconciler) grantWorkloadRollPermit(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster, node *valkeyiov1alpha1.ValkeyNode) (nodeResult, error) {
log := logf.FromContext(ctx)
desiredHash := ""
if node.Annotations != nil {
desiredHash = node.Annotations[desiredWorkloadRevisionAnnotation]
}
if desiredHash == "" {
// Condition True but annotation not yet set; wait for node controller.
log.V(1).Info("ValkeyNode workload drift pending without desired hash, waiting", "name", node.Name)
return nodeRequeued, nil
}
if !workloadPermitAllows(node, desiredHash) {
patchBase := node.DeepCopy()
if setNodeAnnotation(node, allowWorkloadRevisionAnnotation, desiredHash) {
if err := r.Patch(ctx, node, client.MergeFrom(patchBase)); err != nil {
return nodeUnchanged, err
}
log.Info("granted workload roll permit", "name", node.Name, "hash", desiredHash)
r.Recorder.Eventf(cluster, node, corev1.EventTypeNormal, "WorkloadRollPermitted", "PermitWorkloadRoll",
"Granted workload roll permit for %s (hash %s)", node.Name, desiredHash)
}
}
return nodeRequeued, nil
}
// otherNodeHasInFlightWorkloadRoll reports whether any ValkeyNode in this cluster
// other than excludeName currently holds a workload roll permit.
func (r *ValkeyClusterReconciler) otherNodeHasInFlightWorkloadRoll(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster, excludeName string) (bool, error) {
list := &valkeyiov1alpha1.ValkeyNodeList{}
if err := r.List(ctx, list, client.InNamespace(cluster.Namespace), client.MatchingLabels{LabelCluster: cluster.Name}); err != nil {
return false, err
}
for i := range list.Items {
n := &list.Items[i]
if n.Name == excludeName {
continue
}
if nodeHasInFlightWorkloadRoll(n) {
return true, nil
}
}
return false, nil
}
const (
// gracePeriodBufferSeconds is added on top of cluster-manual-failover-timeout
// so the SIGTERM-triggered failover has headroom to finish before SIGKILL.
gracePeriodBufferSeconds = 10
// defaultFailoverTimeoutSeconds mirrors the Valkey default for
// cluster-manual-failover-timeout (5000ms).
defaultFailoverTimeoutSeconds = 5
// defaultGracePeriodSeconds mirrors the Kubernetes default
// terminationGracePeriodSeconds.
defaultGracePeriodSeconds = 30
)
// failoverTimeoutSeconds returns cluster-manual-failover-timeout in whole
// seconds (rounded up), or the Valkey default when unset or unparseable.
func failoverTimeoutSeconds(config map[string]string) int64 {
v, ok := config["cluster-manual-failover-timeout"]
if !ok {
return defaultFailoverTimeoutSeconds
}
ms, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64)
if err != nil || ms <= 0 {
return defaultFailoverTimeoutSeconds
}
return (ms + 999) / 1000
}
// recommendedGracePeriodSeconds is the smallest terminationGracePeriodSeconds
// that lets a SIGTERM-triggered failover finish before SIGKILL.
func recommendedGracePeriodSeconds(cluster *valkeyiov1alpha1.ValkeyCluster) int64 {
return failoverTimeoutSeconds(cluster.Spec.Config) + gracePeriodBufferSeconds
}
// effectiveGracePeriodSeconds is the grace period the operator applies to the
// Valkey pods: the user's value when set, otherwise a safe default that is at
// least the Kubernetes default and the recommended minimum.
func effectiveGracePeriodSeconds(cluster *valkeyiov1alpha1.ValkeyCluster) int64 {
if cluster.Spec.TerminationGracePeriodSeconds != nil {
return *cluster.Spec.TerminationGracePeriodSeconds
}
if rec := recommendedGracePeriodSeconds(cluster); rec > defaultGracePeriodSeconds {
return rec
}
return defaultGracePeriodSeconds
}
// buildClusterValkeyNode constructs the ValkeyNode CR for a given (shard, node) position.
func buildClusterValkeyNode(cluster *valkeyiov1alpha1.ValkeyCluster, shardIndex int, nodeIndex int) *valkeyiov1alpha1.ValkeyNode {
// Start with recommended k8s labels; instance is the cluster name and component is "valkey-node".
l := baseLabels(cluster.Name, "valkey-node")
// Inherit user-defined labels from the parent cluster at lower priority.
for k, v := range cluster.Labels {
if _, exists := l[k]; !exists {
l[k] = v
}
}
// Operator-specific labels always take precedence.
l[LabelCluster] = cluster.Name
l[LabelShardIndex] = strconv.Itoa(shardIndex)
l[LabelNodeIndex] = strconv.Itoa(nodeIndex)
var scheduling valkeyiov1alpha1.SchedulingSpec
if cluster.Spec.Scheduling != nil {
scheduling = *cluster.Spec.Scheduling
}
// Only set the field when it differs from the Kubernetes default, so existing
// clusters that resolve to the default keep a nil value and are not rolled on
// operator upgrade.
// Store the user's value verbatim when set, so an explicit change (including
// back to the Kubernetes default) always propagates to the pod. When unset,
// only populate the field if the derived default deviates from the Kubernetes
// pod default, so existing clusters that resolve to the default are not rolled
// on operator upgrade.
var gracePeriod *int64
if cluster.Spec.TerminationGracePeriodSeconds != nil {
g := *cluster.Spec.TerminationGracePeriodSeconds
gracePeriod = &g
} else if d := effectiveGracePeriodSeconds(cluster); d != defaultGracePeriodSeconds {
gracePeriod = &d
}
// Curate node-axis scheduling primitives from node.spread, merged with the
// user's escape-hatch passthrough. Preserve nil when nothing is curated.
shardMode, primariesMode, podsMode := effectiveNodeSpread(cluster.Spec.Scheduling)
affinity := withNodeShardAntiAffinity(scheduling.Affinity, cluster.Name, shardIndex, shardMode)
topologySpreadConstraints := scheduling.TopologySpreadConstraints
if curated := nodeSpreadTSCs(cluster.Name, nodeIndex, primariesMode, podsMode); len(curated) > 0 {
topologySpreadConstraints = append(
append([]corev1.TopologySpreadConstraint{}, topologySpreadConstraints...),
curated...,
)
}
return &valkeyiov1alpha1.ValkeyNode{
ObjectMeta: metav1.ObjectMeta{
Name: valkeyNodeName(cluster.Name, shardIndex, nodeIndex),
Namespace: cluster.Namespace,
Labels: l,
},
Spec: valkeyiov1alpha1.ValkeyNodeSpec{
Image: cluster.Spec.Image,
ImagePullSecrets: cluster.Spec.ImagePullSecrets,
WorkloadType: cluster.Spec.WorkloadType,
Persistence: cluster.Spec.Persistence,
Resources: cluster.Spec.Resources,
NodeSelector: scheduling.NodeSelector,
Affinity: affinity,
Tolerations: scheduling.Tolerations,
PriorityClassName: scheduling.PriorityClassName,
TopologySpreadConstraints: topologySpreadConstraints,
Exporter: cluster.Spec.Exporter,
Containers: cluster.Spec.Containers,
ServerConfigMapName: GetServerConfigMapName(cluster.Name),
UsersACLSecretName: getInternalSecretName(cluster.Name),
TLS: cluster.Spec.TLS,
Config: cluster.Spec.Config,
PodSecurityContext: cluster.Spec.PodSecurityContext,
TerminationGracePeriodSeconds: gracePeriod,
},
}
}
func (r *ValkeyClusterReconciler) getValkeyClusterState(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster, nodes *valkeyiov1alpha1.ValkeyNodeList, username, password string) *valkey.ClusterState {
ips := []string{}
for _, node := range nodes.Items {
if node.Status.PodIP == "" {
continue
}
ips = append(ips, node.Status.PodIP)
}
var tlsConfig *tls.Config
if cluster.Spec.TLS != nil && cluster.Spec.TLS.Certificate.SecretName != "" {
serverName := fmt.Sprintf("%s.%s.svc.cluster.local", headlessServiceName(cluster.Name), cluster.Namespace)
cfg, err := getTLSConfig(ctx, r.APIReader, cluster.Spec.TLS.Certificate.SecretName, serverName, cluster.Namespace)
if err == nil {
tlsConfig = cfg
}
}
return valkey.GetClusterState(ctx, ips, DefaultPort, username, password, tlsConfig)
}
// findMeetTarget picks the best node to MEET all isolated nodes against.
// Priority: (1) a shard primary, it owns slots and is an established cluster
// member even if cluster_known_nodes is 1 (e.g. a single-node cluster being
// scaled up); (2) a non-isolated pending node from a previous MEET batch;
// (3) the first isolated node as a bootstrap seed when every single node is
// isolated (fresh bootstrap, first reconcile).
func findMeetTarget(state *valkey.ClusterState, isolated []*valkey.NodeState) *valkey.NodeState {
for _, shard := range state.Shards {
if p := shard.GetPrimaryNode(); p != nil {
return p
}
}
for _, node := range state.PendingNodes {
if !node.IsIsolated() {
return node
}
}
return isolated[0]
}
// meetIsolatedNodes issues CLUSTER MEET for every isolated pending node
// (cluster_known_nodes <= 1). Phase 2 (assignSlotsToPendingPrimaries)
// refuses to assign slots to isolated nodes, so every node is guaranteed
// to pass through this function before receiving slots or replicating.
//
// Before issuing MEET, we set each node's config epoch above the cluster's
// current epoch.
//
// MEET is idempotent and has no ordering dependencies, so all isolated nodes
// can be introduced in a single pass. We pick a single "meet target" node
// and MEET all others against it:
//
// - If any non-isolated node exists (shard primary with cluster_known_nodes
// > 1, or a pending node from a previous MEET batch), use it as the
// target so new nodes join the existing cluster.
// - If all nodes are isolated (fresh bootstrap), use the first isolated
// node as a bootstrap seed. All others MEET this seed, and gossip
// propagates the full topology from there.
//
// Returns the number of nodes that were MEET'd.
func (r *ValkeyClusterReconciler) meetIsolatedNodes(ctx context.Context, cluster *valkeyiov1alpha1.ValkeyCluster, state *valkey.ClusterState) (int, error) {
log := logf.FromContext(ctx)
var isolated []*valkey.NodeState
for _, node := range state.PendingNodes {
if node.IsIsolated() {
isolated = append(isolated, node)
}
}
if len(isolated) == 0 {
return 0, nil
}