-
Notifications
You must be signed in to change notification settings - Fork 40
/
synchronizer.go
743 lines (575 loc) · 21.8 KB
/
synchronizer.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
// Copyright 2019 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 kubernetes
import (
"encoding/json"
"fmt"
"reflect"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
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"
jsonpatch "k8s.io/apimachinery/pkg/util/jsonmergepatch"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/dynamic/dynamicinformer"
"k8s.io/client-go/rest"
"k8s.io/klog"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
dplv1alpha1 "github.com/open-cluster-management/multicloud-operators-deployable/pkg/apis/apps/v1"
appv1alpha1 "github.com/open-cluster-management/multicloud-operators-subscription/pkg/apis/apps/v1"
"github.com/open-cluster-management/multicloud-operators-subscription/pkg/utils"
)
// TemplateUnit defines the basic unit of Template and whether it should be updated or not
type TemplateUnit struct {
*unstructured.Unstructured
Source string
ResourceUpdated bool
StatusUpdated bool
}
// ResourceMap is a registry for all resources
type ResourceMap struct {
GroupVersionResource schema.GroupVersionResource
Namespaced bool
ServerUpdated bool
TemplateMap map[string]*TemplateUnit
}
// KubeSynchronizer handles resources to a kube endpoint
type KubeSynchronizer struct {
Interval int
LocalClient client.Client
RemoteClient client.Client
localConfig *rest.Config
DynamicClient dynamic.Interface
KubeResources map[schema.GroupVersionKind]*ResourceMap
SynchronizerID *types.NamespacedName
Extension Extension
eventrecorder *utils.EventRecorder
stopCh chan struct{}
resetcache bool
rediscover bool
dynamicFactory dynamicinformer.DynamicSharedInformerFactory
}
var (
crdresource = "customresourcedefinitions"
)
var defaultSynchronizer *KubeSynchronizer
// Add creates the default syncrhonizer and add the start function as runnable into manager
func Add(mgr manager.Manager, hubconfig *rest.Config, syncid *types.NamespacedName, interval int) error {
var err error
defaultSynchronizer, err = CreateSynchronizer(mgr.GetConfig(), hubconfig, mgr.GetScheme(), syncid, interval, defaultExtension)
if err != nil {
klog.Error("Failed to create synchronizer with error: ", err)
return err
}
return mgr.Add(defaultSynchronizer)
}
// GetDefaultSynchronizer - return the default kubernetse synchronizer
func GetDefaultSynchronizer() *KubeSynchronizer {
return defaultSynchronizer
}
// CreateSynchronizer createa an instance of synchrizer with give api-server config
func CreateSynchronizer(config, remoteConfig *rest.Config, scheme *runtime.Scheme, syncid *types.NamespacedName,
interval int, ext Extension) (*KubeSynchronizer, error) {
if klog.V(utils.QuiteLogLel) {
fnName := utils.GetFnName()
klog.Infof("Entering: %v()", fnName)
defer klog.Infof("Exiting: %v()", fnName)
}
var err error
dynamicClient := dynamic.NewForConfigOrDie(config)
s := &KubeSynchronizer{
Interval: interval,
SynchronizerID: syncid,
DynamicClient: dynamicClient,
localConfig: config,
KubeResources: make(map[schema.GroupVersionKind]*ResourceMap),
Extension: ext,
}
s.LocalClient, err = client.New(config, client.Options{})
if err != nil {
klog.Error("Failed to initialize client to update local status. err: ", err)
return nil, err
}
s.RemoteClient = s.LocalClient
if remoteConfig != nil {
s.RemoteClient, err = client.New(remoteConfig, client.Options{})
if err != nil {
klog.Error("Failed to initialize client to update remote status. err: ", err)
return nil, err
}
}
defaultExtension.localClient = s.LocalClient
defaultExtension.remoteClient = s.RemoteClient
if ext == nil {
s.Extension = defaultExtension
}
s.eventrecorder, err = utils.NewEventRecorder(config, scheme)
if err != nil {
klog.Error("Failed to create event recorder. err: ", err)
return nil, err
}
s.resetcache = true
s.rediscover = false
s.discoverResourcesOnce()
return s, nil
}
// Start the discovery and start caches
func (sync *KubeSynchronizer) Start(s <-chan struct{}) error {
if klog.V(utils.QuiteLogLel) {
fnName := utils.GetFnName()
klog.Infof("Entering: %v()", fnName)
defer klog.Infof("Exiting: %v()", fnName)
}
sync.rediscoverResource()
go wait.Until(func() {
sync.houseKeeping()
}, time.Duration(sync.Interval)*time.Second, s)
<-s
return nil
}
//HouseKeeping - Apply resources defined in sync.KubeResources
func (sync *KubeSynchronizer) houseKeeping() {
crdUpdated := false
// make sure the template map and the actual resource are aligned
for gvk, res := range sync.KubeResources {
var err error
klog.V(5).Infof("Applying templates in gvk: %#v, res: %#v", gvk, res)
if res.ServerUpdated {
err = sync.checkServerObjects(gvk, res)
if res.GroupVersionResource.Resource == crdresource {
klog.V(5).Info("CRD Updated! let's discover it!")
crdUpdated = true
}
res.ServerUpdated = false
}
if err != nil {
klog.Error("Error in checking server objects of gvk:", gvk, "error:", err, " skipping")
continue
}
sync.applyKindTemplates(res)
}
if crdUpdated || sync.rediscover {
sync.rediscoverResource()
sync.rediscover = false
}
}
func (sync *KubeSynchronizer) GetInterval() int {
return sync.Interval
}
func (sync *KubeSynchronizer) checkServerObjects(gvk schema.GroupVersionKind, res *ResourceMap) error {
if res == nil {
errmsg := "Checking server objects with nil map"
klog.Error(errmsg)
return errors.NewBadRequest(errmsg)
}
klog.V(5).Info("Checking Server object:", res.GroupVersionResource)
objlist, err := sync.DynamicClient.Resource(res.GroupVersionResource).List(metav1.ListOptions{})
if err != nil {
return err
}
var dl dynamic.ResourceInterface
for _, o := range objlist.Items {
obj := o
if !sync.Extension.IsObjectOwnedBySynchronizer(&obj, sync.SynchronizerID) {
continue
}
host := sync.Extension.GetHostFromObject(&obj)
dpl := utils.GetHostDeployableFromObject(&obj)
source := utils.GetSourceFromObject(&obj)
if dpl == nil || host == nil {
continue
}
reskey := sync.generateResourceMapKey(*host, *dpl)
tplunit, ok := res.TemplateMap[reskey]
if res.Namespaced {
dl = sync.DynamicClient.Resource(res.GroupVersionResource).Namespace(obj.GetNamespace())
} else {
dl = sync.DynamicClient.Resource(res.GroupVersionResource)
}
if !ok {
// Harvest from system
if obj.GetDeletionTimestamp() == nil {
klog.V(3).Infof("Havesting tplunit from cluster host: %#v, obj: %#v, TemplateMap: %#v", dpl, obj, res.TemplateMap)
unit := &TemplateUnit{
ResourceUpdated: false,
StatusUpdated: false,
Unstructured: obj.DeepCopy(),
Source: source,
}
unit.Unstructured.SetGroupVersionKind(gvk)
res.TemplateMap[reskey] = unit
}
} else {
if tplunit.Source != source {
klog.V(3).Info("Havesting resource ", dpl.Namespace, "/", dpl.Name, " but owned by other source, skipping")
continue
}
status := obj.Object["status"]
klog.V(4).Info("Found for ", dpl, ", tplunit:", tplunit, "Doing obj ", obj.GetNamespace(), "/", obj.GetName(), " with status:", status)
delete(obj.Object, "status")
err = sync.Extension.UpdateHostStatus(err, tplunit.Unstructured, status)
if err != nil {
klog.Error("Failed to update host status with error:", err)
}
if tplunit.ResourceUpdated {
continue
}
if !reflect.DeepEqual(obj, tplunit.Unstructured.Object) {
newobj := tplunit.Unstructured.DeepCopy()
newobj.SetResourceVersion(obj.GetResourceVersion())
_, err = dl.Update(newobj, metav1.UpdateOptions{})
klog.V(5).Info("Check - Updated existing Resource to", tplunit, " with err:", err)
sync.eventrecorder.RecordEvent(tplunit.Unstructured, "UpdateResource",
"Synchronizer updated resource "+tplunit.GetName()+"of gvk:"+tplunit.GroupVersionKind().String()+" for retry", err)
if err == nil {
tplunit.ResourceUpdated = true
}
}
// don't process the err of status update. leave it to next round house keeping
if err != nil {
return err
}
klog.V(5).Info("Updated template ", tplunit.Unstructured.GetName(), ":", tplunit.ResourceUpdated)
res.TemplateMap[reskey] = tplunit
}
}
return nil
}
func (sync *KubeSynchronizer) createNewResourceByTemplateUnit(ri dynamic.ResourceInterface, tplunit *TemplateUnit) error {
klog.V(5).Info("Apply - Creating New Resource ", tplunit)
tplunit.Unstructured.SetResourceVersion("")
obj, err := ri.Create(tplunit.Unstructured, metav1.CreateOptions{})
// Auto Create Namespace if not exist
if err != nil && errors.IsNotFound(err) {
ns := &corev1.Namespace{}
ns.Name = tplunit.GetNamespace()
nsus := &unstructured.Unstructured{}
nsus.Object, err = runtime.DefaultUnstructuredConverter.ToUnstructured(ns)
if err == nil {
nsus.SetGroupVersionKind(schema.GroupVersionKind{
Version: "v1",
Kind: "Namespace",
})
sync.eventrecorder.RecordEvent(nsus, "CreateNamespace",
"Synchronizer created namespace "+ns.Name+" for resource "+tplunit.GetName(), err)
_, err = sync.DynamicClient.Resource(schema.GroupVersionResource{
Version: "v1",
Resource: "namespaces",
}).Create(nsus, metav1.CreateOptions{})
if err == nil {
// try again
obj, err = ri.Create(tplunit.Unstructured, metav1.CreateOptions{})
}
}
}
if err != nil {
tplunit.ResourceUpdated = false
klog.Error("Failed to apply resource with error: ", err)
return err
}
obj.SetGroupVersionKind(tplunit.GroupVersionKind())
sync.eventrecorder.RecordEvent(obj, "CreateResource",
"Synchronizer created resource "+tplunit.GetName()+" of gvk:"+obj.GroupVersionKind().String(), err)
tplunit.ResourceUpdated = true
if obj != nil {
err = sync.Extension.UpdateHostStatus(err, tplunit.Unstructured, obj.Object["status"])
} else {
err = sync.Extension.UpdateHostStatus(err, tplunit.Unstructured, nil)
}
if err != nil {
klog.Error("Failed to update host status with error: ", err)
}
return err
}
func (sync *KubeSynchronizer) updateResourceByTemplateUnit(ri dynamic.ResourceInterface,
obj *unstructured.Unstructured, tplunit *TemplateUnit, isService bool) error {
var err error
tplown := sync.Extension.GetHostFromObject(tplunit)
if tplown != nil && !sync.Extension.IsObjectOwnedByHost(obj, *tplown, sync.SynchronizerID) {
errmsg := "Obj " + tplunit.GetNamespace() + "/" + tplunit.GetName() + " exists and owned by others, backoff"
klog.Info(errmsg)
tplunit.ResourceUpdated = false
err = sync.Extension.UpdateHostStatus(errors.NewBadRequest(errmsg), tplunit.Unstructured, nil)
if err != nil {
klog.Error("Failed to update host status for existing resource with error:", err)
}
return err
}
newobj := tplunit.Unstructured.DeepCopy()
newobj.SetResourceVersion(obj.GetResourceVersion())
if isService {
var objb, tplb, pb []byte
objb, err = obj.MarshalJSON()
if err != nil {
klog.Error("Failed to marshall obj with error:", err)
return err
}
tplb, err = tplunit.MarshalJSON()
if err != nil {
klog.Error("Failed to marshall tplunit with error:", err)
return err
}
pb, err = jsonpatch.CreateThreeWayJSONMergePatch(tplb, tplb, objb)
if err != nil {
klog.Error("Failed to make patch with error:", err)
return err
}
klog.V(4).Info("Generating Patch for service update.\nObjb:", string(objb), "\ntplb:", string(tplb), "\nPatch:", string(pb))
_, err = ri.Patch(obj.GetName(), types.MergePatchType, pb, metav1.PatchOptions{})
} else {
_, err = ri.Update(newobj, metav1.UpdateOptions{})
}
sync.eventrecorder.RecordEvent(tplunit.Unstructured, "UpdateResource",
"Synchronizer updated resource for template "+tplunit.GetName()+" of gvk:"+tplunit.GroupVersionKind().String(), err)
klog.V(5).Info("Check - Updated existing Resource to", tplunit, " with err:", err)
if err == nil {
tplunit.ResourceUpdated = true
} else {
klog.Error("Failed to update resource with error:", err)
}
sterr := sync.Extension.UpdateHostStatus(err, tplunit.Unstructured, obj.Object["status"])
if sterr != nil {
klog.Error("Failed to update host status with error:", err)
}
return nil
}
var serviceGVR = schema.GroupVersionResource{
Version: "v1",
Resource: "Service",
}
func (sync *KubeSynchronizer) applyKindTemplates(res *ResourceMap) {
nri := sync.DynamicClient.Resource(res.GroupVersionResource)
for k, tplunit := range res.TemplateMap {
err := sync.applyTemplate(nri, res.Namespaced, k, tplunit, (res.GroupVersionResource == serviceGVR))
if err != nil {
klog.Error("Failed to apply kind template", tplunit.Unstructured, "with error:", err)
}
}
}
func (sync *KubeSynchronizer) applyTemplate(nri dynamic.NamespaceableResourceInterface, namespaced bool,
k string, tplunit *TemplateUnit, isService bool) error {
klog.V(3).Info("Applying (key:", k, ") template:", tplunit, tplunit.Unstructured, "updated:", tplunit.ResourceUpdated)
var ri dynamic.ResourceInterface
if namespaced {
ri = nri.Namespace(tplunit.GetNamespace())
} else {
ri = nri
}
obj, err := ri.Get(tplunit.GetName(), metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
err = sync.createNewResourceByTemplateUnit(ri, tplunit)
} else {
klog.Error("Failed to apply resource with error:", err)
}
} else if !tplunit.ResourceUpdated {
err = sync.updateResourceByTemplateUnit(ri, obj, tplunit, isService)
// don't process the err of status update. leave it to next round house keeping
}
// leave the sync the check routine, not this one
klog.V(3).Info("Applied Kind Template ", tplunit.Unstructured, " error:", err)
return err
}
// DeRegisterTemplate applies the resource in spec.template to given kube
func (sync *KubeSynchronizer) DeRegisterTemplate(host, dpl types.NamespacedName, source string) error {
if klog.V(utils.QuiteLogLel) {
fnName := utils.GetFnName()
klog.Infof("Entering: %v()", fnName)
defer klog.Infof("Exiting: %v()", fnName)
}
// check resource template map for deployables
klog.V(2).Info("Deleting template ", dpl, "for source:", source)
for _, resmap := range sync.KubeResources {
// all templates are added with annotations, no need to check nil
if len(resmap.TemplateMap) > 0 {
klog.V(5).Info("Checking valid resource map: ", resmap.GroupVersionResource)
}
reskey := sync.generateResourceMapKey(host, dpl)
tplunit, ok := resmap.TemplateMap[reskey]
if !ok || tplunit.Source != source {
if tplunit != nil {
klog.V(5).Infof("Delete - skipping tplunit with other source, resmap source: %v, source: %v", tplunit.Source, source)
}
continue
}
delete(resmap.TemplateMap, reskey)
klog.V(5).Info("Deleted template ", dpl, "in resource map ", resmap.GroupVersionResource)
if !resmap.GroupVersionResource.Empty() {
var dl dynamic.ResourceInterface
if resmap.Namespaced {
dl = sync.DynamicClient.Resource(resmap.GroupVersionResource).Namespace(tplunit.GetNamespace())
} else {
dl = sync.DynamicClient.Resource(resmap.GroupVersionResource)
}
// check resource ownership
tgtobj, err := dl.Get(tplunit.GetName(), metav1.GetOptions{})
if err == nil {
if sync.Extension.IsObjectOwnedByHost(tgtobj, host, sync.SynchronizerID) {
klog.V(5).Info("Resource is owned by ", host, "Deleting ", tplunit.Unstructured)
deletepolicy := metav1.DeletePropagationBackground
err = dl.Delete(tplunit.GetName(), &metav1.DeleteOptions{PropagationPolicy: &deletepolicy})
sync.eventrecorder.RecordEvent(tplunit.Unstructured, "DeleteResource",
"Synchronizer deleted resource "+tplunit.GetName()+" of gvk:"+tplunit.GroupVersionKind().String()+" by deregister", err)
if err != nil {
klog.Error("Failed to delete tplunit in kubernetes, with error:", err)
}
sterr := sync.Extension.UpdateHostStatus(err, tplunit.Unstructured, nil)
if sterr != nil {
klog.Error("Failed to update host status, with error:", err)
}
}
}
}
klog.V(5).Info("Deleted resource ", dpl, "in k8s")
}
return nil
}
// RegisterTemplate applies the resource in spec.template to given kube
func (sync *KubeSynchronizer) RegisterTemplate(host types.NamespacedName, instance *dplv1alpha1.Deployable, source string) error {
// Parse the resource in template
if klog.V(utils.QuiteLogLel) {
fnName := utils.GetFnName()
klog.Infof("Entering: %v()", fnName)
defer klog.Infof("Exiting: %v()", fnName)
}
var err error
template := &unstructured.Unstructured{}
if instance.Spec.Template == nil {
klog.Warning("Processing local deployable without template:", instance)
return nil
}
if instance.Spec.Template.Object != nil {
template.Object, err = runtime.DefaultUnstructuredConverter.ToUnstructured(instance.Spec.Template.Object.DeepCopyObject())
} else {
err = json.Unmarshal(instance.Spec.Template.Raw, template)
klog.V(3).Info("Processing Local with template:", template, ", syncid: ", sync.SynchronizerID, ", host: ", host)
}
if err != nil {
klog.Error("Failed to unmashal template with error: ", err, " with ", string(instance.Spec.Template.Raw))
return err
}
if template.GetKind() == "" {
return errors.NewBadRequest("Failed to update template with empty kind. gvk:" + template.GetObjectKind().GroupVersionKind().String())
}
// set name to deployable name if not given
if template.GetName() == "" {
template.SetName(instance.GetName())
}
// carry/override with deployable labels
tpllbls := template.GetLabels()
if tpllbls == nil {
tpllbls = make(map[string]string)
}
for k, v := range instance.GetLabels() {
tpllbls[k] = v
}
template.SetLabels(tpllbls)
tplgvk := template.GetObjectKind().GroupVersionKind()
validgvk := sync.GetValidatedGVK(tplgvk)
if validgvk == nil {
return errors.NewBadRequest("GroupVersionKind of Template is not supported. " + tplgvk.String())
}
template.SetGroupVersionKind(*validgvk)
resmap, ok := sync.KubeResources[*validgvk]
if !ok {
// register new kind
resmap = &ResourceMap{
GroupVersionResource: schema.GroupVersionResource{},
TemplateMap: make(map[string]*TemplateUnit),
Namespaced: true,
}
klog.V(5).Info("Adding new resource from registration. kind: ", template.GetKind(), " GroupVersionResource: ", resmap.GroupVersionResource)
}
if resmap.Namespaced && template.GetNamespace() == "" {
template.SetNamespace(instance.GetNamespace())
}
dpl := types.NamespacedName{
Name: instance.GetName(),
Namespace: instance.GetNamespace(),
}
reskey := sync.generateResourceMapKey(host, dpl)
// Try to get template object, take error as not exist, will check again anyway.
if len(instance.GetObjectMeta().GetFinalizers()) > 0 {
// Deployable in being deleted, de-register template and return
klog.V(5).Info("Deployable has finalizers, ready to delete object", instance)
err = sync.DeRegisterTemplate(host, dpl, source)
if err != nil {
klog.Error("Failed to deregister template when there are finalizer(s) with error: ", err)
}
return nil
}
// step out if the target resource is not from this deployable
existingTemplateUnit, ok := resmap.TemplateMap[reskey]
if ok && !sync.Extension.IsObjectOwnedByHost(existingTemplateUnit.Unstructured, host, sync.SynchronizerID) {
return errors.NewBadRequest(fmt.Sprintf("Resource owned by other owner: %s vs %s. Backing off.",
sync.Extension.GetHostFromObject(existingTemplateUnit.Unstructured).String(), host.String()))
}
if !utils.IsLocalDeployable(instance) {
klog.V(5).Info("Deployable is not (no longer) local, ready to delete object", instance)
err = sync.DeRegisterTemplate(host, dpl, source)
if err != nil {
klog.Error("Failed to deregister template when the deployable is not local, with error:", err)
}
instance.Status.ResourceStatus = nil
instance.Status.Message = ""
instance.Status.Reason = ""
return nil
}
err = sync.Extension.SetHostToObject(template, host, sync.SynchronizerID)
if err != nil {
klog.Error("Failed to set host to object with error:", err)
}
tplanno := template.GetAnnotations()
tplanno[dplv1alpha1.AnnotationHosting] = instance.GetNamespace() + "/" + instance.GetName()
tplanno[appv1alpha1.AnnotationSyncSource] = source
template.SetAnnotations(tplanno)
// apply override in template
if sync.SynchronizerID != nil {
ovmap, err := utils.PrepareOverrides(*sync.SynchronizerID, instance)
if err != nil {
klog.Error("Failed to prepare override for instance: ", instance)
return err
}
template, err = utils.OverrideTemplate(template, ovmap)
if err != nil {
klog.Error("Failed to apply override for instance: ", instance)
return err
}
}
klog.V(4).Info("overrided template: ", template)
// skip no-op to template
if existingTemplateUnit != nil && reflect.DeepEqual(existingTemplateUnit.Unstructured, template) {
klog.V(2).Info("Skipping.. template in registry is the same ", existingTemplateUnit)
return nil
}
templateUnit := &TemplateUnit{
ResourceUpdated: false,
StatusUpdated: false,
Unstructured: template.DeepCopy(),
Source: source,
}
resmap.TemplateMap[reskey] = templateUnit
sync.KubeResources[template.GetObjectKind().GroupVersionKind()] = resmap
klog.V(2).Info("Registered template ", template, "to KubeResource map:", template.GetObjectKind().GroupVersionKind(), "for source: ", source)
return nil
}
func (sync *KubeSynchronizer) generateResourceMapKey(host, dpl types.NamespacedName) string {
return host.String() + "/" + dpl.String()
}