sigs.k8s.io/cluster-api@v1.7.1/controllers/external/tracker.go (about) 1 /* 2 Copyright 2020 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package external 18 19 import ( 20 "fmt" 21 "sync" 22 23 "github.com/go-logr/logr" 24 "github.com/pkg/errors" 25 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 26 "k8s.io/apimachinery/pkg/runtime" 27 "sigs.k8s.io/controller-runtime/pkg/cache" 28 "sigs.k8s.io/controller-runtime/pkg/controller" 29 "sigs.k8s.io/controller-runtime/pkg/handler" 30 "sigs.k8s.io/controller-runtime/pkg/predicate" 31 "sigs.k8s.io/controller-runtime/pkg/source" 32 33 "sigs.k8s.io/cluster-api/util/predicates" 34 ) 35 36 // ObjectTracker is a helper struct to deal when watching external unstructured objects. 37 type ObjectTracker struct { 38 m sync.Map 39 40 Controller controller.Controller 41 Cache cache.Cache 42 } 43 44 // Watch uses the controller to issue a Watch only if the object hasn't been seen before. 45 func (o *ObjectTracker) Watch(log logr.Logger, obj runtime.Object, handler handler.EventHandler, p ...predicate.Predicate) error { 46 // Consider this a no-op if the controller isn't present. 47 if o.Controller == nil { 48 return nil 49 } 50 51 gvk := obj.GetObjectKind().GroupVersionKind() 52 key := gvk.GroupKind().String() 53 if _, loaded := o.m.LoadOrStore(key, struct{}{}); loaded { 54 return nil 55 } 56 57 u := &unstructured.Unstructured{} 58 u.SetGroupVersionKind(gvk) 59 60 log.Info(fmt.Sprintf("Adding watch on external object %q", gvk.String())) 61 err := o.Controller.Watch( 62 source.Kind(o.Cache, u), 63 handler, 64 append(p, predicates.ResourceNotPaused(log))..., 65 ) 66 if err != nil { 67 o.m.Delete(key) 68 return errors.Wrapf(err, "failed to add watch on external object %q", gvk.String()) 69 } 70 return nil 71 }