/
fdb_cluster.go
1379 lines (1169 loc) · 47.2 KB
/
fdb_cluster.go
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
/*
* fdb_cluster.go
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2023 Apple Inc. and the FoundationDB project 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 fixtures
import (
ctx "context"
"fmt"
"golang.org/x/sync/errgroup"
"k8s.io/apimachinery/pkg/types"
"log"
"math"
"strconv"
"strings"
"sync"
"time"
"k8s.io/client-go/util/retry"
fdbv1beta2 "github.com/FoundationDB/fdb-kubernetes-operator/api/v1beta2"
"github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
kubeErrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// FdbCluster is a fixture that allows tests to manipulate an FDB cluster with some name.
// Depending on how it was instantiated, the cluster may or may not exist, and may or may not
// be part of an HA configuration.
type FdbCluster struct {
cluster *fdbv1beta2.FoundationDBCluster
factory *Factory
}
// GetFDBImage return the FDB image used for the current version, defined in the FoundationDBClusterSpec.
func (fdbCluster *FdbCluster) GetFDBImage() string {
return fdbv1beta2.SelectImageConfig(fdbCluster.GetClusterSpec().MainContainer.ImageConfigs, fdbCluster.cluster.Spec.Version).
Image()
}
// GetSidecarImageForVersion return the sidecar image used for the specified version.
func (fdbCluster *FdbCluster) GetSidecarImageForVersion(version string) string {
return fdbv1beta2.SelectImageConfig(fdbCluster.GetClusterSpec().SidecarContainer.ImageConfigs, version).
Image()
}
// ExecuteCmdOnPod will run the provided command in a Shell.
func (fdbCluster *FdbCluster) ExecuteCmdOnPod(
pod corev1.Pod,
container string,
command string,
printOutput bool,
) (string, string, error) {
return fdbCluster.factory.ExecuteCmd(pod.Namespace, pod.Name, container, command, printOutput)
}
func (factory *Factory) createFdbClusterObject(
cluster *fdbv1beta2.FoundationDBCluster,
) *FdbCluster {
return &FdbCluster{
cluster,
factory,
}
}
// GetResourceLabels returns the resource labels for all created resources of the current FoundationDBCluster.
func (fdbCluster *FdbCluster) GetResourceLabels() map[string]string {
return fdbCluster.cluster.GetResourceLabels()
}
// Name returns the name for the FoundationDBCluster.
func (fdbCluster *FdbCluster) Name() string {
return fdbCluster.cluster.Name
}
func (fdbCluster *FdbCluster) getClient() client.Client {
return fdbCluster.factory.GetControllerRuntimeClient()
}
// Namespace returns the namespace for the FoundationDBCluster.
func (fdbCluster *FdbCluster) Namespace() string {
return fdbCluster.cluster.Namespace
}
// WaitUntilExists synchronously waits until the cluster exists. Usually called after Create().
func (fdbCluster *FdbCluster) WaitUntilExists() {
clusterRequest := fdbv1beta2.FoundationDBCluster{}
key := client.ObjectKeyFromObject(fdbCluster.cluster)
gomega.Eventually(func() error {
return fdbCluster.getClient().
Get(ctx.Background(), key, &clusterRequest)
}).WithTimeout(2 * time.Minute).ShouldNot(gomega.HaveOccurred())
}
// Create asynchronously creates this FDB cluster.
func (fdbCluster *FdbCluster) Create() error {
return fdbCluster.getClient().Create(ctx.Background(), fdbCluster.cluster)
}
// Update asynchronously updates this FDB cluster definition.
func (fdbCluster *FdbCluster) Update() error {
return fdbCluster.getClient().Update(ctx.Background(), fdbCluster.cluster)
}
// ReconciliationOptions defines the different reconciliation options.
type ReconciliationOptions struct {
allowSoftReconciliation bool
creationTrackerLogger CreationTrackerLogger
minimumGeneration int64
timeOutInSeconds int
pollTimeInSeconds int
}
// ReconciliationOption defines the reconciliation option.
type ReconciliationOption func(*ReconciliationOptions)
// SoftReconcileOption specifies that the reconciliation is completed as soon as the Status.Generations.Reconciled reaches the
// expected generation. Independent of other possible Generations, e.g. it could be still the case that the operator has to
// delete additional Process Groups.
func SoftReconcileOption(enable bool) ReconciliationOption {
return func(options *ReconciliationOptions) {
options.allowSoftReconciliation = enable
}
}
// CreationTrackerLoggerOption sets the creation tracker that will printout the time for the different creation stages.
func CreationTrackerLoggerOption(creationTrackerLogger CreationTrackerLogger) ReconciliationOption {
return func(options *ReconciliationOptions) {
options.creationTrackerLogger = creationTrackerLogger
}
}
// MinimumGenerationOption specifies the minimum generation to be reconciled too.
func MinimumGenerationOption(minimumGeneration int64) ReconciliationOption {
return func(options *ReconciliationOptions) {
options.minimumGeneration = minimumGeneration
}
}
// TimeOutInSecondsOption defines the timeout for the reconciliation. If not set the default is 4800 seconds
func TimeOutInSecondsOption(timeOutInSeconds int) ReconciliationOption {
return func(options *ReconciliationOptions) {
options.timeOutInSeconds = timeOutInSeconds
}
}
// PollTimeInSecondsOption defines the polling time for the reconciliation. If not set the default is 10 seconds
func PollTimeInSecondsOption(pollTimeInSeconds int) ReconciliationOption {
return func(options *ReconciliationOptions) {
options.pollTimeInSeconds = pollTimeInSeconds
}
}
// MakeReconciliationOptionsStruct applies the provided options to the ReconciliationOptions.
func MakeReconciliationOptionsStruct(
options ...func(*ReconciliationOptions),
) *ReconciliationOptions {
reconciliationOptions := &ReconciliationOptions{}
for _, option := range options {
option(reconciliationOptions)
}
if reconciliationOptions.timeOutInSeconds == 0 {
// Wait for 30 minutes as timeout.
reconciliationOptions.timeOutInSeconds = 1800
}
if reconciliationOptions.pollTimeInSeconds == 0 {
reconciliationOptions.pollTimeInSeconds = 10
}
return reconciliationOptions
}
// WaitForReconciliation waits for the cluster to be reconciled based on the provided options.
func (fdbCluster *FdbCluster) WaitForReconciliation(options ...func(*ReconciliationOptions)) error {
reconciliationOptions := MakeReconciliationOptionsStruct(options...)
return fdbCluster.waitForReconciliationToGeneration(
reconciliationOptions.minimumGeneration,
reconciliationOptions.allowSoftReconciliation,
reconciliationOptions.creationTrackerLogger,
reconciliationOptions.timeOutInSeconds,
reconciliationOptions.pollTimeInSeconds,
)
}
// waitForReconciliationToGeneration waits for a specific generation to be reached.
func (fdbCluster *FdbCluster) waitForReconciliationToGeneration(
minimumGeneration int64,
softReconciliationAllowed bool,
creationTrackerLogger CreationTrackerLogger,
timeOutInSeconds int,
pollTimeInSeconds int,
) error {
if timeOutInSeconds < pollTimeInSeconds {
return fmt.Errorf(
"timeout %d is less than poll time %d",
timeOutInSeconds,
pollTimeInSeconds,
)
}
log.Printf(
"waiting until the cluster %s/%s is healthy and reconciled",
fdbCluster.cluster.Namespace,
fdbCluster.cluster.Name,
)
if minimumGeneration > 0 {
log.Printf(
"waiting for generation %d, current generation: %d",
minimumGeneration,
fdbCluster.cluster.Generation,
)
}
var creationTracker *fdbClusterCreationTracker
if creationTrackerLogger != nil {
creationTracker = newFdbClusterCreationTracker(
fdbCluster.getClient(),
creationTrackerLogger,
)
}
checkIfReconciliationIsDone := func(cluster *fdbv1beta2.FoundationDBCluster) bool {
if creationTracker != nil {
creationTracker.trackProgress(cluster)
}
var reconciled bool
if softReconciliationAllowed {
reconciled = cluster.Status.Generations.Reconciled == cluster.ObjectMeta.Generation
} else {
reconciled = cluster.Status.Generations == fdbv1beta2.ClusterGenerationStatus{Reconciled: cluster.ObjectMeta.Generation}
}
if minimumGeneration > 0 {
reconciled = reconciled &&
cluster.Status.Generations.Reconciled >= minimumGeneration
}
if reconciled {
log.Printf(
"reconciled name=%s, namespace=%s, generation:%d",
fdbCluster.cluster.Name,
fdbCluster.cluster.Namespace,
fdbCluster.cluster.Generation,
)
return true
}
return false
}
err := fdbCluster.WaitUntilWithForceReconcile(pollTimeInSeconds, timeOutInSeconds, checkIfReconciliationIsDone)
if creationTracker != nil {
creationTracker.report()
}
return err
}
// WaitUntilWithForceReconcile will wait either until the checkMethod returns true or until the timeout is hit.
func (fdbCluster *FdbCluster) WaitUntilWithForceReconcile(pollTimeInSeconds int, timeOutInSeconds int, checkMethod func(cluster *fdbv1beta2.FoundationDBCluster) bool) error {
// Printout the initial state of the cluster before we moving forward waiting for the checkMethod to return true.
fdbCluster.factory.DumpState(fdbCluster)
lastForcedReconciliationTime := time.Now()
forceReconcileDuration := 4 * time.Minute
return wait.PollImmediate(
time.Duration(pollTimeInSeconds)*time.Second,
time.Duration(timeOutInSeconds)*time.Second,
func() (bool, error) {
resCluster := fdbCluster.GetCluster()
if checkMethod(resCluster) {
return true, nil
}
// Force a reconcile if needed.
if time.Since(lastForcedReconciliationTime) >= forceReconcileDuration {
fdbCluster.ForceReconcile()
lastForcedReconciliationTime = time.Now()
}
return false, nil
},
)
}
// ForceReconcile will add an annotation with the current timestamp on the FoundationDBCluster resource to make sure
// the operator reconciliation loop is triggered. This is used to speed up some test cases.
func (fdbCluster *FdbCluster) ForceReconcile() {
log.Printf("ForceReconcile: Status Generations=%s, Metadata Generation=%d",
ToJSON(fdbCluster.cluster.Status.Generations),
fdbCluster.cluster.ObjectMeta.Generation)
fdbCluster.factory.DumpState(fdbCluster)
patch := client.MergeFrom(fdbCluster.cluster.DeepCopy())
if fdbCluster.cluster.Annotations == nil {
fdbCluster.cluster.Annotations = make(map[string]string)
}
fdbCluster.cluster.Annotations["foundationdb.org/reconcile"] = strconv.FormatInt(
time.Now().UnixNano(),
10,
)
// This will apply an Annotation to the object which will trigger the reconcile loop.
// This should speed up the reconcile phase.
err := fdbCluster.getClient().Patch(
ctx.Background(),
fdbCluster.cluster,
patch)
if err != nil {
log.Println("error patching annotation to force reconcile, error:", err.Error())
}
}
// GetCluster returns the FoundationDBCluster of the cluster. This will fetch the latest value from the Kubernetes API.
func (fdbCluster *FdbCluster) GetCluster() *fdbv1beta2.FoundationDBCluster {
var cluster *fdbv1beta2.FoundationDBCluster
gomega.Eventually(func() error {
var err error
cluster, err = fdbCluster.factory.getClusterStatus(
fdbCluster.Name(),
fdbCluster.Namespace(),
)
if err != nil {
log.Println(
"error fetching information for FoundationDBCluster",
fdbCluster.Name(),
"in",
fdbCluster.Namespace(),
"got error:",
err.Error(),
)
}
return err
}).WithTimeout(2 * time.Minute).WithPolling(1 * time.Second).ShouldNot(gomega.HaveOccurred())
// Update the cached cluster
fdbCluster.cluster = cluster
return cluster
}
// GetCachedCluster returns the current cluster definition stored in the fdbCluster struct. This could be outdated and
// if you need the most recent version of the definition you should use `GetCluster`. This method is useful if you want
// to inspect fields that are not changing.
func (fdbCluster *FdbCluster) GetCachedCluster() *fdbv1beta2.FoundationDBCluster {
return fdbCluster.cluster
}
// SetDatabaseConfiguration sets the provided DatabaseConfiguration for the FoundationDBCluster.
func (fdbCluster *FdbCluster) SetDatabaseConfiguration(
config fdbv1beta2.DatabaseConfiguration,
waitForReconcile bool,
) error {
fdbCluster.cluster.Spec.DatabaseConfiguration = config
fdbCluster.UpdateClusterSpec()
if !waitForReconcile {
return nil
}
return fdbCluster.WaitForReconciliation()
}
// UpdateClusterSpec ensures that the FoundationDBCluster will be updated in Kubernetes. This method has a retry mechanism
// implemented and ensures that the provided (local) Spec matches the Spec in Kubernetes.
func (fdbCluster *FdbCluster) UpdateClusterSpec() {
fdbCluster.UpdateClusterSpecWithSpec(fdbCluster.cluster.Spec.DeepCopy())
}
// UpdateClusterSpecWithSpec ensures that the FoundationDBCluster will be updated in Kubernetes. This method as a retry mechanism
// implemented and ensures that the provided (local) Spec matches the Spec in Kubernetes. You must make sure that you call
// fdbCluster.GetCluster() before updating the spec, to make sure you are not overwriting the current state with an outdated state.
// An example on how to update a field with this method:
//
// spec := fdbCluster.GetCluster().Spec.DeepCopy() // Fetch the current Spec.
// spec.Version = "7.1.27" // Make your changes.
//
// fdbCluster.UpdateClusterSpecWithSpec(spec) // Update the spec.
func (fdbCluster *FdbCluster) UpdateClusterSpecWithSpec(desiredSpec *fdbv1beta2.FoundationDBClusterSpec) {
fetchedCluster := &fdbv1beta2.FoundationDBCluster{}
// This is flaky. It sometimes responds with an error saying that the object has been updated.
// Try a few times before giving up.
gomega.Eventually(func() bool {
err := fdbCluster.getClient().
Get(ctx.Background(), client.ObjectKeyFromObject(fdbCluster.cluster), fetchedCluster)
if err != nil {
log.Println("UpdateClusterSpec: error fetching cluster:", err)
return false
}
specUpdated := equality.Semantic.DeepEqual(fetchedCluster.Spec, *desiredSpec)
log.Println("UpdateClusterSpec: specUpdated:", specUpdated)
if specUpdated {
return true
}
desiredSpec.DeepCopyInto(&fetchedCluster.Spec)
err = fdbCluster.getClient().Update(ctx.Background(), fetchedCluster)
if err != nil {
log.Println("UpdateClusterSpec: error updating cluster:", err)
}
// Retry here and let the method fetch the latest version of the cluster again until the spec is updated.
return false
}).WithTimeout(10 * time.Minute).WithPolling(1 * time.Second).Should(gomega.BeTrue())
fdbCluster.cluster = fetchedCluster
}
// GetAllPods returns all pods, even if not running.
func (fdbCluster *FdbCluster) GetAllPods() *corev1.PodList {
podList := &corev1.PodList{}
gomega.Eventually(func() error {
return fdbCluster.getClient().
List(ctx.TODO(), podList, client.MatchingLabels(fdbCluster.cluster.GetMatchLabels()))
}).WithTimeout(1 * time.Minute).WithPolling(1 * time.Second).ShouldNot(gomega.HaveOccurred())
return podList
}
// GetPods returns only running Pods.
func (fdbCluster *FdbCluster) GetPods() *corev1.PodList {
podList := &corev1.PodList{}
gomega.Eventually(func() error {
return fdbCluster.getClient().List(ctx.TODO(), podList,
client.InNamespace(fdbCluster.Namespace()),
client.MatchingLabels(fdbCluster.cluster.GetMatchLabels()),
client.MatchingFields(map[string]string{"status.phase": string(corev1.PodRunning)}),
)
}).WithTimeout(1 * time.Minute).WithPolling(1 * time.Second).ShouldNot(gomega.HaveOccurred())
return podList
}
// GetPodsNames GetS all Running Pods and return their names.
func (fdbCluster *FdbCluster) GetPodsNames() []string {
results := make([]string, 0)
podList := fdbCluster.GetPods()
for _, pod := range podList.Items {
results = append(results, pod.Name)
}
return results
}
func (fdbCluster *FdbCluster) getPodsByProcessClass(
processClass fdbv1beta2.ProcessClass,
) *corev1.PodList {
podList := &corev1.PodList{}
gomega.Eventually(func() error {
return fdbCluster.getClient().List(ctx.TODO(), podList,
client.InNamespace(fdbCluster.Namespace()),
client.MatchingLabels(map[string]string{
fdbv1beta2.FDBClusterLabel: fdbCluster.cluster.Name,
fdbv1beta2.FDBProcessClassLabel: string(processClass)}))
}).WithTimeout(1 * time.Minute).WithPolling(1 * time.Second).ShouldNot(gomega.HaveOccurred())
return podList
}
// GetLogPods returns all Pods of this cluster that have the process class log.
func (fdbCluster *FdbCluster) GetLogPods() *corev1.PodList {
return fdbCluster.getPodsByProcessClass(fdbv1beta2.ProcessClassLog)
}
// GetStatelessPods returns all Pods of this cluster that have the process class stateless.
func (fdbCluster *FdbCluster) GetStatelessPods() *corev1.PodList {
return fdbCluster.getPodsByProcessClass(fdbv1beta2.ProcessClassStateless)
}
// GetStoragePods returns all Pods of this cluster that have the process class storage.
func (fdbCluster *FdbCluster) GetStoragePods() *corev1.PodList {
return fdbCluster.getPodsByProcessClass(fdbv1beta2.ProcessClassStorage)
}
// GetTransactionPods returns all Pods of this cluster that have the process class transaction.
func (fdbCluster *FdbCluster) GetTransactionPods() *corev1.PodList {
return fdbCluster.getPodsByProcessClass(fdbv1beta2.ProcessClassTransaction)
}
// GetPod returns the Pod with the given name that runs in the same namespace as the FoundationDBCluster.
func (fdbCluster *FdbCluster) GetPod(name string) *corev1.Pod {
pod := &corev1.Pod{}
// Retry if for some reasons an error is returned
gomega.Eventually(func() error {
return fdbCluster.getClient().
Get(ctx.TODO(), client.ObjectKey{Name: name, Namespace: fdbCluster.Namespace()}, pod)
}).WithTimeout(2 * time.Minute).WithPolling(1 * time.Second).ShouldNot(gomega.HaveOccurred())
return pod
}
// GetPodIDs returns all the process group IDs for all Pods of this cluster that have the matching process class.
func (fdbCluster *FdbCluster) GetPodIDs(processClass fdbv1beta2.ProcessClass) map[fdbv1beta2.ProcessGroupID]fdbv1beta2.None {
pods := fdbCluster.GetPods()
podIDs := make(map[fdbv1beta2.ProcessGroupID]fdbv1beta2.None, len(pods.Items))
for _, pod := range pods.Items {
if pod.GetLabels()[fdbv1beta2.FDBProcessClassLabel] != string(processClass) {
continue
}
log.Println(pod.Name)
podIDs[GetProcessGroupID(pod)] = fdbv1beta2.None{}
}
return podIDs
}
// GetVolumeClaimsForProcesses returns a list of volume claims belonging to this cluster and the specific process class.
func (fdbCluster *FdbCluster) GetVolumeClaimsForProcesses(
processClass fdbv1beta2.ProcessClass,
) *corev1.PersistentVolumeClaimList {
volumeClaimList := &corev1.PersistentVolumeClaimList{}
gomega.Expect(
fdbCluster.getClient().
List(ctx.TODO(), volumeClaimList,
client.InNamespace(fdbCluster.Namespace()),
client.MatchingLabels(map[string]string{
fdbv1beta2.FDBClusterLabel: fdbCluster.cluster.Name,
fdbv1beta2.FDBProcessClassLabel: string(processClass),
})),
).NotTo(gomega.HaveOccurred())
return volumeClaimList
}
// GetLogServersPerPod returns the current expected Log server per pod.
func (fdbCluster *FdbCluster) GetLogServersPerPod() int {
return fdbCluster.cluster.GetLogServersPerPod()
}
// SetLogServersPerPod set the LogServersPerPod field in the cluster spec.
func (fdbCluster *FdbCluster) SetLogServersPerPod(
serverPerPod int,
waitForReconcile bool,
) error {
fdbCluster.cluster.Spec.LogServersPerPod = serverPerPod
fdbCluster.UpdateClusterSpec()
if !waitForReconcile {
return nil
}
return fdbCluster.WaitForReconciliation()
}
// GetStorageServerPerPod returns the current expected storage server per pod.
func (fdbCluster *FdbCluster) GetStorageServerPerPod() int {
return fdbCluster.cluster.GetStorageServersPerPod()
}
func (fdbCluster *FdbCluster) setStorageServerPerPod(
serverPerPod int,
waitForReconcile bool,
) error {
fdbCluster.cluster.Spec.StorageServersPerPod = serverPerPod
fdbCluster.UpdateClusterSpec()
if !waitForReconcile {
return nil
}
return fdbCluster.WaitForReconciliation()
}
// SetStorageServerPerPod set the SetStorageServerPerPod field in the cluster spec.
func (fdbCluster *FdbCluster) SetStorageServerPerPod(serverPerPod int) error {
return fdbCluster.setStorageServerPerPod(serverPerPod, true)
}
// SetTransactionServerPerPod set the LogServersPerPod field in the cluster spec and changes log Pods to transaction Pods.
func (fdbCluster *FdbCluster) SetTransactionServerPerPod(
serverPerPod int,
processCount int,
waitForReconcile bool,
) error {
fdbCluster.cluster.Spec.LogServersPerPod = serverPerPod
fdbCluster.cluster.Spec.ProcessCounts.Transaction = processCount
fdbCluster.cluster.Spec.ProcessCounts.Log = 0
fdbCluster.UpdateClusterSpec()
if !waitForReconcile {
return nil
}
return fdbCluster.WaitForReconciliation()
}
// ReplacePod replaces the provided Pod if it's part of the FoundationDBCluster.
func (fdbCluster *FdbCluster) ReplacePod(pod corev1.Pod, waitForReconcile bool) {
fdbCluster.cluster.Spec.ProcessGroupsToRemove = []fdbv1beta2.ProcessGroupID{GetProcessGroupID(pod)}
fdbCluster.UpdateClusterSpec()
if !waitForReconcile {
return
}
gomega.Expect(fdbCluster.WaitForReconciliation(SoftReconcileOption(true))).NotTo(gomega.HaveOccurred())
}
// ReplacePods replaces the provided Pods in the current FoundationDBCluster.
func (fdbCluster *FdbCluster) ReplacePods(pods []corev1.Pod, waitForReconcile bool) {
for _, pod := range pods {
fdbCluster.cluster.Spec.ProcessGroupsToRemove = append(
fdbCluster.cluster.Spec.ProcessGroupsToRemove,
GetProcessGroupID(pod),
)
}
fdbCluster.UpdateClusterSpec()
if !waitForReconcile {
return
}
gomega.Expect(fdbCluster.WaitForReconciliation()).NotTo(gomega.HaveOccurred())
}
// ClearProcessGroupsToRemove clears the InstancesToRemove list in the cluster
// spec.
func (fdbCluster *FdbCluster) ClearProcessGroupsToRemove() error {
fdbCluster.cluster.Spec.ProcessGroupsToRemove = nil
fdbCluster.UpdateClusterSpec()
return fdbCluster.WaitForReconciliation()
}
// SetVolumeSize updates the volume size for the specified process class.
func (fdbCluster *FdbCluster) SetVolumeSize(
processClass fdbv1beta2.ProcessClass,
size resource.Quantity,
) error {
processSettings, ok := fdbCluster.cluster.Spec.Processes[processClass]
if !ok || processSettings.VolumeClaimTemplate == nil {
processSettings, ok = fdbCluster.cluster.Spec.Processes[fdbv1beta2.ProcessClassGeneral]
if !ok {
return fmt.Errorf("could not find process setting for %s", processClass)
}
}
setting := fdbCluster.cluster.Spec.Processes[processClass]
// Set the new volume claim template
if processSettings.VolumeClaimTemplate == nil {
setting.VolumeClaimTemplate = &corev1.PersistentVolumeClaim{
Spec: corev1.PersistentVolumeClaimSpec{
Resources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceStorage: size,
},
},
},
}
} else {
setting.VolumeClaimTemplate = processSettings.VolumeClaimTemplate.DeepCopy()
setting.VolumeClaimTemplate.Spec.Resources.Requests[corev1.ResourceStorage] = size
}
fdbCluster.cluster.Spec.Processes[processClass] = setting
fdbCluster.UpdateClusterSpec()
return fdbCluster.WaitForReconciliation()
}
// GetVolumeSize returns the volume size for the specified process class.
func (fdbCluster *FdbCluster) GetVolumeSize(
processClass fdbv1beta2.ProcessClass,
) (resource.Quantity, error) {
processSettings, ok := fdbCluster.cluster.Spec.Processes[processClass]
if !ok || processSettings.VolumeClaimTemplate == nil {
processSettings, ok = fdbCluster.cluster.Spec.Processes[fdbv1beta2.ProcessClassGeneral]
if !ok || processSettings.VolumeClaimTemplate == nil {
return resource.MustParse("128G"), nil
}
}
return processSettings.VolumeClaimTemplate.Spec.Resources.Requests[corev1.ResourceStorage], nil
}
func (fdbCluster *FdbCluster) updateLogProcessCount(
newLogProcessCount int,
waitForReconcile bool,
) error {
fdbCluster.cluster.Spec.ProcessCounts.Log = newLogProcessCount
fdbCluster.UpdateClusterSpec()
if !waitForReconcile {
return nil
}
return fdbCluster.WaitForReconciliation()
}
// UpdateLogProcessCount updates the log process count in the cluster spec.
func (fdbCluster *FdbCluster) UpdateLogProcessCount(newLogProcessCount int) error {
return fdbCluster.updateLogProcessCount(newLogProcessCount, true)
}
// SetPodAsUnschedulable sets the provided Pod on the NoSchedule list of the current FoundationDBCluster. This will make
// sure that the Pod is stuck in Pending.
func (fdbCluster *FdbCluster) SetPodAsUnschedulable(pod corev1.Pod) error {
fdbCluster.SetProcessGroupsAsUnschedulable([]fdbv1beta2.ProcessGroupID{GetProcessGroupID(pod)})
fetchedPod := &corev1.Pod{}
return wait.PollImmediate(2*time.Second, 5*time.Minute, func() (bool, error) {
err := fdbCluster.getClient().
Get(ctx.Background(), client.ObjectKeyFromObject(&pod), fetchedPod)
if err != nil {
if kubeErrors.IsNotFound(err) {
return false, nil
}
return false, err
}
// Try deleting the Pod as a workaround until the operator handle all cases.
if fetchedPod.Spec.NodeName != "" && fetchedPod.DeletionTimestamp.IsZero() {
_ = fdbCluster.getClient().Delete(ctx.Background(), &pod)
}
return fetchedPod.Spec.NodeName == "", nil
})
}
// SetProcessGroupsAsUnschedulable sets the provided process groups on the NoSchedule list of the current FoundationDBCluster. This will make
// sure that the Pod is stuck in Pending.
func (fdbCluster *FdbCluster) SetProcessGroupsAsUnschedulable(processGroups []fdbv1beta2.ProcessGroupID) {
fdbCluster.cluster.Spec.Buggify.NoSchedule = processGroups
fdbCluster.UpdateClusterSpec()
}
// ClearBuggifyNoSchedule this will reset the NoSchedule setting for the current FoundationDBCluster.
func (fdbCluster *FdbCluster) ClearBuggifyNoSchedule(waitForReconcile bool) error {
fdbCluster.cluster.Spec.Buggify.NoSchedule = nil
fdbCluster.UpdateClusterSpec()
if !waitForReconcile {
return nil
}
return fdbCluster.WaitForReconciliation()
}
func (fdbCluster *FdbCluster) setPublicIPSource(
publicIPSource fdbv1beta2.PublicIPSource,
waitForReconcile bool,
) error {
fdbCluster.cluster.Spec.Routing.PublicIPSource = &publicIPSource
fdbCluster.UpdateClusterSpec()
if !waitForReconcile {
return nil
}
return fdbCluster.WaitForReconciliation()
}
// SetTLS will enabled or disable the TLS setting in the current FoundationDBCluster.
func (fdbCluster *FdbCluster) SetTLS(
enableMainContainerTLS bool,
enableSidecarContainerTLS bool,
) error {
fdbCluster.cluster.Spec.MainContainer.EnableTLS = enableMainContainerTLS
fdbCluster.cluster.Spec.SidecarContainer.EnableTLS = enableSidecarContainerTLS
fdbCluster.UpdateClusterSpec()
return fdbCluster.WaitForReconciliation()
}
// SetPublicIPSource will set the public IP source of the current FoundationDBCluster to the provided IP source.
func (fdbCluster *FdbCluster) SetPublicIPSource(publicIPSource fdbv1beta2.PublicIPSource) error {
return fdbCluster.setPublicIPSource(publicIPSource, true)
}
// GetServices returns the services associated with the current FoundationDBCluster.
func (fdbCluster *FdbCluster) GetServices() *corev1.ServiceList {
serviceList := &corev1.ServiceList{}
gomega.Expect(
fdbCluster.getClient().List(
ctx.TODO(),
serviceList,
client.InNamespace(fdbCluster.Namespace()),
client.MatchingLabels(fdbCluster.GetResourceLabels())),
).NotTo(gomega.HaveOccurred())
return serviceList
}
// SetAutoReplacements will enabled or disable the auto replacement feature and allows to specify the detection time for a replacement.
func (fdbCluster *FdbCluster) SetAutoReplacements(enabled bool, detectionTime time.Duration) error {
return fdbCluster.SetAutoReplacementsWithWait(enabled, detectionTime, true)
}
// SetAutoReplacementsWithWait set the auto replacement setting on the operator and only waits for the cluster to reconcile
// if wait is set to true.
func (fdbCluster *FdbCluster) SetAutoReplacementsWithWait(
enabled bool,
detectionTime time.Duration,
wait bool,
) error {
detectionTimeSec := int(detectionTime.Seconds())
fdbCluster.cluster.Spec.AutomationOptions.Replacements.Enabled = &enabled
fdbCluster.cluster.Spec.AutomationOptions.Replacements.FailureDetectionTimeSeconds = &detectionTimeSec
fdbCluster.UpdateClusterSpec()
if !wait {
return nil
}
return fdbCluster.WaitForReconciliation()
}
// UpdateCoordinatorSelection allows to update the coordinator selection for the current FoundationDBCluster.
func (fdbCluster *FdbCluster) UpdateCoordinatorSelection(
setting []fdbv1beta2.CoordinatorSelectionSetting,
) error {
fdbCluster.cluster.Spec.CoordinatorSelection = setting
fdbCluster.UpdateClusterSpec()
return fdbCluster.WaitForReconciliation()
}
// SetProcessGroupPrefix will set the process group prefix setting.
func (fdbCluster *FdbCluster) SetProcessGroupPrefix(prefix string) error {
fdbCluster.cluster.Spec.ProcessGroupIDPrefix = prefix
fdbCluster.UpdateClusterSpec()
return fdbCluster.WaitForReconciliation()
}
// SetSkipReconciliation will set the skip setting for the current FoundationDBCluster. This setting will make sure that
// the operator is not taking any actions on this cluster.
func (fdbCluster *FdbCluster) SetSkipReconciliation(skip bool) error {
fdbCluster.cluster.Spec.Skip = skip
// Skip wait for reconciliation since this spec update is in the operator itself and by setting it, the operator
// skips reconciliation.
fdbCluster.UpdateClusterSpec()
return nil
}
// WaitForPodRemoval will wait until the specified Pod is deleted.
func (fdbCluster *FdbCluster) WaitForPodRemoval(pod *corev1.Pod) error {
if pod == nil {
return nil
}
log.Printf("waiting until the pod %s/%s is deleted", pod.Namespace, pod.Name)
counter := 0
forceReconcile := 10
// Poll every 2 seconds for a maximum of 40 minutes.
fetchedPod := &corev1.Pod{}
err := wait.PollImmediate(2*time.Second, 40*time.Minute, func() (bool, error) {
err := fdbCluster.getClient().
Get(ctx.Background(), client.ObjectKeyFromObject(pod), fetchedPod)
if err != nil {
if kubeErrors.IsNotFound(err) {
return true, nil
}
}
resCluster := fdbCluster.GetCluster()
// We have to force a reconcile because the operator only reacts to events.
// The network partition of the Pod won't trigger any reconcile and we would have to wait for 10h.
if counter >= forceReconcile {
patch := client.MergeFrom(resCluster.DeepCopy())
if resCluster.Annotations == nil {
resCluster.Annotations = make(map[string]string)
}
resCluster.Annotations["foundationdb.org/reconcile"] = strconv.FormatInt(
time.Now().UnixNano(),
10,
)
// This will apply an Annotation to the object which will trigger the reconcile loop.
// This should speed up the reconcile phase.
_ = fdbCluster.getClient().Patch(
ctx.Background(),
resCluster,
patch)
counter = -1
}
counter++
return false, nil
})
if err == nil {
return nil
}
return fmt.Errorf("pod %s/%s was not removed in the expected time", pod.Namespace, pod.Name)
}
// GetClusterSpec returns the current cluster spec.
func (fdbCluster *FdbCluster) GetClusterSpec() fdbv1beta2.FoundationDBClusterSpec {
// Ensure we fetch the latest state to ensure we return the latest spec and not a cached state.
_ = fdbCluster.GetCluster()
return fdbCluster.cluster.Spec
}
// BounceClusterWithoutWait will restart all fdberver processes in the current FoundationDBCluster without waiting for the
// cluster to become available again.
func (fdbCluster *FdbCluster) BounceClusterWithoutWait() error {
var retries int
var err error
// We try to execute the bounce command 5 times
for retries < 5 {
_, _, err = fdbCluster.RunFdbCliCommandInOperatorWithoutRetry(
"kill; kill all; sleep 5",
true,
30,
)
if err != nil {
log.Println(err)
retries++
continue
}
return nil
}
return err
}
// SetFinalizerForPvc allows to set the finalizers for the provided PVC.
func (fdbCluster *FdbCluster) SetFinalizerForPvc(
finalizers []string,
pvc corev1.PersistentVolumeClaim,
) error {
patch := client.MergeFrom(pvc.DeepCopy())
pvc.SetFinalizers(finalizers)
return fdbCluster.getClient().Patch(ctx.Background(), &pvc, patch)
}
// UpdateStorageClass this will set the StorageClass for the provided process class of the current FoundationDBCluster.
func (fdbCluster *FdbCluster) UpdateStorageClass(
storageClass string,
processClass fdbv1beta2.ProcessClass,
) error {
log.Println("Updating storage class for", processClass, "to", storageClass)
resCluster := fdbCluster.GetCluster()
patch := client.MergeFrom(resCluster.DeepCopy())
resCluster.Spec.Processes[processClass].VolumeClaimTemplate.Spec.StorageClassName = &storageClass
_ = fdbCluster.getClient().Patch(ctx.Background(), resCluster, patch)
return fdbCluster.WaitForReconciliation()
}
// UpgradeCluster will upgrade the cluster to the specified version. If waitForReconciliation is set to true this method will
// block until the cluster is fully upgraded and all Pods are running the new image version.
func (fdbCluster *FdbCluster) UpgradeCluster(version string, waitForReconciliation bool) error {
// Ensure we have pulled that latest state of the cluster.
_ = fdbCluster.GetCluster()
log.Printf(
"Upgrading cluster from version %s to version %s",
fdbCluster.cluster.Spec.Version,
version,
)
fdbCluster.cluster.Spec.Version = version
log.Println("Spec version", fdbCluster.cluster.Spec.Version)
fdbCluster.UpdateClusterSpec()
// Ensure the version is actually upgraded.
gomega.Expect(fdbCluster.cluster.Spec.Version).To(gomega.Equal(version))
if waitForReconciliation {
log.Println("Waiting for generation:", fdbCluster.cluster.Generation)
return fdbCluster.WaitForReconciliation(MinimumGenerationOption(fdbCluster.cluster.Generation))
}
return nil
}
// SetEmptyMonitorConf sets the buggify option EmptyMonitorConf for the current FoundationDBCluster.
func (fdbCluster *FdbCluster) SetEmptyMonitorConf(enable bool) error {
fdbCluster.cluster.Spec.Buggify.EmptyMonitorConf = enable
fdbCluster.UpdateClusterSpec()
if !enable {
err := fdbCluster.WaitForReconciliation()
if err != nil {