MCPcopy
hub / github.com/open-policy-agent/gatekeeper / doAddWatch

Method doAddWatch

pkg/watch/manager.go:147–202  ·  view source on GitHub ↗
(ctx context.Context, r *Registrar, gvk schema.GroupVersionKind)

Source from the content-addressed store, hash-verified

145}
146
147func (wm *Manager) doAddWatch(ctx context.Context, r *Registrar, gvk schema.GroupVersionKind) error {
148 // lock acquired by caller
149
150 if r == nil {
151 return fmt.Errorf("nil registrar cannot watch")
152 }
153
154 // watchers is everyone who is *already* watching.
155 watchers := wm.watchedKinds[gvk]
156
157 // m is everyone who *wants* to watch.
158 m := wm.managedKinds.Get() // Not a deadlock but beware if assumptions change...
159 if _, ok := m[gvk]; !ok {
160 return fmt.Errorf("could not mark %+v as managed", gvk)
161 }
162
163 // Sanity
164 if !m[gvk].registrars[r] {
165 return fmt.Errorf("registrar %s not in desired watch set", r.parentName)
166 }
167
168 if watchers.registrars[r] {
169 // Already watching.
170 return nil
171 }
172
173 switch {
174 case len(watchers.registrars) > 0:
175 // Someone else was watching, replay events in the cache to the new watcher.
176 wm.requestReplay(r, gvk)
177 default:
178 u := &unstructured.Unstructured{}
179 u.SetGroupVersionKind(gvk)
180 informer, err := wm.cache.GetInformer(ctx, u, cache.BlockUntilSynced(false))
181 if err != nil || informer == nil {
182 // This is expected to fail if a CRD is unregistered.
183 return fmt.Errorf("getting informer for kind: %+v %w", gvk, err)
184 }
185
186 // First watcher gets a fresh informer, register for events.
187 if _, err := informer.AddEventHandler(wm); err != nil {
188 return err
189 }
190 }
191
192 // Mark it as watched.
193 wv := vitals{
194 gvk: gvk,
195 registrars: map[*Registrar]bool{r: true},
196 }
197 wm.watchedKinds[gvk] = watchers.merge(wv)
198 if err := wm.metrics.reportGvkCount(int64(len(wm.watchedKinds))); err != nil {
199 log.Error(err, "while trying to report gvk count metric")
200 }
201 return nil
202}
203
204func (wm *Manager) removeWatch(ctx context.Context, r *Registrar, gvk schema.GroupVersionKind) error {

Callers 2

addWatchMethod · 0.95
replaceWatchesMethod · 0.95

Calls 7

requestReplayMethod · 0.95
AddEventHandlerMethod · 0.80
mergeMethod · 0.80
reportGvkCountMethod · 0.80
GetInformerMethod · 0.65
GetMethod · 0.45
ErrorMethod · 0.45

Tested by

no test coverage detected