forked from docker-archive/classicswarm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.go
66 lines (53 loc) · 1.27 KB
/
event.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package cluster
import (
"errors"
"sync"
log "github.com/Sirupsen/logrus"
"github.com/samalba/dockerclient"
)
// Event is exported
type Event struct {
dockerclient.Event
Engine *Engine `json:"-"`
}
// EventHandler is exported
type EventHandler interface {
Handle(*Event) error
}
// EventHandlers is a map of EventHandler
type EventHandlers struct {
sync.RWMutex
eventHandlers map[EventHandler]struct{}
}
// NewEventHandlers returns a EventHandlers
func NewEventHandlers() *EventHandlers {
return &EventHandlers{
eventHandlers: make(map[EventHandler]struct{}),
}
}
// Handle callbacks for the events
func (eh *EventHandlers) Handle(e *Event) {
eh.RLock()
defer eh.RUnlock()
for h := range eh.eventHandlers {
if err := h.Handle(e); err != nil {
log.Error(err)
}
}
}
// RegisterEventHandler registers an event handler.
func (eh *EventHandlers) RegisterEventHandler(h EventHandler) error {
eh.Lock()
defer eh.Unlock()
if _, ok := eh.eventHandlers[h]; ok {
return errors.New("event handler already set")
}
eh.eventHandlers[h] = struct{}{}
return nil
}
// UnregisterEventHandler unregisters a previously registered event handler.
func (eh *EventHandlers) UnregisterEventHandler(h EventHandler) {
eh.Lock()
defer eh.Unlock()
delete(eh.eventHandlers, h)
}