/
graphite.go
90 lines (74 loc) · 1.93 KB
/
graphite.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
package bin
import (
"fmt"
"github.com/peter-mount/go-kernel/v2"
"github.com/peter-mount/golib/statistics"
amqp "github.com/rabbitmq/amqp091-go"
)
type Graphite struct {
statistics statistics.Statistics
channel *amqp.Channel
config *Config
}
func (g *Graphite) Name() string {
return "Graphite"
}
func (a *Graphite) Init(k *kernel.Kernel) error {
service, err := k.AddService(&Config{})
if err != nil {
return err
}
a.config = (service).(*Config)
return nil
}
func (g *Graphite) Start() error {
// Custom statistics engine, capture every 10s so we submit to Graphite at
// intervals it's expecting
g.statistics.Log = false
g.statistics.Schedule = "0/10 * * * * *"
g.statistics.Configure()
if g.config.Graphite.Enabled {
// Default exchange is "graphite"
if g.config.Graphite.Exchange == "" {
g.config.Graphite.Exchange = "graphite"
}
err := g.config.RabbitMQ.Connect()
if err != nil {
return err
}
g.channel, err = g.config.RabbitMQ.NewChannel()
if err != nil {
return err
}
// We are a statistics Recorder
g.statistics.Recorder = g
}
return nil
}
// PublishStatistic Handles publishing statistics to Graphite over RabbitMQ
func (g *Graphite) PublishStatistic(name string, s *statistics.Statistic) {
// Get will be the latency
g.publish(name+".value", s.Value, s.Timestamp)
// Count the number of messages
g.publish(name+".count", s.Count, s.Timestamp)
// Min/Max latency values - don't send if max<min - i.e. no data!
if s.Max >= s.Min {
g.publish(name+".min", s.Min, s.Timestamp)
g.publish(name+".max", s.Max, s.Timestamp)
}
}
func (g *Graphite) publish(name string, val int64, ts int64) {
statName := name
if g.config.Graphite.Prefix != "" {
statName = g.config.Graphite.Prefix + "." + name
}
msg := fmt.Sprintf("%s %d %d", statName, val, ts)
_ = g.channel.Publish(
g.config.Graphite.Exchange,
statName,
false,
false,
amqp.Publishing{
Body: []byte(msg),
})
}