forked from segmentio/analytics-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
report.go
298 lines (266 loc) · 7.06 KB
/
report.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package analytics
import (
"fmt"
"io"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/avast/retry-go"
metrics "github.com/rcrowley/go-metrics"
datadog "github.com/zorkian/go-datadog-api"
)
// Reporter provides a function to reporting metrics.
type Reporter interface {
Report(metricName string, value interface{}, tags []string, ts time.Time)
Flush() error
AddTags(tags ...string)
}
func splitTags(name string) (string, []string) {
tokens := strings.Split(name, ".")
if len(tokens) <= 1 {
return name, []string{}
}
names := []string{}
tags := []string{}
for _, token := range tokens {
if strings.Contains(token, ":") {
tags = append(tags, token)
} else {
names = append(names, token)
}
}
return strings.Join(names, "."), tags
}
func (c *client) reportAll(prefix string, reporters []Reporter) {
if len(reporters) == 0 {
return
}
ts := time.Now()
metrics := c.metricsRegistry.GetAll()
go func() {
for key, metric := range metrics {
for measure, value := range metric {
name, tags := splitTags(key)
name = prefix + "." + name
for _, r := range reporters {
r.Report(name+"."+measure, value, tags, ts)
}
}
}
for _, r := range reporters {
if err := r.Flush(); err != nil {
c.Config.Logger.Errorf("flush failed for reporter %s: %s", r, err)
}
}
}()
}
var hostname = func() string {
h, err := os.Hostname()
if err != nil {
return "localhost"
}
return h
}()
// DiscardReporter discards all metrics, useful for tests.
type DiscardReporter struct{}
// Report reports metrics.
func (r DiscardReporter) Report(metricName string, value interface{}, tags []string, ts time.Time) {}
// AddTags adds tags to be added to each metric reported.
func (r *DiscardReporter) AddTags(tags ...string) {}
// Flush flushes reported metrics.
func (r *DiscardReporter) Flush() error { return nil }
// LogReporter report metrics as a log.
type LogReporter struct {
logger Logger
tags []string
}
// NewLogReporter returns new log repoter ready to use.
func NewLogReporter(l ...Logger) *LogReporter {
if len(l) == 0 {
l = []Logger{newDefaultLogger()}
}
return &LogReporter{
logger: l[0],
tags: []string{},
}
}
// Report reports metrics.
func (r LogReporter) Report(metricName string, value interface{}, tags []string, ts time.Time) {
allTags := append(tags, r.tags...)
r.logger.Logf("%s[%s] = %v", metricName, strings.Join(allTags, ", "), value)
}
// Flush flushes reported metrics.
func (r *LogReporter) Flush() error { return nil }
// AddTags adds tags to be added to each metric reported.
func (r *LogReporter) AddTags(tags ...string) {
r.tags = append(r.tags, tags...)
}
func newHTTPTransport() *http.Transport {
return &http.Transport{
DisableKeepAlives: true,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 30 * time.Second,
}
}
// NewDatadogReporter is a factory method to create Datadog reporter
// with sane defaults.
func NewDatadogReporter(apiKey, appKey string, tags ...string) *DatadogReporter {
dr := DatadogReporter{
Client: datadog.NewClient(apiKey, appKey),
}
dr.Client.HttpClient = &http.Client{
Timeout: time.Second * 30,
Transport: newHTTPTransport(),
}
dr.logger = newDefaultLogger()
dr.tags = append(tags, "transport:http", "sdkversion:go-"+Version)
return &dr
}
// WithLogger sets logger to DatadogReporter.
func (dd *DatadogReporter) WithLogger(logger Logger) *DatadogReporter {
dd.logger = logger
return dd
}
// DatadogReporter reports metrics to DataDog.
type DatadogReporter struct {
Client *datadog.Client
logger Logger
metrics []datadog.Metric
tags []string
sync.Mutex
}
// AddTags adds tags to be added to each metric reported.
func (dd *DatadogReporter) AddTags(tags ...string) {
dd.Lock()
defer dd.Unlock()
dd.tags = append(dd.tags, tags...)
}
// Flush flushes reported metrics.
func (dd *DatadogReporter) Flush() error {
dd.Lock()
metrics := dd.metrics
dd.metrics = []datadog.Metric{}
dd.Unlock()
err := retry.Do(
func() error {
return dd.Client.PostMetrics(metrics)
},
retry.OnRetry(func(iteration uint, err error) {
dd.logger.Errorf("Reporting metrics failed for the %d time: %s", iteration, err)
}),
retry.RetryIf(func(err error) bool {
if err == io.EOF {
dd.Client.HttpClient.Transport = newHTTPTransport()
return true
}
return false
}),
)
if err != nil {
return fmt.Errorf("submission metrics to DataDog failed for the last time, metrics are gone: %s", err)
}
return nil
}
// Report sends provided metric to Datadog.
func (dd *DatadogReporter) Report(metricName string, value interface{}, tags []string, ts time.Time) {
metricType := "gauge"
metricValue, err := func() (float64, error) {
switch v := value.(type) {
case float64:
return v, nil
case int64:
return float64(v), nil
case int:
return float64(v), nil
}
return 0, fmt.Errorf("can't handle value %+v", value)
}()
if err != nil {
dd.logger.Errorf("Serializing value for metric %s(%+v) failed: %s", metricName, value, err)
return
}
metricTimestamp := float64(ts.Truncate(time.Minute).Unix())
allTags := append(tags, "hostname:"+hostname)
allTags = append(allTags, dd.tags...)
metric := datadog.Metric{
Metric: &metricName,
Type: &metricType,
Tags: allTags,
Points: []datadog.DataPoint{{&metricTimestamp, &metricValue}},
}
dd.Lock()
dd.metrics = append(dd.metrics, metric)
dd.Unlock()
}
func (c *client) resetMetrics() {
ms := c.metricsRegistry.GetAll()
for name := range ms {
metric := c.metricsRegistry.Get(name)
switch m := metric.(type) {
case metrics.Counter:
m.Clear()
case metrics.Gauge:
m.Update(0)
case metrics.Histogram:
// do nothing as Histogram has it's own internal cleanup
}
}
}
type countersFunc func(tags ...string) metrics.Counter
// newCounters returns factory for tagged counters.
func (c *client) newCounters(name string) countersFunc {
counters := make(map[string]metrics.Counter)
mu := &sync.Mutex{}
return func(tags ...string) metrics.Counter {
fullName := strings.Join(append([]string{name}, tags...), ".")
mu.Lock()
defer mu.Unlock()
counter, ok := counters[fullName]
if !ok {
counter = c.metricsRegistry.GetOrRegister(
fullName,
metrics.NewCounter(),
).(metrics.Counter)
counters[fullName] = counter
}
return counter
}
}
func (c *client) loopMetrics() {
var reporters = c.Config.Reporters
if len(reporters) == 0 {
c.Logger.Logf("No reporters are configured, metrics won't be reported")
}
ep := strings.Split(c.Config.Endpoint, "/")
enrichReporter := func(reporter Reporter) {
reporter.AddTags(
"key:"+fmt.Sprintf("%.6s", c.key),
"endpoint:"+fmt.Sprintf("%.9s", ep[len(ep)-1]),
)
if ctx := c.Config.DefaultContext; ctx != nil {
if app := ctx.App.Name; app != "" {
reporter.AddTags("app:" + app)
}
if version := ctx.App.Version; version != "" {
reporter.AddTags("appversion:" + version)
}
}
}
for _, reporter := range reporters {
enrichReporter(reporter)
}
for {
select {
case <-c.quit:
return
case <-time.Tick(60 * time.Second):
c.reportAll("evas.events", reporters)
c.resetMetrics()
}
}
}