-
Notifications
You must be signed in to change notification settings - Fork 32
/
collector.go
92 lines (73 loc) · 1.63 KB
/
collector.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
package procstats
import (
"io"
"runtime"
"sync"
"time"
)
type Collector interface {
Collect()
}
type CollectorFunc func()
func (f CollectorFunc) Collect() { f() }
type Config struct {
Collector Collector
CollectInterval time.Duration
}
func MultiCollector(collectors ...Collector) Collector {
return CollectorFunc(func() {
for _, c := range collectors {
c.Collect()
}
})
}
func StartCollector(collector Collector) io.Closer {
return StartCollectorWith(Config{Collector: collector})
}
func StartCollectorWith(config Config) io.Closer {
config = setConfigDefaults(config)
stop := make(chan struct{})
join := make(chan struct{})
go func() {
// Locks the OS thread, stats collection heavily relies on blocking
// syscalls, letting other goroutines execute on the same thread
// increases the chance for the Go runtime to detected that the thread
// is blocked and schedule a new one.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
defer close(join)
ticker := time.NewTicker(config.CollectInterval)
config.Collector.Collect()
for {
select {
case <-ticker.C:
config.Collector.Collect()
case <-stop:
return
}
}
}()
return &closer{stop: stop, join: join}
}
func setConfigDefaults(config Config) Config {
if config.CollectInterval == 0 {
config.CollectInterval = 15 * time.Second
}
if config.Collector == nil {
config.Collector = MultiCollector()
}
return config
}
type closer struct {
once sync.Once
stop chan<- struct{}
join <-chan struct{}
}
func (c *closer) Close() error {
c.once.Do(c.close)
return nil
}
func (c *closer) close() {
close(c.stop)
<-c.join
}