forked from AliyunContainerService/pouch
/
container_monitor.go
82 lines (65 loc) · 1.52 KB
/
container_monitor.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package mgr
import (
"fmt"
"github.com/alibaba/pouch/pkg/log"
)
const (
// EvExit represents container's exit event.
EvExit = iota
// TODO add more
)
// ContainerEvent represents the container's events.
type ContainerEvent struct {
Kind int
c *Container
handle func(*Container) error
}
// String returns container's event type as a string.
func (e *ContainerEvent) String() string {
switch e.Kind {
case EvExit:
return fmt.Sprintf("%s exit", e.c.ID)
default:
return "none"
}
}
// WithHandle sets the event's handler.
func (e *ContainerEvent) WithHandle(handle func(*Container) error) *ContainerEvent {
e.handle = handle
return e
}
// ContainerExitEvent represents container's exit event.
func ContainerExitEvent(c *Container) *ContainerEvent {
return &ContainerEvent{
Kind: EvExit,
c: c,
}
}
// TODO add more events
// ContainerMonitor is used to monitor contianer's event.
type ContainerMonitor struct {
c chan *ContainerEvent
}
// NewContainerMonitor returns one ContainerMonitor object.
func NewContainerMonitor() *ContainerMonitor {
m := &ContainerMonitor{
c: make(chan *ContainerEvent, 1000),
}
go func() {
for {
ev := <-m.c
log.With(nil).Debugf("receive event: %s", ev)
if ev.handle != nil {
log.With(nil).Infof("handle event: %s", ev)
if err := ev.handle(ev.c); err != nil {
log.With(nil).Errorf("failed to handle event: %s", ev)
}
}
}
}()
return m
}
// PostEvent sends a event to monitor.
func (m *ContainerMonitor) PostEvent(ev *ContainerEvent) {
m.c <- ev
}