-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpoller.go
99 lines (79 loc) · 1.99 KB
/
poller.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
98
99
// Copyright 2017 Bobby Powers. All rights reserved.
// Use of this source code is governed by the ISC
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"log"
"time"
"github.com/containerd/cgroups"
)
type Record struct {
Time time.Time
Value uint64
Kernel uint64
}
type Stats struct {
Rss []Record
}
type endReq struct {
result chan<- *Stats
}
type Poller struct {
in chan<- *endReq
stats *Stats
}
func NewPoller(cgroup cgroups.Cgroup, freq int) (*Poller, error) {
durationStr := fmt.Sprintf("%fs", 1/float64(freq))
duration, err := time.ParseDuration(durationStr)
if err != nil {
return nil, fmt.Errorf("bad frequency (%d): %s", freq, err)
}
if duration <= 0 {
return nil, fmt.Errorf("expected positive duration, not %s", duration)
}
ch := make(chan *endReq)
p := &Poller{
in: ch,
stats: &Stats{},
}
// kick this off once at the start
if err := p.poll(time.Now(), cgroup); err != nil {
return nil, fmt.Errorf("poll: %s", err)
}
go p.poller(cgroup, ch, duration)
return p, nil
}
func (p *Poller) poll(t time.Time, cgroup cgroups.Cgroup) error {
stats, err := cgroup.Stat(cgroups.IgnoreNotExist)
if err != nil || stats == nil {
return fmt.Errorf("cg.Stat: %s", err)
}
if stats.Memory == nil {
return fmt.Errorf("cg.Stat: returned nil Memory stats")
}
p.stats.Rss = append(p.stats.Rss, Record{t, stats.Memory.Usage.Usage, stats.Memory.Kernel.Usage})
return nil
}
// loop that runs in its own goroutine, reading stats at the desired
// frequency until shouldEnd is received
func (p *Poller) poller(cgroup cgroups.Cgroup, shouldEnd <-chan *endReq, duration time.Duration) {
ticker := time.NewTicker(duration)
defer ticker.Stop()
for {
select {
case waiter := <-shouldEnd:
waiter.result <- p.stats
return
case t := <-ticker.C:
if err := p.poll(t, cgroup); err != nil {
log.Printf("mstat: %s", err)
}
}
}
}
func (p *Poller) End() *Stats {
result := make(chan *Stats)
p.in <- &endReq{result}
return <-result
}