-
Notifications
You must be signed in to change notification settings - Fork 667
Expand file tree
/
Copy pathpgadmin_test.go
More file actions
878 lines (736 loc) · 26.4 KB
/
pgadmin_test.go
File metadata and controls
878 lines (736 loc) · 26.4 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
//go:build envtest
// +build envtest
/*
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.
*/
package postgrescluster
import (
"context"
"io"
"testing"
"github.com/pkg/errors"
"gotest.tools/v3/assert"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"github.com/crunchydata/postgres-operator/internal/initialize"
"github.com/crunchydata/postgres-operator/internal/naming"
"github.com/crunchydata/postgres-operator/internal/testing/cmp"
"github.com/crunchydata/postgres-operator/internal/testing/require"
"github.com/crunchydata/postgres-operator/pkg/apis/postgres-operator.crunchydata.com/v1beta1"
)
func TestGeneratePGAdminConfigMap(t *testing.T) {
_, cc := setupKubernetes(t)
require.ParallelCapacity(t, 0)
reconciler := &Reconciler{Client: cc}
cluster := &v1beta1.PostgresCluster{}
cluster.Namespace = "some-ns"
cluster.Name = "pg1"
t.Run("Unspecified", func(t *testing.T) {
for _, spec := range []*v1beta1.UserInterfaceSpec{
nil, new(v1beta1.UserInterfaceSpec),
} {
cluster := cluster.DeepCopy()
cluster.Spec.UserInterface = spec
configmap, specified, err := reconciler.generatePGAdminConfigMap(cluster)
assert.NilError(t, err)
assert.Assert(t, !specified)
assert.Equal(t, configmap.Namespace, cluster.Namespace)
assert.Equal(t, configmap.Name, "pg1-pgadmin")
}
})
cluster.Spec.UserInterface = &v1beta1.UserInterfaceSpec{
PGAdmin: &v1beta1.PGAdminPodSpec{},
}
t.Run("Data,ObjectMeta,TypeMeta", func(t *testing.T) {
cluster := cluster.DeepCopy()
configmap, specified, err := reconciler.generatePGAdminConfigMap(cluster)
assert.NilError(t, err)
assert.Assert(t, specified)
assert.Assert(t, cmp.MarshalMatches(configmap.TypeMeta, `
apiVersion: v1
kind: ConfigMap
`))
assert.Assert(t, cmp.MarshalMatches(configmap.ObjectMeta, `
creationTimestamp: null
labels:
postgres-operator.crunchydata.com/cluster: pg1
postgres-operator.crunchydata.com/role: pgadmin
name: pg1-pgadmin
namespace: some-ns
ownerReferences:
- apiVersion: postgres-operator.crunchydata.com/v1beta1
blockOwnerDeletion: true
controller: true
kind: PostgresCluster
name: pg1
uid: ""
`))
assert.Assert(t, len(configmap.Data) > 0, "expected some configuration")
})
t.Run("Annotations,Labels", func(t *testing.T) {
cluster := cluster.DeepCopy()
cluster.Spec.Metadata = &v1beta1.Metadata{
Annotations: map[string]string{"a": "v1", "b": "v2"},
Labels: map[string]string{"c": "v3", "d": "v4"},
}
cluster.Spec.UserInterface.PGAdmin.Metadata = &v1beta1.Metadata{
Annotations: map[string]string{"a": "v5", "e": "v6"},
Labels: map[string]string{"c": "v7", "f": "v8"},
}
configmap, specified, err := reconciler.generatePGAdminConfigMap(cluster)
assert.NilError(t, err)
assert.Assert(t, specified)
// Annotations present in the metadata.
assert.DeepEqual(t, configmap.ObjectMeta.Annotations, map[string]string{
"a": "v5", "b": "v2", "e": "v6",
})
// Labels present in the metadata.
assert.DeepEqual(t, configmap.ObjectMeta.Labels, map[string]string{
"c": "v7", "d": "v4", "f": "v8",
"postgres-operator.crunchydata.com/cluster": "pg1",
"postgres-operator.crunchydata.com/role": "pgadmin",
})
})
}
func TestGeneratePGAdminService(t *testing.T) {
_, cc := setupKubernetes(t)
require.ParallelCapacity(t, 0)
reconciler := &Reconciler{
Client: cc,
Recorder: new(record.FakeRecorder),
}
cluster := &v1beta1.PostgresCluster{}
cluster.Namespace = "my-ns"
cluster.Name = "my-cluster"
t.Run("Unspecified", func(t *testing.T) {
for _, spec := range []*v1beta1.UserInterfaceSpec{
nil, new(v1beta1.UserInterfaceSpec),
} {
cluster := cluster.DeepCopy()
cluster.Spec.UserInterface = spec
service, specified, err := reconciler.generatePGAdminService(cluster)
assert.NilError(t, err)
assert.Assert(t, !specified)
assert.Assert(t, marshalMatches(service.ObjectMeta, `
creationTimestamp: null
name: my-cluster-pgadmin
namespace: my-ns
`))
}
})
cluster.Spec.UserInterface = &v1beta1.UserInterfaceSpec{
PGAdmin: &v1beta1.PGAdminPodSpec{},
}
alwaysExpect := func(t testing.TB, service *corev1.Service) {
assert.Assert(t, marshalMatches(service.TypeMeta, `
apiVersion: v1
kind: Service
`))
assert.Assert(t, marshalMatches(service.ObjectMeta, `
creationTimestamp: null
labels:
postgres-operator.crunchydata.com/cluster: my-cluster
postgres-operator.crunchydata.com/role: pgadmin
name: my-cluster-pgadmin
namespace: my-ns
ownerReferences:
- apiVersion: postgres-operator.crunchydata.com/v1beta1
blockOwnerDeletion: true
controller: true
kind: PostgresCluster
name: my-cluster
uid: ""
`))
// Always gets a ClusterIP (never None).
assert.Equal(t, service.Spec.ClusterIP, "")
assert.DeepEqual(t, service.Spec.Selector, map[string]string{
"postgres-operator.crunchydata.com/cluster": "my-cluster",
"postgres-operator.crunchydata.com/role": "pgadmin",
})
}
t.Run("AnnotationsLabels", func(t *testing.T) {
cluster := cluster.DeepCopy()
cluster.Spec.Metadata = &v1beta1.Metadata{
Annotations: map[string]string{"a": "v1"},
Labels: map[string]string{"b": "v2"},
}
service, specified, err := reconciler.generatePGAdminService(cluster)
assert.NilError(t, err)
assert.Assert(t, specified)
// Annotations present in the metadata.
assert.DeepEqual(t, service.ObjectMeta.Annotations, map[string]string{
"a": "v1",
})
// Labels present in the metadata.
assert.DeepEqual(t, service.ObjectMeta.Labels, map[string]string{
"b": "v2",
"postgres-operator.crunchydata.com/cluster": "my-cluster",
"postgres-operator.crunchydata.com/role": "pgadmin",
})
// Labels not in the selector.
assert.DeepEqual(t, service.Spec.Selector, map[string]string{
"postgres-operator.crunchydata.com/cluster": "my-cluster",
"postgres-operator.crunchydata.com/role": "pgadmin",
})
// Add metadata to individual service
cluster.Spec.UserInterface.PGAdmin.Service = &v1beta1.ServiceSpec{
Metadata: &v1beta1.Metadata{
Annotations: map[string]string{"c": "v3"},
Labels: map[string]string{"d": "v4",
"postgres-operator.crunchydata.com/cluster": "wrongName"},
},
}
service, specified, err = reconciler.generatePGAdminService(cluster)
assert.NilError(t, err)
assert.Assert(t, specified)
// Annotations present in the metadata.
assert.DeepEqual(t, service.ObjectMeta.Annotations, map[string]string{
"a": "v1",
"c": "v3",
})
// Labels present in the metadata.
assert.DeepEqual(t, service.ObjectMeta.Labels, map[string]string{
"b": "v2",
"d": "v4",
"postgres-operator.crunchydata.com/cluster": "my-cluster",
"postgres-operator.crunchydata.com/role": "pgadmin",
})
// Labels not in the selector.
assert.DeepEqual(t, service.Spec.Selector, map[string]string{
"postgres-operator.crunchydata.com/cluster": "my-cluster",
"postgres-operator.crunchydata.com/role": "pgadmin",
})
})
t.Run("NoServiceSpec", func(t *testing.T) {
service, specified, err := reconciler.generatePGAdminService(cluster)
assert.NilError(t, err)
assert.Assert(t, specified)
alwaysExpect(t, service)
// Defaults to ClusterIP.
assert.Equal(t, service.Spec.Type, corev1.ServiceTypeClusterIP)
assert.Assert(t, marshalMatches(service.Spec.Ports, `
- appProtocol: http
name: pgadmin
port: 5050
protocol: TCP
targetPort: pgadmin
`))
})
types := []struct {
Type string
Expect func(testing.TB, *corev1.Service)
}{
{Type: "ClusterIP", Expect: func(t testing.TB, service *corev1.Service) {
assert.Equal(t, service.Spec.Type, corev1.ServiceTypeClusterIP)
}},
{Type: "NodePort", Expect: func(t testing.TB, service *corev1.Service) {
assert.Equal(t, service.Spec.Type, corev1.ServiceTypeNodePort)
}},
{Type: "LoadBalancer", Expect: func(t testing.TB, service *corev1.Service) {
assert.Equal(t, service.Spec.Type, corev1.ServiceTypeLoadBalancer)
}},
}
for _, test := range types {
t.Run(test.Type, func(t *testing.T) {
cluster := cluster.DeepCopy()
cluster.Spec.UserInterface.PGAdmin.Service = &v1beta1.ServiceSpec{Type: test.Type}
service, specified, err := reconciler.generatePGAdminService(cluster)
assert.NilError(t, err)
assert.Assert(t, specified)
alwaysExpect(t, service)
test.Expect(t, service)
assert.Assert(t, marshalMatches(service.Spec.Ports, `
- appProtocol: http
name: pgadmin
port: 5050
protocol: TCP
targetPort: pgadmin
`))
})
}
typesAndPort := []struct {
Description string
Type string
NodePort *int32
Expect func(testing.TB, *corev1.Service, error)
}{
{Description: "ClusterIP with Port 32000", Type: "ClusterIP",
NodePort: initialize.Int32(32000), Expect: func(t testing.TB, service *corev1.Service, err error) {
assert.ErrorContains(t, err, "NodePort cannot be set with type ClusterIP on Service \"my-cluster-pgadmin\"")
assert.Assert(t, service == nil)
}},
{Description: "NodePort with Port 32001", Type: "NodePort",
NodePort: initialize.Int32(32001), Expect: func(t testing.TB, service *corev1.Service, err error) {
assert.NilError(t, err)
assert.Equal(t, service.Spec.Type, corev1.ServiceTypeNodePort)
alwaysExpect(t, service)
assert.Assert(t, marshalMatches(service.Spec.Ports, `
- appProtocol: http
name: pgadmin
nodePort: 32001
port: 5050
protocol: TCP
targetPort: pgadmin
`))
}},
{Description: "LoadBalancer with Port 32002", Type: "LoadBalancer",
NodePort: initialize.Int32(32002), Expect: func(t testing.TB, service *corev1.Service, err error) {
assert.NilError(t, err)
assert.Equal(t, service.Spec.Type, corev1.ServiceTypeLoadBalancer)
alwaysExpect(t, service)
assert.Assert(t, marshalMatches(service.Spec.Ports, `
- appProtocol: http
name: pgadmin
nodePort: 32002
port: 5050
protocol: TCP
targetPort: pgadmin
`))
}},
}
for _, test := range typesAndPort {
t.Run(test.Description, func(t *testing.T) {
cluster := cluster.DeepCopy()
cluster.Spec.UserInterface.PGAdmin.Service =
&v1beta1.ServiceSpec{Type: test.Type, NodePort: test.NodePort}
service, specified, err := reconciler.generatePGAdminService(cluster)
test.Expect(t, service, err)
// whether or not an error is encountered, 'specified' is true because
// the service *should* exist
assert.Assert(t, specified)
})
}
}
func TestReconcilePGAdminService(t *testing.T) {
ctx := context.Background()
_, cc := setupKubernetes(t)
require.ParallelCapacity(t, 1)
reconciler := &Reconciler{Client: cc, Owner: client.FieldOwner(t.Name())}
cluster := testCluster()
cluster.Namespace = setupNamespace(t, cc).Name
assert.NilError(t, cc.Create(ctx, cluster))
t.Run("Unspecified", func(t *testing.T) {
cluster := cluster.DeepCopy()
cluster.Spec.UserInterface = nil
service, err := reconciler.reconcilePGAdminService(ctx, cluster)
assert.NilError(t, err)
assert.Assert(t, service == nil)
})
cluster.Spec.UserInterface = &v1beta1.UserInterfaceSpec{
PGAdmin: &v1beta1.PGAdminPodSpec{},
}
t.Run("NoServiceSpec", func(t *testing.T) {
service, err := reconciler.reconcilePGAdminService(ctx, cluster)
assert.NilError(t, err)
assert.Assert(t, service != nil)
t.Cleanup(func() { assert.Check(t, cc.Delete(ctx, service)) })
assert.Assert(t, service.Spec.ClusterIP != "",
"expected to be assigned a ClusterIP")
})
serviceTypes := []string{"ClusterIP", "NodePort", "LoadBalancer"}
// Confirm that each ServiceType can be reconciled.
for _, serviceType := range serviceTypes {
t.Run(serviceType, func(t *testing.T) {
cluster := cluster.DeepCopy()
cluster.Spec.UserInterface.PGAdmin.Service = &v1beta1.ServiceSpec{Type: serviceType}
service, err := reconciler.reconcilePGAdminService(ctx, cluster)
assert.NilError(t, err)
assert.Assert(t, service != nil)
t.Cleanup(func() { assert.Check(t, cc.Delete(ctx, service)) })
assert.Assert(t, service.Spec.ClusterIP != "",
"expected to be assigned a ClusterIP")
})
}
// CRD validation looks only at the new/incoming value of fields. Confirm
// that each ServiceType can change to any other ServiceType. Forbidding
// certain transitions requires a validating webhook.
for _, beforeType := range serviceTypes {
for _, changeType := range serviceTypes {
t.Run(beforeType+"To"+changeType, func(t *testing.T) {
cluster := cluster.DeepCopy()
cluster.Spec.UserInterface.PGAdmin.Service = &v1beta1.ServiceSpec{Type: beforeType}
before, err := reconciler.reconcilePGAdminService(ctx, cluster)
assert.NilError(t, err)
t.Cleanup(func() { assert.Check(t, cc.Delete(ctx, before)) })
cluster.Spec.UserInterface.PGAdmin.Service.Type = changeType
after, err := reconciler.reconcilePGAdminService(ctx, cluster)
// LoadBalancers are provisioned by a separate controller that
// updates the Service soon after creation. The API may return
// a conflict error when we race to update it, even though we
// don't send a resourceVersion in our payload. Retry.
if apierrors.IsConflict(err) {
t.Log("conflict:", err)
after, err = reconciler.reconcilePGAdminService(ctx, cluster)
}
assert.NilError(t, err, "\n%#v", errors.Unwrap(err))
assert.Equal(t, after.Spec.ClusterIP, before.Spec.ClusterIP,
"expected to keep the same ClusterIP")
})
}
}
}
func TestReconcilePGAdminStatefulSet(t *testing.T) {
ctx := context.Background()
_, cc := setupKubernetes(t)
require.ParallelCapacity(t, 1)
reconciler := &Reconciler{Client: cc, Owner: client.FieldOwner(t.Name())}
ns := setupNamespace(t, cc)
cluster := pgAdminTestCluster(*ns)
assert.NilError(t, cc.Create(ctx, cluster))
t.Cleanup(func() { assert.Check(t, cc.Delete(ctx, cluster)) })
configmap := &corev1.ConfigMap{}
configmap.Name = "test-cm"
pvc := &corev1.PersistentVolumeClaim{}
pvc.Name = "test-pvc"
t.Run("verify StatefulSet", func(t *testing.T) {
err := reconciler.reconcilePGAdminStatefulSet(ctx, cluster, configmap, pvc)
assert.NilError(t, err)
selector, err := naming.AsSelector(metav1.LabelSelector{
MatchLabels: map[string]string{
naming.LabelCluster: cluster.Name,
},
})
assert.NilError(t, err)
list := appsv1.StatefulSetList{}
assert.NilError(t, cc.List(ctx, &list, client.InNamespace(cluster.Namespace),
client.MatchingLabelsSelector{Selector: selector}))
assert.Equal(t, len(list.Items), 1)
assert.Equal(t, list.Items[0].Spec.ServiceName, "test-cluster-pods")
template := list.Items[0].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
assert.Assert(t, cmp.MarshalMatches(template.ObjectMeta, `
creationTimestamp: null
labels:
postgres-operator.crunchydata.com/cluster: test-cluster
postgres-operator.crunchydata.com/data: pgadmin
postgres-operator.crunchydata.com/role: pgadmin
`))
compare := `
automountServiceAccountToken: false
containers: null
dnsPolicy: ClusterFirst
enableServiceLinks: false
restartPolicy: Always
schedulerName: default-scheduler
securityContext:
fsGroup: 26
fsGroupChangePolicy: OnRootMismatch
terminationGracePeriodSeconds: 30
`
assert.Assert(t, cmp.MarshalMatches(template.Spec, compare))
})
t.Run("verify customized deployment", func(t *testing.T) {
customcluster := pgAdminTestCluster(*ns)
// add pod level customizations
customcluster.Name = "custom-cluster"
// annotation and label
customcluster.Spec.UserInterface.PGAdmin.Metadata = &v1beta1.Metadata{
Annotations: map[string]string{
"annotation1": "annotationvalue",
},
Labels: map[string]string{
"label1": "labelvalue",
},
}
// scheduling constraints
customcluster.Spec.UserInterface.PGAdmin.Affinity = &corev1.Affinity{
NodeAffinity: &corev1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{
NodeSelectorTerms: []corev1.NodeSelectorTerm{{
MatchExpressions: []corev1.NodeSelectorRequirement{{
Key: "key",
Operator: "Exists",
}},
}},
},
},
}
customcluster.Spec.UserInterface.PGAdmin.Tolerations = []corev1.Toleration{
{Key: "sometoleration"},
}
if cluster.Spec.UserInterface.PGAdmin.PriorityClassName != nil {
customcluster.Spec.UserInterface.PGAdmin.PriorityClassName = initialize.String("testpriorityclass")
}
customcluster.Spec.UserInterface.PGAdmin.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"},
},
},
},
}
// set an image pull secret
customcluster.Spec.ImagePullSecrets = []corev1.LocalObjectReference{{
Name: "myImagePullSecret"}}
assert.NilError(t, cc.Create(ctx, customcluster))
t.Cleanup(func() { assert.Check(t, cc.Delete(ctx, customcluster)) })
err := reconciler.reconcilePGAdminStatefulSet(ctx, customcluster, configmap, pvc)
assert.NilError(t, err)
selector, err := naming.AsSelector(metav1.LabelSelector{
MatchLabels: map[string]string{
naming.LabelCluster: customcluster.Name,
},
})
assert.NilError(t, err)
list := appsv1.StatefulSetList{}
assert.NilError(t, cc.List(ctx, &list, client.InNamespace(customcluster.Namespace),
client.MatchingLabelsSelector{Selector: selector}))
assert.Equal(t, len(list.Items), 1)
assert.Equal(t, list.Items[0].Spec.ServiceName, "custom-cluster-pods")
template := list.Items[0].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
assert.Assert(t, cmp.MarshalMatches(template.ObjectMeta, `
annotations:
annotation1: annotationvalue
creationTimestamp: null
labels:
label1: labelvalue
postgres-operator.crunchydata.com/cluster: custom-cluster
postgres-operator.crunchydata.com/data: pgadmin
postgres-operator.crunchydata.com/role: pgadmin
`))
compare := `
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: key
operator: Exists
automountServiceAccountToken: false
containers: null
dnsPolicy: ClusterFirst
enableServiceLinks: false
imagePullSecrets:
- name: myImagePullSecret
restartPolicy: Always
schedulerName: default-scheduler
securityContext:
fsGroup: 26
fsGroupChangePolicy: OnRootMismatch
terminationGracePeriodSeconds: 30
tolerations:
- key: sometoleration
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
`
assert.Assert(t, cmp.MarshalMatches(template.Spec, compare))
})
}
func TestReconcilePGAdminDataVolume(t *testing.T) {
ctx := context.Background()
_, tClient := setupKubernetes(t)
require.ParallelCapacity(t, 1)
reconciler := &Reconciler{
Client: tClient,
Owner: client.FieldOwner(t.Name()),
}
ns := setupNamespace(t, tClient)
cluster := pgAdminTestCluster(*ns)
assert.NilError(t, tClient.Create(ctx, cluster))
t.Cleanup(func() { assert.Check(t, tClient.Delete(ctx, cluster)) })
t.Run("DataVolume", func(t *testing.T) {
pvc, err := reconciler.reconcilePGAdminDataVolume(ctx, cluster)
assert.NilError(t, err)
assert.Assert(t, metav1.IsControlledBy(pvc, cluster))
assert.Equal(t, pvc.Labels[naming.LabelCluster], cluster.Name)
assert.Equal(t, pvc.Labels[naming.LabelRole], naming.RolePGAdmin)
assert.Equal(t, pvc.Labels[naming.LabelData], naming.DataPGAdmin)
assert.Assert(t, marshalMatches(pvc.Spec, `
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: storage-class-for-data
volumeMode: Filesystem
`))
})
}
func TestReconcilePGAdminUsers(t *testing.T) {
ctx := context.Background()
t.Run("Disabled", func(t *testing.T) {
r := new(Reconciler)
cluster := new(v1beta1.PostgresCluster)
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, nil, nil))
})
// pgAdmin enabled
cluster := &v1beta1.PostgresCluster{}
cluster.Namespace = "ns1"
cluster.Name = "pgc1"
cluster.Spec.Port = initialize.Int32(5432)
cluster.Spec.UserInterface =
&v1beta1.UserInterfaceSpec{PGAdmin: &v1beta1.PGAdminPodSpec{}}
t.Run("NoPods", func(t *testing.T) {
r := new(Reconciler)
r.Client = fake.NewClientBuilder().Build()
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, nil, nil))
})
// Pod in the namespace
pod := corev1.Pod{}
pod.Namespace = cluster.Namespace
pod.Name = cluster.Name + "-pgadmin-0"
t.Run("ContainerNotRunning", func(t *testing.T) {
pod := pod.DeepCopy()
pod.DeletionTimestamp = nil
pod.Status.ContainerStatuses = nil
r := new(Reconciler)
r.Client = fake.NewClientBuilder().WithObjects(pod).Build()
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, nil, nil))
})
t.Run("PodTerminating", func(t *testing.T) {
pod := pod.DeepCopy()
pod.DeletionTimestamp = new(metav1.Time)
*pod.DeletionTimestamp = metav1.Now()
pod.Status.ContainerStatuses =
[]corev1.ContainerStatus{{Name: naming.ContainerPGAdmin}}
pod.Status.ContainerStatuses[0].State.Running =
new(corev1.ContainerStateRunning)
r := new(Reconciler)
r.Client = fake.NewClientBuilder().WithObjects(pod).Build()
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, nil, nil))
})
t.Run("PodHealthy", func(t *testing.T) {
cluster := cluster.DeepCopy()
pod := pod.DeepCopy()
pod.DeletionTimestamp = nil
pod.Status.ContainerStatuses =
[]corev1.ContainerStatus{{Name: naming.ContainerPGAdmin}}
pod.Status.ContainerStatuses[0].State.Running =
new(corev1.ContainerStateRunning)
r := new(Reconciler)
r.Client = fake.NewClientBuilder().WithObjects(pod).Build()
calls := 0
r.PodExec = func(
namespace, pod, container string,
stdin io.Reader, stdout, stderr io.Writer, command ...string,
) error {
calls++
assert.Equal(t, pod, "pgc1-pgadmin-0")
assert.Equal(t, namespace, cluster.Namespace)
assert.Equal(t, container, naming.ContainerPGAdmin)
return nil
}
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, nil, nil))
assert.Equal(t, calls, 1, "PodExec should be called once")
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, nil, nil))
assert.Equal(t, calls, 1, "PodExec should not be called again")
// Do the thing when users change.
users := []v1beta1.PostgresUserSpec{{Name: "u1"}}
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, users, nil))
assert.Equal(t, calls, 2, "PodExec should be called once")
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, users, nil))
assert.Equal(t, calls, 2, "PodExec should not be called again")
// Do the thing when passwords change.
passwords := map[string]*corev1.Secret{
"u1": {Data: map[string][]byte{"password": []byte(`something`)}},
}
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, users, passwords))
assert.Equal(t, calls, 3, "PodExec should be called once")
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, users, passwords))
assert.Equal(t, calls, 3, "PodExec should not be called again")
passwords["u1"].Data["password"] = []byte(`rotated`)
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, users, passwords))
assert.Equal(t, calls, 4, "PodExec should be called once")
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, users, passwords))
assert.Equal(t, calls, 4, "PodExec should not be called again")
t.Run("ThenDisabled", func(t *testing.T) {
// TODO(cbandy): Revisit this when there is more than one UI.
cluster := cluster.DeepCopy()
cluster.Spec.UserInterface = nil
assert.Assert(t, cluster.Status.UserInterface != nil, "expected some status")
r := new(Reconciler)
assert.NilError(t, r.reconcilePGAdminUsers(ctx, cluster, users, passwords))
assert.Assert(t, cluster.Status.UserInterface == nil, "expected no status")
})
})
}
func pgAdminTestCluster(ns corev1.Namespace) *v1beta1.PostgresCluster {
return &v1beta1.PostgresCluster{
ObjectMeta: metav1.ObjectMeta{
Name: "test-cluster",
Namespace: ns.Name,
},
Spec: v1beta1.PostgresClusterSpec{
PostgresVersion: 13,
InstanceSets: []v1beta1.PostgresInstanceSetSpec{{
DataVolumeClaimSpec: testVolumeClaimSpec(),
}},
Backups: v1beta1.Backups{
PGBackRest: v1beta1.PGBackRestArchive{
Repos: []v1beta1.PGBackRestRepo{{
Name: "repo1",
Volume: &v1beta1.RepoPVC{
VolumeClaimSpec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce},
Resources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceStorage: resource.MustParse("1Gi"),
},
},
},
},
}},
},
},
UserInterface: &v1beta1.UserInterfaceSpec{
PGAdmin: &v1beta1.PGAdminPodSpec{
Image: "test-image",
DataVolumeClaimSpec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce},
Resources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceStorage: resource.MustParse("1Gi"),
},
},
StorageClassName: initialize.String("storage-class-for-data"),
},
},
},
},
}
}