forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 3
/
store_test.go
1296 lines (1166 loc) · 38.7 KB
/
store_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package registry
import (
"fmt"
"path"
"reflect"
"strconv"
"strings"
"sync"
"testing"
"time"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/meta"
"k8s.io/kubernetes/pkg/api/rest"
"k8s.io/kubernetes/pkg/api/testapi"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/fields"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/pkg/registry/core/pod"
"k8s.io/kubernetes/pkg/registry/generic"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/selection"
"k8s.io/kubernetes/pkg/storage"
etcdstorage "k8s.io/kubernetes/pkg/storage/etcd"
etcdtesting "k8s.io/kubernetes/pkg/storage/etcd/testing"
"k8s.io/kubernetes/pkg/storage/storagebackend/factory"
storagetesting "k8s.io/kubernetes/pkg/storage/testing"
"k8s.io/kubernetes/pkg/util/validation/field"
"k8s.io/kubernetes/pkg/util/wait"
)
type testGracefulStrategy struct {
testRESTStrategy
}
func (t testGracefulStrategy) CheckGracefulDelete(ctx api.Context, obj runtime.Object, options *api.DeleteOptions) bool {
return true
}
var _ rest.RESTGracefulDeleteStrategy = testGracefulStrategy{}
type testOrphanDeleteStrategy struct {
*testRESTStrategy
}
func (t *testOrphanDeleteStrategy) DefaultGarbageCollectionPolicy() rest.GarbageCollectionPolicy {
return rest.OrphanDependents
}
type testRESTStrategy struct {
runtime.ObjectTyper
api.NameGenerator
namespaceScoped bool
allowCreateOnUpdate bool
allowUnconditionalUpdate bool
}
func (t *testRESTStrategy) NamespaceScoped() bool { return t.namespaceScoped }
func (t *testRESTStrategy) AllowCreateOnUpdate() bool { return t.allowCreateOnUpdate }
func (t *testRESTStrategy) AllowUnconditionalUpdate() bool { return t.allowUnconditionalUpdate }
func (t *testRESTStrategy) PrepareForCreate(ctx api.Context, obj runtime.Object) {
metaObj, err := meta.Accessor(obj)
if err != nil {
panic(err.Error())
}
labels := metaObj.GetLabels()
if labels == nil {
labels = map[string]string{}
}
labels["prepare_create"] = "true"
metaObj.SetLabels(labels)
}
func (t *testRESTStrategy) PrepareForUpdate(ctx api.Context, obj, old runtime.Object) {}
func (t *testRESTStrategy) Validate(ctx api.Context, obj runtime.Object) field.ErrorList {
return nil
}
func (t *testRESTStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) field.ErrorList {
return nil
}
func (t *testRESTStrategy) Canonicalize(obj runtime.Object) {}
func NewTestGenericStoreRegistry(t *testing.T) (factory.DestroyFunc, *Store) {
return newTestGenericStoreRegistry(t, false)
}
// matchPodName returns selection predicate that matches any pod with name in the set.
// Makes testing simpler.
func matchPodName(names ...string) storage.SelectionPredicate {
// Note: even if pod name is a field, we have to use labels,
// because field selector doesn't support "IN" operator.
l, err := labels.NewRequirement("name", selection.In, names)
if err != nil {
panic("Labels requirement must validate successfully")
}
return storage.SelectionPredicate{
Label: labels.Everything().Add(*l),
Field: fields.Everything(),
GetAttrs: func(obj runtime.Object) (label labels.Set, field fields.Set, err error) {
pod := obj.(*api.Pod)
return labels.Set{"name": pod.ObjectMeta.Name}, nil, nil
},
}
}
func matchEverything() storage.SelectionPredicate {
return storage.SelectionPredicate{
Label: labels.Everything(),
Field: fields.Everything(),
GetAttrs: func(obj runtime.Object) (label labels.Set, field fields.Set, err error) {
return nil, nil, nil
},
}
}
func TestStoreList(t *testing.T) {
podA := &api.Pod{
ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "bar"},
Spec: api.PodSpec{NodeName: "machine"},
}
podB := &api.Pod{
ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "foo"},
Spec: api.PodSpec{NodeName: "machine"},
}
testContext := api.WithNamespace(api.NewContext(), "test")
noNamespaceContext := api.NewContext()
table := map[string]struct {
in *api.PodList
m storage.SelectionPredicate
out runtime.Object
context api.Context
}{
"notFound": {
in: nil,
m: matchEverything(),
out: &api.PodList{Items: []api.Pod{}},
},
"normal": {
in: &api.PodList{Items: []api.Pod{*podA, *podB}},
m: matchEverything(),
out: &api.PodList{Items: []api.Pod{*podA, *podB}},
},
"normalFiltered": {
in: &api.PodList{Items: []api.Pod{*podA, *podB}},
m: matchPodName("foo"),
out: &api.PodList{Items: []api.Pod{*podB}},
},
"normalFilteredNoNamespace": {
in: &api.PodList{Items: []api.Pod{*podA, *podB}},
m: matchPodName("foo"),
out: &api.PodList{Items: []api.Pod{*podB}},
context: noNamespaceContext,
},
"normalFilteredMatchMultiple": {
in: &api.PodList{Items: []api.Pod{*podA, *podB}},
m: matchPodName("foo", "makeMatchSingleReturnFalse"),
out: &api.PodList{Items: []api.Pod{*podB}},
},
}
for name, item := range table {
ctx := testContext
if item.context != nil {
ctx = item.context
}
destroyFunc, registry := NewTestGenericStoreRegistry(t)
if item.in != nil {
if err := storagetesting.CreateList("/pods", registry.Storage, item.in); err != nil {
t.Errorf("Unexpected error %v", err)
}
}
list, err := registry.ListPredicate(ctx, item.m, nil)
if err != nil {
t.Errorf("Unexpected error %v", err)
continue
}
// DeepDerivative e,a is needed here b/c the storage layer sets ResourceVersion
if e, a := item.out, list; !api.Semantic.DeepDerivative(e, a) {
t.Errorf("%v: Expected %#v, got %#v", name, e, a)
}
destroyFunc()
}
}
// TestStoreListResourceVersion tests that if List with ResourceVersion > 0, it will wait until
// the results are as fresh as given version.
func TestStoreListResourceVersion(t *testing.T) {
fooPod := &api.Pod{
ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "foo"},
Spec: api.PodSpec{NodeName: "machine"},
}
barPod := &api.Pod{
ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "bar"},
Spec: api.PodSpec{NodeName: "machine"},
}
ctx := api.WithNamespace(api.NewContext(), "test")
destroyFunc, registry := newTestGenericStoreRegistry(t, true)
defer destroyFunc()
obj, err := registry.Create(ctx, fooPod)
if err != nil {
t.Fatal(err)
}
versioner := etcdstorage.APIObjectVersioner{}
rev, err := versioner.ObjectResourceVersion(obj)
if err != nil {
t.Fatal(err)
}
waitListCh := make(chan runtime.Object, 1)
go func(listRev uint64) {
option := &api.ListOptions{ResourceVersion: strconv.FormatUint(listRev, 10)}
// It will wait until we create the second pod.
l, err := registry.List(ctx, option)
if err != nil {
close(waitListCh)
t.Fatal(err)
return
}
waitListCh <- l
}(rev + 1)
select {
case <-time.After(500 * time.Millisecond):
case l := <-waitListCh:
t.Fatalf("expected waiting, but get %#v", l)
}
if _, err := registry.Create(ctx, barPod); err != nil {
t.Fatal(err)
}
select {
case <-time.After(wait.ForeverTestTimeout):
t.Fatalf("timeout after %v", wait.ForeverTestTimeout)
case l, ok := <-waitListCh:
if !ok {
return
}
pl := l.(*api.PodList).Items
if len(pl) != 2 {
t.Errorf("Expected get 2 items, but got %d", len(pl))
}
}
}
func TestStoreCreate(t *testing.T) {
gracefulPeriod := int64(50)
podA := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test"},
Spec: api.PodSpec{NodeName: "machine"},
}
podB := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test"},
Spec: api.PodSpec{NodeName: "machine2"},
}
testContext := api.WithNamespace(api.NewContext(), "test")
destroyFunc, registry := NewTestGenericStoreRegistry(t)
defer destroyFunc()
// re-define delete strategy to have graceful delete capability
registry.DeleteStrategy = pod.Strategy
// create the object
objA, err := registry.Create(testContext, podA)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// get the object
checkobj, err := registry.Get(testContext, podA.Name)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// verify objects are equal
if e, a := objA, checkobj; !reflect.DeepEqual(e, a) {
t.Errorf("Expected %#v, got %#v", e, a)
}
// now try to create the second pod
_, err = registry.Create(testContext, podB)
if !errors.IsAlreadyExists(err) {
t.Errorf("Unexpected error: %v", err)
}
// verify graceful delete capability is defined
_, ok := registry.DeleteStrategy.(rest.RESTGracefulDeleteStrategy)
if !ok {
t.Fatalf("No graceful capability set.")
}
// now delete pod with graceful period set
delOpts := &api.DeleteOptions{GracePeriodSeconds: &gracefulPeriod}
_, err = registry.Delete(testContext, podA.Name, delOpts)
if err != nil {
t.Fatalf("Failed to delete pod gracefully. Unexpected error: %v", err)
}
// try to create before graceful deletion period is over
_, err = registry.Create(testContext, podA)
if err == nil || !errors.IsAlreadyExists(err) {
t.Fatalf("Expected 'already exists' error from storage, but got %v", err)
}
// check the 'alredy exists' msg was edited
msg := &err.(*errors.StatusError).ErrStatus.Message
if !strings.Contains(*msg, "object is being deleted:") {
t.Errorf("Unexpected error without the 'object is being deleted:' in message: %v", err)
}
}
func updateAndVerify(t *testing.T, ctx api.Context, registry *Store, pod *api.Pod) bool {
obj, _, err := registry.Update(ctx, pod.Name, rest.DefaultUpdatedObjectInfo(pod, api.Scheme))
if err != nil {
t.Errorf("Unexpected error: %v", err)
return false
}
checkObj, err := registry.Get(ctx, pod.Name)
if err != nil {
t.Errorf("Unexpected error: %v", err)
return false
}
if e, a := obj, checkObj; !reflect.DeepEqual(e, a) {
t.Errorf("Expected %#v, got %#v", e, a)
return false
}
return true
}
func TestStoreUpdate(t *testing.T) {
podA := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test"},
Spec: api.PodSpec{NodeName: "machine"},
}
podB := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test"},
Spec: api.PodSpec{NodeName: "machine2"},
}
podAWithResourceVersion := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "7"},
Spec: api.PodSpec{NodeName: "machine"},
}
testContext := api.WithNamespace(api.NewContext(), "test")
destroyFunc, registry := NewTestGenericStoreRegistry(t)
defer destroyFunc()
// Test1 try to update a non-existing node
_, _, err := registry.Update(testContext, podA.Name, rest.DefaultUpdatedObjectInfo(podA, api.Scheme))
if !errors.IsNotFound(err) {
t.Errorf("Unexpected error: %v", err)
}
// Test2 createIfNotFound and verify
registry.UpdateStrategy.(*testRESTStrategy).allowCreateOnUpdate = true
if !updateAndVerify(t, testContext, registry, podA) {
t.Errorf("Unexpected error updating podA")
}
registry.UpdateStrategy.(*testRESTStrategy).allowCreateOnUpdate = false
// Test3 outofDate
_, _, err = registry.Update(testContext, podAWithResourceVersion.Name, rest.DefaultUpdatedObjectInfo(podAWithResourceVersion, api.Scheme))
if !errors.IsConflict(err) {
t.Errorf("Unexpected error updating podAWithResourceVersion: %v", err)
}
// Test4 normal update and verify
if !updateAndVerify(t, testContext, registry, podB) {
t.Errorf("Unexpected error updating podB")
}
// Test5 unconditional update
// NOTE: The logic for unconditional updates doesn't make sense to me, and imho should be removed.
// doUnconditionalUpdate := resourceVersion == 0 && e.UpdateStrategy.AllowUnconditionalUpdate()
// ^^ That condition can *never be true due to the creation of root objects.
//
// registry.UpdateStrategy.(*testRESTStrategy).allowUnconditionalUpdate = true
// updateAndVerify(t, testContext, registry, podAWithResourceVersion)
}
func TestNoOpUpdates(t *testing.T) {
destroyFunc, registry := NewTestGenericStoreRegistry(t)
defer destroyFunc()
newPod := func() *api.Pod {
return &api.Pod{
ObjectMeta: api.ObjectMeta{
Namespace: api.NamespaceDefault,
Name: "foo",
Labels: map[string]string{"prepare_create": "true"},
},
Spec: api.PodSpec{NodeName: "machine"},
}
}
var err error
var createResult runtime.Object
if createResult, err = registry.Create(api.NewDefaultContext(), newPod()); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
createdPod, err := registry.Get(api.NewDefaultContext(), "foo")
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
var updateResult runtime.Object
p := newPod()
if updateResult, _, err = registry.Update(api.NewDefaultContext(), p.Name, rest.DefaultUpdatedObjectInfo(p, api.Scheme)); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Check whether we do not return empty result on no-op update.
if !reflect.DeepEqual(createResult, updateResult) {
t.Errorf("no-op update should return a correct value, got: %#v", updateResult)
}
updatedPod, err := registry.Get(api.NewDefaultContext(), "foo")
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
createdMeta, err := meta.Accessor(createdPod)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
updatedMeta, err := meta.Accessor(updatedPod)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if createdMeta.GetResourceVersion() != updatedMeta.GetResourceVersion() {
t.Errorf("no-op update should be ignored and not written to etcd")
}
}
// TODO: Add a test to check no-op update if we have object with ResourceVersion
// already stored in etcd. Currently there is no easy way to store object with
// ResourceVersion in etcd.
type testPodExport struct{}
func (t testPodExport) Export(ctx api.Context, obj runtime.Object, exact bool) error {
pod := obj.(*api.Pod)
if pod.Labels == nil {
pod.Labels = map[string]string{}
}
pod.Labels["exported"] = "true"
pod.Labels["exact"] = strconv.FormatBool(exact)
return nil
}
func TestStoreCustomExport(t *testing.T) {
podA := api.Pod{
ObjectMeta: api.ObjectMeta{
Namespace: "test",
Name: "foo",
Labels: map[string]string{},
},
Spec: api.PodSpec{NodeName: "machine"},
}
destroyFunc, registry := NewTestGenericStoreRegistry(t)
defer destroyFunc()
registry.ExportStrategy = testPodExport{}
testContext := api.WithNamespace(api.NewContext(), "test")
registry.UpdateStrategy.(*testRESTStrategy).allowCreateOnUpdate = true
if !updateAndVerify(t, testContext, registry, &podA) {
t.Errorf("Unexpected error updating podA")
}
obj, err := registry.Export(testContext, podA.Name, unversioned.ExportOptions{})
if err != nil {
t.Errorf("unexpected error: %v", err)
}
exportedPod := obj.(*api.Pod)
if exportedPod.Labels["exported"] != "true" {
t.Errorf("expected: exported->true, found: %s", exportedPod.Labels["exported"])
}
if exportedPod.Labels["exact"] != "false" {
t.Errorf("expected: exact->false, found: %s", exportedPod.Labels["exact"])
}
if exportedPod.Labels["prepare_create"] != "true" {
t.Errorf("expected: prepare_create->true, found: %s", exportedPod.Labels["prepare_create"])
}
delete(exportedPod.Labels, "exported")
delete(exportedPod.Labels, "exact")
delete(exportedPod.Labels, "prepare_create")
exportObjectMeta(&podA.ObjectMeta, false)
podA.Spec = exportedPod.Spec
if !reflect.DeepEqual(&podA, exportedPod) {
t.Errorf("expected:\n%v\nsaw:\n%v\n", &podA, exportedPod)
}
}
func TestStoreBasicExport(t *testing.T) {
podA := api.Pod{
ObjectMeta: api.ObjectMeta{
Namespace: "test",
Name: "foo",
Labels: map[string]string{},
},
Spec: api.PodSpec{NodeName: "machine"},
Status: api.PodStatus{HostIP: "1.2.3.4"},
}
destroyFunc, registry := NewTestGenericStoreRegistry(t)
defer destroyFunc()
testContext := api.WithNamespace(api.NewContext(), "test")
registry.UpdateStrategy.(*testRESTStrategy).allowCreateOnUpdate = true
if !updateAndVerify(t, testContext, registry, &podA) {
t.Errorf("Unexpected error updating podA")
}
obj, err := registry.Export(testContext, podA.Name, unversioned.ExportOptions{})
if err != nil {
t.Errorf("unexpected error: %v", err)
}
exportedPod := obj.(*api.Pod)
if exportedPod.Labels["prepare_create"] != "true" {
t.Errorf("expected: prepare_create->true, found: %s", exportedPod.Labels["prepare_create"])
}
delete(exportedPod.Labels, "prepare_create")
exportObjectMeta(&podA.ObjectMeta, false)
podA.Spec = exportedPod.Spec
if !reflect.DeepEqual(&podA, exportedPod) {
t.Errorf("expected:\n%v\nsaw:\n%v\n", &podA, exportedPod)
}
}
func TestStoreGet(t *testing.T) {
podA := &api.Pod{
ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "foo"},
Spec: api.PodSpec{NodeName: "machine"},
}
testContext := api.WithNamespace(api.NewContext(), "test")
destroyFunc, registry := NewTestGenericStoreRegistry(t)
defer destroyFunc()
_, err := registry.Get(testContext, podA.Name)
if !errors.IsNotFound(err) {
t.Errorf("Unexpected error: %v", err)
}
registry.UpdateStrategy.(*testRESTStrategy).allowCreateOnUpdate = true
if !updateAndVerify(t, testContext, registry, podA) {
t.Errorf("Unexpected error updating podA")
}
}
func TestStoreDelete(t *testing.T) {
podA := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo"},
Spec: api.PodSpec{NodeName: "machine"},
}
testContext := api.WithNamespace(api.NewContext(), "test")
destroyFunc, registry := NewTestGenericStoreRegistry(t)
defer destroyFunc()
// test failure condition
_, err := registry.Delete(testContext, podA.Name, nil)
if !errors.IsNotFound(err) {
t.Errorf("Unexpected error: %v", err)
}
// create pod
_, err = registry.Create(testContext, podA)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// delete object
_, err = registry.Delete(testContext, podA.Name, nil)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// try to get a item which should be deleted
_, err = registry.Get(testContext, podA.Name)
if !errors.IsNotFound(err) {
t.Errorf("Unexpected error: %v", err)
}
}
// TestGracefulStoreCanDeleteIfExistingGracePeriodZero tests recovery from
// race condition where the graceful delete is unable to complete
// in prior operation, but the pod remains with deletion timestamp
// and grace period set to 0.
func TestGracefulStoreCanDeleteIfExistingGracePeriodZero(t *testing.T) {
deletionTimestamp := unversioned.NewTime(time.Now())
deletionGracePeriodSeconds := int64(0)
initialGeneration := int64(1)
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "foo",
Generation: initialGeneration,
DeletionGracePeriodSeconds: &deletionGracePeriodSeconds,
DeletionTimestamp: &deletionTimestamp,
},
Spec: api.PodSpec{NodeName: "machine"},
}
testContext := api.WithNamespace(api.NewContext(), "test")
destroyFunc, registry := NewTestGenericStoreRegistry(t)
registry.EnableGarbageCollection = false
defaultDeleteStrategy := testRESTStrategy{api.Scheme, api.SimpleNameGenerator, true, false, true}
registry.DeleteStrategy = testGracefulStrategy{defaultDeleteStrategy}
defer destroyFunc()
graceful, gracefulPending, err := rest.BeforeDelete(registry.DeleteStrategy, testContext, pod, api.NewDeleteOptions(0))
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if graceful {
t.Fatalf("graceful should be false if object has DeletionTimestamp and DeletionGracePeriodSeconds is 0")
}
if gracefulPending {
t.Fatalf("gracefulPending should be false if object has DeletionTimestamp and DeletionGracePeriodSeconds is 0")
}
}
func TestGracefulStoreHandleFinalizers(t *testing.T) {
initialGeneration := int64(1)
podWithFinalizer := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", Finalizers: []string{"foo.com/x"}, Generation: initialGeneration},
Spec: api.PodSpec{NodeName: "machine"},
}
testContext := api.WithNamespace(api.NewContext(), "test")
destroyFunc, registry := NewTestGenericStoreRegistry(t)
registry.EnableGarbageCollection = true
defaultDeleteStrategy := testRESTStrategy{api.Scheme, api.SimpleNameGenerator, true, false, true}
registry.DeleteStrategy = testGracefulStrategy{defaultDeleteStrategy}
defer destroyFunc()
// create pod
_, err := registry.Create(testContext, podWithFinalizer)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// delete the pod with grace period=0, the pod should still exist because it has a finalizer
_, err = registry.Delete(testContext, podWithFinalizer.Name, api.NewDeleteOptions(0))
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
_, err = registry.Get(testContext, podWithFinalizer.Name)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
updatedPodWithFinalizer := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", Finalizers: []string{"foo.com/x"}, ResourceVersion: podWithFinalizer.ObjectMeta.ResourceVersion},
Spec: api.PodSpec{NodeName: "machine"},
}
_, _, err = registry.Update(testContext, updatedPodWithFinalizer.ObjectMeta.Name, rest.DefaultUpdatedObjectInfo(updatedPodWithFinalizer, api.Scheme))
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// the object should still exist, because it still has a finalizer
_, err = registry.Get(testContext, podWithFinalizer.Name)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
podWithNoFinalizer := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: podWithFinalizer.ObjectMeta.ResourceVersion},
Spec: api.PodSpec{NodeName: "anothermachine"},
}
_, _, err = registry.Update(testContext, podWithFinalizer.ObjectMeta.Name, rest.DefaultUpdatedObjectInfo(podWithNoFinalizer, api.Scheme))
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// the pod should be removed, because its finalizer is removed
_, err = registry.Get(testContext, podWithFinalizer.Name)
if !errors.IsNotFound(err) {
t.Fatalf("Unexpected error: %v", err)
}
}
func TestNonGracefulStoreHandleFinalizers(t *testing.T) {
initialGeneration := int64(1)
podWithFinalizer := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", Finalizers: []string{"foo.com/x"}, Generation: initialGeneration},
Spec: api.PodSpec{NodeName: "machine"},
}
testContext := api.WithNamespace(api.NewContext(), "test")
destroyFunc, registry := NewTestGenericStoreRegistry(t)
registry.EnableGarbageCollection = true
defer destroyFunc()
// create pod
_, err := registry.Create(testContext, podWithFinalizer)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// delete object with nil delete options doesn't delete the object
_, err = registry.Delete(testContext, podWithFinalizer.Name, nil)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// the object should still exist
obj, err := registry.Get(testContext, podWithFinalizer.Name)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
podWithFinalizer, ok := obj.(*api.Pod)
if !ok {
t.Errorf("Unexpected object: %#v", obj)
}
if podWithFinalizer.ObjectMeta.DeletionTimestamp == nil {
t.Errorf("Expect the object to have DeletionTimestamp set, but got %#v", podWithFinalizer.ObjectMeta)
}
if podWithFinalizer.ObjectMeta.DeletionGracePeriodSeconds == nil || *podWithFinalizer.ObjectMeta.DeletionGracePeriodSeconds != 0 {
t.Errorf("Expect the object to have 0 DeletionGracePeriodSecond, but got %#v", podWithFinalizer.ObjectMeta)
}
if podWithFinalizer.Generation <= initialGeneration {
t.Errorf("Deletion didn't increase Generation.")
}
updatedPodWithFinalizer := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", Finalizers: []string{"foo.com/x"}, ResourceVersion: podWithFinalizer.ObjectMeta.ResourceVersion},
Spec: api.PodSpec{NodeName: "machine"},
}
_, _, err = registry.Update(testContext, updatedPodWithFinalizer.ObjectMeta.Name, rest.DefaultUpdatedObjectInfo(updatedPodWithFinalizer, api.Scheme))
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// the object should still exist, because it still has a finalizer
obj, err = registry.Get(testContext, podWithFinalizer.Name)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
podWithFinalizer, ok = obj.(*api.Pod)
if !ok {
t.Errorf("Unexpected object: %#v", obj)
}
podWithNoFinalizer := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: podWithFinalizer.ObjectMeta.ResourceVersion},
Spec: api.PodSpec{NodeName: "anothermachine"},
}
_, _, err = registry.Update(testContext, podWithFinalizer.ObjectMeta.Name, rest.DefaultUpdatedObjectInfo(podWithNoFinalizer, api.Scheme))
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// the pod should be removed, because its finalizer is removed
_, err = registry.Get(testContext, podWithFinalizer.Name)
if !errors.IsNotFound(err) {
t.Errorf("Unexpected error: %v", err)
}
}
func TestStoreDeleteWithOrphanDependents(t *testing.T) {
initialGeneration := int64(1)
podWithOrphanFinalizer := func(name string) *api.Pod {
return &api.Pod{
ObjectMeta: api.ObjectMeta{Name: name, Finalizers: []string{"foo.com/x", api.FinalizerOrphan, "bar.com/y"}, Generation: initialGeneration},
Spec: api.PodSpec{NodeName: "machine"},
}
}
podWithOtherFinalizers := func(name string) *api.Pod {
return &api.Pod{
ObjectMeta: api.ObjectMeta{Name: name, Finalizers: []string{"foo.com/x", "bar.com/y"}, Generation: initialGeneration},
Spec: api.PodSpec{NodeName: "machine"},
}
}
podWithNoFinalizer := func(name string) *api.Pod {
return &api.Pod{
ObjectMeta: api.ObjectMeta{Name: name, Generation: initialGeneration},
Spec: api.PodSpec{NodeName: "machine"},
}
}
podWithOnlyOrphanFinalizer := func(name string) *api.Pod {
return &api.Pod{
ObjectMeta: api.ObjectMeta{Name: name, Finalizers: []string{api.FinalizerOrphan}, Generation: initialGeneration},
Spec: api.PodSpec{NodeName: "machine"},
}
}
trueVar, falseVar := true, false
orphanOptions := &api.DeleteOptions{OrphanDependents: &trueVar}
nonOrphanOptions := &api.DeleteOptions{OrphanDependents: &falseVar}
nilOrphanOptions := &api.DeleteOptions{}
// defaultDeleteStrategy doesn't implement rest.GarbageCollectionDeleteStrategy.
defaultDeleteStrategy := &testRESTStrategy{api.Scheme, api.SimpleNameGenerator, true, false, true}
// orphanDeleteStrategy indicates the default garbage collection policy is
// to orphan dependentes.
orphanDeleteStrategy := &testOrphanDeleteStrategy{defaultDeleteStrategy}
testcases := []struct {
pod *api.Pod
options *api.DeleteOptions
strategy rest.RESTDeleteStrategy
expectNotFound bool
updatedFinalizers []string
}{
// cases run with DeleteOptions.OrphanDedependents=true
{
podWithOrphanFinalizer("pod1"),
orphanOptions,
defaultDeleteStrategy,
false,
[]string{"foo.com/x", api.FinalizerOrphan, "bar.com/y"},
},
{
podWithOtherFinalizers("pod2"),
orphanOptions,
defaultDeleteStrategy,
false,
[]string{"foo.com/x", "bar.com/y", api.FinalizerOrphan},
},
{
podWithNoFinalizer("pod3"),
orphanOptions,
defaultDeleteStrategy,
false,
[]string{api.FinalizerOrphan},
},
{
podWithOnlyOrphanFinalizer("pod4"),
orphanOptions,
defaultDeleteStrategy,
false,
[]string{api.FinalizerOrphan},
},
// cases run with DeleteOptions.OrphanDedependents=false
// these cases all have oprhanDeleteStrategy, which should be ignored
// because DeleteOptions has the highest priority.
{
podWithOrphanFinalizer("pod5"),
nonOrphanOptions,
orphanDeleteStrategy,
false,
[]string{"foo.com/x", "bar.com/y"},
},
{
podWithOtherFinalizers("pod6"),
nonOrphanOptions,
orphanDeleteStrategy,
false,
[]string{"foo.com/x", "bar.com/y"},
},
{
podWithNoFinalizer("pod7"),
nonOrphanOptions,
orphanDeleteStrategy,
true,
[]string{},
},
{
podWithOnlyOrphanFinalizer("pod8"),
nonOrphanOptions,
orphanDeleteStrategy,
true,
[]string{},
},
// cases run with nil DeleteOptions.OrphanDependents. If the object
// already has the orphan finalizer, then the DeleteStrategy should be
// ignored. Otherwise the DeleteStrategy decides whether to add the
// orphan finalizer.
{
podWithOrphanFinalizer("pod9"),
nilOrphanOptions,
defaultDeleteStrategy,
false,
[]string{"foo.com/x", api.FinalizerOrphan, "bar.com/y"},
},
{
podWithOrphanFinalizer("pod10"),
nilOrphanOptions,
orphanDeleteStrategy,
false,
[]string{"foo.com/x", api.FinalizerOrphan, "bar.com/y"},
},
{
podWithOtherFinalizers("pod11"),
nilOrphanOptions,
defaultDeleteStrategy,
false,
[]string{"foo.com/x", "bar.com/y"},
},
{
podWithOtherFinalizers("pod12"),
nilOrphanOptions,
orphanDeleteStrategy,
false,
[]string{"foo.com/x", "bar.com/y", api.FinalizerOrphan},
},
{
podWithNoFinalizer("pod13"),
nilOrphanOptions,
defaultDeleteStrategy,
true,
[]string{},
},
{
podWithNoFinalizer("pod14"),
nilOrphanOptions,
orphanDeleteStrategy,
false,
[]string{api.FinalizerOrphan},
},
{
podWithOnlyOrphanFinalizer("pod15"),
nilOrphanOptions,
defaultDeleteStrategy,
false,
[]string{api.FinalizerOrphan},
},
{
podWithOnlyOrphanFinalizer("pod16"),
nilOrphanOptions,
orphanDeleteStrategy,
false,
[]string{api.FinalizerOrphan},
},
// cases run with nil DeleteOptions should have exact same behavior.
// They should be exactly the same as above cases where
// DeleteOptions.OrphanDependents is nil.
{
podWithOrphanFinalizer("pod17"),
nil,
defaultDeleteStrategy,
false,
[]string{"foo.com/x", api.FinalizerOrphan, "bar.com/y"},
},
{
podWithOrphanFinalizer("pod18"),
nil,
orphanDeleteStrategy,
false,
[]string{"foo.com/x", api.FinalizerOrphan, "bar.com/y"},
},
{
podWithOtherFinalizers("pod19"),
nil,
defaultDeleteStrategy,
false,
[]string{"foo.com/x", "bar.com/y"},
},
{
podWithOtherFinalizers("pod20"),
nil,
orphanDeleteStrategy,
false,
[]string{"foo.com/x", "bar.com/y", api.FinalizerOrphan},
},
{
podWithNoFinalizer("pod21"),
nil,
defaultDeleteStrategy,
true,
[]string{},
},
{
podWithNoFinalizer("pod22"),
nil,
orphanDeleteStrategy,
false,
[]string{api.FinalizerOrphan},
},