This repository has been archived by the owner on Mar 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexporter.go
397 lines (353 loc) · 10.5 KB
/
exporter.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package mackerel
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"go.opentelemetry.io/otel/api/global"
"go.opentelemetry.io/otel/api/metric"
"go.opentelemetry.io/otel/label"
export "go.opentelemetry.io/otel/sdk/export/metric"
"go.opentelemetry.io/otel/sdk/export/metric/aggregation"
"go.opentelemetry.io/otel/sdk/metric/controller/push"
processor "go.opentelemetry.io/otel/sdk/metric/processor/basic"
"go.opentelemetry.io/otel/sdk/metric/selector/simple"
"go.opentelemetry.io/otel/sdk/resource"
"github.com/mackerelio-labs/mackerelexporter-go/internal/graphdef"
"github.com/mackerelio-labs/mackerelexporter-go/internal/metricname"
"github.com/mackerelio-labs/mackerelexporter-go/internal/tag"
"github.com/mackerelio/mackerel-client-go"
)
// InstallNewPipeline instantiates a NewExportPipeline and registers it globally.
func InstallNewPipeline(opts ...Option) (*push.Controller, http.HandlerFunc, error) {
pusher, handler, err := NewExportPipeline(opts...)
if err != nil {
return nil, nil, err
}
global.SetMeterProvider(pusher.MeterProvider())
return pusher, handler, err
}
// NewExportPipeline sets up a complete export pipeline.
func NewExportPipeline(opts ...Option) (*push.Controller, http.HandlerFunc, error) {
// There are few types in simple; inexpensive, sketch, exact.
s := simple.NewWithExactDistribution()
exporter, err := NewExporter(opts...)
if err != nil {
return nil, nil, err
}
var o []push.Option
o = append(o, push.WithPeriod(time.Minute))
if len(exporter.opts.Tags) > 0 {
res := resource.New(exporter.opts.Tags...)
o = append(o, push.WithResource(res))
}
p := processor.New(s, exporter)
pusher := push.New(p, exporter, o...)
pusher.Start()
if h, _ := exporter.c.(http.Handler); h != nil {
return pusher, h.ServeHTTP, nil
}
return pusher, nil, nil
}
// Option is function type that is passed to NewExporter function.
type Option func(*options)
type options struct {
APIKey string
Quantiles []float64
Hints []string
BaseURL *url.URL
Tags []label.KeyValue
Debug bool
}
// WithAPIKey sets the Mackerel API Key.
func WithAPIKey(apiKey string) Option {
return func(o *options) {
o.APIKey = apiKey
}
}
// WithQuantiles sets quantiles for recording measure metrics.
// Each quantiles must be unique and its precision must be greater or equal than 0.01.
func WithQuantiles(quantiles []float64) Option {
for _, q := range quantiles {
if q < 0.0 || q > 1.0 {
panic(aggregation.ErrInvalidQuantile)
}
}
return func(o *options) {
o.Quantiles = quantiles
}
}
// WithHints sets hints for decision the name of the Graph Definition.
func WithHints(hints []string) Option {
return func(o *options) {
o.Hints = hints
}
}
// WithBaseURL sets base URL for Mackerel API.
func WithBaseURL(baseURL *url.URL) Option {
return func(o *options) {
o.BaseURL = baseURL
}
}
// WithResource sets resource tags.
func WithResource(tags ...label.KeyValue) Option {
return func(o *options) {
o.Tags = tags
}
}
// WithDebug enables logs for debugging.
func WithDebug() Option {
return func(o *options) {
o.Debug = true
}
}
type mackerelClient interface {
FindServices() ([]*mackerel.Service, error)
CreateService(param *mackerel.CreateServiceParam) (*mackerel.Service, error)
FindRoles(serviceName string) ([]*mackerel.Role, error)
CreateRole(serviceName string, param *mackerel.CreateRoleParam) (*mackerel.Role, error)
FindHosts(param *mackerel.FindHostsParam) ([]*mackerel.Host, error)
CreateHost(param *mackerel.CreateHostParam) (string, error)
UpdateHost(hostID string, param *mackerel.UpdateHostParam) (string, error)
CreateGraphDefs(defs []*mackerel.GraphDefsParam) error
PostHostMetricValues(metrics []*mackerel.HostMetricValue) error
PostServiceMetricValues(name string, metrics []*mackerel.MetricValue) error
}
// Exporter is a stats exporter that uploads data to Mackerel.
type Exporter struct {
c mackerelClient
opts *options
hosts map[string]string // value is Mackerel's host ID
serviceRoles map[string]map[string]struct{}
graphDefs map[string]*mackerel.GraphDefsParam
graphMetricDefs map[string]struct{}
}
var _ export.Exporter = &Exporter{}
// NewExporter creates a new Exporter.
func NewExporter(opts ...Option) (*Exporter, error) {
var o options
for _, opt := range opts {
opt(&o)
}
if o.Quantiles == nil {
// This values equal to stdout exporter's values
o.Quantiles = []float64{0.5, 0.9, 0.99}
}
var c mackerelClient = &handlerClient{}
if o.APIKey != "" {
p := mackerel.NewClient(o.APIKey)
if o.BaseURL != nil {
p.BaseURL = o.BaseURL
}
p.Verbose = o.Debug
c = p
}
// TODO(lufia): Should I use pull.Controller?
// see https://github.com/open-telemetry/opentelemetry-go/pull/751
return &Exporter{
c: c,
opts: &o,
hosts: make(map[string]string),
serviceRoles: make(map[string]map[string]struct{}),
graphDefs: make(map[string]*mackerel.GraphDefsParam),
graphMetricDefs: make(map[string]struct{}),
}, nil
}
// ExportKindFor implements ExportKindSelector.
func (e *Exporter) ExportKindFor(*metric.Descriptor, aggregation.Kind) export.ExportKind {
// TODO: Should we determine ExportKind using arguments?
return export.DeltaExporter
}
type (
registration struct {
res *tag.Resource
graphDef *mackerel.GraphDefsParam
metrics []*mackerel.MetricValue
}
customIdentifier string
serviceName string
)
// Export exports the provide metric record to Mackerel.
func (e *Exporter) Export(ctx context.Context, a export.CheckpointSet) error {
var regs []*registration
a.ForEach(e, func(r export.Record) error {
reg, err := e.convertToRegistration(r, r.Resource())
if err != nil {
return err
}
regs = append(regs, reg)
return nil
})
var (
hostMetrics []*mackerel.HostMetricValue
serviceMetrics = make(map[string][]*mackerel.MetricValue)
graphDefs = make(map[string]*mackerel.GraphDefsParam)
)
for _, reg := range regs {
switch t := metricType(reg.res); s := t.(type) {
case customIdentifier:
id := string(s)
if _, ok := e.hosts[id]; !ok {
h, err := e.upsertHost(reg.res)
if err != nil {
return err
}
e.hosts[id] = h
}
hostID := e.hosts[id]
for _, m := range reg.metrics {
hostMetrics = append(hostMetrics, &mackerel.HostMetricValue{
HostID: hostID,
MetricValue: m,
})
}
case serviceName:
name := string(s)
if err := e.registerService(name); err != nil {
return err
}
serviceMetrics[name] = append(serviceMetrics[name], reg.metrics...)
default:
continue
}
if reg.graphDef != nil {
for _, m := range reg.graphDef.Metrics {
if _, ok := e.graphMetricDefs[m.Name]; ok {
// A graph is already registered; not need registration.
continue
}
if g, ok := graphDefs[reg.graphDef.Name]; ok {
g.Metrics = append(g.Metrics, m)
} else {
graphDefs[reg.graphDef.Name] = reg.graphDef
}
}
}
}
var defs []*mackerel.GraphDefsParam
for _, d := range graphDefs {
defs = append(defs, d)
}
if len(defs) > 0 {
if err := e.c.CreateGraphDefs(defs); err != nil {
return fmt.Errorf("can't create graph-defs: %w", err)
}
e.mergeGraphDefs(graphDefs)
}
if len(hostMetrics) > 0 {
if err := e.c.PostHostMetricValues(hostMetrics); err != nil {
return fmt.Errorf("can't post host metrics: %w", err)
}
}
for s, a := range serviceMetrics {
if err := e.c.PostServiceMetricValues(s, a); err != nil {
return fmt.Errorf("can't post service metrics: %w", err)
}
}
return nil
}
func metricType(res *tag.Resource) interface{} {
if s := res.CustomIdentifier(); s != "" {
return customIdentifier(s)
}
if s := res.ServiceName(); s != "" {
return serviceName(s)
}
return nil
}
func (e *Exporter) mergeGraphDefs(defs map[string]*mackerel.GraphDefsParam) {
for k, v := range defs {
if p, ok := e.graphDefs[k]; ok {
p.Metrics = append(p.Metrics, v.Metrics...)
} else {
e.graphDefs[k] = v
}
for _, m := range v.Metrics {
e.graphMetricDefs[m.Name] = struct{}{}
}
}
}
func (e *Exporter) convertToRegistration(r export.Record, res *resource.Resource) (*registration, error) {
var reg registration
desc := r.Descriptor()
kind := desc.NumberKind()
var t tag.Resource
labels := append(r.Labels().ToSlice(), res.Attributes()...)
if err := tag.UnmarshalTags(labels, &t); err != nil {
return nil, err
}
reg.res = &t
// TODO(lufia): Enforce the metric to be the custom metric if hint is exist
name := metricname.Canonical(desc.Name())
hint := e.lookupHint(desc.Name())
aggr := r.Aggregation()
reg.metrics = e.metricValues(name, aggr, kind)
if !strings.HasPrefix(name, "custom.") {
return ®, nil
}
opts := graphdef.Options{
Name: hint,
Unit: desc.Unit(),
Kind: kind,
Quantiles: e.opts.Quantiles,
}
g, err := graphdef.New(name, desc.MetricKind(), opts)
if err != nil {
return nil, err
}
reg.graphDef = g
return ®, nil
}
func (e *Exporter) lookupHint(name string) string {
for _, s := range e.opts.Hints {
if metricname.Match(name, s) {
return metricname.Canonical(s)
}
}
return ""
}
func (e *Exporter) metricValues(name string, aggr aggregation.Aggregation, kind metric.NumberKind) []*mackerel.MetricValue {
var a []*mackerel.MetricValue
// see https://github.com/open-telemetry/opentelemetry-go/blob/master/sdk/metric/selector/simple/simple.go
if p, ok := aggr.(aggregation.Distribution); ok {
// metric.Value{Record|Obserb}erKind: MinMaxSumCount, Distribution, Points
if min, err := p.Min(); err == nil {
a = append(a, metricValue(metricname.Join(name, "min"), min.AsInterface(kind)))
}
if max, err := p.Max(); err == nil {
a = append(a, metricValue(metricname.Join(name, "max"), max.AsInterface(kind)))
}
for _, quantile := range e.opts.Quantiles {
q, err := p.Quantile(quantile)
if err != nil {
continue
}
qname := metricname.Percentile(quantile)
a = append(a, metricValue(metricname.Join(name, qname), q.AsInterface(kind)))
}
} else if p, ok := aggr.(aggregation.LastValue); ok {
// Where this aggregator is used in?
if last, _, err := p.LastValue(); err == nil {
a = append(a, metricValue(name, last.AsInterface(kind)))
}
} else if p, ok := aggr.(aggregation.Sum); ok {
// metric.CounterKind, etc: Sum
if sum, err := p.Sum(); err == nil {
a = append(a, metricValue(name, sum.AsInterface(kind)))
}
}
return a
}
func metricValue(name string, v interface{}) *mackerel.MetricValue {
return &mackerel.MetricValue{
Name: name,
Time: time.Now().Unix(),
Value: v,
}
}
func (e *Exporter) Handler() http.Handler {
h, _ := e.c.(http.Handler)
return h
}