-
Notifications
You must be signed in to change notification settings - Fork 18
/
otel.go
323 lines (270 loc) · 7.84 KB
/
otel.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
// Package otel contains an o11y.Provider that emits open telemetry gRPC.
// N.B. This has not been tried against a production collector, so we need to
// try it out on a safe / non production traffic service.
package otel
import (
"context"
"fmt"
"os"
"strings"
"sync"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.12.0"
"go.opentelemetry.io/otel/trace"
"github.com/circleci/ex/o11y"
"github.com/circleci/ex/o11y/otel/texttrace"
)
type Config struct {
Dataset string
GrpcHostAndPort string
ResourceAttributes []attribute.KeyValue
SampleTraces bool
SampleKeyFunc func(map[string]any) string
SampleRates map[string]uint
Metrics o11y.ClosableMetricsProvider
}
type Provider struct {
metricsProvider o11y.ClosableMetricsProvider
tracer trace.Tracer
tp *sdktrace.TracerProvider
}
func New(conf Config) (o11y.Provider, error) {
var exporter sdktrace.SpanExporter
exporter, err := texttrace.New(os.Stdout)
if err != nil {
return nil, err
}
if conf.GrpcHostAndPort != "" {
grpc, err := newGRPC(context.Background(), conf.GrpcHostAndPort, conf.Dataset)
if err != nil {
return nil, err
}
var sampler *deterministicSampler
if conf.SampleTraces {
sampler = &deterministicSampler{
sampleKeyFunc: conf.SampleKeyFunc,
sampleRates: conf.SampleRates,
}
}
// use gRPC and text - mainly so sampled out spans still make it to logs
exporter = multipleExporter{
exporters: []sdktrace.SpanExporter{
exporter,
grpc,
},
sampler: sampler,
}
}
tp := traceProvider(exporter, conf)
// set the global options
otel.SetTracerProvider(tp)
propagator := propagation.NewCompositeTextMapPropagator(propagation.Baggage{}, propagation.TraceContext{})
otel.SetTextMapPropagator(propagator)
// TODO check baggage is wired up above
return &Provider{
metricsProvider: conf.Metrics,
tp: tp,
tracer: otel.Tracer(""),
}, nil
}
func traceProvider(exporter sdktrace.SpanExporter, conf Config) *sdktrace.TracerProvider {
ra := append([]attribute.KeyValue{
attribute.String("x-honeycomb-dataset", conf.Dataset),
}, conf.ResourceAttributes...)
res := resource.NewWithAttributes(semconv.SchemaURL, ra...)
bsp := sdktrace.NewBatchSpanProcessor(exporter)
traceOptions := []sdktrace.TracerProviderOption{
sdktrace.WithSpanProcessor(bsp),
// N.B. must pass in the address here since we need to see later mutations
sdktrace.WithSpanProcessor(&globalFields),
sdktrace.WithResource(res),
}
return sdktrace.NewTracerProvider(traceOptions...)
}
func newGRPC(ctx context.Context, endpoint, dataset string) (*otlptrace.Exporter, error) {
opts := []otlptracegrpc.Option{
otlptracegrpc.WithEndpoint(endpoint),
otlptracegrpc.WithInsecure(),
// This header may be used by honeycomb ingestion pathways in the future, but
// it is not currently needed for how the collectors are currently set up, which
// expect a resource attribute instead.
otlptracegrpc.WithHeaders(map[string]string{"x-honeycomb-dataset": dataset}),
}
return otlptrace.New(ctx, otlptracegrpc.NewClient(opts...))
}
type spanCtxKey struct{}
// RawProvider satisfies an interface the helpers need
func (o *Provider) RawProvider() *Provider {
return o
}
func (o Provider) AddGlobalField(key string, val any) {
mustValidateKey(key)
globalFields.addField(key, val)
}
func (o Provider) StartSpan(ctx context.Context, name string) (context.Context, o11y.Span) {
ctx, span := o.tracer.Start(ctx, name)
s := o.wrapSpan(span)
if s != nil {
ctx = context.WithValue(ctx, spanCtxKey{}, s)
}
return ctx, s
}
// GetSpan returns the active span in the given context. It will return nil if there is no span available.
func (o Provider) GetSpan(ctx context.Context) o11y.Span {
if s, ok := ctx.Value(spanCtxKey{}).(*span); ok {
return s
}
return nil
}
func (o Provider) AddField(ctx context.Context, key string, val any) {
s := o.GetSpan(ctx)
if s != nil {
s.AddField(key, val)
}
}
func (o Provider) AddFieldToTrace(ctx context.Context, key string, val any) {
// TODO - some equivalent to adding this field to all child spans to the root span
o.AddField(ctx, key, val)
}
func (o Provider) Log(ctx context.Context, name string, fields ...o11y.Pair) {
// TODO Log
}
func (o Provider) Close(ctx context.Context) {
// TODO Handle these errors in a sensible manner where possible
_ = o.tp.Shutdown(ctx)
if o.metricsProvider != nil {
_ = o.metricsProvider.Close()
}
}
func (o Provider) MetricsProvider() o11y.MetricsProvider {
return o.metricsProvider
}
func (o Provider) Helpers(disableW3c ...bool) o11y.Helpers {
d := false
if len(disableW3c) > 0 {
d = disableW3c[0]
}
return helpers{
p: o,
disableW3c: d,
}
}
func (o Provider) wrapSpan(s trace.Span) *span {
if s == nil {
return nil
}
return &span{
metricsProvider: o.metricsProvider,
span: s,
start: time.Now(),
fields: map[string]any{},
}
}
type span struct {
span trace.Span
metrics []o11y.Metric
metricsProvider o11y.ClosableMetricsProvider
start time.Time
mu sync.RWMutex // mu is a write mutex for the map below (concurrent reads are safe)
fields map[string]any
}
func (s *span) AddField(key string, val any) {
s.AddRawField("app."+key, val)
}
func (s *span) AddRawField(key string, val any) {
mustValidateKey(key)
s.mu.Lock()
s.fields[key] = val
s.mu.Unlock()
if err, ok := val.(error); ok {
// s.span.RecordError() TODO - maybe this
val = err.Error()
}
// Use otel SetName if we are overriding the name attribute
// TODO - should we set the name attribute as well
if key == "name" {
if v, ok := val.(string); ok {
s.span.SetName(v)
}
}
s.span.SetAttributes(attr(key, val))
}
// RecordMetric will only emit a metric if End is called specifically
func (s *span) RecordMetric(metric o11y.Metric) {
s.metrics = append(s.metrics, metric)
}
func (s *span) End() {
// insert the expected field for any timing metric
s.mu.Lock()
s.fields["duration_ms"] = time.Since(s.start) / time.Millisecond
s.mu.Unlock()
s.sendMetric()
s.span.End()
}
func (s *span) sendMetric() {
if s.metricsProvider == nil {
return
}
extractAndSendMetrics(s.metricsProvider)(s.metrics, s.snapshotFields())
}
func (s *span) snapshotFields() map[string]any {
res := map[string]any{}
s.mu.RLock()
defer s.mu.RUnlock()
for k, v := range s.fields {
res[k] = v
}
return res
}
func mustValidateKey(key string) {
if strings.Contains(key, "-") {
panic(fmt.Errorf("key %q cannot contain '-'", key))
}
}
type multipleExporter struct {
exporters []sdktrace.SpanExporter
sampler *deterministicSampler
}
func (m multipleExporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error {
spans = m.sampleSpans(spans)
for _, e := range m.exporters {
if err := e.ExportSpans(ctx, spans); err != nil {
return err
}
}
return nil
}
func (m multipleExporter) Shutdown(ctx context.Context) error {
for _, e := range m.exporters {
if err := e.Shutdown(ctx); err != nil {
return err
}
}
return nil
}
func (m multipleExporter) sampleSpans(spans []sdktrace.ReadOnlySpan) []sdktrace.ReadOnlySpan {
if m.sampler == nil {
return spans
}
ss := make([]sdktrace.ReadOnlySpan, 0, len(spans))
for _, s := range spans {
if ok, rate := m.sampler.shouldSample(s); ok {
ss = append(ss, sampleRateSpan{ReadOnlySpan: s, rate: rate})
}
}
return ss
}
type sampleRateSpan struct {
sdktrace.ReadOnlySpan
rate uint
}
func (s sampleRateSpan) Attributes() []attribute.KeyValue {
return append(s.ReadOnlySpan.Attributes(), attribute.Int("sample_rate", int(s.rate)))
}