-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathetcdmember_controller_test.go
More file actions
2663 lines (2482 loc) · 105 KB
/
Copy pathetcdmember_controller_test.go
File metadata and controls
2663 lines (2482 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2023 Timofey Larkin.
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
*/
package controllers
import (
"context"
"crypto/tls"
"errors"
"strings"
"testing"
"go.etcd.io/etcd/api/v3/etcdserverpb"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
lll "github.com/cozystack/etcd-operator/api/v1alpha2"
)
// TestRemoveMemberFromEtcd_FallbackByName covers reviewer issue #1: when a
// member's status.MemberID is empty (e.g. the pod never became Ready before
// scale-down), the finalizer must still find the etcd-side member by name and
// MemberRemove it. Without this, scale-up + immediate scale-down orphans the
// MemberAdd in etcd's member list.
func TestRemoveMemberFromEtcd_FallbackByName(t *testing.T) {
ctx := context.Background()
// Cluster has two existing members and the never-Ready new member.
cluster := &lll.EtcdCluster{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "ns"}}
existing0 := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{PodName: "test-0"},
}
existing1 := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-1", Namespace: "ns", Labels: memberLabels("test", "test-1")},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{PodName: "test-1"},
}
// test-2 was just MemberAdd'd to etcd but the pod never came up, so
// MemberID is still empty on the CR.
victim := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{
Name: "test-2", Namespace: "ns",
Labels: memberLabels("test", "test-2"),
Finalizers: []string{MemberFinalizer},
},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
// No MemberID, no PodName.
}
// Etcd reflects the situation: 3 members, with test-2 added by URL but
// no Name yet (etcd populates Name only after the joiner reports in).
const orphanID uint64 = 0xc0ffee
fe := newFakeEtcd(0xdeadbeef,
&etcdserverpb.Member{ID: 0xa01, Name: "test-0", PeerURLs: []string{peerURL("http", "test-0", "test", "ns")}},
&etcdserverpb.Member{ID: 0xa02, Name: "test-1", PeerURLs: []string{peerURL("http", "test-1", "test", "ns")}},
&etcdserverpb.Member{ID: orphanID, Name: "", PeerURLs: []string{peerURL("http", "test-2", "test", "ns")}},
)
c, _ := newTestClient(t, cluster, existing0, existing1, victim)
r := &EtcdMemberReconciler{
Client: c,
Scheme: testScheme(t),
EtcdClientFactory: factoryReturning(fe),
}
if err := r.removeMemberFromEtcd(ctx, cluster, victim); err != nil {
t.Fatalf("removeMemberFromEtcd: %v", err)
}
if len(fe.removeCalls) != 1 || fe.removeCalls[0] != orphanID {
t.Fatalf("expected MemberRemove(0x%x); got %v", orphanID, fe.removeCalls)
}
}
// TestRemoveMemberFromEtcd_PeerWithEmptyPodNameRetries covers reviewer
// issue #3: if other members exist on the CR side but none have a PodName
// recorded yet (transient state, controller restart), removeMemberFromEtcd
// must NOT silently return nil — that would let the finalizer clear and
// orphan the etcd-side member. Return an error so we retry.
func TestRemoveMemberFromEtcd_PeerWithEmptyPodNameRetries(t *testing.T) {
ctx := context.Background()
cluster := &lll.EtcdCluster{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "ns"}}
// test-0 has no PodName recorded — simulating mid-bootstrap or
// controller-restart staleness.
other := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
// Status.PodName intentionally empty.
}
victim := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-1", Namespace: "ns", Labels: memberLabels("test", "test-1"), Finalizers: []string{MemberFinalizer}},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{MemberID: "abc"},
}
c, _ := newTestClient(t, cluster, other, victim)
fe := newFakeEtcd(0xdeadbeef)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t), EtcdClientFactory: factoryReturning(fe)}
err := r.removeMemberFromEtcd(ctx, cluster, victim)
if err == nil {
t.Fatalf("expected error when peers exist on CR side but none have PodName set")
}
if len(fe.removeCalls) != 0 {
t.Fatalf("MemberRemove should not be called when endpoints are empty; got %v", fe.removeCalls)
}
}
// TestHandleDeletion_TransientGetErrorReturnsError covers reviewer issue
// #4: a non-NotFound error from getting the owner EtcdCluster must NOT be
// silently treated as "cluster alive" — that risks repeatedly firing
// MemberRemove against a cluster we can't actually introspect. Propagate
// the error so controller-runtime applies backoff.
func TestHandleDeletion_TransientGetErrorReturnsError(t *testing.T) {
ctx := context.Background()
now := metav1.Now()
cluster := &lll.EtcdCluster{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "ns"}}
victim := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{
Name: "test-0", Namespace: "ns",
Labels: memberLabels("test", "test-0"),
Finalizers: []string{MemberFinalizer},
DeletionTimestamp: &now,
},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{MemberID: "abc"},
}
base, _ := newTestClient(t, cluster, victim)
c := &erroringGetClient{
Client: base,
failOnKind: "EtcdCluster",
err: errors.New("apiserver flaked"),
}
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t), EtcdClientFactory: factoryReturning(newFakeEtcd(0xdeadbeef))}
if _, err := r.handleDeletion(ctx, victim); err == nil {
t.Fatalf("expected error from handleDeletion on transient cluster Get error")
}
// Finalizer should still be in place — we didn't get a clean shutdown.
mustGet(t, base, "test-0", "ns", victim)
if !containsFinalizer(victim, MemberFinalizer) {
t.Fatalf("finalizer was removed despite Get error")
}
}
func containsFinalizer(m *lll.EtcdMember, name string) bool {
for _, f := range m.Finalizers {
if f == name {
return true
}
}
return false
}
// TestRemoveMemberFromEtcd_NotFoundIsClean: if the member doesn't appear in
// etcd's list at all, treat it as already gone — no error. Otherwise, the
// finalizer would block forever waiting for an etcd-side state that never
// materialises.
func TestRemoveMemberFromEtcd_NotFoundIsClean(t *testing.T) {
ctx := context.Background()
cluster := &lll.EtcdCluster{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "ns"}}
existing0 := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{PodName: "test-0"},
}
victim := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-9", Namespace: "ns", Labels: memberLabels("test", "test-9"), Finalizers: []string{MemberFinalizer}},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
}
fe := newFakeEtcd(0xdeadbeef,
&etcdserverpb.Member{ID: 0xa01, Name: "test-0", PeerURLs: []string{peerURL("http", "test-0", "test", "ns")}},
)
c, _ := newTestClient(t, cluster, existing0, victim)
r := &EtcdMemberReconciler{
Client: c,
Scheme: testScheme(t),
EtcdClientFactory: factoryReturning(fe),
}
if err := r.removeMemberFromEtcd(ctx, cluster, victim); err != nil {
t.Fatalf("removeMemberFromEtcd should not error when member already gone: %v", err)
}
if len(fe.removeCalls) != 0 {
t.Fatalf("expected no MemberRemove call, got %v", fe.removeCalls)
}
}
// TestEnsurePVC_RefusesStaleOwner covers reviewer issue #2: a same-named PVC
// owned by a now-deleted EtcdMember (pending GC) must NOT be bound to the new
// EtcdMember of the same name. Reusing the prior data dir would crashloop the
// new pod (etcd sees a memberID the cluster has just removed).
func TestEnsurePVC_RefusesStaleOwner(t *testing.T) {
ctx := context.Background()
staleUID := types.UID("old-uid")
freshUID := types.UID("fresh-uid")
stalePVC := &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: "data-test-1",
Namespace: "ns",
OwnerReferences: []metav1.OwnerReference{{
APIVersion: "etcd-operator.cozystack.io/v1alpha2",
Kind: "EtcdMember",
Name: "test-1",
UID: staleUID,
}},
},
Spec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce},
Resources: corev1.VolumeResourceRequirements{
Requests: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("1Gi")},
},
},
}
freshMember := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-1", Namespace: "ns", UID: freshUID, Labels: memberLabels("test", "test-1")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
c, _ := newTestClient(t, freshMember, stalePVC)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
err := r.ensurePVC(ctx, freshMember)
if err == nil {
t.Fatalf("ensurePVC should refuse to reuse a PVC owned by a stale EtcdMember")
}
}
// TestEnsurePVC_RefusesPVCWithNoOwnerRefs: a PVC with no owner refs is no
// longer "adopted" — the only legitimate adoption flow (operator-managed
// scale-to-zero hand-off) is tracked separately and will use explicit
// re-parenting. Until then, ensurePVC accepts only PVCs we created.
func TestEnsurePVC_RefusesPVCWithNoOwnerRefs(t *testing.T) {
ctx := context.Background()
prePVC := &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: "data-test-0",
Namespace: "ns",
},
Spec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce},
Resources: corev1.VolumeResourceRequirements{
Requests: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("1Gi")},
},
},
}
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", UID: types.UID("uid"), Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
c, _ := newTestClient(t, member, prePVC)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
if err := r.ensurePVC(ctx, member); err == nil {
t.Fatalf("ensurePVC should refuse to adopt a PVC with no owner references")
}
}
// TestEnsurePVC_RefusesPVCOwnedByOther: a PVC owned by some other resource
// (a leaked owner ref, a Pod, another operator's CR) must not be silently
// mounted by an etcd member. ensurePVC errors out so the user can untangle
// the conflict explicitly.
func TestEnsurePVC_RefusesPVCOwnedByOther(t *testing.T) {
ctx := context.Background()
otherPVC := &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: "data-test-0",
Namespace: "ns",
OwnerReferences: []metav1.OwnerReference{{
APIVersion: "v1",
Kind: "Pod",
Name: "some-other-pod",
UID: types.UID("other-uid"),
}},
},
Spec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce},
Resources: corev1.VolumeResourceRequirements{
Requests: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("1Gi")},
},
},
}
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", UID: types.UID("uid"), Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
c, _ := newTestClient(t, member, otherPVC)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
if err := r.ensurePVC(ctx, member); err == nil {
t.Fatalf("ensurePVC should refuse to mount a PVC owned by something other than this EtcdMember")
}
}
// TestEnsurePVC_AcceptsOwnPVC: when the existing PVC's owner ref UID matches
// the current EtcdMember (a normal restart-after-pod-delete situation), reuse
// is fine.
func TestEnsurePVC_AcceptsOwnPVC(t *testing.T) {
ctx := context.Background()
uid := types.UID("same-uid")
ownPVC := &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: "data-test-0",
Namespace: "ns",
OwnerReferences: []metav1.OwnerReference{{
APIVersion: "etcd-operator.cozystack.io/v1alpha2",
Kind: "EtcdMember",
Name: "test-0",
UID: uid,
}},
},
Spec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce},
Resources: corev1.VolumeResourceRequirements{
Requests: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("1Gi")},
},
},
}
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", UID: uid, Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
c, _ := newTestClient(t, member, ownPVC)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
if err := r.ensurePVC(ctx, member); err != nil {
t.Fatalf("ensurePVC for own PVC: %v", err)
}
if member.Status.PVCName != "data-test-0" {
t.Fatalf("PVCName not recorded: %q", member.Status.PVCName)
}
}
// TestEnsurePVC_AppliesStorageClassName covers the wiring of
// spec.storage.storageClassName onto the created PVC. The propagation
// is what makes per-cluster StorageClass overrides actually take effect
// — a member spec with the field set must result in
// PersistentVolumeClaim.spec.storageClassName carrying the same value.
func TestEnsurePVC_AppliesStorageClassName(t *testing.T) {
ctx := context.Background()
sc := "replicated"
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", UID: types.UID("mu"), Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{
ClusterName: "test", Version: "3.5.17",
Storage: lll.StorageSpec{Size: quickQty(t, "1Gi"), StorageClassName: &sc},
InitialCluster: "x", ClusterToken: "test",
},
}
c, _ := newTestClient(t, member)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
if err := r.ensurePVC(ctx, member); err != nil {
t.Fatalf("ensurePVC: %v", err)
}
pvc := &corev1.PersistentVolumeClaim{}
if err := c.Get(ctx, types.NamespacedName{Namespace: "ns", Name: "data-test-0"}, pvc); err != nil {
t.Fatalf("PVC not created: %v", err)
}
if pvc.Spec.StorageClassName == nil {
t.Fatalf("PVC.spec.storageClassName is nil; want %q", sc)
}
if *pvc.Spec.StorageClassName != sc {
t.Fatalf("PVC.spec.storageClassName = %q; want %q", *pvc.Spec.StorageClassName, sc)
}
}
// TestEnsurePVC_NilStorageClassNamePassesNil covers the negative case:
// when spec.storage.storageClassName is unset on the member, the
// resulting PVC must have a nil StorageClassName (which means "use the
// namespace's default"), NOT an empty string (which means "explicitly
// no dynamic provisioning"). Conflating the two would silently disable
// dynamic provisioning on clusters that didn't ask for it.
func TestEnsurePVC_NilStorageClassNamePassesNil(t *testing.T) {
ctx := context.Background()
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", UID: types.UID("mu"), Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{
ClusterName: "test", Version: "3.5.17",
Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, // StorageClassName left nil.
InitialCluster: "x", ClusterToken: "test",
},
}
c, _ := newTestClient(t, member)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
if err := r.ensurePVC(ctx, member); err != nil {
t.Fatalf("ensurePVC: %v", err)
}
pvc := &corev1.PersistentVolumeClaim{}
if err := c.Get(ctx, types.NamespacedName{Namespace: "ns", Name: "data-test-0"}, pvc); err != nil {
t.Fatalf("PVC not created: %v", err)
}
if pvc.Spec.StorageClassName != nil {
t.Fatalf("PVC.spec.storageClassName must be nil when not set on the member; got %q", *pvc.Spec.StorageClassName)
}
}
// TestEnsurePVC_AppliesAdditionalMetadata covers the metadata stamp on the
// per-member data PVC: spec.additionalMetadata promises to land on every
// object the operator creates, and PVCs are a prime target for it
// (backup-tool selectors, cost-allocation labels). The PVC must carry the
// merged labels/annotations without a user key shadowing an operator-owned
// label.
func TestEnsurePVC_AppliesAdditionalMetadata(t *testing.T) {
ctx := context.Background()
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", UID: types.UID("mu"), Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{
ClusterName: "test", Version: "3.5.17",
Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")},
InitialCluster: "x", ClusterToken: "test",
AdditionalMetadata: &lll.AdditionalMetadata{
Labels: map[string]string{
"cozystack.io/tenant": "foo",
// Attempt to shadow an operator-owned label: must be ignored.
"app.kubernetes.io/managed-by": "evil",
},
Annotations: map[string]string{"example.com/note": "bar"},
},
},
}
c, _ := newTestClient(t, member)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
if err := r.ensurePVC(ctx, member); err != nil {
t.Fatalf("ensurePVC: %v", err)
}
pvc := &corev1.PersistentVolumeClaim{}
if err := c.Get(ctx, types.NamespacedName{Namespace: "ns", Name: "data-test-0"}, pvc); err != nil {
t.Fatalf("PVC not created: %v", err)
}
if got := pvc.Labels["cozystack.io/tenant"]; got != "foo" {
t.Errorf("PVC additional label not merged: cozystack.io/tenant = %q, want foo", got)
}
if got := pvc.Labels["app.kubernetes.io/managed-by"]; got != "etcd-operator" {
t.Errorf("PVC operator-owned label clobbered: app.kubernetes.io/managed-by = %q, want etcd-operator", got)
}
if got := pvc.Annotations["example.com/note"]; got != "bar" {
t.Errorf("PVC additional annotation not merged: example.com/note = %q, want bar", got)
}
}
// TestEnsurePod_RefusesStaleOwner mirrors TestEnsurePVC_RefusesStaleOwner:
// a same-named Pod owned by a now-deleted EtcdMember (pending GC) must
// not be adopted by the fresh EtcdMember of the same name. Less severe
// than the PVC case (Pod state is replaceable), but the operator-managed
// lifecycle would otherwise reconcile a Pod whose spec was written by a
// different controller generation.
func TestEnsurePod_RefusesStaleOwner(t *testing.T) {
ctx := context.Background()
stalePod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "test-1", Namespace: "ns",
OwnerReferences: []metav1.OwnerReference{{
APIVersion: "etcd-operator.cozystack.io/v1alpha2",
Kind: "EtcdMember",
Name: "test-1",
UID: types.UID("old-uid"),
}},
},
}
freshMember := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-1", Namespace: "ns", UID: types.UID("fresh-uid"), Labels: memberLabels("test", "test-1")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
c, _ := newTestClient(t, freshMember, stalePod)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
if err := r.ensurePod(ctx, freshMember); err == nil {
t.Fatalf("ensurePod should refuse to adopt a Pod owned by a stale EtcdMember UID")
}
}
// TestEnsurePod_RefusesPodWithNoOwnerRefs: a same-named Pod with no
// owner refs (manually created, leaked from a previous incarnation
// without GC catching the dependent) is refused — the operator's
// reconcile flow assumes it created and controls the Pod, and adoption
// would silently bind unowned state.
func TestEnsurePod_RefusesPodWithNoOwnerRefs(t *testing.T) {
ctx := context.Background()
prePod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns"},
}
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", UID: types.UID("uid"), Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
c, _ := newTestClient(t, member, prePod)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
if err := r.ensurePod(ctx, member); err == nil {
t.Fatalf("ensurePod should refuse to adopt a Pod with no owner references")
}
}
// TestEnsurePod_RefusesPodOwnedByOther: a Pod owned by some other
// resource (different Kind, different operator's CR, a deployment-
// style controller) must not be adopted. Symmetric with the PVC
// other-owner refusal.
func TestEnsurePod_RefusesPodOwnedByOther(t *testing.T) {
ctx := context.Background()
otherPod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "test-0", Namespace: "ns",
OwnerReferences: []metav1.OwnerReference{{
APIVersion: "apps/v1",
Kind: "ReplicaSet",
Name: "some-rs",
UID: types.UID("other-uid"),
}},
},
}
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", UID: types.UID("uid"), Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
c, _ := newTestClient(t, member, otherPod)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
if err := r.ensurePod(ctx, member); err == nil {
t.Fatalf("ensurePod should refuse to adopt a Pod owned by something other than this EtcdMember")
}
}
// TestEnsurePod_AcceptsOwnPod: when the existing Pod's owner ref UID
// matches the current EtcdMember (the normal post-create steady-state
// case), reuse is fine and Status.PodName / Status.PodUID get recorded.
func TestEnsurePod_AcceptsOwnPod(t *testing.T) {
ctx := context.Background()
uid := types.UID("same-uid")
ownPod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "test-0", Namespace: "ns", UID: types.UID("pod-uid"),
OwnerReferences: []metav1.OwnerReference{{
APIVersion: "etcd-operator.cozystack.io/v1alpha2",
Kind: "EtcdMember",
Name: "test-0",
UID: uid,
}},
},
}
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", UID: uid, Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
c, _ := newTestClient(t, member, ownPod)
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t)}
if err := r.ensurePod(ctx, member); err != nil {
t.Fatalf("ensurePod for own Pod: %v", err)
}
if member.Status.PodName != "test-0" {
t.Fatalf("PodName not recorded: %q", member.Status.PodName)
}
if member.Status.PodUID != "pod-uid" {
t.Fatalf("PodUID not recorded: %q", member.Status.PodUID)
}
}
// TestUpdateStatus_NoMemberIDKeepsReadyFalse covers reviewer issue #3: a pod
// that's PodReady but without a populated MemberID must not be reported as
// MemberReady=True. Otherwise the cluster controller can count it toward
// readyMembers and a deletion in this window leaves an etcd-side orphan.
func TestUpdateStatus_NoMemberIDKeepsReadyFalse(t *testing.T) {
ctx := context.Background()
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns"},
Status: corev1.PodStatus{
Phase: corev1.PodRunning,
Conditions: []corev1.PodCondition{readyPodCondition()},
},
}
c, _ := newTestClient(t, member, pod)
// Etcd is reachable but it doesn't yet know about test-0 by name —
// simulating the brief window between the pod becoming Ready and etcd
// propagating the joiner's identity.
fe := newFakeEtcd(0xdeadbeef) // empty members list
r := &EtcdMemberReconciler{
Client: c,
Scheme: testScheme(t),
EtcdClientFactory: factoryReturning(fe),
}
if _, err := r.updateStatus(ctx, member); err != nil {
t.Fatalf("updateStatus: %v", err)
}
mustGet(t, c, "test-0", "ns", member)
var ready *metav1.Condition
for i := range member.Status.Conditions {
if member.Status.Conditions[i].Type == lll.MemberReady {
ready = &member.Status.Conditions[i]
}
}
if ready == nil {
t.Fatalf("no MemberReady condition")
}
if ready.Status != metav1.ConditionFalse {
t.Fatalf("Ready=%v, want False (no memberID populated yet)", ready.Status)
}
if ready.Reason != "DiscoveringMemberID" {
t.Fatalf("Reason=%q, want DiscoveringMemberID", ready.Reason)
}
if member.Status.MemberID != "" {
t.Fatalf("MemberID populated unexpectedly: %q", member.Status.MemberID)
}
}
// TestUpdateStatus_PopulatesMemberIDAndFlipsReady: the happy path — etcd
// knows about this member by name, we record the hex ID and flip Ready=True.
func TestUpdateStatus_PopulatesMemberIDAndFlipsReady(t *testing.T) {
ctx := context.Background()
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns"},
Status: corev1.PodStatus{
Phase: corev1.PodRunning,
Conditions: []corev1.PodCondition{readyPodCondition()},
},
}
c, _ := newTestClient(t, member, pod)
const wantID uint64 = 0xae36f238164a08ad
fe := newFakeEtcd(0xdeadbeef,
&etcdserverpb.Member{ID: wantID, Name: "test-0", PeerURLs: []string{peerURL("http", "test-0", "test", "ns")}},
)
r := &EtcdMemberReconciler{
Client: c,
Scheme: testScheme(t),
EtcdClientFactory: factoryReturning(fe),
}
if _, err := r.updateStatus(ctx, member); err != nil {
t.Fatalf("updateStatus: %v", err)
}
mustGet(t, c, "test-0", "ns", member)
if member.Status.MemberID != "ae36f238164a08ad" {
t.Fatalf("MemberID = %q, want ae36f238164a08ad", member.Status.MemberID)
}
var ready *metav1.Condition
for i := range member.Status.Conditions {
if member.Status.Conditions[i].Type == lll.MemberReady {
ready = &member.Status.Conditions[i]
}
}
if ready == nil || ready.Status != metav1.ConditionTrue {
t.Fatalf("Ready condition = %+v, want True", ready)
}
}
// TestRemoveMemberFromEtcd_LastMemberIsNoOp: if no other members exist (the
// cluster is being torn down or this is genuinely the last member), the
// finalizer can't reach a peer to call MemberRemove. Don't block — return
// nil so the finalizer can clear and the resource gets GC'd.
func TestRemoveMemberFromEtcd_LastMemberIsNoOp(t *testing.T) {
ctx := context.Background()
cluster := &lll.EtcdCluster{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "ns"}}
victim := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{
Name: "test-0", Namespace: "ns",
Labels: memberLabels("test", "test-0"),
Finalizers: []string{MemberFinalizer},
},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{MemberID: "abc"},
}
c, _ := newTestClient(t, cluster, victim)
r := &EtcdMemberReconciler{
Client: c,
Scheme: testScheme(t),
EtcdClientFactory: factoryReturning(newFakeEtcd(0xdead)), // never reached
}
if err := r.removeMemberFromEtcd(ctx, cluster, victim); err != nil {
t.Fatalf("removeMemberFromEtcd should be a no-op when no peers reachable; got %v", err)
}
}
// TestRemoveMemberFromEtcd_FactoryError: if we can build no etcd client at
// all, the finalizer must surface the error and retry rather than silently
// removing the finalizer (which would leave the etcd-side member orphaned).
func TestRemoveMemberFromEtcd_FactoryError(t *testing.T) {
ctx := context.Background()
cluster := &lll.EtcdCluster{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "ns"}}
otherMember := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-1", Namespace: "ns", Labels: memberLabels("test", "test-1")},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{PodName: "test-1"},
}
victim := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", Labels: memberLabels("test", "test-0"), Finalizers: []string{MemberFinalizer}},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{MemberID: "abc"},
}
c, _ := newTestClient(t, cluster, otherMember, victim)
r := &EtcdMemberReconciler{
Client: c,
Scheme: testScheme(t),
EtcdClientFactory: failingFactory(errors.New("dial timeout")),
}
err := r.removeMemberFromEtcd(ctx, cluster, victim)
if err == nil {
t.Fatalf("expected error from removeMemberFromEtcd when factory fails")
}
}
// TestUpdateStatus_PodNotReadyKeepsReadyFalse covers the symmetric case to
// #3: if the pod itself isn't Ready, MemberReady should be False with reason
// PodNotReady (and we should never even attempt MemberID discovery).
func TestUpdateStatus_PodNotReadyKeepsReadyFalse(t *testing.T) {
ctx := context.Background()
member := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17", Storage: lll.StorageSpec{Size: quickQty(t, "1Gi")}, InitialCluster: "x", ClusterToken: "test"},
}
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns"},
Status: corev1.PodStatus{
Phase: corev1.PodPending,
Conditions: []corev1.PodCondition{{
Type: corev1.PodReady, Status: corev1.ConditionFalse,
LastTransitionTime: metav1.Now(),
}},
},
}
c, _ := newTestClient(t, member, pod)
// Factory should never be called when pod isn't Ready; using a failing
// factory asserts that.
r := &EtcdMemberReconciler{
Client: c,
Scheme: testScheme(t),
EtcdClientFactory: failingFactory(errors.New("must not be called")),
}
if _, err := r.updateStatus(ctx, member); err != nil {
t.Fatalf("updateStatus: %v", err)
}
mustGet(t, c, "test-0", "ns", member)
var ready *metav1.Condition
for i := range member.Status.Conditions {
if member.Status.Conditions[i].Type == lll.MemberReady {
ready = &member.Status.Conditions[i]
}
}
if ready == nil || ready.Status != metav1.ConditionFalse || ready.Reason != "PodNotReady" {
t.Fatalf("Ready condition = %+v, want False/PodNotReady", ready)
}
}
// TestBuildPod_LivenessIsNotQuorumAware covers B1: the liveness probe must
// not require quorum. A liveness HTTPGet on /health kills every member
// during a transient partition. The check is a TCP socket on the peer
// port — process-alive only.
func TestBuildPod_LivenessIsNotQuorumAware(t *testing.T) {
r := &EtcdMemberReconciler{}
pod := r.buildPod(&lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns"},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17"},
})
lp := pod.Spec.Containers[0].LivenessProbe
if lp == nil {
t.Fatalf("missing liveness probe entirely")
}
if lp.HTTPGet != nil {
t.Fatalf("liveness probe must not use HTTPGet (would require quorum on /health); got HTTPGet=%+v", lp.HTTPGet)
}
if lp.TCPSocket == nil {
t.Fatalf("liveness probe should use TCPSocket")
}
if lp.TCPSocket.Port.IntValue() != 2380 {
t.Fatalf("liveness TCP port = %d, want 2380 (peer)", lp.TCPSocket.Port.IntValue())
}
}
// TestBuildPod_AppliesSchedulingAndMetadata covers the additionalMetadata,
// affinity, and topologySpreadConstraints passthrough: buildPod must stamp
// the Pod with the member's scheduling fields and merge the extra
// labels/annotations, without letting a user-supplied label shadow an
// operator-owned one.
func TestBuildPod_AppliesSchedulingAndMetadata(t *testing.T) {
r := &EtcdMemberReconciler{}
aff := &corev1.Affinity{
PodAntiAffinity: &corev1.PodAntiAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: []corev1.PodAffinityTerm{{
TopologyKey: "kubernetes.io/hostname",
}},
},
}
tsc := []corev1.TopologySpreadConstraint{{
MaxSkew: 1,
TopologyKey: "topology.kubernetes.io/zone",
WhenUnsatisfiable: corev1.DoNotSchedule,
}}
pod := r.buildPod(&lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns"},
Spec: lll.EtcdMemberSpec{
ClusterName: "test",
Version: "3.5.17",
Affinity: aff,
TopologySpreadConstraints: tsc,
AdditionalMetadata: &lll.AdditionalMetadata{
Labels: map[string]string{
"cozystack.io/tenant": "foo",
// Attempt to shadow an operator-owned label: must be ignored.
"app.kubernetes.io/managed-by": "evil",
},
Annotations: map[string]string{"example.com/note": "bar"},
},
},
})
if !equality.Semantic.DeepEqual(pod.Spec.Affinity, aff) {
t.Errorf("pod affinity = %+v, want %+v", pod.Spec.Affinity, aff)
}
if !equality.Semantic.DeepEqual(pod.Spec.TopologySpreadConstraints, tsc) {
t.Errorf("pod topologySpreadConstraints = %+v, want %+v", pod.Spec.TopologySpreadConstraints, tsc)
}
if got := pod.Labels["cozystack.io/tenant"]; got != "foo" {
t.Errorf("additional label not merged: cozystack.io/tenant = %q, want foo", got)
}
if got := pod.Labels["app.kubernetes.io/managed-by"]; got != "etcd-operator" {
t.Errorf("operator-owned label was overridden: app.kubernetes.io/managed-by = %q, want etcd-operator", got)
}
if got := pod.Annotations["example.com/note"]; got != "bar" {
t.Errorf("additional annotation not merged: example.com/note = %q, want bar", got)
}
}
// TestBuildPod_NoAdditionalMetadataLeavesAnnotationsNil guards that a member
// without additionalMetadata produces a Pod with no annotations (rather than
// an empty non-nil map), keeping the no-op path clean.
func TestBuildPod_NoAdditionalMetadataLeavesAnnotationsNil(t *testing.T) {
r := &EtcdMemberReconciler{}
pod := r.buildPod(&lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns"},
Spec: lll.EtcdMemberSpec{ClusterName: "test", Version: "3.5.17"},
})
if pod.Annotations != nil {
t.Errorf("expected nil annotations, got %+v", pod.Annotations)
}
if pod.Spec.Affinity != nil {
t.Errorf("expected nil affinity, got %+v", pod.Spec.Affinity)
}
}
// TestRemoveMemberFromEtcd_SkipsDeletingPeers covers B4: when other members
// are themselves Terminating, removeMemberFromEtcd must not dial their
// (about-to-vanish) endpoints. Filter active members first.
func TestRemoveMemberFromEtcd_SkipsDeletingPeers(t *testing.T) {
ctx := context.Background()
now := metav1.Now()
cluster := &lll.EtcdCluster{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "ns"}}
healthy := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{PodName: "test-0"},
}
dying := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-2", Namespace: "ns", Labels: memberLabels("test", "test-2"),
DeletionTimestamp: &now, Finalizers: []string{MemberFinalizer}},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{PodName: "test-2"},
}
victim := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-1", Namespace: "ns", Labels: memberLabels("test", "test-1"),
Finalizers: []string{MemberFinalizer}},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{MemberID: "0000000000000002", PodName: "test-1"},
}
c, _ := newTestClient(t, cluster, healthy, dying, victim)
// Record the endpoints the factory was called with.
var seenEndpoints []string
fe := newFakeEtcd(0xdeadbeef,
&etcdserverpb.Member{ID: 0x1, Name: "test-0", PeerURLs: []string{peerURL("http", "test-0", "test", "ns")}},
&etcdserverpb.Member{ID: 0x2, Name: "test-1", PeerURLs: []string{peerURL("http", "test-1", "test", "ns")}},
&etcdserverpb.Member{ID: 0x3, Name: "test-2", PeerURLs: []string{peerURL("http", "test-2", "test", "ns")}},
)
factory := func(_ context.Context, eps []string, _ *tls.Config, _, _ string) (EtcdClusterClient, error) {
seenEndpoints = append([]string(nil), eps...)
return fe, nil
}
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t), EtcdClientFactory: factory}
if err := r.removeMemberFromEtcd(ctx, cluster, victim); err != nil {
t.Fatalf("removeMemberFromEtcd: %v", err)
}
for _, ep := range seenEndpoints {
if ep == clientURL("http", "test-2", "test", "ns") {
t.Fatalf("dialed a Terminating peer (test-2); endpoints were %v", seenEndpoints)
}
}
if len(seenEndpoints) != 1 || seenEndpoints[0] != clientURL("http", "test-0", "test", "ns") {
t.Fatalf("expected dial only against test-0; got %v", seenEndpoints)
}
}
// TestDiscoverMemberID_FallsBackToPeers covers B5: if the member's own pod
// is crashlooping, peer members still know its ID. discoverMemberID must
// dial peers, not just self.
func TestDiscoverMemberID_FallsBackToPeers(t *testing.T) {
ctx := context.Background()
cluster := &lll.EtcdCluster{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "ns"}}
now := metav1.Now()
peer := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-0", Namespace: "ns", Labels: memberLabels("test", "test-0")},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
Status: lll.EtcdMemberStatus{
PodName: "test-0", MemberID: "0000000000000001",
IsVoter: true,
Conditions: []metav1.Condition{{Type: lll.MemberReady, Status: metav1.ConditionTrue, Reason: "PodReady", LastTransitionTime: now}},
},
}
target := &lll.EtcdMember{
ObjectMeta: metav1.ObjectMeta{Name: "test-1", Namespace: "ns", Labels: memberLabels("test", "test-1")},
Spec: lll.EtcdMemberSpec{ClusterName: "test"},
}
c, _ := newTestClient(t, cluster, peer, target)
// Factory inspects endpoints; if the first is self URL, error; if peer
// URL is present, succeed with a fake that knows about target.
const wantID uint64 = 0xfeedface
fe := newFakeEtcd(0xdead,
&etcdserverpb.Member{ID: 0x1, Name: "test-0", PeerURLs: []string{peerURL("http", "test-0", "test", "ns")}},
&etcdserverpb.Member{ID: wantID, Name: "test-1", PeerURLs: []string{peerURL("http", "test-1", "test", "ns")}},
)
var capturedEndpoints []string
factory := func(_ context.Context, eps []string, _ *tls.Config, _, _ string) (EtcdClusterClient, error) {
capturedEndpoints = append([]string(nil), eps...)
return fe, nil
}
r := &EtcdMemberReconciler{Client: c, Scheme: testScheme(t), EtcdClientFactory: factory}
id, err := r.discoverMemberID(ctx, target)
if err != nil {
t.Fatalf("discoverMemberID: %v", err)
}
if id != wantID {
t.Fatalf("id = %x, want %x", id, wantID)
}
// Assert at least one peer URL is in the endpoint list (and not just self).
wantPeer := clientURL("http", "test-0", "test", "ns")
hasPeer := false
for _, ep := range capturedEndpoints {
if ep == wantPeer {