/
periodic_metron_notifier.go
75 lines (60 loc) · 1.56 KB
/
periodic_metron_notifier.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
package metrics
import (
"time"
"code.cloudfoundry.org/clock"
"code.cloudfoundry.org/lager/v3"
dropsonde_metrics "github.com/cloudfoundry/dropsonde/metrics"
)
func sendMetric(key string, value int) {
dropsonde_metrics.SendValue(key, float64(value), "Metric")
}
func sendDuration(duration time.Duration) {
dropsonde_metrics.SendValue("MetricsReporting", float64(duration), "nanos")
}
type PeriodicMetronNotifier struct {
Interval time.Duration
Logger lager.Logger
Clock clock.Clock
metrics Metrics
stopped chan struct{}
}
func NewPeriodicMetronNotifier(
logger lager.Logger,
metrics Metrics,
interval time.Duration,
clock clock.Clock,
) *PeriodicMetronNotifier {
return &PeriodicMetronNotifier{
Interval: interval,
Logger: logger,
Clock: clock,
metrics: metrics,
stopped: make(chan struct{}),
}
}
func (notifier PeriodicMetronNotifier) Start() {
logger := notifier.Logger.Session("metrics-notifier", lager.Data{"interval": notifier.Interval.String()})
logger.Info("starting")
ticker := notifier.Clock.NewTicker(notifier.Interval)
go func() {
defer ticker.Stop()
logger.Info("started", lager.Data{"time": notifier.Clock.Now()})
defer logger.Info("finished")
for {
select {
case <-ticker.C():
startedAt := notifier.Clock.Now()
for key, metric := range notifier.metrics {
sendMetric(key, metric())
}
finishedAt := notifier.Clock.Now()
sendDuration(finishedAt.Sub(startedAt))
case <-notifier.stopped:
return
}
}
}()
}
func (notifier PeriodicMetronNotifier) Stop() {
close(notifier.stopped)
}