forked from grafana/alloy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracing.go
More file actions
215 lines (177 loc) · 6.23 KB
/
tracing.go
File metadata and controls
215 lines (177 loc) · 6.23 KB
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
// Package tracing implements the tracing subsystem of Grafana Alloy. The
// tracing subsystem exposes a [trace.TraceProvider] which accepts traces and
// forwards them to a running component for further processing.
package tracing
import (
"context"
"sync"
"time"
"github.com/grafana/alloy/internal/build"
"github.com/grafana/alloy/internal/component/otelcol"
"github.com/grafana/alloy/internal/runtime/tracing/internal/jaegerremote"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
tracesdk "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
"go.opentelemetry.io/otel/trace"
)
const serviceName = "alloy"
// Defaults for all Options structs.
var (
DefaultOptions = Options{
SamplingFraction: 0.1, // Keep 10% of spans
WriteTo: []otelcol.Consumer{}, // Don't send spans anywhere.
SendTraceparent: false,
}
DefaultJaegerRemoteSamplerOptions = JaegerRemoteSamplerOptions{
URL: "http://127.0.0.1:5778/sampling",
MaxOperations: 256,
RefreshInterval: time.Minute,
}
)
// Options control the tracing subsystem.
type Options struct {
// SamplingFraction determines which rate of traces to sample. A value of 1
// means to keep 100% of traces. A value of 0 means to keep 0% of traces.
SamplingFraction float64 `alloy:"sampling_fraction,attr,optional"`
SendTraceparent bool `alloy:"send_traceparent,attr,optional"`
// Sampler holds optional samplers to configure on top of the sampling
// fraction.
Sampler SamplerOptions `alloy:"sampler,block,optional"`
// WriteTo holds a set of OpenTelemetry Collector consumers where internal
// traces should be sent.
WriteTo []otelcol.Consumer `alloy:"write_to,attr,optional"`
}
type SamplerOptions struct {
JaegerRemote *JaegerRemoteSamplerOptions `alloy:"jaeger_remote,block,optional"`
// TODO(rfratto): if support for another sampler is added, SamplerOptions
// must enforce that only one inner block is provided.
}
type JaegerRemoteSamplerOptions struct {
URL string `alloy:"url,attr,optional"`
MaxOperations int `alloy:"max_operations,attr,optional"`
RefreshInterval time.Duration `alloy:"refresh_interval,attr,optional"`
}
// SetToDefault implements syntax.Defaulter.
func (opts *Options) SetToDefault() {
*opts = DefaultOptions
}
// SetToDefault implements syntax.Defaulter.
func (opts *JaegerRemoteSamplerOptions) SetToDefault() {
*opts = DefaultJaegerRemoteSamplerOptions
}
// Tracer is the tracing subsystem of Grafana Alloy. It implements
// [trace.TracerProvider] and can be used to forward internally generated
// traces to a OpenTelemetry Collector-compatible Alloy component.
type Tracer struct {
trace.TracerProvider
sampler *lazySampler
client *client
exp *otlptrace.Exporter
tp *tracesdk.TracerProvider
samplerMut sync.Mutex
jaegerRemoteSampler *jaegerremote.Sampler // In-use jaeger remote sampler (may be nil).
}
var _ trace.TracerProvider = (*Tracer)(nil)
// New creates a new tracing subsystem. Call Run to start the tracing
// subsystem.
func New(cfg Options) (*Tracer, error) {
res, err := resource.New(
context.Background(),
resource.WithSchemaURL(semconv.SchemaURL),
resource.WithAttributes(
semconv.ServiceNameKey.String(serviceName),
semconv.ServiceVersionKey.String(build.Version),
),
resource.WithProcessRuntimeDescription(),
resource.WithTelemetrySDK(),
)
if err != nil {
return nil, err
}
// Create a lazy sampler and pre-seed it with the sampling fraction.
var sampler lazySampler
sampler.SetSampler(tracesdk.TraceIDRatioBased(cfg.SamplingFraction))
setOTELTraceContextPropagators(cfg)
shimClient := &client{}
exp := otlptrace.NewUnstarted(shimClient)
tp := tracesdk.NewTracerProvider(
tracesdk.WithBatcher(exp),
tracesdk.WithSampler(tracesdk.ParentBased(&sampler)),
tracesdk.WithResource(res),
)
t := &Tracer{
sampler: &sampler,
client: shimClient,
exp: exp,
tp: tp,
}
if err := t.Update(cfg); err != nil {
return nil, err
}
return t, nil
}
// Update provides a new config to the tracing subsystem.
func (t *Tracer) Update(opts Options) error {
t.samplerMut.Lock()
defer t.samplerMut.Unlock()
setOTELTraceContextPropagators(opts)
t.client.UpdateWriteTo(opts.WriteTo)
// Stop the previous instance of the Jaeger remote sampler if it exists. The
// sampler can still make sampling decisions after being closed; it just
// won't poll anymore.
if t.jaegerRemoteSampler != nil {
t.jaegerRemoteSampler.Close()
t.jaegerRemoteSampler = nil
}
// Remote samplers accept a "seed" sampler to use before the remote is
// available. Get the current sampler from the previous iteration.
lastSampler := t.sampler.Sampler()
switch {
case opts.Sampler.JaegerRemote != nil:
t.jaegerRemoteSampler = jaegerremote.New(
serviceName,
jaegerremote.WithSamplingServerURL(opts.Sampler.JaegerRemote.URL),
jaegerremote.WithSamplingRefreshInterval(opts.Sampler.JaegerRemote.RefreshInterval),
jaegerremote.WithMaxOperations(opts.Sampler.JaegerRemote.MaxOperations),
jaegerremote.WithInitialSampler(lastSampler),
)
t.sampler.SetSampler(t.jaegerRemoteSampler)
default:
t.sampler.SetSampler(tracesdk.TraceIDRatioBased(opts.SamplingFraction))
}
return nil
}
func setOTELTraceContextPropagators(opts Options) {
var propagators []propagation.TextMapPropagator
if opts.SendTraceparent {
propagators = append(
propagators,
propagation.TraceContext{},
propagation.Baggage{},
)
}
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagators...))
}
// Run starts the tracing subsystem and runs it until the provided context is
// canceled. If the tracing subsystem could not be started, an error is
// returned.
//
// Run returns no error upon normal shutdown.
func (t *Tracer) Run(ctx context.Context) error {
if err := t.exp.Start(ctx); err != nil {
return err
}
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := t.tp.Shutdown(shutdownCtx); err != nil {
return err
}
return nil
}
func (t *Tracer) Tracer(name string, options ...trace.TracerOption) trace.Tracer {
return t.tp.Tracer(name, options...)
}