forked from KyleBanks/dockerstats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonitor.go
69 lines (58 loc) · 1.38 KB
/
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
package dockerstats
import (
"sync"
)
type testComm struct {
statsFn func() ([]Stats, error)
}
func (t testComm) Stats() ([]Stats, error) {
return t.statsFn()
}
// Monitor provides the ability to recieve a constant stream of statistics for each running Docker
// container.
//
// Each `StatsResult` sent through the channel contains either an `error` or a
// `Stats` slice equal in length to the number of running Docker containers.
type Monitor struct {
Stream chan *StatsResult
Comm Communicator
mu sync.Mutex
stopped bool
}
// NewMonitor initializes and returns a Monitor which can recieve a stream of Docker container statistics.
func NewMonitor() *Monitor {
m := Monitor{
Stream: make(chan *StatsResult),
Comm: DefaultCommunicator,
}
m.start()
return &m
}
// Stop tells the monitor to stop streaming Docker container statistics.
func (m *Monitor) Stop() {
m.mu.Lock()
m.stopped = true
m.mu.Unlock()
}
// start begins polling for Docker container statistics, and sends them through the Monitor's
// stream to be consumed.
func (m *Monitor) start() {
go func() {
for {
m.mu.Lock()
stopped := m.stopped
// Do not defer! If the channel blocks below it
// can lead to deadlock situations.
m.mu.Unlock()
if stopped {
close(m.Stream)
break
}
s, err := m.Comm.Stats()
m.Stream <- &StatsResult{
Stats: s,
Error: err,
}
}
}()
}