-
Notifications
You must be signed in to change notification settings - Fork 667
Expand file tree
/
Copy pathpgbackrest_test.go
More file actions
3802 lines (3472 loc) · 125 KB
/
pgbackrest_test.go
File metadata and controls
3802 lines (3472 loc) · 125 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
//go:build envtest
// +build envtest
package postgrescluster
/*
Copyright 2021 - 2022 Crunchy Data Solutions, Inc.
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.
*/
import (
"context"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"testing"
"time"
"go.opentelemetry.io/otel"
"gotest.tools/v3/assert"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/rand"
"k8s.io/apimachinery/pkg/util/wait"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/crunchydata/postgres-operator/internal/initialize"
"github.com/crunchydata/postgres-operator/internal/naming"
"github.com/crunchydata/postgres-operator/internal/pgbackrest"
"github.com/crunchydata/postgres-operator/internal/pki"
"github.com/crunchydata/postgres-operator/internal/testing/require"
"github.com/crunchydata/postgres-operator/pkg/apis/postgres-operator.crunchydata.com/v1beta1"
)
var testCronSchedule string = "*/15 * * * *"
func fakePostgresCluster(clusterName, namespace, clusterUID string,
includeDedicatedRepo bool) *v1beta1.PostgresCluster {
postgresCluster := &v1beta1.PostgresCluster{
ObjectMeta: metav1.ObjectMeta{
Name: clusterName,
Namespace: namespace,
UID: types.UID(clusterUID),
},
Spec: v1beta1.PostgresClusterSpec{
Port: initialize.Int32(5432),
Shutdown: initialize.Bool(false),
PostgresVersion: 13,
ImagePullSecrets: []corev1.LocalObjectReference{{
Name: "myImagePullSecret"},
},
Image: "example.com/crunchy-postgres-ha:test",
InstanceSets: []v1beta1.PostgresInstanceSetSpec{{
Name: "instance1",
DataVolumeClaimSpec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteMany},
Resources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceStorage: resource.MustParse("1Gi"),
},
},
},
}},
Backups: v1beta1.Backups{
PGBackRest: v1beta1.PGBackRestArchive{
Image: "example.com/crunchy-pgbackrest:test",
Jobs: &v1beta1.BackupJobs{
PriorityClassName: initialize.String("some-priority-class"),
},
Global: map[string]string{"repo2-test": "config",
"repo3-test": "config", "repo4-test": "config"},
Repos: []v1beta1.PGBackRestRepo{{
Name: "repo1",
S3: &v1beta1.RepoS3{
Bucket: "bucket",
Endpoint: "endpoint",
Region: "region",
},
}, {
Name: "repo2",
Azure: &v1beta1.RepoAzure{
Container: "container",
},
}, {
Name: "repo3",
GCS: &v1beta1.RepoGCS{
Bucket: "bucket",
},
}, {
Name: "repo4",
S3: &v1beta1.RepoS3{
Bucket: "bucket",
Endpoint: "endpoint",
Region: "region",
},
}},
},
},
},
}
if includeDedicatedRepo {
postgresCluster.Spec.Backups.PGBackRest.Repos[0] = v1beta1.PGBackRestRepo{
Name: "repo1",
Volume: &v1beta1.RepoPVC{
VolumeClaimSpec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteMany},
Resources: corev1.ResourceRequirements{
Requests: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceStorage: resource.MustParse("1Gi"),
},
},
},
},
}
postgresCluster.Spec.Backups.PGBackRest.RepoHost = &v1beta1.PGBackRestRepoHost{
PriorityClassName: initialize.String("some-priority-class"),
Resources: corev1.ResourceRequirements{},
Affinity: &corev1.Affinity{},
Tolerations: []corev1.Toleration{
{Key: "woot"},
},
TopologySpreadConstraints: []corev1.TopologySpreadConstraint{
{
MaxSkew: int32(1),
TopologyKey: "fakekey",
WhenUnsatisfiable: corev1.ScheduleAnyway,
LabelSelector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{Key: naming.LabelCluster, Operator: "In", Values: []string{"somename"}},
{Key: naming.LabelData, Operator: "Exists"},
},
},
},
},
}
}
// always add schedule info to the first repo
postgresCluster.Spec.Backups.PGBackRest.Repos[0].BackupSchedules = &v1beta1.PGBackRestBackupSchedules{
Full: &testCronSchedule,
Differential: &testCronSchedule,
Incremental: &testCronSchedule,
}
return postgresCluster
}
func fakeObservedCronJobs() []*batchv1.CronJob {
return []*batchv1.CronJob{
{
ObjectMeta: metav1.ObjectMeta{
Name: "fake-cronjob",
}}}
}
func TestReconcilePGBackRest(t *testing.T) {
// Garbage collector cleans up test resources before the test completes
if strings.EqualFold(os.Getenv("USE_EXISTING_CLUSTER"), "true") {
t.Skip("USE_EXISTING_CLUSTER: Test fails due to garbage collection")
}
tEnv, tClient := setupKubernetes(t)
require.ParallelCapacity(t, 2)
r := &Reconciler{}
ctx, cancel := setupManager(t, tEnv.Config, func(mgr manager.Manager) {
r = &Reconciler{
Client: mgr.GetClient(),
Recorder: mgr.GetEventRecorderFor(ControllerName),
Tracer: otel.Tracer(ControllerName),
Owner: ControllerName,
}
})
t.Cleanup(func() { teardownManager(cancel, t) })
clusterName := "hippocluster"
clusterUID := "hippouid"
ns := setupNamespace(t, tClient)
// create a PostgresCluster to test with
postgresCluster := fakePostgresCluster(clusterName, ns.GetName(), clusterUID, true)
// create a service account to test with
serviceAccount, err := r.reconcilePGBackRestRBAC(ctx, postgresCluster)
assert.NilError(t, err)
assert.Assert(t, serviceAccount != nil)
// create the 'observed' instances and set the leader
instances := &observedInstances{
forCluster: []*Instance{{Name: "instance1",
Pods: []*corev1.Pod{{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{naming.LabelRole: naming.RolePatroniLeader},
},
Spec: corev1.PodSpec{},
}},
}, {Name: "instance2"}, {Name: "instance3"}},
}
// set status
postgresCluster.Status = v1beta1.PostgresClusterStatus{
Patroni: v1beta1.PatroniStatus{SystemIdentifier: "12345abcde"},
PGBackRest: &v1beta1.PGBackRestStatus{
RepoHost: &v1beta1.RepoHostStatus{Ready: true},
Repos: []v1beta1.RepoStatus{{Name: "repo1", StanzaCreated: true}}},
}
// set conditions
clusterConditions := map[string]metav1.ConditionStatus{
ConditionRepoHostReady: metav1.ConditionTrue,
ConditionReplicaCreate: metav1.ConditionTrue,
}
for condition, status := range clusterConditions {
meta.SetStatusCondition(&postgresCluster.Status.Conditions, metav1.Condition{
Type: condition, Reason: "testing", Status: status})
}
rootCA, err := pki.NewRootCertificateAuthority()
assert.NilError(t, err)
result, err := r.reconcilePGBackRest(ctx, postgresCluster, instances, rootCA)
if err != nil || result != (reconcile.Result{}) {
t.Errorf("unable to reconcile pgBackRest: %v", err)
}
// repo is the first defined repo
repo := postgresCluster.Spec.Backups.PGBackRest.Repos[0]
// test that the repo was created properly
t.Run("verify pgbackrest dedicated repo StatefulSet", func(t *testing.T) {
// get the pgBackRest repo sts using the labels we expect it to have
dedicatedRepos := &appsv1.StatefulSetList{}
if err := tClient.List(ctx, dedicatedRepos, client.InNamespace(ns.Name),
client.MatchingLabels{
naming.LabelCluster: clusterName,
naming.LabelPGBackRest: "",
naming.LabelPGBackRestDedicated: "",
}); err != nil {
t.Fatal(err)
}
repo := appsv1.StatefulSet{}
// verify that we found a repo sts as expected
if len(dedicatedRepos.Items) == 0 {
t.Fatal("Did not find a dedicated repo sts")
} else if len(dedicatedRepos.Items) > 1 {
t.Fatal("Too many dedicated repo sts's found")
} else {
repo = dedicatedRepos.Items[0]
}
// verify proper number of replicas
if *repo.Spec.Replicas != 1 {
t.Errorf("%v replicas found for dedicated repo sts, expected %v",
repo.Spec.Replicas, 1)
}
// verify proper ownership
var foundOwnershipRef bool
for _, r := range repo.GetOwnerReferences() {
if r.Kind == "PostgresCluster" && r.Name == clusterName &&
r.UID == types.UID(clusterUID) {
foundOwnershipRef = true
break
}
}
if !foundOwnershipRef {
t.Errorf("did not find expected ownership references")
}
// verify proper matching labels
expectedLabels := map[string]string{
naming.LabelCluster: clusterName,
naming.LabelPGBackRest: "",
naming.LabelPGBackRestDedicated: "",
}
expectedLabelsSelector, err := metav1.LabelSelectorAsSelector(
metav1.SetAsLabelSelector(expectedLabels))
if err != nil {
t.Error(err)
}
if !expectedLabelsSelector.Matches(labels.Set(repo.GetLabels())) {
t.Errorf("dedicated repo host is missing an expected label: found=%v, expected=%v",
repo.GetLabels(), expectedLabels)
}
template := repo.Spec.Template.DeepCopy()
// Containers and Volumes should be populated.
assert.Assert(t, len(template.Spec.Containers) != 0)
assert.Assert(t, len(template.Spec.InitContainers) != 0)
assert.Assert(t, len(template.Spec.Volumes) != 0)
// Ignore Containers and Volumes in the comparison below.
template.Spec.Containers = nil
template.Spec.InitContainers = nil
template.Spec.Volumes = nil
// TODO(tjmoore4): Add additional tests to test appending existing
// topology spread constraints and spec.disableDefaultPodScheduling being
// set to true (as done in instance StatefulSet tests).
assert.Assert(t, marshalMatches(template.Spec, `
affinity: {}
automountServiceAccountToken: false
containers: null
dnsPolicy: ClusterFirst
enableServiceLinks: false
imagePullSecrets:
- name: myImagePullSecret
priorityClassName: some-priority-class
restartPolicy: Always
schedulerName: default-scheduler
securityContext:
fsGroup: 26
fsGroupChangePolicy: OnRootMismatch
shareProcessNamespace: true
terminationGracePeriodSeconds: 30
tolerations:
- key: woot
topologySpreadConstraints:
- labelSelector:
matchExpressions:
- key: postgres-operator.crunchydata.com/cluster
operator: In
values:
- somename
- key: postgres-operator.crunchydata.com/data
operator: Exists
maxSkew: 1
topologyKey: fakekey
whenUnsatisfiable: ScheduleAnyway
- labelSelector:
matchExpressions:
- key: postgres-operator.crunchydata.com/data
operator: In
values:
- postgres
- pgbackrest
matchLabels:
postgres-operator.crunchydata.com/cluster: hippocluster
maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
- labelSelector:
matchExpressions:
- key: postgres-operator.crunchydata.com/data
operator: In
values:
- postgres
- pgbackrest
matchLabels:
postgres-operator.crunchydata.com/cluster: hippocluster
maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
`))
// verify that the repohost container exists and contains the proper env vars
var repoHostContExists bool
for _, c := range repo.Spec.Template.Spec.Containers {
if c.Name == naming.PGBackRestRepoContainerName {
repoHostContExists = true
}
}
// now verify the proper env within the container
if !repoHostContExists {
t.Errorf("dedicated repo host is missing a container with name %s",
naming.PGBackRestRepoContainerName)
}
repoHostStatus := postgresCluster.Status.PGBackRest.RepoHost
if repoHostStatus != nil {
if repoHostStatus.APIVersion != "apps/v1" || repoHostStatus.Kind != "StatefulSet" {
t.Errorf("invalid version/kind for dedicated repo host status")
}
} else {
t.Errorf("dedicated repo host status is missing")
}
var foundConditionRepoHostsReady bool
for _, c := range postgresCluster.Status.Conditions {
if c.Type == "PGBackRestRepoHostReady" {
foundConditionRepoHostsReady = true
break
}
}
if !foundConditionRepoHostsReady {
t.Errorf("status condition PGBackRestRepoHostsReady is missing")
}
events := &corev1.EventList{}
if err := wait.Poll(time.Second/2, Scale(time.Second*2), func() (bool, error) {
if err := tClient.List(ctx, events, &client.MatchingFields{
"involvedObject.kind": "PostgresCluster",
"involvedObject.name": clusterName,
"involvedObject.namespace": ns.Name,
"involvedObject.uid": clusterUID,
"reason": "RepoHostCreated",
}); err != nil {
return false, err
}
if len(events.Items) != 1 {
return false, nil
}
return true, nil
}); err != nil {
t.Error(err)
}
})
t.Run("verify pgbackrest repo volumes", func(t *testing.T) {
// get the pgBackRest repo sts using the labels we expect it to have
repoVols := &corev1.PersistentVolumeClaimList{}
if err := tClient.List(ctx, repoVols, client.InNamespace(ns.Name),
client.MatchingLabels{
naming.LabelCluster: clusterName,
naming.LabelPGBackRest: "",
naming.LabelPGBackRestRepoVolume: "",
}); err != nil {
t.Fatal(err)
}
assert.Assert(t, len(repoVols.Items) > 0)
for _, r := range postgresCluster.Spec.Backups.PGBackRest.Repos {
if r.Volume == nil {
continue
}
var foundRepoVol bool
for _, v := range repoVols.Items {
if v.GetName() ==
naming.PGBackRestRepoVolume(postgresCluster, r.Name).Name {
foundRepoVol = true
break
}
}
assert.Assert(t, foundRepoVol)
}
})
t.Run("verify pgbackrest configuration", func(t *testing.T) {
config := &corev1.ConfigMap{}
if err := tClient.Get(ctx, types.NamespacedName{
Name: naming.PGBackRestConfig(postgresCluster).Name,
Namespace: postgresCluster.GetNamespace(),
}, config); err != nil {
assert.NilError(t, err)
}
assert.Assert(t, len(config.Data) > 0)
var instanceConfFound, dedicatedRepoConfFound bool
for k, v := range config.Data {
if v != "" {
if k == pgbackrest.CMInstanceKey {
instanceConfFound = true
} else if k == pgbackrest.CMRepoKey {
dedicatedRepoConfFound = true
}
}
}
assert.Check(t, instanceConfFound)
assert.Check(t, dedicatedRepoConfFound)
})
t.Run("verify pgbackrest schedule cronjob", func(t *testing.T) {
// set status
postgresCluster.Status = v1beta1.PostgresClusterStatus{
Patroni: v1beta1.PatroniStatus{SystemIdentifier: "12345abcde"},
PGBackRest: &v1beta1.PGBackRestStatus{
Repos: []v1beta1.RepoStatus{{Name: "repo1", StanzaCreated: true}}},
}
// set conditions
clusterConditions := map[string]metav1.ConditionStatus{
ConditionRepoHostReady: metav1.ConditionTrue,
ConditionReplicaCreate: metav1.ConditionTrue,
}
for condition, status := range clusterConditions {
meta.SetStatusCondition(&postgresCluster.Status.Conditions, metav1.Condition{
Type: condition, Reason: "testing", Status: status})
}
requeue := r.reconcileScheduledBackups(ctx, postgresCluster, serviceAccount, fakeObservedCronJobs())
assert.Assert(t, !requeue)
returnedCronJob := &batchv1.CronJob{}
if err := tClient.Get(ctx, types.NamespacedName{
Name: postgresCluster.Name + "-repo1-full",
Namespace: postgresCluster.GetNamespace(),
}, returnedCronJob); err != nil {
assert.NilError(t, err)
}
// check returned cronjob matches set spec
assert.Equal(t, returnedCronJob.Name, "hippocluster-repo1-full")
assert.Equal(t, returnedCronJob.Spec.Schedule, testCronSchedule)
assert.Equal(t, returnedCronJob.Spec.ConcurrencyPolicy, batchv1.ForbidConcurrent)
assert.Equal(t, returnedCronJob.Spec.JobTemplate.Spec.Template.Spec.Containers[0].Name,
"pgbackrest")
assert.Assert(t, returnedCronJob.Spec.JobTemplate.Spec.Template.Spec.Containers[0].SecurityContext != &corev1.SecurityContext{})
})
t.Run("verify pgbackrest schedule found", func(t *testing.T) {
assert.Assert(t, backupScheduleFound(repo, "full"))
testrepo := v1beta1.PGBackRestRepo{
Name: "repo1",
BackupSchedules: &v1beta1.PGBackRestBackupSchedules{
Full: &testCronSchedule,
Differential: &testCronSchedule,
Incremental: &testCronSchedule,
}}
assert.Assert(t, backupScheduleFound(testrepo, "full"))
assert.Assert(t, backupScheduleFound(testrepo, "diff"))
assert.Assert(t, backupScheduleFound(testrepo, "incr"))
})
t.Run("verify pgbackrest schedule not found", func(t *testing.T) {
assert.Assert(t, !backupScheduleFound(repo, "notabackuptype"))
noscheduletestrepo := v1beta1.PGBackRestRepo{Name: "repo1"}
assert.Assert(t, !backupScheduleFound(noscheduletestrepo, "full"))
})
t.Run("pgbackrest schedule suspended status", func(t *testing.T) {
returnedCronJob := &batchv1.CronJob{}
if err := tClient.Get(ctx, types.NamespacedName{
Name: postgresCluster.Name + "-repo1-full",
Namespace: postgresCluster.GetNamespace(),
}, returnedCronJob); err != nil {
assert.NilError(t, err)
}
t.Run("pgbackrest schedule suspended false", func(t *testing.T) {
assert.Assert(t, !*returnedCronJob.Spec.Suspend)
})
t.Run("shutdown", func(t *testing.T) {
*postgresCluster.Spec.Shutdown = true
postgresCluster.Spec.Standby = nil
requeue := r.reconcileScheduledBackups(ctx,
postgresCluster, serviceAccount, fakeObservedCronJobs())
assert.Assert(t, !requeue)
assert.NilError(t, tClient.Get(ctx, types.NamespacedName{
Name: postgresCluster.Name + "-repo1-full",
Namespace: postgresCluster.GetNamespace(),
}, returnedCronJob))
assert.Assert(t, *returnedCronJob.Spec.Suspend)
})
t.Run("standby", func(t *testing.T) {
*postgresCluster.Spec.Shutdown = false
postgresCluster.Spec.Standby = &v1beta1.PostgresStandbySpec{
Enabled: true,
}
requeue := r.reconcileScheduledBackups(ctx,
postgresCluster, serviceAccount, fakeObservedCronJobs())
assert.Assert(t, !requeue)
assert.NilError(t, tClient.Get(ctx, types.NamespacedName{
Name: postgresCluster.Name + "-repo1-full",
Namespace: postgresCluster.GetNamespace(),
}, returnedCronJob))
assert.Assert(t, *returnedCronJob.Spec.Suspend)
})
})
}
func TestReconcilePGBackRestRBAC(t *testing.T) {
// Garbage collector cleans up test resources before the test completes
if strings.EqualFold(os.Getenv("USE_EXISTING_CLUSTER"), "true") {
t.Skip("USE_EXISTING_CLUSTER: Test fails due to garbage collection")
}
ctx := context.Background()
_, tClient := setupKubernetes(t)
require.ParallelCapacity(t, 0)
r := &Reconciler{Client: tClient, Owner: client.FieldOwner(t.Name())}
clusterName := "hippocluster"
clusterUID := "hippouid"
ns := setupNamespace(t, tClient)
// create a PostgresCluster to test with
postgresCluster := fakePostgresCluster(clusterName, ns.GetName(), clusterUID, true)
postgresCluster.Status.PGBackRest = &v1beta1.PGBackRestStatus{
Repos: []v1beta1.RepoStatus{{Name: "repo1", StanzaCreated: false}},
}
serviceAccount, err := r.reconcilePGBackRestRBAC(ctx, postgresCluster)
assert.NilError(t, err)
assert.Assert(t, serviceAccount != nil)
// first verify the service account has been created
sa := &corev1.ServiceAccount{}
err = tClient.Get(ctx, types.NamespacedName{
Name: naming.PGBackRestRBAC(postgresCluster).Name,
Namespace: postgresCluster.GetNamespace(),
}, sa)
assert.NilError(t, err)
role := &rbacv1.Role{}
err = tClient.Get(ctx, types.NamespacedName{
Name: naming.PGBackRestRBAC(postgresCluster).Name,
Namespace: postgresCluster.GetNamespace(),
}, role)
assert.NilError(t, err)
assert.Assert(t, len(role.Rules) > 0)
roleBinding := &rbacv1.RoleBinding{}
err = tClient.Get(ctx, types.NamespacedName{
Name: naming.PGBackRestRBAC(postgresCluster).Name,
Namespace: postgresCluster.GetNamespace(),
}, roleBinding)
assert.NilError(t, err)
assert.Assert(t, roleBinding.RoleRef.Name == role.GetName())
var foundSubject bool
for _, subject := range roleBinding.Subjects {
if subject.Name == sa.GetName() {
foundSubject = true
}
}
assert.Assert(t, foundSubject)
}
func TestReconcileStanzaCreate(t *testing.T) {
tEnv, tClient := setupKubernetes(t)
require.ParallelCapacity(t, 0)
r := &Reconciler{}
ctx, cancel := setupManager(t, tEnv.Config, func(mgr manager.Manager) {
r = &Reconciler{
Client: mgr.GetClient(),
Recorder: mgr.GetEventRecorderFor(ControllerName),
Tracer: otel.Tracer(ControllerName),
Owner: ControllerName,
}
})
t.Cleanup(func() { teardownManager(cancel, t) })
clusterName := "hippocluster"
clusterUID := "hippouid"
ns := setupNamespace(t, tClient)
// create a PostgresCluster to test with
postgresCluster := fakePostgresCluster(clusterName, ns.GetName(), clusterUID, true)
postgresCluster.Status.PGBackRest = &v1beta1.PGBackRestStatus{
Repos: []v1beta1.RepoStatus{{Name: "repo1", StanzaCreated: false}},
}
instances := newObservedInstances(postgresCluster, nil, []corev1.Pod{{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{"status": `"role":"master"`},
Labels: map[string]string{
naming.LabelCluster: postgresCluster.GetName(),
naming.LabelInstance: "",
naming.LabelRole: naming.RolePatroniLeader,
},
},
}})
stanzaCreateFail := func(namespace, pod, container string, stdin io.Reader, stdout,
stderr io.Writer, command ...string) error {
return errors.New("fake stanza create failed")
}
stanzaCreateSuccess := func(namespace, pod, container string, stdin io.Reader, stdout,
stderr io.Writer, command ...string) error {
return nil
}
// now verify a stanza create success
r.PodExec = stanzaCreateSuccess
meta.SetStatusCondition(&postgresCluster.Status.Conditions, metav1.Condition{
ObservedGeneration: postgresCluster.GetGeneration(),
Type: ConditionRepoHostReady,
Status: metav1.ConditionTrue,
Reason: "RepoHostReady",
Message: "pgBackRest dedicated repository host is ready",
})
configHashMistmatch, err := r.reconcileStanzaCreate(ctx, postgresCluster, instances, "abcde12345")
assert.NilError(t, err)
assert.Assert(t, !configHashMistmatch)
events := &corev1.EventList{}
err = wait.Poll(time.Second/2, Scale(time.Second*2), func() (bool, error) {
if err := tClient.List(ctx, events, &client.MatchingFields{
"involvedObject.kind": "PostgresCluster",
"involvedObject.name": clusterName,
"involvedObject.namespace": ns.Name,
"involvedObject.uid": clusterUID,
"reason": "StanzasCreated",
}); err != nil {
return false, err
}
if len(events.Items) != 1 {
return false, nil
}
return true, nil
})
assert.NilError(t, err)
// status should indicate stanzas were created
for _, r := range postgresCluster.Status.PGBackRest.Repos {
assert.Assert(t, r.StanzaCreated)
}
// now verify failure event
postgresCluster = fakePostgresCluster(clusterName, ns.GetName(), clusterUID, true)
postgresCluster.Status.PGBackRest = &v1beta1.PGBackRestStatus{
Repos: []v1beta1.RepoStatus{{Name: "repo1", StanzaCreated: false}},
}
r.PodExec = stanzaCreateFail
meta.SetStatusCondition(&postgresCluster.Status.Conditions, metav1.Condition{
ObservedGeneration: postgresCluster.GetGeneration(),
Type: ConditionRepoHostReady,
Status: metav1.ConditionTrue,
Reason: "RepoHostReady",
Message: "pgBackRest dedicated repository host is ready",
})
postgresCluster.Status.Patroni = v1beta1.PatroniStatus{
SystemIdentifier: "6952526174828511264",
}
configHashMismatch, err := r.reconcileStanzaCreate(ctx, postgresCluster, instances, "abcde12345")
assert.Error(t, err, "fake stanza create failed: ")
assert.Assert(t, !configHashMismatch)
events = &corev1.EventList{}
err = wait.Poll(time.Second/2, Scale(time.Second*2), func() (bool, error) {
if err := tClient.List(ctx, events, &client.MatchingFields{
"involvedObject.kind": "PostgresCluster",
"involvedObject.name": clusterName,
"involvedObject.namespace": ns.Name,
"involvedObject.uid": clusterUID,
"reason": "UnableToCreateStanzas",
}); err != nil {
return false, err
}
if len(events.Items) != 1 {
return false, nil
}
return true, nil
})
assert.NilError(t, err)
// status should indicate stanza were not created
for _, r := range postgresCluster.Status.PGBackRest.Repos {
assert.Assert(t, !r.StanzaCreated)
}
}
func TestGetPGBackRestExecSelector(t *testing.T) {
testCases := []struct {
cluster *v1beta1.PostgresCluster
repo v1beta1.PGBackRestRepo
desc string
expectedSelector string
expectedContainer string
}{{
desc: "volume repo defined dedicated repo host enabled",
cluster: &v1beta1.PostgresCluster{
ObjectMeta: metav1.ObjectMeta{Name: "hippo"},
},
repo: v1beta1.PGBackRestRepo{
Name: "repo1",
Volume: &v1beta1.RepoPVC{},
},
expectedSelector: "postgres-operator.crunchydata.com/cluster=hippo," +
"postgres-operator.crunchydata.com/pgbackrest=," +
"postgres-operator.crunchydata.com/pgbackrest-dedicated=",
expectedContainer: "pgbackrest",
}, {
desc: "cloud repo defined no repo host enabled",
cluster: &v1beta1.PostgresCluster{
ObjectMeta: metav1.ObjectMeta{Name: "hippo"},
},
repo: v1beta1.PGBackRestRepo{
Name: "repo1",
S3: &v1beta1.RepoS3{},
},
expectedSelector: "postgres-operator.crunchydata.com/cluster=hippo," +
"postgres-operator.crunchydata.com/instance," +
"postgres-operator.crunchydata.com/role=master",
expectedContainer: "database",
}}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
selector, container, err := getPGBackRestExecSelector(tc.cluster, tc.repo)
assert.NilError(t, err)
assert.Assert(t, selector.String() == tc.expectedSelector)
assert.Assert(t, container == tc.expectedContainer)
})
}
}
func TestReconcileReplicaCreateBackup(t *testing.T) {
// Garbage collector cleans up test resources before the test completes
if strings.EqualFold(os.Getenv("USE_EXISTING_CLUSTER"), "true") {
t.Skip("USE_EXISTING_CLUSTER: Test fails due to garbage collection")
}
ctx := context.Background()
_, tClient := setupKubernetes(t)
require.ParallelCapacity(t, 1)
r := &Reconciler{Client: tClient, Owner: client.FieldOwner(t.Name())}
clusterName := "hippocluster"
clusterUID := "hippouid"
ns := setupNamespace(t, tClient)
// create a PostgresCluster to test with
postgresCluster := fakePostgresCluster(clusterName, ns.GetName(), clusterUID, true)
// set status for the "replica create" repo, e.g. the repo ad index 0
postgresCluster.Status.PGBackRest = &v1beta1.PGBackRestStatus{
Repos: []v1beta1.RepoStatus{{Name: "repo1", StanzaCreated: false}},
}
instances := newObservedInstances(postgresCluster, nil, []corev1.Pod{{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{"status": `"role":"master"`},
Labels: map[string]string{
naming.LabelCluster: postgresCluster.GetName(),
naming.LabelInstance: "",
naming.LabelRole: naming.RolePatroniLeader,
},
},
}})
meta.SetStatusCondition(&postgresCluster.Status.Conditions, metav1.Condition{
ObservedGeneration: postgresCluster.GetGeneration(),
Type: ConditionRepoHostReady,
Status: metav1.ConditionTrue,
Reason: "RepoHostReady",
Message: "pgBackRest dedicated repository host is ready",
})
meta.SetStatusCondition(&postgresCluster.Status.Conditions, metav1.Condition{
ObservedGeneration: postgresCluster.GetGeneration(),
Type: ConditionReplicaRepoReady,
Status: metav1.ConditionTrue,
Reason: "StanzaCreated",
Message: "pgBackRest replica create repo is ready for backups",
})
postgresCluster.Status.Patroni = v1beta1.PatroniStatus{
SystemIdentifier: "6952526174828511264",
}
replicaCreateRepo := postgresCluster.Spec.Backups.PGBackRest.Repos[0]
configHash := "abcde12345"
sa := &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{Name: "hippo-sa"},
}
err := r.reconcileReplicaCreateBackup(ctx, postgresCluster, instances,
[]*batchv1.Job{}, sa, configHash, replicaCreateRepo)
assert.NilError(t, err)
// now find the expected job
jobs := &batchv1.JobList{}
err = tClient.List(ctx, jobs, &client.ListOptions{
Namespace: postgresCluster.Namespace,
LabelSelector: naming.PGBackRestBackupJobSelector(clusterName, replicaCreateRepo.Name,
naming.BackupReplicaCreate),
})
assert.NilError(t, err)
assert.Equal(t, len(jobs.Items), 1, "expected 1 job")
backupJob := jobs.Items[0]
var foundOwnershipRef bool
// verify ownership refs
for _, ref := range backupJob.ObjectMeta.GetOwnerReferences() {
if ref.Name == clusterName {
foundOwnershipRef = true
break
}
}
assert.Assert(t, foundOwnershipRef)
var foundConfigAnnotation, foundHashAnnotation bool
// verify annotations
for k, v := range backupJob.GetAnnotations() {
if k == naming.PGBackRestCurrentConfig && v == naming.PGBackRestRepoContainerName {
foundConfigAnnotation = true
}
if k == naming.PGBackRestConfigHash && v == configHash {
foundHashAnnotation = true
}
}
assert.Assert(t, foundConfigAnnotation)
assert.Assert(t, foundHashAnnotation)
// verify container & env vars
assert.Assert(t, len(backupJob.Spec.Template.Spec.Containers) == 1)
assert.Assert(t,
backupJob.Spec.Template.Spec.Containers[0].Name == naming.PGBackRestRepoContainerName)
container := backupJob.Spec.Template.Spec.Containers[0]
for _, env := range container.Env {
switch env.Name {
case "COMMAND":
assert.Assert(t, env.Value == "backup")
case "COMMAND_OPTS":
assert.Assert(t, env.Value == "--stanza=db --repo=1")
case "COMPARE_HASH":
assert.Assert(t, env.Value == "true")
case "CONTAINER":
assert.Assert(t, env.Value == naming.PGBackRestRepoContainerName)
case "NAMESPACE":
assert.Assert(t, env.Value == ns.Name)
case "SELECTOR":
assert.Assert(t, env.Value == "postgres-operator.crunchydata.com/cluster=hippocluster,"+
"postgres-operator.crunchydata.com/pgbackrest=,"+
"postgres-operator.crunchydata.com/pgbackrest-dedicated=")
}
}
// verify mounted configuration is present
assert.Assert(t, len(container.VolumeMounts) == 1)
// verify volume for configuration is present
assert.Assert(t, len(backupJob.Spec.Template.Spec.Volumes) == 1)
// verify the image pull secret
assert.Assert(t, backupJob.Spec.Template.Spec.ImagePullSecrets != nil)
assert.Equal(t, backupJob.Spec.Template.Spec.ImagePullSecrets[0].Name,
"myImagePullSecret")
// verify the priority class
assert.Equal(t, backupJob.Spec.Template.Spec.PriorityClassName, "some-priority-class")
// now set the job to complete
backupJob.Status.Conditions = append(backupJob.Status.Conditions,
batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue})
// call reconcile function again
err = r.reconcileReplicaCreateBackup(ctx, postgresCluster, instances,
[]*batchv1.Job{&backupJob}, sa, configHash, replicaCreateRepo)
assert.NilError(t, err)
// verify the proper conditions have been set
var foundCompletedCondition bool
condition := meta.FindStatusCondition(postgresCluster.Status.Conditions, ConditionReplicaCreate)
if condition != nil && (condition.Status == metav1.ConditionTrue) {
foundCompletedCondition = true
}
assert.Assert(t, foundCompletedCondition)