/
storage.go
1076 lines (965 loc) · 33.8 KB
/
storage.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 2023 Google LLC
//
// 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 fake
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"sync"
"testing"
jsonpatch "github.com/evanphx/json-patch"
"github.com/google/go-cmp/cmp/cmpopts"
"k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
utilrand "k8s.io/apimachinery/pkg/util/rand"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/klog/v2"
"kpt.dev/configsync/pkg/api/configsync"
"kpt.dev/configsync/pkg/core"
"kpt.dev/configsync/pkg/kinds"
"kpt.dev/configsync/pkg/util/log"
"sigs.k8s.io/cli-utils/pkg/testutil"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// RealNow is the default Now function used by NewClient.
func RealNow() metav1.Time {
return metav1.Now()
}
// MemoryStorage is an in-memory simulation of the Kubernetes APIServer.
//
// Many resource-agnostic features are implemented to facilitate testing
// controllers and other libraries.
// No resource-specific controller behaviors are implemented.
type MemoryStorage struct {
scheme *runtime.Scheme
watchSupervisor *WatchSupervisor
// Now is a hook to replace time.Now for testing.
// Default impl is RealNow.
Now func() metav1.Time
lock sync.RWMutex
// objects caches the stored objects in memory.
// The map is indexed by ID.
// TODO: The version stored should be the storage version according to the scheme.
objects map[core.ID]*unstructured.Unstructured
}
// NewInMemoryStorage constructs a new MemoryStorage
func NewInMemoryStorage(scheme *runtime.Scheme, watchSupervisor *WatchSupervisor) *MemoryStorage {
return &MemoryStorage{
scheme: scheme,
watchSupervisor: watchSupervisor,
Now: RealNow,
objects: make(map[core.ID]*unstructured.Unstructured),
}
}
// TestGet gets an object from storage, without validation or type conversion.
// Use for testing what exactly is in storage.
// The object is NOT a copy. Use with caution.
func (ms *MemoryStorage) TestGet(id core.ID) (*unstructured.Unstructured, bool) {
ms.lock.Lock()
defer ms.lock.Unlock()
uObj, found := ms.objects[id]
return uObj, found
}
// TestGetAll gets all objects from storage, without validation or type conversion.
// Use for testing what exactly is in storage.
// The map is a copy, but the objects are NOT copies. Use with caution.
func (ms *MemoryStorage) TestGetAll() map[core.ID]*unstructured.Unstructured {
ms.lock.Lock()
defer ms.lock.Unlock()
mapCopy := make(map[core.ID]*unstructured.Unstructured, len(ms.objects))
for id, uObj := range ms.objects {
mapCopy[id] = uObj
}
return mapCopy
}
// TestPut adds or replaces an object in storage without sending events or
// triggering garbage collection.
// Use for initializing or replacing what exactly is in storage.
func (ms *MemoryStorage) TestPut(obj client.Object) error {
ms.lock.Lock()
defer ms.lock.Unlock()
id, err := lookupObjectID(obj, ms.scheme)
if err != nil {
return err
}
_, _, err = ms.putWithoutLock(id, obj)
if err != nil {
return fmt.Errorf("failed to put object into storage: %s %s: %w", id.Kind, id.ObjectKey, err)
}
return nil
}
// TestPutAll adds or replaces multiple objects in storage without sending
// events or triggering garbage collection.
// Use for initializing or replacing what exactly is in storage.
func (ms *MemoryStorage) TestPutAll(objs ...client.Object) error {
ms.lock.Lock()
defer ms.lock.Unlock()
for _, obj := range objs {
id, err := lookupObjectID(obj, ms.scheme)
if err != nil {
return err
}
_, _, err = ms.putWithoutLock(id, obj)
if err != nil {
return fmt.Errorf("failed to put object into storage: %s %s: %w", id.Kind, id.ObjectKey, err)
}
}
return nil
}
func (ms *MemoryStorage) putWithoutLock(id core.ID, obj client.Object) (*unstructured.Unstructured, bool, error) {
cachedObj := ms.objects[id]
uObj, err := ms.prepareObject(obj)
if err != nil {
return cachedObj, false, err
}
if cachedObj != nil {
// If nothing but the generation and/or resourceVersion changed, skip the put
newGen := uObj.GetGeneration()
uObj.SetGeneration(cachedObj.GetGeneration())
newRV := uObj.GetResourceVersion()
uObj.SetResourceVersion(cachedObj.GetResourceVersion())
if equality.Semantic.DeepEqual(cachedObj, uObj) {
klog.V(5).Infof("MemoryStorage.Put (%s): No Diff", id)
return cachedObj, false, nil
}
uObj.SetGeneration(newGen)
uObj.SetResourceVersion(newRV)
}
klog.V(5).Infof("MemoryStorage.Put (%s): Diff (- Old, + New):\n%s",
id, log.AsYAMLDiffWithScheme(cachedObj, uObj, ms.scheme))
ms.objects[id] = uObj
return uObj, true, nil
}
// prepareObject converts the object to the scheme-preferred version, converts
// to unstructured, and removes all nil fields recursively.
func (ms *MemoryStorage) prepareObject(obj client.Object) (*unstructured.Unstructured, error) {
storageGVK, err := ms.storageGVK(obj)
if err != nil {
return nil, err
}
// Convert to typed with the scheme-preferred version
tObj, err := kinds.ToTypedWithVersion(obj, storageGVK, ms.scheme)
if err != nil {
return nil, fmt.Errorf("failed to convert to scheme-preferred version: %w", err)
}
cObj, err := kinds.ObjectAsClientObject(tObj)
if err != nil {
return nil, err
}
// Set defaults (must be passed a typed object registered with the scheme)
ms.scheme.Default(cObj)
// Convert to Unstructured
uObj, err := kinds.ToUnstructured(cObj, ms.scheme)
if err != nil {
return nil, err
}
return uObj, nil
}
// storageGVK returns the preferred GVK for storage, according to the scheme.
// Note: This may not match upstream Kubernetes, because k8s.io/api does not
// include all conversion code or all internal versions.
// As long as this is consistent, and not lossy, it should be fine for testing.
func (ms *MemoryStorage) storageGVK(obj client.Object) (schema.GroupVersionKind, error) {
gvk, err := kinds.Lookup(obj, ms.scheme)
if err != nil {
return schema.GroupVersionKind{}, err
}
// Store as highest-priority version with the kind registered
for _, gv := range ms.scheme.PrioritizedVersionsForGroup(gvk.Group) {
priorityGVK := gv.WithKind(gvk.Kind)
if ms.scheme.Recognizes(gv.WithKind(gvk.Kind)) {
return priorityGVK, nil
}
}
// Kind not found in any of the prioritized versions for this group.
// Probably means SetVersionPriority wasn't called with this GVK.
// This is true for most groups with only one version.
return gvk, nil
}
// sendPutEvent sends added/modified events and triggers (foreground) garbage collection.
func (ms *MemoryStorage) sendPutEvent(ctx context.Context, id core.ID, eventType watch.EventType) error {
if eventType != watch.Added && eventType != watch.Modified {
return fmt.Errorf("sendPutEvent: invalid EventType: %v", eventType)
}
uObj := ms.objects[id]
// Send event to watchers
// TODO: send the event asynchronously, even if the caller cancelled the context.
ms.watchSupervisor.Send(ctx, id.GroupKind, watch.Event{
Type: eventType,
Object: uObj,
})
// TODO: support background garbage collection & orphan
// Simulate apiserver garbage collection
if uObj.GetDeletionTimestamp() != nil && len(uObj.GetFinalizers()) == 0 {
klog.V(5).Infof("Found deleteTimestamp and 0 finalizers: Deleting %s (ResourceVersion: %q)",
kinds.ObjectSummary(uObj), uObj.GetResourceVersion())
err := ms.deleteWithoutLock(ctx, uObj, nil)
if err != nil {
return err
}
}
return nil
}
func (ms *MemoryStorage) listObjects(gk schema.GroupKind) []*unstructured.Unstructured {
var result []*unstructured.Unstructured
for _, o := range ms.objects {
if o.GetObjectKind().GroupVersionKind().GroupKind() != gk {
continue
}
result = append(result, o)
}
return result
}
// Get an object from storage
func (ms *MemoryStorage) Get(_ context.Context, gvk schema.GroupVersionKind, key client.ObjectKey, obj client.Object, opts *client.GetOptions) error {
ms.lock.RLock()
defer ms.lock.RUnlock()
err := ms.validateGetOptions(opts)
if err != nil {
return err
}
id := core.ID{
GroupKind: gvk.GroupKind(),
ObjectKey: key,
}
cachedObj, ok := ms.objects[id]
if !ok {
return newNotFound(id)
}
klog.V(6).Infof("Getting(cached) %s (Generation: %v, ResourceVersion: %q): %s",
kinds.ObjectSummary(cachedObj),
cachedObj.GetGeneration(), cachedObj.GetResourceVersion(),
log.AsJSON(cachedObj))
// Convert to a typed object, optionally convert between versions
tObj, err := kinds.ToTypedWithVersion(cachedObj, gvk, ms.scheme)
if err != nil {
return err
}
// Convert from the typed object to whatever type the caller asked for.
// If it's the same, it'll just do a DeepCopyInto.
if err = ms.scheme.Convert(tObj, obj, nil); err != nil {
return err
}
// TODO: Remove GVK from typed objects
obj.GetObjectKind().SetGroupVersionKind(gvk)
klog.V(6).Infof("Getting %s (Generation: %v, ResourceVersion: %q): %s",
kinds.ObjectSummary(obj),
obj.GetGeneration(), obj.GetResourceVersion(),
log.AsJSON(obj))
return nil
}
func (ms *MemoryStorage) validateGetOptions(opts *client.GetOptions) error {
if opts == nil {
return nil
}
if opts.Raw != nil && opts.Raw.ResourceVersion != "" {
return fmt.Errorf("fake.MemoryStorage.List: opts.Raw.ResourceVersion=%q: not yet implemented", opts.Raw.ResourceVersion)
}
return nil
}
// List all the objects in storage that match the resource type and list objects.
func (ms *MemoryStorage) List(_ context.Context, list client.ObjectList, opts *client.ListOptions) error {
ms.lock.RLock()
defer ms.lock.RUnlock()
err := ms.validateListOptions(opts)
if err != nil {
return err
}
_, isList := list.(meta.List)
if !isList {
return fmt.Errorf("called fake.MemoryStorage.List on non-List %s",
kinds.ObjectSummary(list))
}
// Populate the GVK, if not populated.
// The normal rest client populates it from the apiserver response anyway.
listGVK, err := kinds.Lookup(list, ms.scheme)
if err != nil {
return err
}
gvk := kinds.ItemGVKForListGVK(listGVK)
if gvk.Kind == listGVK.Kind {
return fmt.Errorf("fake.MemoryStorage.List called with non-List GVK %q", listGVK.String())
}
list.GetObjectKind().SetGroupVersionKind(listGVK)
// Get the List results from the cache as an UnstructuredList.
uList := &unstructured.UnstructuredList{}
uList.SetGroupVersionKind(listGVK)
// Populate the items
for _, obj := range ms.listObjects(gvk.GroupKind()) {
// Convert to a unstructured object with optional version conversion
uObj, err := kinds.ToUnstructuredWithVersion(obj, gvk, ms.scheme)
if err != nil {
return err
}
// Skip objects that don't match the ListOptions filters
ok, err := matchesListFilters(uObj, opts, ms.scheme)
if err != nil {
return err
}
if !ok {
// No match
continue
}
// TODO: Remove GVK from items of typed lists
// if _, ok := list.(*unstructured.UnstructuredList); !ok {
// delete(uObj.Object, "apiVersion")
// delete(uObj.Object, "kind")
// }
uList.Items = append(uList.Items, *uObj)
}
// Convert from the UnstructuredList to whatever type the caller asked for.
// If it's the same, it'll just do a DeepCopyInto.
err = ms.scheme.Convert(uList, list, nil)
if err != nil {
return err
}
// TODO: Remove GVK from typed objects
list.GetObjectKind().SetGroupVersionKind(listGVK)
klog.V(6).Infof("Listing %s (ResourceVersion: %q, Items: %d): %s",
kinds.ObjectSummary(list),
list.GetResourceVersion(), len(uList.Items),
log.AsJSON(list))
return nil
}
func (ms *MemoryStorage) validateListOptions(opts *client.ListOptions) error {
if opts == nil {
return nil
}
if opts.Continue != "" {
return fmt.Errorf("fake.MemoryStorage.List: opts.Continue=%q: not yet implemented", opts.Continue)
}
if opts.Limit != 0 {
// TODO: Implement limit for List & Watch calls.
// Our tests don't need it yet, but watchtools.UntilWithSync passes it,
// so just return the whole set of objects for now.
// Since we don't return a Continue token, it won't retry, and should
// just handle all the return values, even if there's more than the
// requested limit.
klog.Warningf("fake.MemoryStorage.List: opts.Limit=%d: not yet implemented (no limit)", opts.Limit)
}
return nil
}
// Create an object in storage
func (ms *MemoryStorage) Create(ctx context.Context, obj client.Object, opts *client.CreateOptions) error {
ms.lock.Lock()
defer ms.lock.Unlock()
err := ms.validateCreateOptions(opts)
if err != nil {
return err
}
// create a generated name
// See https://github.com/kubernetes/apiserver/blob/9d3d7b483aa6949b82103fc5b0f132126676c37b/pkg/storage/names/generate.go
if obj.GetName() == "" && obj.GetGenerateName() != "" {
randomString := utilrand.String(5)
obj.SetName(obj.GetGenerateName() + randomString)
}
// Convert to a typed object for storage, with GVK populated.
tObj, err := toTypedClientObject(obj, ms.scheme)
if err != nil {
return err
}
id, err := lookupObjectID(tObj, ms.scheme)
if err != nil {
return err
}
_, found := ms.objects[id]
if found {
return newAlreadyExists(id)
}
initResourceVersion(tObj)
initGeneration(tObj)
initUID(tObj)
klog.V(5).Infof("Creating %s (Generation: %v, ResourceVersion: %q)",
kinds.ObjectSummary(tObj),
tObj.GetGeneration(), tObj.GetResourceVersion())
cachedObj, diff, err := ms.putWithoutLock(id, tObj)
if err != nil {
return err
}
// Copy everything back to input object, even if no diff
if err := ms.scheme.Convert(cachedObj, obj, nil); err != nil {
return fmt.Errorf("failed to update input object: %w", err)
}
// TODO: Remove GVK from typed objects
obj.GetObjectKind().SetGroupVersionKind(cachedObj.GroupVersionKind())
if diff {
return ms.sendPutEvent(ctx, id, watch.Added)
}
return nil
}
func (ms *MemoryStorage) validateCreateOptions(opts *client.CreateOptions) error {
if opts == nil {
return nil
}
if len(opts.DryRun) > 0 {
if len(opts.DryRun) > 1 || opts.DryRun[0] != metav1.DryRunAll {
return fmt.Errorf("invalid dry run option: %+v", opts.DryRun)
}
}
if opts.FieldManager != "" && opts.FieldManager != configsync.FieldManager {
return fmt.Errorf("invalid field manager option: %v", opts.FieldManager)
}
return nil
}
// Delete an object in storage
func (ms *MemoryStorage) Delete(ctx context.Context, obj client.Object, opts *client.DeleteOptions) error {
ms.lock.Lock()
defer ms.lock.Unlock()
return ms.deleteWithoutLock(ctx, obj, opts)
}
func (ms *MemoryStorage) deleteWithoutLock(ctx context.Context, obj client.Object, opts *client.DeleteOptions) error {
err := ms.validateDeleteOptions(opts)
if err != nil {
return err
}
id, err := lookupObjectID(obj, ms.scheme)
if err != nil {
return err
}
cachedObj, found := ms.objects[id]
if !found {
return newNotFound(id)
}
if obj.GetUID() != "" && obj.GetUID() != cachedObj.GetUID() {
return newConflictingUID(id, obj.GetResourceVersion(), cachedObj.GetResourceVersion())
}
if obj.GetResourceVersion() != "" && obj.GetResourceVersion() != cachedObj.GetResourceVersion() {
return newConflictingResourceVersion(id, obj.GetResourceVersion(), cachedObj.GetResourceVersion())
}
// Simulate apiserver delayed deletion for finalizers
if len(cachedObj.GetFinalizers()) > 0 {
if cachedObj.GetDeletionTimestamp() == nil {
klog.V(5).Infof("Found %d finalizers: Adding deleteTimestamp to %s (ResourceVersion: %q)",
len(cachedObj.GetFinalizers()), kinds.ObjectSummary(cachedObj), cachedObj.GetResourceVersion())
newObj := cachedObj.DeepCopyObject().(client.Object)
now := ms.Now()
newObj.SetDeletionTimestamp(&now)
// TODO: propagate DeleteOptions -> UpdateOptions
err := ms.updateWithoutLock(ctx, newObj, nil)
if err != nil {
return err
}
return nil
}
klog.V(5).Infof("Found %d finalizers and deleteTimestamp=%q on %s (ResourceVersion: %q): Ignoring delete request",
len(cachedObj.GetFinalizers()), cachedObj.GetDeletionTimestamp(), kinds.ObjectSummary(cachedObj), cachedObj.GetResourceVersion())
return nil
}
// Delete method in real typed client(https://github.com/kubernetes-sigs/controller-runtime/blob/v0.14.1/pkg/client/typed_client.go#L84)
// does not copy the latest values back to input object which is different from other methods.
klog.V(5).Infof("Deleting %s (Generation: %v, ResourceVersion: %q): Diff (- Old, + New):\n%s",
kinds.ObjectSummary(cachedObj),
cachedObj.GetGeneration(), cachedObj.GetResourceVersion(),
log.AsYAMLDiffWithScheme(cachedObj, nil, ms.scheme))
// Default to background deletion propagation, if unspecified
propagationPolicy := metav1.DeletePropagationBackground
if opts != nil && opts.PropagationPolicy != nil {
propagationPolicy = *opts.PropagationPolicy
}
switch propagationPolicy {
case metav1.DeletePropagationForeground:
// Delete managed objects beforehand
err = ms.deleteManagedObjectsWithoutLock(ctx, id)
if err != nil {
return err
}
delete(ms.objects, id)
// TODO: send the event asynchronously, even if the caller cancelled the context.
ms.watchSupervisor.Send(ctx, id.GroupKind, watch.Event{
Type: watch.Deleted,
Object: cachedObj,
})
case metav1.DeletePropagationBackground:
// Delete managed objects afterwards
delete(ms.objects, id)
// TODO: send the event asynchronously, even if the caller cancelled the context.
ms.watchSupervisor.Send(ctx, id.GroupKind, watch.Event{
Type: watch.Deleted,
Object: cachedObj,
})
// TODO: implement thread-safe background deletion propagation with retry & back-off.
// For now, just delete before returning. This should help catch GC concurrency errors.
err = ms.deleteManagedObjectsWithoutLock(ctx, id)
if err != nil {
return err
}
default:
return fmt.Errorf("fake.MemoryStorage.Delete: DeleteOptions.PropagationPolicy=%q: not yet implemented", *opts.PropagationPolicy)
}
return nil
}
func (ms *MemoryStorage) validateDeleteOptions(opts *client.DeleteOptions) error {
if opts == nil {
return nil
}
if opts.DryRun != nil {
return fmt.Errorf("fake.MemoryStorage.Delete: DeleteOptions.DryRun=%+v: not yet implemented",
opts.DryRun)
}
if opts.GracePeriodSeconds != nil {
return fmt.Errorf("fake.MemoryStorage.Delete: DeleteOptions.GracePeriodSeconds=%d: not yet implemented",
*opts.GracePeriodSeconds)
}
if opts.Preconditions != nil {
return fmt.Errorf("fake.MemoryStorage.Delete: DeleteOptions.Preconditions=%+v: not yet implemented",
opts.Preconditions)
}
if opts.PropagationPolicy != nil {
switch *opts.PropagationPolicy {
case metav1.DeletePropagationForeground:
case metav1.DeletePropagationBackground:
default:
return fmt.Errorf("fake.MemoryStorage.Delete: DeleteOptions.PropagationPolicy=%q: not yet implemented",
*opts.PropagationPolicy)
}
}
return nil
}
// deleteManagedObjectsWithoutLock deletes objects whose ownerRef is the specified obj.
// TODO: retry on error (probably can't actually fail)
func (ms *MemoryStorage) deleteManagedObjectsWithoutLock(ctx context.Context, parentID core.ID) error {
// find then delete, to avoid concurrent map read/write
var childObjs []*unstructured.Unstructured
for storedID, storedObj := range ms.objects {
// owned objects must be in the same namespace
if storedID.Namespace != parentID.Namespace {
continue
}
for _, parentRef := range storedObj.GetOwnerReferences() {
parentRefGVK := schema.FromAPIVersionAndKind(parentRef.APIVersion, parentRef.Kind)
if parentRef.Name != parentID.Name || parentRefGVK.GroupKind() != parentID.GroupKind {
continue
}
klog.V(5).Infof("Garbage collecting child object %s of deleted object %s",
kinds.ObjectSummary(storedObj), parentID)
childObjs = append(childObjs, storedObj)
break
}
}
if len(childObjs) == 0 {
return nil
}
policy := metav1.DeletePropagationForeground
deleteOpts := &client.DeleteOptions{PropagationPolicy: &policy}
for _, childObj := range childObjs {
// Shallow copy the object to avoid DeepCopy or modifying the cache
obj := &unstructured.Unstructured{}
obj.SetGroupVersionKind(childObj.GroupVersionKind())
obj.SetName(childObj.GetName())
obj.SetNamespace(childObj.GetNamespace())
// don't delete if the object has been replaced since lookup (unlikely due to lock)
obj.SetUID(childObj.GetUID())
// don't delete if the object has been modified since lookup (unlikely due to lock)
// TODO: when async, this could cause a conflict, which will require re-lookup to verify the owner ref hasn't been removed.
obj.SetResourceVersion(childObj.GetResourceVersion())
if err := ms.deleteWithoutLock(ctx, obj, deleteOpts); err != nil {
if apierrors.IsNotFound(err) && meta.IsNoMatchError(err) {
// Already deleted (unlikely due to lock)
break
}
return fmt.Errorf("failed to garbage collect object %s owned by deleted object %v: %w",
kinds.ObjectSummary(obj), parentID, err)
}
}
return nil
}
// Update an object in storage
func (ms *MemoryStorage) Update(ctx context.Context, obj client.Object, opts *client.UpdateOptions) error {
ms.lock.Lock()
defer ms.lock.Unlock()
return ms.updateWithoutLock(ctx, obj, opts)
}
// updateWithoutLock implements Update, but without the lock.
// This allows it to be called by Delete when finalizers are present.
func (ms *MemoryStorage) updateWithoutLock(ctx context.Context, obj client.Object, opts *client.UpdateOptions) error {
err := ms.validateUpdateOptions(opts)
if err != nil {
return err
}
// Convert to a typed object for storage, with GVK populated.
tObj, err := toTypedClientObject(obj, ms.scheme)
if err != nil {
return err
}
id, err := lookupObjectID(obj, ms.scheme)
if err != nil {
return err
}
cachedObj, found := ms.objects[id]
if !found {
return newNotFound(id)
}
oldStatus, hasStatus, err := ms.getStatusFromObject(cachedObj)
if err != nil {
return err
}
if opts != nil && len(opts.DryRun) > 0 {
// don't merge or store the result
return nil
}
if obj.GetUID() == "" {
tObj.SetUID(cachedObj.GetUID())
} else if obj.GetUID() != cachedObj.GetUID() {
return newConflictingUID(id, obj.GetResourceVersion(), cachedObj.GetResourceVersion())
}
if obj.GetResourceVersion() == "" {
tObj.SetResourceVersion(cachedObj.GetResourceVersion())
} else if obj.GetResourceVersion() != cachedObj.GetResourceVersion() {
return newConflictingResourceVersion(id, obj.GetResourceVersion(), cachedObj.GetResourceVersion())
}
if err = incrementResourceVersion(tObj); err != nil {
return fmt.Errorf("failed to increment resourceVersion: %w", err)
}
if err = ms.updateGeneration(cachedObj, tObj); err != nil {
return fmt.Errorf("failed to update generation: %w", err)
}
if hasStatus {
tObj, err = ms.updateObjectStatus(tObj, oldStatus)
if err != nil {
return err
}
}
klog.V(5).Infof("Updating %s (Generation: %v, ResourceVersion: %q)",
kinds.ObjectSummary(tObj),
tObj.GetGeneration(), tObj.GetResourceVersion())
cachedObj, diff, err := ms.putWithoutLock(id, tObj)
if err != nil {
return err
}
// Copy everything back to input object, even if no diff
if err := ms.scheme.Convert(cachedObj, obj, nil); err != nil {
return fmt.Errorf("failed to update input object: %w", err)
}
// TODO: Remove GVK from typed objects
obj.GetObjectKind().SetGroupVersionKind(cachedObj.GroupVersionKind())
if diff {
return ms.sendPutEvent(ctx, id, watch.Modified)
}
return nil
}
func (ms *MemoryStorage) validateUpdateOptions(opts *client.UpdateOptions) error {
if opts == nil {
return nil
}
if len(opts.DryRun) > 0 {
if len(opts.DryRun) > 1 || opts.DryRun[0] != metav1.DryRunAll {
return fmt.Errorf("invalid dry run option: %+v", opts.DryRun)
}
}
if opts.FieldManager != "" && opts.FieldManager != configsync.FieldManager {
return fmt.Errorf("invalid field manager option: %v", opts.FieldManager)
}
return nil
}
func (ms *MemoryStorage) getStatusFromObject(obj client.Object) (map[string]interface{}, bool, error) {
uObj, err := kinds.ToUnstructured(obj, ms.scheme)
if err != nil {
return nil, false, err
}
return unstructured.NestedMap(uObj.Object, "status")
}
func (ms *MemoryStorage) updateObjectStatus(obj client.Object, status map[string]interface{}) (client.Object, error) {
uObj, err := kinds.ToUnstructured(obj, ms.scheme)
if err != nil {
return nil, err
}
if err = unstructured.SetNestedMap(uObj.Object, status, "status"); err != nil {
return obj, err
}
return toTypedClientObject(uObj, ms.scheme)
}
// Patch an object in storage
func (ms *MemoryStorage) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts *client.PatchOptions) error {
ms.lock.Lock()
defer ms.lock.Unlock()
err := ms.validatePatchOptions(opts, patch)
if err != nil {
return err
}
gvk, err := kinds.Lookup(obj, ms.scheme)
if err != nil {
return fmt.Errorf("failed to lookup GVK from scheme: %w", err)
}
patchData, err := patch.Data(obj)
if err != nil {
return fmt.Errorf("failed to build patch: %w", err)
}
id, err := lookupObjectID(obj, ms.scheme)
if err != nil {
return err
}
cachedObj, found := ms.objects[id]
// TODO: What do we do if the patch version isn't the same as the preferred/cached version???
// Do we need to convert the stored version to the patch version? What if that's lossy?
// Is it possible to convert a patch version without patching the object first?
// Probably not...
var mergedData []byte
switch patch.Type() {
case types.ApplyPatchType:
// WARNING: If you need to test SSA with multiple managers, do it in e2e tests!
// Unfortunately, there's no good way to replicate the field-manager
// behavior of Server-Side Apply, because some of the code used by the
// apiserver is internal and can't be imported.
// So we're using Update behavior here instead, since that's effectively
// how SSA acts when there's only one field manager.
// Since we're treating the patch data as the full intent, we don't need
// to merge with the cached object, just preserve the ResourceVersion.
mergedData = patchData
case types.MergePatchType:
if found {
oldData, err := json.Marshal(cachedObj)
if err != nil {
return err
}
mergedData, err = jsonpatch.MergePatch(oldData, patchData)
if err != nil {
return err
}
} else {
mergedData = patchData
}
case types.StrategicMergePatchType:
if found {
rObj, err := kinds.NewClientObjectForGVK(gvk, ms.scheme)
if err != nil {
return err
}
oldData, err := json.Marshal(cachedObj)
if err != nil {
return err
}
mergedData, err = strategicpatch.StrategicMergePatch(oldData, patchData, rObj)
if err != nil {
return err
}
} else {
mergedData = patchData
}
case types.JSONPatchType:
patch, err := jsonpatch.DecodePatch(patchData)
if err != nil {
return err
}
oldData, err := json.Marshal(cachedObj)
if err != nil {
return err
}
mergedData, err = patch.Apply(oldData)
if err != nil {
return err
}
default:
return fmt.Errorf("fake.MemoryStorage.Patch: Patch.Type=%q: not yet implemented", patch.Type())
}
// Use a new object, instead of updating the cached object,
// because unmarshal doesn't always delete unspecified fields.
uObj := &unstructured.Unstructured{}
if err = uObj.UnmarshalJSON(mergedData); err != nil {
return fmt.Errorf("failed to unmarshal patch data: %w", err)
}
if found {
uObj.SetResourceVersion(cachedObj.GetResourceVersion())
} else {
uObj.SetResourceVersion("0") // init to allow incrementing
}
if err := incrementResourceVersion(uObj); err != nil {
return fmt.Errorf("failed to increment resourceVersion: %w", err)
}
if found {
// Copy status from cache
// TODO: copy other sub-resources too
// TODO: Add support for sub-resource patch
oldStatus, hasStatus, err := unstructured.NestedMap(cachedObj.Object, "status")
if err != nil {
return err
}
if hasStatus {
if err = unstructured.SetNestedMap(uObj.Object, oldStatus, "status"); err != nil {
return err
}
}
// Update generation if spec changed
if err = ms.updateGeneration(cachedObj, uObj); err != nil {
return fmt.Errorf("failed to update generation: %w", err)
}
} else {
uObj.SetGeneration(1)
}
klog.V(5).Infof("Patching %s (Found: %v, Generation: %v, ResourceVersion: %q)",
id, found,
uObj.GetGeneration(), uObj.GetResourceVersion())
cachedObj, diff, err := ms.putWithoutLock(id, uObj)
if err != nil {
return err
}
// Copy everything back to input object, even if no diff
if err := ms.scheme.Convert(cachedObj, obj, nil); err != nil {
return fmt.Errorf("failed to update input object:: %w", err)
}
// TODO: Remove GVK from typed objects
obj.GetObjectKind().SetGroupVersionKind(cachedObj.GroupVersionKind())
if diff {
return ms.sendPutEvent(ctx, id, watch.Modified)
}
return nil
}
func (ms *MemoryStorage) validatePatchOptions(opts *client.PatchOptions, patch client.Patch) error {
if opts == nil {
return nil
}
if len(opts.DryRun) > 0 {
if len(opts.DryRun) > 1 || opts.DryRun[0] != metav1.DryRunAll {
return fmt.Errorf("invalid dry run option: %+v", opts.DryRun)
}
}
if opts.FieldManager != "" && opts.FieldManager != configsync.FieldManager {
return fmt.Errorf("invalid field manager option: %v", opts.FieldManager)
}
if patch != client.Apply && opts.Force != nil {
return fmt.Errorf("invalid force option: Forbidden: may not be specified for non-apply patch")
}
return nil
}
func (ms *MemoryStorage) updateGeneration(oldObj, newObj client.Object) error {
uOldObj, err := ms.prepareObject(oldObj)
if err != nil {
return err
}
oldCopyContent := uOldObj.UnstructuredContent()
uNewObj, err := ms.prepareObject(newObj)
if err != nil {
return err
}
newCopyContent := uNewObj.UnstructuredContent()
// ignore metadata
delete(newCopyContent, "metadata")
delete(oldCopyContent, "metadata")
// Assume all objects have a status sub-resource, and ignore it.
// TODO: figure out how to detect if this resource has a status sub-resource.
delete(newCopyContent, "status")
delete(oldCopyContent, "status")
if !equality.Semantic.DeepEqual(newCopyContent, oldCopyContent) {
newObj.SetGeneration(oldObj.GetGeneration() + 1)
} else {
newObj.SetGeneration(oldObj.GetGeneration())
}
return nil
}
// DeleteAllOf deletes all the objects of the specified resource.
func (ms *MemoryStorage) DeleteAllOf(_ context.Context, _ client.ObjectList, _ *client.DeleteAllOfOptions) error {
// TODO: Implement DeleteAllOf, if needed
return errors.New("fake.MemoryStorage.DeleteAllOf: not yet implemented")
}
// Watch the specified objects.
// The returned watcher will stream events to the ResultChan until Stop is called.
func (ms *MemoryStorage) Watch(_ context.Context, exampleList client.ObjectList, opts *client.ListOptions) (watch.Interface, error) {
err := ms.validateListOptions(opts)
if err != nil {
return nil, err
}
listGVK, err := kinds.Lookup(exampleList, ms.scheme)
if err != nil {
return nil, fmt.Errorf("failed to lookup GVK from scheme: %w", err)
}
gvk := kinds.ItemGVKForListGVK(listGVK)
if gvk.Kind == listGVK.Kind {
return nil, fmt.Errorf("fake.MemoryStorage.Watch called with non-List GVK: %v", listGVK)
}
klog.V(6).Infof("Watching %s (Options: %+v)",
kinds.ObjectSummary(exampleList), opts)
watcher := NewWatcher(ms.watchSupervisor, gvk.GroupKind(), exampleList, opts)
// TODO: Should Client.Watch's context.Done cancel the background stream or just the initial request?
// If yes, StartWatcher needs to take a context.
// client-go's FakeDynamicClient.Watch seems to just ignore the context, so that's what we're doing here too.
watcher.Start(context.Background())
return watcher, nil
}
func initResourceVersion(obj client.Object) {