knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/configmap/manual_watcher.go (about) 1 /* 2 Copyright 2018 The Knative 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 configmap 18 19 import ( 20 "sync" 21 22 corev1 "k8s.io/api/core/v1" 23 ) 24 25 // ManualWatcher will notify Observers when a ConfigMap is manually reported as changed 26 type ManualWatcher struct { 27 Namespace string 28 29 // Guards observers 30 sync.RWMutex 31 observers map[string][]Observer 32 } 33 34 var _ Watcher = (*ManualWatcher)(nil) 35 36 // Watch implements Watcher 37 func (w *ManualWatcher) Watch(name string, o ...Observer) { 38 w.Lock() 39 defer w.Unlock() 40 41 if w.observers == nil { 42 w.observers = make(map[string][]Observer, 1) 43 } 44 w.observers[name] = append(w.observers[name], o...) 45 } 46 47 // ForEach implements Watcher 48 func (w *ManualWatcher) ForEach(f func(string, []Observer) error) error { 49 for k, v := range w.observers { 50 if err := f(k, v); err != nil { 51 return err 52 } 53 } 54 return nil 55 } 56 57 // Start implements Watcher 58 func (w *ManualWatcher) Start(<-chan struct{}) error { 59 return nil 60 } 61 62 // OnChange invokes the callbacks of all observers of the given ConfigMap. 63 func (w *ManualWatcher) OnChange(configMap *corev1.ConfigMap) { 64 if configMap.Namespace != w.Namespace { 65 return 66 } 67 // Within our namespace, take the lock and see if there are any registered observers. 68 w.RLock() 69 defer w.RUnlock() 70 // Iterate over the observers and invoke their callbacks. 71 for _, o := range w.observers[configMap.Name] { 72 o(configMap) 73 } 74 }