-
Notifications
You must be signed in to change notification settings - Fork 19
/
event.go
52 lines (45 loc) · 1.2 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
package workload
import (
"context"
"sync"
"github.com/projecteru2/agent/types"
"github.com/projecteru2/agent/utils"
"github.com/projecteru2/core/log"
)
// EventHandler define event handler
type EventHandler struct {
sync.Mutex
handlers map[string]func(context.Context, *types.WorkloadEventMessage)
}
// NewEventHandler new a event handler
func NewEventHandler() *EventHandler {
return &EventHandler{handlers: make(map[string]func(context.Context, *types.WorkloadEventMessage))}
}
// Handle hand a event
func (e *EventHandler) Handle(action string, h func(context.Context, *types.WorkloadEventMessage)) {
e.Lock()
defer e.Unlock()
e.handlers[action] = h
}
// Watch watch change
func (e *EventHandler) Watch(ctx context.Context, c <-chan *types.WorkloadEventMessage) {
logger := log.WithFunc("Watch")
for {
select {
case ev, ok := <-c:
if !ok {
logger.Info(ctx, "event chan closed")
return
}
logger.Infof(ctx, "monitor: workload id %s action %s", ev.ID, ev.Action)
e.Lock()
if h := e.handlers[ev.Action]; h != nil {
_ = utils.Pool.Submit(func() { h(ctx, ev) })
}
e.Unlock()
case <-ctx.Done():
logger.Info(ctx, "context canceled, stop watching")
return
}
}
}