blob: c2222f153a39119f8c712677a747d25172db179b [file] [log] [blame]
Elia Battistonc8d0d462022-02-22 16:30:51 +01001// Copyright (c) 2017-2018 Uber Technologies, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package config
16
17import (
18 "errors"
19 "fmt"
20 "io"
21 "strings"
22 "time"
23
24 "github.com/opentracing/opentracing-go"
25 "github.com/uber/jaeger-client-go/utils"
26
27 "github.com/uber/jaeger-client-go"
28 "github.com/uber/jaeger-client-go/internal/baggage/remote"
29 throttler "github.com/uber/jaeger-client-go/internal/throttler/remote"
30 "github.com/uber/jaeger-client-go/rpcmetrics"
31 "github.com/uber/jaeger-client-go/transport"
32 "github.com/uber/jaeger-lib/metrics"
33)
34
35const defaultSamplingProbability = 0.001
36
37// Configuration configures and creates Jaeger Tracer
38type Configuration struct {
39 // ServiceName specifies the service name to use on the tracer.
40 // Can be provided by FromEnv() via the environment variable named JAEGER_SERVICE_NAME
41 ServiceName string `yaml:"serviceName"`
42
43 // Disabled makes the config return opentracing.NoopTracer.
44 // Value can be provided by FromEnv() via the environment variable named JAEGER_DISABLED.
45 Disabled bool `yaml:"disabled"`
46
47 // RPCMetrics enables generations of RPC metrics (requires metrics factory to be provided).
48 // Value can be provided by FromEnv() via the environment variable named JAEGER_RPC_METRICS
49 RPCMetrics bool `yaml:"rpc_metrics"`
50
51 // Gen128Bit instructs the tracer to generate 128-bit wide trace IDs, compatible with W3C Trace Context.
52 // Value can be provided by FromEnv() via the environment variable named JAEGER_TRACEID_128BIT.
53 Gen128Bit bool `yaml:"traceid_128bit"`
54
55 // Tags can be provided by FromEnv() via the environment variable named JAEGER_TAGS
56 Tags []opentracing.Tag `yaml:"tags"`
57
58 Sampler *SamplerConfig `yaml:"sampler"`
59 Reporter *ReporterConfig `yaml:"reporter"`
60 Headers *jaeger.HeadersConfig `yaml:"headers"`
61 BaggageRestrictions *BaggageRestrictionsConfig `yaml:"baggage_restrictions"`
62 Throttler *ThrottlerConfig `yaml:"throttler"`
63}
64
65// SamplerConfig allows initializing a non-default sampler. All fields are optional.
66type SamplerConfig struct {
67 // Type specifies the type of the sampler: const, probabilistic, rateLimiting, or remote.
68 // Can be provided by FromEnv() via the environment variable named JAEGER_SAMPLER_TYPE
69 Type string `yaml:"type"`
70
71 // Param is a value passed to the sampler.
72 // Valid values for Param field are:
73 // - for "const" sampler, 0 or 1 for always false/true respectively
74 // - for "probabilistic" sampler, a probability between 0 and 1
75 // - for "rateLimiting" sampler, the number of spans per second
76 // - for "remote" sampler, param is the same as for "probabilistic"
77 // and indicates the initial sampling rate before the actual one
78 // is received from the mothership.
79 // Can be provided by FromEnv() via the environment variable named JAEGER_SAMPLER_PARAM
80 Param float64 `yaml:"param"`
81
82 // SamplingServerURL is the URL of sampling manager that can provide
83 // sampling strategy to this service.
84 // Can be provided by FromEnv() via the environment variable named JAEGER_SAMPLING_ENDPOINT
85 SamplingServerURL string `yaml:"samplingServerURL"`
86
87 // SamplingRefreshInterval controls how often the remotely controlled sampler will poll
88 // sampling manager for the appropriate sampling strategy.
89 // Can be provided by FromEnv() via the environment variable named JAEGER_SAMPLER_REFRESH_INTERVAL
90 SamplingRefreshInterval time.Duration `yaml:"samplingRefreshInterval"`
91
92 // MaxOperations is the maximum number of operations that the PerOperationSampler
93 // will keep track of. If an operation is not tracked, a default probabilistic
94 // sampler will be used rather than the per operation specific sampler.
95 // Can be provided by FromEnv() via the environment variable named JAEGER_SAMPLER_MAX_OPERATIONS.
96 MaxOperations int `yaml:"maxOperations"`
97
98 // Opt-in feature for applications that require late binding of span name via explicit
99 // call to SetOperationName when using PerOperationSampler. When this feature is enabled,
100 // the sampler will return retryable=true from OnCreateSpan(), thus leaving the sampling
101 // decision as non-final (and the span as writeable). This may lead to degraded performance
102 // in applications that always provide the correct span name on trace creation.
103 //
104 // For backwards compatibility this option is off by default.
105 OperationNameLateBinding bool `yaml:"operationNameLateBinding"`
106
107 // Options can be used to programmatically pass additional options to the Remote sampler.
108 Options []jaeger.SamplerOption
109}
110
111// ReporterConfig configures the reporter. All fields are optional.
112type ReporterConfig struct {
113 // QueueSize controls how many spans the reporter can keep in memory before it starts dropping
114 // new spans. The queue is continuously drained by a background go-routine, as fast as spans
115 // can be sent out of process.
116 // Can be provided by FromEnv() via the environment variable named JAEGER_REPORTER_MAX_QUEUE_SIZE
117 QueueSize int `yaml:"queueSize"`
118
119 // BufferFlushInterval controls how often the buffer is force-flushed, even if it's not full.
120 // It is generally not useful, as it only matters for very low traffic services.
121 // Can be provided by FromEnv() via the environment variable named JAEGER_REPORTER_FLUSH_INTERVAL
122 BufferFlushInterval time.Duration
123
124 // LogSpans, when true, enables LoggingReporter that runs in parallel with the main reporter
125 // and logs all submitted spans. Main Configuration.Logger must be initialized in the code
126 // for this option to have any effect.
127 // Can be provided by FromEnv() via the environment variable named JAEGER_REPORTER_LOG_SPANS
128 LogSpans bool `yaml:"logSpans"`
129
130 // LocalAgentHostPort instructs reporter to send spans to jaeger-agent at this address.
131 // Can be provided by FromEnv() via the environment variable named JAEGER_AGENT_HOST / JAEGER_AGENT_PORT
132 LocalAgentHostPort string `yaml:"localAgentHostPort"`
133
134 // DisableAttemptReconnecting when true, disables udp connection helper that periodically re-resolves
135 // the agent's hostname and reconnects if there was a change. This option only
136 // applies if LocalAgentHostPort is specified.
137 // Can be provided by FromEnv() via the environment variable named JAEGER_REPORTER_ATTEMPT_RECONNECTING_DISABLED
138 DisableAttemptReconnecting bool `yaml:"disableAttemptReconnecting"`
139
140 // AttemptReconnectInterval controls how often the agent client re-resolves the provided hostname
141 // in order to detect address changes. This option only applies if DisableAttemptReconnecting is false.
142 // Can be provided by FromEnv() via the environment variable named JAEGER_REPORTER_ATTEMPT_RECONNECT_INTERVAL
143 AttemptReconnectInterval time.Duration
144
145 // CollectorEndpoint instructs reporter to send spans to jaeger-collector at this URL.
146 // Can be provided by FromEnv() via the environment variable named JAEGER_ENDPOINT
147 CollectorEndpoint string `yaml:"collectorEndpoint"`
148
149 // User instructs reporter to include a user for basic http authentication when sending spans to jaeger-collector.
150 // Can be provided by FromEnv() via the environment variable named JAEGER_USER
151 User string `yaml:"user"`
152
153 // Password instructs reporter to include a password for basic http authentication when sending spans to
154 // jaeger-collector.
155 // Can be provided by FromEnv() via the environment variable named JAEGER_PASSWORD
156 Password string `yaml:"password"`
157
158 // HTTPHeaders instructs the reporter to add these headers to the http request when reporting spans.
159 // This field takes effect only when using HTTPTransport by setting the CollectorEndpoint.
160 HTTPHeaders map[string]string `yaml:"http_headers"`
161}
162
163// BaggageRestrictionsConfig configures the baggage restrictions manager which can be used to whitelist
164// certain baggage keys. All fields are optional.
165type BaggageRestrictionsConfig struct {
166 // DenyBaggageOnInitializationFailure controls the startup failure mode of the baggage restriction
167 // manager. If true, the manager will not allow any baggage to be written until baggage restrictions have
168 // been retrieved from jaeger-agent. If false, the manager wil allow any baggage to be written until baggage
169 // restrictions have been retrieved from jaeger-agent.
170 DenyBaggageOnInitializationFailure bool `yaml:"denyBaggageOnInitializationFailure"`
171
172 // HostPort is the hostPort of jaeger-agent's baggage restrictions server
173 HostPort string `yaml:"hostPort"`
174
175 // RefreshInterval controls how often the baggage restriction manager will poll
176 // jaeger-agent for the most recent baggage restrictions.
177 RefreshInterval time.Duration `yaml:"refreshInterval"`
178}
179
180// ThrottlerConfig configures the throttler which can be used to throttle the
181// rate at which the client may send debug requests.
182type ThrottlerConfig struct {
183 // HostPort of jaeger-agent's credit server.
184 HostPort string `yaml:"hostPort"`
185
186 // RefreshInterval controls how often the throttler will poll jaeger-agent
187 // for more throttling credits.
188 RefreshInterval time.Duration `yaml:"refreshInterval"`
189
190 // SynchronousInitialization determines whether or not the throttler should
191 // synchronously fetch credits from the agent when an operation is seen for
192 // the first time. This should be set to true if the client will be used by
193 // a short lived service that needs to ensure that credits are fetched
194 // upfront such that sampling or throttling occurs.
195 SynchronousInitialization bool `yaml:"synchronousInitialization"`
196}
197
198type nullCloser struct{}
199
200func (*nullCloser) Close() error { return nil }
201
202// New creates a new Jaeger Tracer, and a closer func that can be used to flush buffers
203// before shutdown.
204//
205// Deprecated: use NewTracer() function
206func (c Configuration) New(
207 serviceName string,
208 options ...Option,
209) (opentracing.Tracer, io.Closer, error) {
210 if serviceName != "" {
211 c.ServiceName = serviceName
212 }
213
214 return c.NewTracer(options...)
215}
216
217// NewTracer returns a new tracer based on the current configuration, using the given options,
218// and a closer func that can be used to flush buffers before shutdown.
219func (c Configuration) NewTracer(options ...Option) (opentracing.Tracer, io.Closer, error) {
220 if c.Disabled {
221 return &opentracing.NoopTracer{}, &nullCloser{}, nil
222 }
223
224 if c.ServiceName == "" {
225 return nil, nil, errors.New("no service name provided")
226 }
227
228 opts := applyOptions(options...)
229 tracerMetrics := jaeger.NewMetrics(opts.metrics, nil)
230 if c.RPCMetrics {
231 Observer(
232 rpcmetrics.NewObserver(
233 opts.metrics.Namespace(metrics.NSOptions{Name: "jaeger-rpc", Tags: map[string]string{"component": "jaeger"}}),
234 rpcmetrics.DefaultNameNormalizer,
235 ),
236 )(&opts) // adds to c.observers
237 }
238 if c.Sampler == nil {
239 c.Sampler = &SamplerConfig{
240 Type: jaeger.SamplerTypeRemote,
241 Param: defaultSamplingProbability,
242 }
243 }
244 if c.Reporter == nil {
245 c.Reporter = &ReporterConfig{}
246 }
247
248 sampler := opts.sampler
249 if sampler == nil {
250 s, err := c.Sampler.NewSampler(c.ServiceName, tracerMetrics)
251 if err != nil {
252 return nil, nil, err
253 }
254 sampler = s
255 }
256
257 reporter := opts.reporter
258 if reporter == nil {
259 r, err := c.Reporter.NewReporter(c.ServiceName, tracerMetrics, opts.logger)
260 if err != nil {
261 return nil, nil, err
262 }
263 reporter = r
264 }
265
266 tracerOptions := []jaeger.TracerOption{
267 jaeger.TracerOptions.Metrics(tracerMetrics),
268 jaeger.TracerOptions.Logger(opts.logger),
269 jaeger.TracerOptions.CustomHeaderKeys(c.Headers),
270 jaeger.TracerOptions.PoolSpans(opts.poolSpans),
271 jaeger.TracerOptions.ZipkinSharedRPCSpan(opts.zipkinSharedRPCSpan),
272 jaeger.TracerOptions.MaxTagValueLength(opts.maxTagValueLength),
273 jaeger.TracerOptions.NoDebugFlagOnForcedSampling(opts.noDebugFlagOnForcedSampling),
274 }
275
276 if c.Gen128Bit || opts.gen128Bit {
277 tracerOptions = append(tracerOptions, jaeger.TracerOptions.Gen128Bit(true))
278 }
279
280 if opts.randomNumber != nil {
281 tracerOptions = append(tracerOptions, jaeger.TracerOptions.RandomNumber(opts.randomNumber))
282 }
283
284 for _, tag := range opts.tags {
285 tracerOptions = append(tracerOptions, jaeger.TracerOptions.Tag(tag.Key, tag.Value))
286 }
287
288 for _, tag := range c.Tags {
289 tracerOptions = append(tracerOptions, jaeger.TracerOptions.Tag(tag.Key, tag.Value))
290 }
291
292 for _, obs := range opts.observers {
293 tracerOptions = append(tracerOptions, jaeger.TracerOptions.Observer(obs))
294 }
295
296 for _, cobs := range opts.contribObservers {
297 tracerOptions = append(tracerOptions, jaeger.TracerOptions.ContribObserver(cobs))
298 }
299
300 for format, injector := range opts.injectors {
301 tracerOptions = append(tracerOptions, jaeger.TracerOptions.Injector(format, injector))
302 }
303
304 for format, extractor := range opts.extractors {
305 tracerOptions = append(tracerOptions, jaeger.TracerOptions.Extractor(format, extractor))
306 }
307
308 if c.BaggageRestrictions != nil {
309 mgr := remote.NewRestrictionManager(
310 c.ServiceName,
311 remote.Options.Metrics(tracerMetrics),
312 remote.Options.Logger(opts.logger),
313 remote.Options.HostPort(c.BaggageRestrictions.HostPort),
314 remote.Options.RefreshInterval(c.BaggageRestrictions.RefreshInterval),
315 remote.Options.DenyBaggageOnInitializationFailure(
316 c.BaggageRestrictions.DenyBaggageOnInitializationFailure,
317 ),
318 )
319 tracerOptions = append(tracerOptions, jaeger.TracerOptions.BaggageRestrictionManager(mgr))
320 }
321
322 if c.Throttler != nil {
323 debugThrottler := throttler.NewThrottler(
324 c.ServiceName,
325 throttler.Options.Metrics(tracerMetrics),
326 throttler.Options.Logger(opts.logger),
327 throttler.Options.HostPort(c.Throttler.HostPort),
328 throttler.Options.RefreshInterval(c.Throttler.RefreshInterval),
329 throttler.Options.SynchronousInitialization(
330 c.Throttler.SynchronousInitialization,
331 ),
332 )
333
334 tracerOptions = append(tracerOptions, jaeger.TracerOptions.DebugThrottler(debugThrottler))
335 }
336
337 tracer, closer := jaeger.NewTracer(
338 c.ServiceName,
339 sampler,
340 reporter,
341 tracerOptions...,
342 )
343
344 return tracer, closer, nil
345}
346
347// InitGlobalTracer creates a new Jaeger Tracer, and sets it as global OpenTracing Tracer.
348// It returns a closer func that can be used to flush buffers before shutdown.
349func (c Configuration) InitGlobalTracer(
350 serviceName string,
351 options ...Option,
352) (io.Closer, error) {
353 if c.Disabled {
354 return &nullCloser{}, nil
355 }
356 tracer, closer, err := c.New(serviceName, options...)
357 if err != nil {
358 return nil, err
359 }
360 opentracing.SetGlobalTracer(tracer)
361 return closer, nil
362}
363
364// NewSampler creates a new sampler based on the configuration
365func (sc *SamplerConfig) NewSampler(
366 serviceName string,
367 metrics *jaeger.Metrics,
368) (jaeger.Sampler, error) {
369 samplerType := strings.ToLower(sc.Type)
370 if samplerType == jaeger.SamplerTypeConst {
371 return jaeger.NewConstSampler(sc.Param != 0), nil
372 }
373 if samplerType == jaeger.SamplerTypeProbabilistic {
374 if sc.Param >= 0 && sc.Param <= 1.0 {
375 return jaeger.NewProbabilisticSampler(sc.Param)
376 }
377 return nil, fmt.Errorf(
378 "invalid Param for probabilistic sampler; expecting value between 0 and 1, received %v",
379 sc.Param,
380 )
381 }
382 if samplerType == jaeger.SamplerTypeRateLimiting {
383 return jaeger.NewRateLimitingSampler(sc.Param), nil
384 }
385 if samplerType == jaeger.SamplerTypeRemote || sc.Type == "" {
386 sc2 := *sc
387 sc2.Type = jaeger.SamplerTypeProbabilistic
388 initSampler, err := sc2.NewSampler(serviceName, nil)
389 if err != nil {
390 return nil, err
391 }
392 options := []jaeger.SamplerOption{
393 jaeger.SamplerOptions.Metrics(metrics),
394 jaeger.SamplerOptions.InitialSampler(initSampler),
395 jaeger.SamplerOptions.SamplingServerURL(sc.SamplingServerURL),
396 jaeger.SamplerOptions.MaxOperations(sc.MaxOperations),
397 jaeger.SamplerOptions.OperationNameLateBinding(sc.OperationNameLateBinding),
398 jaeger.SamplerOptions.SamplingRefreshInterval(sc.SamplingRefreshInterval),
399 }
400 options = append(options, sc.Options...)
401 return jaeger.NewRemotelyControlledSampler(serviceName, options...), nil
402 }
403 return nil, fmt.Errorf("unknown sampler type (%s)", sc.Type)
404}
405
406// NewReporter instantiates a new reporter that submits spans to the collector
407func (rc *ReporterConfig) NewReporter(
408 serviceName string,
409 metrics *jaeger.Metrics,
410 logger jaeger.Logger,
411) (jaeger.Reporter, error) {
412 sender, err := rc.newTransport(logger)
413 if err != nil {
414 return nil, err
415 }
416 reporter := jaeger.NewRemoteReporter(
417 sender,
418 jaeger.ReporterOptions.QueueSize(rc.QueueSize),
419 jaeger.ReporterOptions.BufferFlushInterval(rc.BufferFlushInterval),
420 jaeger.ReporterOptions.Logger(logger),
421 jaeger.ReporterOptions.Metrics(metrics))
422 if rc.LogSpans && logger != nil {
423 logger.Infof("Initializing logging reporter\n")
424 reporter = jaeger.NewCompositeReporter(jaeger.NewLoggingReporter(logger), reporter)
425 }
426 return reporter, err
427}
428
429func (rc *ReporterConfig) newTransport(logger jaeger.Logger) (jaeger.Transport, error) {
430 switch {
431 case rc.CollectorEndpoint != "":
432 httpOptions := []transport.HTTPOption{transport.HTTPHeaders(rc.HTTPHeaders)}
433 if rc.User != "" && rc.Password != "" {
434 httpOptions = append(httpOptions, transport.HTTPBasicAuth(rc.User, rc.Password))
435 }
436 return transport.NewHTTPTransport(rc.CollectorEndpoint, httpOptions...), nil
437 default:
438 return jaeger.NewUDPTransportWithParams(jaeger.UDPTransportParams{
439 AgentClientUDPParams: utils.AgentClientUDPParams{
440 HostPort: rc.LocalAgentHostPort,
441 Logger: logger,
442 DisableAttemptReconnecting: rc.DisableAttemptReconnecting,
443 AttemptReconnectInterval: rc.AttemptReconnectInterval,
444 },
445 })
446 }
447}