-
Notifications
You must be signed in to change notification settings - Fork 3
/
watch.go
97 lines (85 loc) · 1.68 KB
/
watch.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package daemon
import (
log "github.com/Sirupsen/logrus"
"github.com/docker/docker/pkg/watch"
"sync"
"time"
)
const WatchStateEvent = "WatchState"
type StateWatcher struct {
result chan watch.Event
stopped bool
sync.Mutex
}
func NewStateWatcher() *StateWatcher {
return &StateWatcher{
result: make(chan watch.Event),
stopped: false,
}
}
func (sw *StateWatcher) ResultChan() <-chan watch.Event {
sw.Lock()
r := sw.result
sw.Unlock()
return r
}
// Emit sends a watch event.
func (sw *StateWatcher) Emit(obj watch.Object) {
sw.Lock()
defer sw.Unlock()
if !sw.stopped {
sw.result <- watch.Event{WatchStateEvent, obj}
} else {
log.Debugf("watching channel is stopped, ignore event %v", obj)
}
}
func (sw *StateWatcher) Stop() {
sw.Lock()
defer sw.Unlock()
log.Debugf("stopping watching channel")
if !sw.stopped {
close(sw.result)
sw.stopped = true
}
}
func (sw *StateWatcher) Start() {
sw.Lock()
defer sw.Unlock()
if sw.stopped {
sw.result = make(chan watch.Event)
sw.stopped = false
}
}
type WatchState struct {
Running bool
Paused bool
Restarting bool
Pid int
ExitCode int
StartedAt time.Time
FinishedAt time.Time
}
func (s *State) setByWatchState(ws *WatchState) {
s.Lock()
s.Running = ws.Running
s.Paused = ws.Paused
s.Restarting = ws.Restarting
s.Pid = ws.Pid
s.ExitCode = ws.ExitCode
s.StartedAt = ws.StartedAt
s.FinishedAt = ws.FinishedAt
s.Unlock()
}
func (s *State) ToWatchState() *WatchState {
s.Lock()
defer s.Unlock()
return &WatchState{
Running: s.Running,
Paused: s.Paused,
Restarting: s.Restarting,
Pid: s.Pid,
ExitCode: s.ExitCode,
StartedAt: s.StartedAt,
FinishedAt: s.FinishedAt,
}
}