This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
gauge.go
74 lines (62 loc) · 1.45 KB
/
gauge.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
package metrics
import (
"sync"
"time"
)
const DefaultGaugePollingInterval = 1 * time.Second
var (
gaugeMu sync.Mutex
gaugeRegistry = make([]*Gauge, 0)
)
func init() {
go pollAllGauges()
}
// GaugeFunc is used in a polling loop to get the metric's value. Processing here is
// expected to be fairly light weight since we use a single polling thread to process
// all gauges.
type GaugeFunc func() float64
// Gauge measures a metric's value at a point in time
type Gauge struct {
client Client
f GaugeFunc
name string
tags []string
}
// NewGauge returns a new Gauge that polls the value returned by f
func NewGauge(client Client, name string, f GaugeFunc, tagOptions ...TagOption) (*Gauge, error) {
if err := validateMetricName(name); err != nil {
return nil, err
}
g := &Gauge{
client: client,
f: f,
name: name,
tags: GetTags(tagOptions...),
}
// Lazy load the poller
gaugeMu.Lock()
gaugeRegistry = append(gaugeRegistry, g)
gaugeMu.Unlock()
return g, nil
}
func pollAllGauges() {
for {
time.Sleep(DefaultGaugePollingInterval)
gaugeMu.Lock()
for _, gauge := range gaugeRegistry {
_ = gauge.client.Gauge(gauge.name, gauge.f(), gauge.tags)
}
gaugeMu.Unlock()
}
}
// Stop removes the gauge from being polled
func (g *Gauge) Stop() {
gaugeMu.Lock()
for i, gauge := range gaugeRegistry {
if g == gauge {
gaugeRegistry = append(gaugeRegistry[:i], gaugeRegistry[i+1:]...)
break
}
}
gaugeMu.Unlock()
}