-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
212 lines (190 loc) · 4.93 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package main
import (
"context"
"flag"
"fmt"
"log"
"math"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/mackerelio/mackerel-client-go"
"github.com/mackerelio-labs/mackerel-statsd/metricname"
"github.com/mackerelio-labs/mackerel-statsd/parser"
"github.com/mackerelio-labs/mackerel-statsd/statsd"
)
// Sink is a destination to collect- and to flush-metrics.
type Sink struct {
// key is metric name.
counterValues map[string]float64
counterLock sync.RWMutex
// key is metric name.
timerValues map[string][]float64
timerLock sync.RWMutex
}
func NewSink() *Sink {
return &Sink{
counterValues: make(map[string]float64),
timerValues: make(map[string][]float64),
}
}
var sink = NewSink()
func (s *Sink) AppendValue(m *parser.Metric) {
switch m.Type {
case parser.TypeCounter:
s.counterLock.Lock()
s.counterValues[m.Name] += m.Value / m.SamplingRate
s.counterLock.Unlock()
case parser.TypeTimer:
s.timerLock.Lock()
v := m.Value / 1000 // milliseconds to seconds
s.timerValues[m.Name] = append(s.timerValues[m.Name], v/m.SamplingRate)
s.timerLock.Unlock()
}
}
func (s *Sink) FlushCounterValue() []*mackerel.MetricValue {
s.counterLock.Lock()
metrics := make([]*mackerel.MetricValue, 0, len(s.counterValues))
for k, v := range s.counterValues {
metrics = append(metrics, &mackerel.MetricValue{
Name: k,
Value: v,
Time: time.Now().Unix(),
})
s.counterValues[k] = 0
}
s.counterLock.Unlock()
return metrics
}
func CalculateStatistics(values []float64) (min, max, average, p50, p95, p99 float64) {
if len(values) == 0 {
return
}
max = 0.0
min = math.Inf(1)
sum := 0.0
for _, v := range values {
max = math.Max(max, v)
min = math.Min(min, v)
sum += v
}
average = sum / float64(len(values))
// TODO: implement percentile support
return
}
func (s *Sink) FlushTimerValue() []*mackerel.MetricValue {
now := time.Now().Unix()
s.timerLock.Lock()
metrics := make([]*mackerel.MetricValue, 0, len(s.timerValues)*6)
for name, values := range s.timerValues {
min, max, average, _, _, _ := CalculateStatistics(values)
metrics = append(metrics, &mackerel.MetricValue{
Name: metricname.Join(name, "min"),
Value: min,
Time: now,
})
metrics = append(metrics, &mackerel.MetricValue{
Name: metricname.Join(name, "max"),
Value: max,
Time: now,
})
metrics = append(metrics, &mackerel.MetricValue{
Name: metricname.Join(name, "average"),
Value: average,
Time: now,
})
s.timerValues[name] = nil
}
s.timerLock.Unlock()
return metrics
}
type Exporter struct {
metricNames map[string]struct{}
}
type MackerelClient interface {
PostHostMetricValuesByHostID(hostID string, values []*mackerel.MetricValue) error
CreateGraphDefs(params []*mackerel.GraphDefsParam) error
}
func (e *Exporter) ExportMetrics(s *Sink, hostID string, client MackerelClient) error {
if e.metricNames == nil {
e.metricNames = make(map[string]struct{})
}
counterMetrics := s.FlushCounterValue()
timerMetrics := s.FlushTimerValue()
var metrics []*mackerel.MetricValue
metrics = append(metrics, counterMetrics...)
metrics = append(metrics, timerMetrics...)
for _, m := range timerMetrics {
name := metricname.Group(m.Name)
if _, ok := e.metricNames[name]; !ok {
log.Printf("creating graphDefs: %s\n", name)
err := client.CreateGraphDefs([]*mackerel.GraphDefsParam{
{
Name: name,
Unit: "seconds",
Metrics: []*mackerel.GraphDefsMetric{
{Name: metricname.Join(name, "*"), DisplayName: "%1"},
},
},
})
if err != nil {
log.Printf("creating graphdDefs: %s failed: %v\n", name, err)
continue
}
}
e.metricNames[name] = struct{}{}
}
log.Printf("post %d metrics\n", len(metrics))
if len(metrics) > 0 {
err := client.PostHostMetricValuesByHostID(hostID, metrics)
if err != nil {
return err
}
}
return nil
}
var (
flagInterval = flag.Duration("interval", 60*time.Second, "flush interval")
flagHostID = flag.String("host", "", "Post host metric values to <`hostID`>")
flagAddr = flag.String("addr", ":8125", "`addr`ess to listen")
)
func main() {
flag.Parse()
hostID := *flagHostID
if hostID == "" {
log.Fatalln("must specify -host")
}
apiKey := os.Getenv("MACKEREL_APIKEY")
if apiKey == "" {
log.Fatalln("must set MACKEREL_APIKEY")
}
client := mackerel.NewClient(apiKey)
ticker := time.NewTicker(*flagInterval)
defer ticker.Stop()
var e Exporter
go func() {
for {
select {
case <-ticker.C:
err := e.ExportMetrics(sink, hostID, client)
if err != nil {
// TODO: retry
log.Println(err)
}
}
}
}()
var server statsd.Server
server.Error = func(err error) {
log.Println(err)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)
defer stop()
server.ListenAndServe(ctx, *flagAddr, func(addr string, m *parser.Metric) error {
sink.AppendValue(m)
fmt.Printf("From: %v Receiving metric: %+v\n", addr, m.Value)
return nil
})
}