github.com/ali-iotechsys/cli@v20.10.0+incompatible/cli/command/events_utils.go (about) 1 package command 2 3 import ( 4 "sync" 5 6 eventtypes "github.com/docker/docker/api/types/events" 7 "github.com/sirupsen/logrus" 8 ) 9 10 // EventHandler is abstract interface for user to customize 11 // own handle functions of each type of events 12 type EventHandler interface { 13 Handle(action string, h func(eventtypes.Message)) 14 Watch(c <-chan eventtypes.Message) 15 } 16 17 // InitEventHandler initializes and returns an EventHandler 18 func InitEventHandler() EventHandler { 19 return &eventHandler{handlers: make(map[string]func(eventtypes.Message))} 20 } 21 22 type eventHandler struct { 23 handlers map[string]func(eventtypes.Message) 24 mu sync.Mutex 25 } 26 27 func (w *eventHandler) Handle(action string, h func(eventtypes.Message)) { 28 w.mu.Lock() 29 w.handlers[action] = h 30 w.mu.Unlock() 31 } 32 33 // Watch ranges over the passed in event chan and processes the events based on the 34 // handlers created for a given action. 35 // To stop watching, close the event chan. 36 func (w *eventHandler) Watch(c <-chan eventtypes.Message) { 37 for e := range c { 38 w.mu.Lock() 39 h, exists := w.handlers[e.Action] 40 w.mu.Unlock() 41 if !exists { 42 continue 43 } 44 logrus.Debugf("event handler: received event: %v", e) 45 go h(e) 46 } 47 }