-
Notifications
You must be signed in to change notification settings - Fork 13
/
provider.go
375 lines (311 loc) · 10.2 KB
/
provider.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
package otel
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/go-kit/kit/metrics"
"github.com/go-kit/kit/metrics/generic"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/metric/global"
"go.opentelemetry.io/otel/metric/instrument"
"go.opentelemetry.io/otel/metric/instrument/asyncfloat64"
"go.opentelemetry.io/otel/metric/instrument/syncfloat64"
metricexport "go.opentelemetry.io/otel/sdk/export/metric"
"go.opentelemetry.io/otel/sdk/metric/aggregator/histogram"
metriccontroller "go.opentelemetry.io/otel/sdk/metric/controller/basic"
processor "go.opentelemetry.io/otel/sdk/metric/processor/basic"
"go.opentelemetry.io/otel/sdk/metric/selector/simple"
"go.opentelemetry.io/otel/sdk/resource"
xmetrics "github.com/heroku/x/go-kit/metrics"
"github.com/heroku/x/go-kit/metrics/provider/otel/selector/explicit"
)
var _ metrics.Counter = (*Counter)(nil)
var _ metrics.Gauge = (*Gauge)(nil)
var _ metrics.Histogram = (*Histogram)(nil)
const (
// The values of these attributes should be the service name.
serviceKey = "_service"
serviceNameKey = "service.name"
componentKey = "component"
// The "service.namespace" attribute should be the cloud/deploy (e.g. "va01").
serviceNamespaceKey = "service.namespace"
// The "service.instance.id" attribute will be an identifier for this specific instance of the service (e.g. "web.1").
serviceInstanceIDKey = "service.instance.id"
// The values of these attributes should be the stage (e.g. "production").
stageKey = "stage"
subserviceKey = "_subservice"
// The value of the "cloud" attribute should be the cloud (e.g. "heroku.com")
cloudKey = "cloud"
)
// Provider initializes a global otlp meter provider that can collect metrics and
// use a collector to push those metrics to various backends (e.g. Argus, Honeycomb).
// Initialize with New(...). An initialized Provider must be started before
// it can be used to provide a Meter (i.e. p.Start()).
type Provider struct {
ctx context.Context // used for init and shutdown of the otlp exporter and other bits of this Provider
serviceNameResource *resource.Resource
optionCache explicit.OptionCache
selector metricexport.AggregatorSelector
exporter *otlpmetric.Exporter
controller *metriccontroller.Controller
defaultTags []string
prefix string
collectPeriod time.Duration
mu sync.Mutex
counters map[string]*Counter
gauges map[string]*Gauge
histograms map[string]*Histogram
}
// New returns a new, unstarted Provider. Use its Start() method to start
// and establish a connection with its exporter's collector agent.
func New(ctx context.Context, serviceName string, opts ...Option) (xmetrics.Provider, error) {
p := Provider{
ctx: ctx,
counters: make(map[string]*Counter),
gauges: make(map[string]*Gauge),
histograms: make(map[string]*Histogram),
}
defaultOpts := []Option{
WithAttributes(
attribute.String(serviceKey, serviceName),
attribute.String(serviceNameKey, serviceName),
attribute.String(componentKey, serviceName),
),
WithDefaultAggregator(),
WithDefaultEndpointExporter(),
}
opts = append(defaultOpts, opts...)
for _, opt := range opts {
if err := opt(&p); err != nil {
return nil, fmt.Errorf("failed to apply options: %w", err)
}
}
// If not set, use default collect period.
if p.collectPeriod == 0 {
p.collectPeriod = metriccontroller.DefaultPeriod
}
// initialize the controller
p.controller = metriccontroller.New(
processor.NewFactory(simple.NewWithHistogramDistribution(), p.exporter),
metriccontroller.WithExporter(p.exporter),
metriccontroller.WithResource(p.serviceNameResource),
metriccontroller.WithCollectPeriod(p.collectPeriod),
)
global.SetMeterProvider(p.controller)
return &p, nil
}
// Start starts the provider's controller and exporter.
func (p *Provider) Start() error {
if err := p.controller.Start(p.ctx); err != nil {
return fmt.Errorf("failed to start controller: %w", err)
}
if err := p.exporter.Start(p.ctx); err != nil {
return fmt.Errorf("failed to start exporter: %w", err)
}
return nil
}
// Stop shuts down the provider's controller and exporter.
// It should be used to ensure the metrics provider drains all metrics before exiting the program.
func (p *Provider) Stop() {
_ = p.controller.Stop(p.ctx)
_ = p.exporter.Shutdown(p.ctx)
}
// Flush stops and starts the controller in order to flush metrics
// immediately, without having to wait until the next collection occurs.
// The flush is synchronous and returns an error if the controller fails to
// flush or cannot restart after flushing.
func (p *Provider) Flush() error {
if err := p.controller.Stop(p.ctx); err != nil {
return err
}
if err := p.controller.Start(p.ctx); err != nil {
return err
}
return nil
}
// Meter returns an oltp meter used for the creation of metric instruments.
// This relies on the Provider's controller having been properly initialized.
func (p *Provider) Meter(name string) metric.Meter {
m := global.Meter(name)
return m
}
// Counter is a counter.
type Counter struct {
syncfloat64.UpDownCounter
name string
labels []string
attributes []attribute.KeyValue
p *Provider
}
// Add implements metrics.Counter.
func (c *Counter) Add(delta float64) {
c.UpDownCounter.Add(c.p.ctx, delta, c.attributes...)
}
// With implements metrics.Counter.
func (c *Counter) With(labelValues ...string) metrics.Counter {
lvs := append(append([]string(nil), c.labels...), labelValues...)
return c.p.newCounter(c.name, lvs...)
}
// NewCounter creates a new Counter.
func (p *Provider) NewCounter(name string) metrics.Counter {
return p.newCounter(prefixName(p.prefix, name), p.defaultTags...)
}
func (p *Provider) newCounter(name string, labelValues ...string) metrics.Counter {
p.mu.Lock()
defer p.mu.Unlock()
k := keyName(name, labelValues...)
m := p.Meter(name)
if _, ok := p.counters[k]; !ok {
c, err := m.SyncFloat64().UpDownCounter(name)
if err != nil {
// TODO: handle error
}
p.counters[k] = &Counter{
UpDownCounter: c,
labels: labelValues,
attributes: makeAttributes(labelValues),
p: p,
name: name,
}
}
return p.counters[k]
}
// Gauge is a gauge.
type Gauge struct {
Gauge *generic.Gauge
observer asyncfloat64.Gauge
name string
labels []string
attributes []attribute.KeyValue
p *Provider
}
// NewGauge implements metrics.Provider.
func (p *Provider) NewGauge(name string) metrics.Gauge {
return p.newGauge(prefixName(p.prefix, name), p.defaultTags...)
}
func (p *Provider) newGauge(name string, labelValues ...string) metrics.Gauge {
p.mu.Lock()
defer p.mu.Unlock()
k := keyName(name, labelValues...)
m := p.Meter(name)
attributes := makeAttributes(labelValues)
if _, ok := p.gauges[k]; !ok {
gg := generic.NewGauge(name)
g, err := m.AsyncFloat64().Gauge(name)
if err != nil {
// TODO: handle error
}
m.RegisterCallback([]instrument.Asynchronous{g}, func(ctx context.Context) {
g.Observe(ctx, gg.Value())
})
p.gauges[k] = &Gauge{
Gauge: gg,
observer: g,
labels: labelValues,
attributes: attributes,
name: name,
p: p,
}
}
return p.gauges[k]
}
// With implements metrics.Gauge.
func (g *Gauge) With(labelValues ...string) metrics.Gauge {
lvs := append(append([]string(nil), g.labels...), labelValues...)
return g.p.newGauge(g.name, lvs...)
}
// Set implements metrics.Gauge.
func (g *Gauge) Set(value float64) {
g.Gauge.Set(value)
}
// Add implements metrics.Gauge.
func (g *Gauge) Add(delta float64) {
g.Gauge.Add(delta)
}
// Histogram is a histogram.
type Histogram struct {
syncfloat64.Histogram
name string
labels []string
attributes []attribute.KeyValue
p *Provider
}
func (p *Provider) NewExplicitHistogram(name string, fn xmetrics.DistributionFunc) metrics.Histogram {
boundaries := fn()
prefixedName := prefixName(p.prefix, name)
if p.optionCache != nil {
p.optionCache.Store(prefixedName, histogram.WithExplicitBoundaries(boundaries))
}
return p.newHistogram(prefixedName, p.defaultTags...)
}
// NewHistogram implements metrics.Provider.
func (p *Provider) NewHistogram(name string, _ int) metrics.Histogram {
return p.newHistogram(prefixName(p.prefix, name), p.defaultTags...)
}
func (p *Provider) newHistogram(name string, labelValues ...string) metrics.Histogram {
p.mu.Lock()
defer p.mu.Unlock()
k := keyName(name, labelValues...)
m := p.Meter(name)
if _, ok := p.histograms[k]; !ok {
h, err := m.SyncFloat64().Histogram(name)
if err != nil {
// TODO: handle error
}
p.histograms[k] = &Histogram{
Histogram: h,
name: name,
labels: labelValues,
attributes: makeAttributes(labelValues),
p: p,
}
}
return p.histograms[k]
}
// With implements metrics.Histogram.
func (h *Histogram) With(labelValues ...string) metrics.Histogram {
lvs := append(append([]string(nil), h.labels...), labelValues...)
return h.p.newHistogram(h.name, lvs...)
}
// Observe implements metrics.Histogram.
func (h *Histogram) Observe(value float64) {
h.Histogram.Record(h.p.ctx, value, h.attributes...)
}
// NewCardinalityCounter implements metrics.Provider.
func (p *Provider) NewCardinalityCounter(name string) xmetrics.CardinalityCounter {
return xmetrics.NewHLLCounter(name)
}
func prefixName(prefix, name string) string {
if prefix == "" {
return name
}
return prefix + "." + name
}
// keyName is used as the map key for counters, gauges, and histograms
// and incorporates the name and the labelValues.
func keyName(name string, labelValues ...string) string {
if len(labelValues) == 0 {
return name
}
l := len(labelValues)
parts := make([]string, 0, l/2)
for i := 0; i < l; i += 2 {
parts = append(parts, labelValues[i]+":"+labelValues[i+1])
}
return name + "." + strings.Join(parts, ".")
}
// makeAttributes is used to convert labels into attribute.KeyValues.
func makeAttributes(labels []string) (attributes []attribute.KeyValue) {
attributes = make([]attribute.KeyValue, len(labels))
if len(labels)%2 != 0 {
labels = append(labels, "unknown")
}
for i := 0; i < len(labels); i += 2 {
attributes = append(attributes, attribute.String(labels[i], labels[i+1]))
}
return
}