github.com/containerd/nerdctl@v1.7.7/pkg/eventutil/eventutil.go (about) 1 /* 2 Copyright The containerd 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 eventutil 18 19 import ( 20 "sync" 21 22 "github.com/containerd/containerd/events" 23 ) 24 25 type eventHandler struct { 26 handlers map[string]func(events.Envelope) 27 mu sync.Mutex 28 } 29 30 // InitEventHandler initializes and returns an eventHandler 31 func InitEventHandler() *eventHandler { //nolint:revive 32 return &eventHandler{handlers: make(map[string]func(events.Envelope))} 33 } 34 35 func (w *eventHandler) Handle(action string, h func(events.Envelope)) { 36 w.mu.Lock() 37 w.handlers[action] = h 38 w.mu.Unlock() 39 } 40 41 // Watch ranges over the passed in event chan and processes the events based on the 42 // handlers created for a given action. 43 // To stop watching, close the event chan. 44 func (w *eventHandler) Watch(c <-chan *events.Envelope) { 45 for e := range c { 46 w.mu.Lock() 47 h, exists := w.handlers[e.Topic] 48 w.mu.Unlock() 49 if !exists { 50 continue 51 } 52 go h(*e) 53 } 54 }