-
Notifications
You must be signed in to change notification settings - Fork 57
/
proxy.go
715 lines (629 loc) · 23.6 KB
/
proxy.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
/*
Copyright 2022 The KubeZoo 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 proxy
import (
"context"
"encoding/json"
"fmt"
"github.com/kubewharf/kubezoo/pkg/proxy/pod"
"strings"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
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/watch"
"k8s.io/apiserver/pkg/endpoints/request"
apirequest "k8s.io/apiserver/pkg/endpoints/request"
genericregistry "k8s.io/apiserver/pkg/registry/generic/registry"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/kubernetes/pkg/printers"
printersinternal "k8s.io/kubernetes/pkg/printers/internalversion"
printerstorage "k8s.io/kubernetes/pkg/printers/storage"
"github.com/kubewharf/kubezoo/pkg/common"
"github.com/kubewharf/kubezoo/pkg/dynamic"
"github.com/kubewharf/kubezoo/pkg/util"
)
// tenantProxyWithLister implements StandardStorage
var _ = rest.StandardStorage(&tenantProxyWithLister{})
// tenantProxy implements the converting between tenant object and upstream object.
type tenantProxy struct {
// refactored tenant proxy
kind schema.GroupVersionKind
convertor common.ObjectConvertor
namespaceScoped bool
resource string
subresource string
shortNames []string
isCustomResource bool
// NewFunc returns a new instance of the type this registry returns for a
// GET of a single object
newFunc func() runtime.Object
// NewListFunc returns a new list of the type this registry; it is the
// type returned when the resource is listed
newListFunc func() runtime.Object
// TableConvertor is an optional interface for transforming items or lists
// of items into tabular output. If unset, the default will be used.
tableConvertor rest.TableConvertor
// dynamic client is used to communicate with upstream cluster
dynamicClient dynamic.Interface
groupVersionKindFunc common.GroupVersionKindFunc
}
// tenantProxyWithLister is a wrapper of tenantProxy, it exposes Lister interface to enable installation of List method
// it also exposes TableConvertor interface to convert list to table
type tenantProxyWithLister struct {
tenantProxy
}
func (p *tenantProxyWithLister) NewList() runtime.Object {
return p.newList()
}
func (p *tenantProxyWithLister) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {
return p.list(ctx, options)
}
func (tp *tenantProxyWithLister) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {
if tp.tableConvertor == nil {
return nil, fmt.Errorf("tableConvertor is nil")
}
return tp.tableConvertor.ConvertToTable(ctx, object, tableOptions)
}
func (tc *tenantProxy) NamespaceScoped() bool {
return tc.namespaceScoped
}
func (tc *tenantProxy) ShortNames() []string {
return tc.shortNames
}
// NewTenantProxy returns the tenant proxy which implements the storage intefaces.
func NewTenantProxy(config common.StorageConfig) (rest.Storage, error) {
if config.IsConnecter {
return NewConnecterProxy(config.ProxyTransport, config.UpstreamMaster)
}
if (config.Resource == "pods" || config.Resource == "services" || config.Resource == "nodes") && config.Subresource == "proxy" {
return pod.NewProxyREST(config.ProxyTransport, config.UpstreamMaster)
}
if config.NewFunc == nil && config.NewListFunc == nil {
return nil, fmt.Errorf("both NewFunc and NewListFunc is nil")
}
if config.Subresource != "" && config.NewListFunc != nil {
return nil, fmt.Errorf("subresource (%s:%s) should not have list method", config.Resource, config.Subresource)
}
var tc rest.TableConvertor = printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)}
if config.TableConvertor != nil {
tc = config.TableConvertor
}
proxy := &tenantProxy{
kind: config.Kind,
namespaceScoped: config.NamespaceScoped,
isCustomResource: config.IsCustomResource,
resource: config.Resource,
subresource: config.Subresource,
shortNames: config.ShortNames,
newFunc: config.NewFunc,
newListFunc: config.NewListFunc,
dynamicClient: config.DynamicClient,
convertor: config.Convertor,
groupVersionKindFunc: config.GroupVersionKindFunc,
tableConvertor: tc,
}
if config.NewListFunc == nil {
return proxy, nil
}
return &tenantProxyWithLister{*proxy}, nil
}
// isCustomResourceDefinition checks whether the kind is a CRD or not.
func isCustomResourceDefinition(kind schema.GroupVersionKind) bool {
return kind.GroupKind() == apiextensionsv1.Kind("CustomResourceDefinition")
}
func (tp *tenantProxy) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind {
if tp.groupVersionKindFunc == nil {
return tp.kind
}
return tp.groupVersionKindFunc(containingGV)
}
// getClient returns a dynamic client.
func (tp *tenantProxy) getClient(ctx context.Context) (dynamic.ResourceInterface, error) {
tenantID, ok := util.TenantFrom(ctx)
if !ok {
return nil, fmt.Errorf("tanentID doesn't exist in context")
}
requestInfo, ok := apirequest.RequestInfoFrom(ctx)
if !ok {
return nil, fmt.Errorf("missing requestInfo")
}
var client dynamic.ResourceInterface
gv := tp.kind.GroupVersion()
if tp.isCustomResource {
gv.Group = util.AddTenantIDPrefix(tenantID, gv.Group)
}
client = tp.dynamicClient.Resource(gv.WithResource(tp.resource))
if tp.namespaceScoped && len(requestInfo.Namespace) != 0 {
namespace := util.AddTenantIDPrefix(tenantID, requestInfo.Namespace)
client = tp.dynamicClient.Resource(gv.WithResource(tp.resource)).Namespace(namespace)
}
return client, nil
}
// convertUnstructuredToOutput convert the unstructured to runtime object.
func (tp *tenantProxy) convertUnstructuredToOutput(utd *unstructured.Unstructured, output runtime.Object) error {
if o, ok := output.(*unstructured.Unstructured); ok {
o.SetUnstructuredContent(utd.UnstructuredContent())
return nil
}
kind := tp.GroupVersionKind(tp.kind.GroupVersion())
original, err := nativeScheme.New(kind)
if err != nil {
return err
}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(utd.Object, original); err != nil {
return err
}
if err := nativeScheme.Convert(original, output, context.TODO()); err != nil {
return err
}
return nil
}
// convertUnstructuredListToOutput convert a unstructured list to runtime object.
func (tp *tenantProxy) convertUnstructuredListToOutput(utdList *unstructured.UnstructuredList, output runtime.Object) error {
if o, ok := output.(*unstructured.UnstructuredList); ok {
o.SetUnstructuredContent(utdList.UnstructuredContent())
return nil
}
origin, err := nativeScheme.New(tp.kind.GroupVersion().WithKind(tp.kind.Kind + "List"))
if err != nil {
return err
}
js, err := utdList.MarshalJSON()
if err != nil {
return err
}
if err := json.Unmarshal(js, &origin); err != nil {
return err
}
if err := nativeScheme.Convert(origin, output, context.TODO()); err != nil {
return err
}
return nil
}
// Get finds a resource in the upstream cluster by name and returns it.
// Although it can return an arbitrary error value, IsNotFound(err) is true for the
// returned error value err when the specified resource is not found.
func (tp *tenantProxy) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
if tp.newFunc == nil {
return nil, fmt.Errorf("newFunc is nil")
}
tenantID, ok := util.TenantFrom(ctx)
if !ok {
return nil, fmt.Errorf("tanentID doesn't exist in context")
}
client, err := tp.getClient(ctx)
if err != nil {
return nil, err
}
var utd *unstructured.Unstructured
// todo: renjingsi, expose node to pass Conformance test
if !tp.namespaceScoped && tp.kind.Kind != "Node" {
name = util.ConvertTenantObjectNameToUpstream(name, tenantID, tp.kind)
}
if subResource := tp.subresource; subResource != "" {
utd, err = client.Get(ctx, name, *options, subResource)
} else {
utd, err = client.Get(ctx, name, *options)
}
if err != nil {
return nil, util.TrimTenantIDFromError(err, tenantID)
}
// convert unstructured object to internal for non CRD resources
output := tp.New()
if err := tp.convertUnstructuredToOutput(utd, output); err != nil {
return nil, err
}
if err := tp.convertUpstreamObjectToTenantObject(output, tenantID); err != nil {
return nil, err
}
return output, nil
}
// New returns an empty object that can be used with Update after request data has been put into it.
func (tp *tenantProxy) New() runtime.Object {
if tp.newFunc == nil {
return nil
}
return tp.newFunc()
}
// newList returns an empty object that can be used with the List call.
func (tp *tenantProxy) newList() runtime.Object {
return tp.newListFunc()
}
// Update finds a resource in the storage and updates it. Some implementations
// may allow updates creates the object - they should set the created boolean
// to true.
func (tp *tenantProxy) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo,
_ rest.ValidateObjectFunc, _ rest.ValidateObjectUpdateFunc,
forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
if tp.newFunc == nil {
return nil, false, fmt.Errorf("newFunc is nil")
}
requestInfo, ok := request.RequestInfoFrom(ctx)
if !ok {
return nil, false, fmt.Errorf("missing requestInfo")
}
if requestInfo.Verb == "patch" {
return tp.guaranteedUpdate(ctx, name, objInfo, options)
}
original, err := tp.Get(ctx, name, &metav1.GetOptions{})
if err != nil && !errors.IsNotFound(err) {
return nil, false, err
}
if errors.IsNotFound(err) && !forceAllowCreate {
return nil, false, err
}
obj, err := objInfo.UpdatedObject(ctx, original)
if err != nil {
return nil, false, err
}
return tp.update(ctx, obj, options)
}
// update convert the tenant object to upstream object before updating
// to the upstream server, and then convert the response to tenant object.
func (tp *tenantProxy) update(ctx context.Context, obj runtime.Object, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
tenantID, ok := util.TenantFrom(ctx)
if !ok {
return nil, false, fmt.Errorf("missing tenantID in context")
}
// 1. convert the internal version of tenant object to upstream object
if err := tp.convertTenantObjectToUpstreamObject(obj, tenantID); err != nil {
return nil, false, err
}
// 2. convert the internal obj to unstructured
utd, err := tp.convertInternalObjectToUnstructuredObject(obj)
if err != nil {
return nil, false, err
}
// 3. call update api
var (
got *unstructured.Unstructured
created bool
)
client, err := tp.getClient(ctx)
if err != nil {
return nil, false, err
}
if subresource := tp.subresource; subresource == "" {
got, created, err = client.Update(ctx, utd, *options)
} else if subresource == "status" {
got, err = client.UpdateStatus(ctx, utd, *options)
} else {
got, created, err = client.Update(ctx, utd, *options, subresource)
}
if err != nil {
return nil, false, util.TrimTenantIDFromError(err, tenantID)
}
// 4. convert got to output
output := tp.New()
if err := tp.convertUnstructuredToOutput(got, output); err != nil {
return nil, false, err
}
// 5. convert got to tenant
if err := tp.convertUpstreamObjectToTenantObject(output, tenantID); err != nil {
return nil, false, err
}
return output, created, nil
}
func (tp *tenantProxy) convertInternalObjectToVersionedObject(obj runtime.Object) (runtime.Object, error) {
kind := tp.GroupVersionKind(tp.kind.GroupVersion())
return runtime.UnsafeObjectConvertor(nativeScheme).ConvertToVersion(obj, kind.GroupVersion())
}
func (tp *tenantProxy) convertInternalObjectToUnstructuredObject(obj runtime.Object) (*unstructured.Unstructured, error) {
if utd, ok := obj.(*unstructured.Unstructured); ok {
// for custom resource, the internal object is already unstructured, so skip converting
return utd, nil
}
versioned, err := tp.convertInternalObjectToVersionedObject(obj)
if err != nil {
return nil, err
}
utdObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(versioned)
if err != nil {
return nil, err
}
return &unstructured.Unstructured{Object: utdObj}, nil
}
// Create creates a new version of a resource.
func (tp *tenantProxy) Create(ctx context.Context, obj runtime.Object, _ rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
if tp.newFunc == nil {
return nil, fmt.Errorf("newFunc is nil")
}
tenantID, ok := util.TenantFrom(ctx)
if !ok {
return nil, fmt.Errorf("tanentID doesn't exist in context")
}
// 1. convert the internal version of tenant object to upstream object
if err := tp.convertTenantObjectToUpstreamObject(obj, tenantID); err != nil {
return nil, err
}
// 2. convert the internal obj to unstructured
utd, err := tp.convertInternalObjectToUnstructuredObject(obj)
if err != nil {
return nil, err
}
// 3. call create api
var got *unstructured.Unstructured
client, err := tp.getClient(ctx)
if err != nil {
return nil, err
}
if subresource := tp.subresource; subresource == "" {
got, err = client.Create(ctx, utd, *options)
} else {
got, err = client.Create(ctx, utd, *options, subresource)
}
if err != nil {
return nil, util.TrimTenantIDFromError(err, tenantID)
}
// 4. convert the got(if it is not an unstructured object) to internal
output := tp.New()
if err := tp.convertUnstructuredToOutput(got, output); err != nil {
return nil, err
}
// 5. convert the internal object to tenant
if err := tp.convertUpstreamObjectToTenantObject(output, tenantID); err != nil {
return nil, err
}
return output, nil
}
// Delete convert the tenant object to upstream object before deleting
// to the upstream server, and then convert the response to tenant object.
func (tp *tenantProxy) Delete(ctx context.Context, name string, _ rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) {
if tp.newFunc == nil {
return nil, false, fmt.Errorf("newFunc is nil")
}
tenantID, ok := util.TenantFrom(ctx)
if !ok {
return nil, false, fmt.Errorf("tanentID doesn't exist in context")
}
if !tp.namespaceScoped {
name = util.ConvertTenantObjectNameToUpstream(name, tenantID, tp.kind)
}
var (
got *unstructured.Unstructured
deleted bool
err error
)
client, err := tp.getClient(ctx)
if subresource := tp.subresource; subresource == "" {
got, deleted, err = client.Delete(ctx, name, *options)
} else {
got, deleted, err = client.Delete(ctx, name, *options, subresource)
}
if err != nil {
return nil, deleted, util.TrimTenantIDFromError(err, tenantID)
}
if got.GetAPIVersion() == "v1" && got.GroupVersionKind().Kind == "Status" {
// if we get status, probably we are handling cr object
status := &metav1.Status{}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(got.Object, status); err != nil {
return nil, deleted, util.TrimTenantIDFromError(err, tenantID)
}
ret := util.TrimTenantIDFromStatus(*status, tenantID)
return &ret, deleted, nil
}
output := tp.New()
if err := tp.convertUnstructuredToOutput(got, output); err != nil {
return nil, deleted, err
}
if err := tp.convertUpstreamObjectToTenantObject(output, tenantID); err != nil {
return nil, deleted, err
}
return output, deleted, nil
}
// list convert the tenant object to upstream object before list from
// the upstream server, and then convert the response to tenant object.
func (tp *tenantProxy) list(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {
if tp.newListFunc == nil {
return nil, fmt.Errorf("newListFunc is nil")
}
tenantID, ok := util.TenantFrom(ctx)
if !ok {
return nil, fmt.Errorf("tanentID doesn't exist in context %v", ctx)
}
proxyOptions, err := util.ConvertInternalListOptions(ctx, options, tenantID)
if err != nil {
return nil, err
}
client, err := tp.getClient(ctx)
if err != nil {
return nil, err
}
utdList, err := client.List(ctx, *proxyOptions)
if err != nil {
return nil, util.TrimTenantIDFromError(err, tenantID)
}
utdList = util.FilterUnstructuredList(utdList, tenantID, tp.namespaceScoped)
// convert internal/unstructured list item one by one
for i := range utdList.Items {
// convert each item of the unstructured list to internal version for non-CRD resources
oupObj := tp.New()
if err := tp.convertUnstructuredToOutput(&utdList.Items[i], oupObj); err != nil {
return nil, err
}
// convert to tenant
if err := tp.convertUpstreamObjectToTenantObject(oupObj, tenantID); err != nil {
return nil, err
}
// convert it back to unstructured and put it back to the unstructured list
utd, err := tp.convertInternalObjectToUnstructuredObject(oupObj)
if err != nil {
return nil, err
}
utdList.Items[i] = *utd
}
if tp.isCustomResource {
utdList.SetAPIVersion(util.TrimTenantIDPrefix(tenantID, utdList.GetAPIVersion()))
}
// convert the entire unstructured list to internal version of list for non-CRD resources
oupList := tp.newList()
if err := tp.convertUnstructuredListToOutput(utdList, oupList); err != nil {
return nil, err
}
return oupList, nil
}
// DeleteCollection convert the tenant object to upstream object before listing
// from the upstream server, and then delete the item one by one according to the list.
func (tp *tenantProxy) DeleteCollection(ctx context.Context, _ rest.ValidateObjectFunc, options *metav1.DeleteOptions, listOptions *metainternalversion.ListOptions) (runtime.Object, error) {
if tp.newListFunc == nil {
return nil, fmt.Errorf("newListFunc is nil")
}
tenantID, ok := util.TenantFrom(ctx)
if !ok {
return nil, fmt.Errorf("tanentID doesn't exist in context")
}
proxyListOptions, err := util.ConvertInternalListOptions(ctx, listOptions, tenantID)
if err != nil {
return nil, err
}
client, err := tp.getClient(ctx)
if err != nil {
return nil, err
}
utdList, err := client.List(ctx, *proxyListOptions)
if err != nil {
return nil, util.TrimTenantIDFromError(err, tenantID)
}
utdList = util.FilterUnstructuredList(utdList, tenantID, tp.namespaceScoped)
for i := range utdList.Items {
name := utdList.Items[i].GetName()
_, _, err = client.Delete(ctx, name, *options)
if err != nil {
return nil, util.TrimTenantIDFromError(err, tenantID)
}
}
// convert upstream object to tenant object one at a time
for i := range utdList.Items {
// convert each item of the unstructured list to internal version for non-CRD resources
oupObj := tp.New()
if err := tp.convertUnstructuredToOutput(&utdList.Items[i], oupObj); err != nil {
return nil, err
}
// convert to tenant
if err := tp.convertUpstreamObjectToTenantObject(oupObj, tenantID); err != nil {
return nil, err
}
// convert it back to unstructured and put it back to the unstructured list
utd, err := tp.convertInternalObjectToUnstructuredObject(oupObj)
if err != nil {
return nil, err
}
utdList.Items[i] = *utd
}
//if tp.isCustomResource {
// utdList.SetAPIVersion(util.TrimTenantIDPrefix(tp.tenantID, utdList.GetAPIVersion()))
//}
// convert the entire unstructured list to internal version of list for non-CRD resources
oupList := tp.newList()
if err := tp.convertUnstructuredListToOutput(utdList, oupList); err != nil {
return nil, err
}
return oupList, nil
}
// Watch return a proxy watch if need proxy.
func (tp *tenantProxy) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) {
if tp.newListFunc == nil {
return nil, fmt.Errorf("newListFunc is nil")
}
tenantID, ok := util.TenantFrom(ctx)
if !ok {
return nil, fmt.Errorf("tanentID doesn't exist in context")
}
proxyOpt, err := util.ConvertInternalListOptions(ctx, options, tenantID)
if err != nil {
return nil, err
}
client, err := tp.getClient(ctx)
if err != nil {
return nil, err
}
w, err := client.Watch(ctx, *proxyOpt)
if err != nil {
return nil, util.TrimTenantIDFromError(err, tenantID)
}
return newProxyWatch(w, tp, tenantID)
}
// convertTenantObjectToUpstreamObject converts tenant object to upstream object.
func (tp *tenantProxy) convertTenantObjectToUpstreamObject(obj runtime.Object, tenantID string) error {
// if obj is of type unstructured, it should be custom resource, whose apiVersion is prefixed with tenant id
// (eg: 888888-stable.example.com), leave trimming of tenant id prefix to custom convertor
if _, ok := obj.(*unstructured.Unstructured); !ok {
// GVK for internal type object is always empty, set it with the right kind so that we can pick a convertor for it
obj.GetObjectKind().SetGroupVersionKind(tp.kind)
}
return tp.convertor.ConvertTenantObjectToUpstreamObject(obj, tenantID, tp.namespaceScoped)
}
// convertUpstreamObjectToTenantObject converts upstream object to tenant object.
func (tp *tenantProxy) convertUpstreamObjectToTenantObject(obj runtime.Object, tenantID string) error {
// if obj is of type unstructured, it should be custom resource, whose apiVersion is prefixed with tenant id
// (eg: 888888-stable.example.com), leave trimming of tenant id prefix to custom convertor
if _, ok := obj.(*unstructured.Unstructured); !ok {
// GVK for internal type object is always empty, set it with the right kind so that we can pick a convertor for it
obj.GetObjectKind().SetGroupVersionKind(tp.kind)
}
return tp.convertor.ConvertUpstreamObjectToTenantObject(obj, tenantID, tp.namespaceScoped)
}
// guaranteedUpdate ensures a guaranteed updating.
func (tp *tenantProxy) guaranteedUpdate(ctx context.Context, name string,
objInfo rest.UpdatedObjectInfo, options *metav1.UpdateOptions,
) (runtime.Object, bool, error) {
for {
original, err := tp.Get(ctx, name, &metav1.GetOptions{})
if err != nil && !errors.IsNotFound(err) {
return nil, false, err
}
if errors.IsNotFound(err) {
if err := runtime.SetZeroValue(original); err != nil {
return nil, false, err
}
}
if err := checkPreconditions(objInfo.Preconditions(), original); err != nil {
return nil, false, err
}
updated, err := objInfo.UpdatedObject(ctx, original)
if err != nil {
return nil, false, err
}
got, created, err := tp.update(ctx, updated, options)
if errors.IsConflict(err) && strings.Contains(err.Error(), genericregistry.OptimisticLockErrorMsg) {
// retry update on optimistic lock conflict
continue
}
if err != nil {
return nil, false, err
}
return got, created, nil
}
}
// checkPreconditions checks the precondition for guarantee updating.
func checkPreconditions(preconditions *metav1.Preconditions, obj runtime.Object) error {
if preconditions == nil {
return nil
}
objMeta, err := meta.Accessor(obj)
if err != nil {
return fmt.Errorf("can't enforce preconditions %v on un-introspectable object %v, got error: %v", *preconditions, obj, err)
}
if preconditions.UID != nil && *preconditions.UID != objMeta.GetUID() {
return fmt.Errorf("precondition failed: UID in precondition: %v, UID in object meta: %v", *preconditions.UID, objMeta.GetUID())
}
if preconditions.ResourceVersion != nil && *preconditions.ResourceVersion != objMeta.GetResourceVersion() {
return fmt.Errorf("Precondition failed: ResourceVersion in precondition: %v, ResourceVersion in object meta: %v", *preconditions.ResourceVersion, objMeta.GetResourceVersion())
}
return nil
}