events_utils.go 1.2 KB

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