This repository has been archived by the owner on Aug 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
client.go
493 lines (419 loc) · 14.1 KB
/
client.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
/*
Copyright 2019 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
*/
package testing
import (
"context"
"fmt"
"time"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
clientgotesting "k8s.io/client-go/testing"
ref "k8s.io/client-go/tools/reference"
"sigs.k8s.io/controller-runtime/pkg/client"
)
type clientWrapper struct {
client client.Client
CreateActions []objectAction
UpdateActions []objectAction
PatchActions []PatchAction
DeleteActions []DeleteAction
DeleteCollectionActions []DeleteCollectionAction
StatusUpdateActions []objectAction
StatusPatchActions []PatchAction
genCount int
reactionChain []Reactor
}
var _ client.Client = &clientWrapper{}
func NewFakeClientWrapper(client client.Client) *clientWrapper {
c := &clientWrapper{
client: client,
CreateActions: []objectAction{},
UpdateActions: []objectAction{},
PatchActions: []PatchAction{},
DeleteActions: []DeleteAction{},
DeleteCollectionActions: []DeleteCollectionAction{},
StatusUpdateActions: []objectAction{},
StatusPatchActions: []PatchAction{},
genCount: 0,
reactionChain: []Reactor{},
}
// generate names on create
c.AddReactor("create", "*", func(action Action) (bool, runtime.Object, error) {
if createAction, ok := action.(CreateAction); ok && action.GetSubresource() == "" {
obj := createAction.GetObject()
if objmeta, ok := obj.(metav1.Object); ok {
if objmeta.GetName() == "" && objmeta.GetGenerateName() != "" {
c.genCount++
// mutate the existing obj
objmeta.SetName(fmt.Sprintf("%s%03d", objmeta.GetGenerateName(), c.genCount))
}
}
}
// never handle the action
return false, nil, nil
})
return c
}
func prepareObjects(objs []client.Object) []client.Object {
o := make([]client.Object, len(objs))
for i := range objs {
obj := objs[i].DeepCopyObject().(client.Object)
// default to a non-zero creation timestamp
if obj.GetCreationTimestamp().Time.IsZero() {
obj.SetCreationTimestamp(metav1.NewTime(time.UnixMilli(1000)))
}
o[i] = obj
}
return o
}
func (w *clientWrapper) AddReactor(verb, kind string, reaction ReactionFunc) {
w.reactionChain = append(w.reactionChain, &clientgotesting.SimpleReactor{Verb: verb, Resource: kind, Reaction: reaction})
}
func (w *clientWrapper) PrependReactor(verb, kind string, reaction ReactionFunc) {
w.reactionChain = append([]Reactor{&clientgotesting.SimpleReactor{Verb: verb, Resource: kind, Reaction: reaction}}, w.reactionChain...)
}
func (w *clientWrapper) objmeta(obj runtime.Object) (schema.GroupVersionResource, string, string, error) {
objref, err := ref.GetReference(w.Scheme(), obj)
if err != nil {
return schema.GroupVersionResource{}, "", "", err
}
// NOTE kind != resource, but for this purpose it's good enough
gvr := schema.FromAPIVersionAndKind(objref.APIVersion, objref.Kind).GroupVersion().WithResource(objref.Kind)
return gvr, objref.Namespace, objref.Name, nil
}
func (w *clientWrapper) react(action Action) error {
for _, reactor := range w.reactionChain {
if !reactor.Handles(action) {
continue
}
handled, _, err := reactor.React(action)
if !handled {
continue
}
return err
}
return nil
}
func (w *clientWrapper) Scheme() *runtime.Scheme {
return w.client.Scheme()
}
func (w *clientWrapper) RESTMapper() meta.RESTMapper {
return w.client.RESTMapper()
}
func (w *clientWrapper) GroupVersionKindFor(obj runtime.Object) (schema.GroupVersionKind, error) {
return w.client.GroupVersionKindFor(obj)
}
func (w *clientWrapper) IsObjectNamespaced(obj runtime.Object) (bool, error) {
return w.client.IsObjectNamespaced(obj)
}
func (w *clientWrapper) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
gvr, namespace, name, err := w.objmeta(obj)
if err != nil {
return err
}
// call reactor chain
err = w.react(clientgotesting.NewGetAction(gvr, namespace, name))
if err != nil {
return err
}
return w.client.Get(ctx, key, obj, opts...)
}
func (w *clientWrapper) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {
gvr, _, _, err := w.objmeta(list)
if err != nil {
return err
}
gvk := schema.GroupVersionKind{
Group: gvr.Group,
Version: gvr.Version,
Kind: gvr.Resource,
}
listopts := &client.ListOptions{}
for _, opt := range opts {
opt.ApplyToList(listopts)
}
// call reactor chain
err = w.react(clientgotesting.NewListAction(gvr, gvk, listopts.Namespace, metav1.ListOptions{}))
if err != nil {
return err
}
return w.client.List(ctx, list, opts...)
}
func (w *clientWrapper) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error {
gvr, namespace, _, err := w.objmeta(obj)
if err != nil {
return err
}
// capture action
w.CreateActions = append(w.CreateActions, clientgotesting.NewCreateAction(gvr, namespace, obj.DeepCopyObject()))
// call reactor chain
err = w.react(clientgotesting.NewCreateAction(gvr, namespace, obj))
if err != nil {
return err
}
return w.client.Create(ctx, obj, opts...)
}
func (w *clientWrapper) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error {
gvr, namespace, name, err := w.objmeta(obj)
if err != nil {
return err
}
// capture action
w.DeleteActions = append(w.DeleteActions, clientgotesting.NewDeleteAction(gvr, namespace, name))
// call reactor chain
err = w.react(clientgotesting.NewDeleteAction(gvr, namespace, name))
if err != nil {
return err
}
return w.client.Delete(ctx, obj, opts...)
}
func (w *clientWrapper) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error {
gvr, namespace, _, err := w.objmeta(obj)
if err != nil {
return err
}
// capture action
w.UpdateActions = append(w.UpdateActions, clientgotesting.NewUpdateAction(gvr, namespace, obj.DeepCopyObject()))
// call reactor chain
err = w.react(clientgotesting.NewUpdateAction(gvr, namespace, obj))
if err != nil {
return err
}
return w.client.Update(ctx, obj, opts...)
}
func (w *clientWrapper) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error {
gvr, _, _, err := w.objmeta(obj)
if err != nil {
return err
}
b, err := patch.Data(obj)
if err != nil {
return err
}
// capture action
w.PatchActions = append(w.PatchActions, clientgotesting.NewPatchAction(gvr, obj.GetNamespace(), obj.GetName(), patch.Type(), b))
// call reactor chain
err = w.react(clientgotesting.NewPatchAction(gvr, obj.GetNamespace(), obj.GetName(), patch.Type(), b))
if err != nil {
return err
}
return w.client.Patch(ctx, obj, patch, opts...)
}
func (w *clientWrapper) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error {
gvr, _, _, err := w.objmeta(obj)
if err != nil {
return err
}
deleteopts := &client.DeleteAllOfOptions{}
for _, opt := range opts {
opt.ApplyToDeleteAllOf(deleteopts)
}
labels := ""
if s := deleteopts.LabelSelector; s != nil && !s.Empty() {
labels = s.String()
}
fields := ""
if s := deleteopts.FieldSelector; s != nil && !s.Empty() {
fields = s.String()
}
// capture action
w.DeleteCollectionActions = append(w.DeleteCollectionActions, clientgotesting.NewDeleteCollectionAction(gvr, deleteopts.Namespace, metav1.ListOptions{
LabelSelector: labels,
FieldSelector: fields,
}))
// call reactor chain
err = w.react(clientgotesting.NewDeleteCollectionAction(gvr, deleteopts.Namespace, metav1.ListOptions{
LabelSelector: labels,
FieldSelector: fields,
}))
if err != nil {
return err
}
return w.client.DeleteAllOf(ctx, obj, opts...)
}
func (w *clientWrapper) Status() client.StatusWriter {
return &statusWriterWrapper{
statusWriter: w.client.Status(),
clientWrapper: w,
}
}
func (w *clientWrapper) SubResource(subResource string) client.SubResourceClient {
return &subResourceClientWrapper{
subResource: subResource,
clientWrapper: w,
}
}
type statusWriterWrapper struct {
statusWriter client.StatusWriter
clientWrapper *clientWrapper
}
var _ client.StatusWriter = &statusWriterWrapper{}
func (w *statusWriterWrapper) Create(ctx context.Context, obj client.Object, subResource client.Object, opts ...client.SubResourceCreateOption) error {
gvr, namespace, name, err := w.clientWrapper.objmeta(obj)
if err != nil {
return err
}
// call reactor chain
return w.clientWrapper.react(clientgotesting.NewCreateSubresourceAction(gvr, name, "status", namespace, subResource))
}
func (w *statusWriterWrapper) Update(ctx context.Context, obj client.Object, opts ...client.SubResourceUpdateOption) error {
gvr, namespace, _, err := w.clientWrapper.objmeta(obj)
if err != nil {
return err
}
// capture action
w.clientWrapper.StatusUpdateActions = append(w.clientWrapper.StatusUpdateActions, clientgotesting.NewUpdateSubresourceAction(gvr, "status", namespace, obj.DeepCopyObject()))
// call reactor chain
err = w.clientWrapper.react(clientgotesting.NewUpdateSubresourceAction(gvr, "status", namespace, obj))
if err != nil {
return err
}
return w.statusWriter.Update(ctx, obj, opts...)
}
func (w *statusWriterWrapper) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.SubResourcePatchOption) error {
gvr, _, _, err := w.clientWrapper.objmeta(obj)
if err != nil {
return err
}
b, err := patch.Data(obj)
if err != nil {
return err
}
// capture action
w.clientWrapper.StatusPatchActions = append(w.clientWrapper.StatusPatchActions, clientgotesting.NewPatchSubresourceAction(gvr, obj.GetNamespace(), obj.GetName(), patch.Type(), b, "status"))
// call reactor chain
err = w.clientWrapper.react(clientgotesting.NewPatchSubresourceAction(gvr, obj.GetNamespace(), obj.GetName(), patch.Type(), b, "status"))
if err != nil {
return err
}
return w.statusWriter.Patch(ctx, obj, patch, opts...)
}
type subResourceClientWrapper struct {
subResource string
clientWrapper *clientWrapper
}
var _ client.SubResourceClient = &subResourceClientWrapper{}
func (w *subResourceClientWrapper) Get(ctx context.Context, obj client.Object, subResource client.Object, opts ...client.SubResourceGetOption) error {
gvr, namespace, name, err := w.clientWrapper.objmeta(obj)
if err != nil {
return err
}
// call reactor chain
return w.clientWrapper.react(clientgotesting.NewGetSubresourceAction(gvr, namespace, w.subResource, name))
}
func (w *subResourceClientWrapper) Create(ctx context.Context, obj client.Object, subResource client.Object, opts ...client.SubResourceCreateOption) error {
if w.subResource == "status" {
return w.clientWrapper.Status().Create(ctx, obj, subResource, opts...)
}
gvr, namespace, name, err := w.clientWrapper.objmeta(obj)
if err != nil {
return err
}
// call reactor chain
return w.clientWrapper.react(clientgotesting.NewCreateSubresourceAction(gvr, name, w.subResource, namespace, subResource))
}
func (w *subResourceClientWrapper) Update(ctx context.Context, obj client.Object, opts ...client.SubResourceUpdateOption) error {
if w.subResource == "status" {
return w.clientWrapper.Status().Update(ctx, obj, opts...)
}
gvr, namespace, _, err := w.clientWrapper.objmeta(obj)
if err != nil {
return err
}
// call reactor chain
return w.clientWrapper.react(clientgotesting.NewUpdateSubresourceAction(gvr, w.subResource, namespace, obj))
}
func (w *subResourceClientWrapper) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.SubResourcePatchOption) error {
if w.subResource == "status" {
return w.clientWrapper.Status().Patch(ctx, obj, patch, opts...)
}
gvr, _, _, err := w.clientWrapper.objmeta(obj)
if err != nil {
return err
}
b, err := patch.Data(obj)
if err != nil {
return err
}
// call reactor chain
return w.clientWrapper.react(clientgotesting.NewPatchSubresourceAction(gvr, obj.GetNamespace(), obj.GetName(), patch.Type(), b, w.subResource))
}
// InduceFailure is used in conjunction with reconciler test's WithReactors field.
// Tests that want to induce a failure in a testcase of a reconciler test would add:
//
// WithReactors: []rtesting.ReactionFunc{
// // Makes calls to create stream return an error.
// rtesting.InduceFailure("create", "Stream"),
// },
func InduceFailure(verb, kind string, o ...InduceFailureOpts) ReactionFunc {
var opts *InduceFailureOpts
switch len(o) {
case 0:
opts = &InduceFailureOpts{}
case 1:
opts = &o[0]
default:
panic(fmt.Errorf("expected exactly zero or one InduceFailureOpts, got %v", o))
}
return func(action Action) (handled bool, ret runtime.Object, err error) {
if !action.Matches(verb, kind) {
return false, nil, nil
}
if opts.Namespace != "" && opts.Namespace != action.GetNamespace() {
return false, nil, nil
}
if opts.Name != "" {
switch a := action.(type) {
case namedAction: // matches GetAction, PatchAction, DeleteAction
if opts.Name != a.GetName() {
return false, nil, nil
}
case objectAction: // matches CreateAction, UpdateAction
obj, ok := a.GetObject().(client.Object)
if ok && opts.Name != obj.GetName() {
return false, nil, nil
}
}
}
if opts.SubResource != "" && opts.SubResource != action.GetSubresource() {
return false, nil, nil
}
err = opts.Error
if err == nil {
err = fmt.Errorf("inducing failure for %s %s", action.GetVerb(), action.GetResource().Resource)
}
return true, nil, err
}
}
// CalledAtMostTimes error if the client is called more than the max number of times for a verb and kind
func CalledAtMostTimes(verb, kind string, maxCalls int) ReactionFunc {
callCount := 0
return func(action Action) (handled bool, ret runtime.Object, err error) {
if !action.Matches("list", "ConfigMapList") {
return false, nil, nil
}
callCount++
if callCount <= maxCalls {
return false, nil, nil
}
return true, nil, fmt.Errorf("%s %s called %d times, expected %d call(s)", verb, kind, callCount, maxCalls)
}
}
type namedAction interface {
Action
GetName() string
}
type objectAction interface {
Action
GetObject() runtime.Object
}
type InduceFailureOpts struct {
Error error
Namespace string
Name string
SubResource string
}