-
Notifications
You must be signed in to change notification settings - Fork 780
/
TracerProviderSdk.cs
616 lines (524 loc) · 23.9 KB
/
TracerProviderSdk.cs
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OpenTelemetry.Internal;
using OpenTelemetry.Resources;
namespace OpenTelemetry.Trace;
internal sealed class TracerProviderSdk : TracerProvider
{
internal const string TracesSamplerConfigKey = "OTEL_TRACES_SAMPLER";
internal const string TracesSamplerArgConfigKey = "OTEL_TRACES_SAMPLER_ARG";
internal readonly IServiceProvider ServiceProvider;
internal readonly IDisposable? OwnedServiceProvider;
internal int ShutdownCount;
internal bool Disposed;
private readonly List<object> instrumentations = new();
private readonly ActivityListener listener;
private readonly Sampler sampler;
private readonly Action<Activity> getRequestedDataAction;
private readonly bool supportLegacyActivity;
private BaseProcessor<Activity>? processor;
internal TracerProviderSdk(
IServiceProvider serviceProvider,
bool ownsServiceProvider)
{
Debug.Assert(serviceProvider != null, "serviceProvider was null");
var state = serviceProvider!.GetRequiredService<TracerProviderBuilderSdk>();
state.RegisterProvider(this);
this.ServiceProvider = serviceProvider!;
if (ownsServiceProvider)
{
this.OwnedServiceProvider = serviceProvider as IDisposable;
Debug.Assert(this.OwnedServiceProvider != null, "serviceProvider was not IDisposable");
}
OpenTelemetrySdkEventSource.Log.TracerProviderSdkEvent("Building TracerProvider.");
var configureProviderBuilders = serviceProvider!.GetServices<IConfigureTracerProviderBuilder>();
foreach (var configureProviderBuilder in configureProviderBuilders)
{
configureProviderBuilder.ConfigureBuilder(serviceProvider!, state);
}
StringBuilder processorsAdded = new StringBuilder();
StringBuilder instrumentationFactoriesAdded = new StringBuilder();
var resourceBuilder = state.ResourceBuilder ?? ResourceBuilder.CreateDefault();
resourceBuilder.ServiceProvider = serviceProvider;
this.Resource = resourceBuilder.Build();
this.sampler = GetSampler(serviceProvider!.GetRequiredService<IConfiguration>(), state.Sampler);
OpenTelemetrySdkEventSource.Log.TracerProviderSdkEvent($"Sampler added = \"{this.sampler.GetType()}\".");
this.supportLegacyActivity = state.LegacyActivityOperationNames.Count > 0;
Regex? legacyActivityWildcardModeRegex = null;
foreach (var legacyName in state.LegacyActivityOperationNames)
{
if (WildcardHelper.ContainsWildcard(legacyName))
{
legacyActivityWildcardModeRegex = WildcardHelper.GetWildcardRegex(state.LegacyActivityOperationNames);
break;
}
}
// Note: Linq OrderBy performs a stable sort, which is a requirement here
IEnumerable<BaseProcessor<Activity>> processors = state.Processors.OrderBy(p => p.PipelineWeight);
state.AddExceptionProcessorIfEnabled(ref processors);
foreach (var processor in processors)
{
this.AddProcessor(processor);
processorsAdded.Append(processor.GetType());
processorsAdded.Append(';');
}
foreach (var instrumentation in state.Instrumentation)
{
if (instrumentation.Instance is not null)
{
this.instrumentations.Add(instrumentation.Instance);
}
instrumentationFactoriesAdded.Append(instrumentation.Name);
instrumentationFactoriesAdded.Append(';');
}
if (processorsAdded.Length != 0)
{
processorsAdded.Remove(processorsAdded.Length - 1, 1);
OpenTelemetrySdkEventSource.Log.TracerProviderSdkEvent($"Processors added = \"{processorsAdded}\".");
}
if (instrumentationFactoriesAdded.Length != 0)
{
instrumentationFactoriesAdded.Remove(instrumentationFactoriesAdded.Length - 1, 1);
OpenTelemetrySdkEventSource.Log.TracerProviderSdkEvent($"Instrumentations added = \"{instrumentationFactoriesAdded}\".");
}
var activityListener = new ActivityListener();
if (this.supportLegacyActivity)
{
Func<Activity, bool>? legacyActivityPredicate = null;
if (legacyActivityWildcardModeRegex != null)
{
legacyActivityPredicate = activity => legacyActivityWildcardModeRegex.IsMatch(activity.OperationName);
}
else
{
legacyActivityPredicate = activity => state.LegacyActivityOperationNames.Contains(activity.OperationName);
}
activityListener.ActivityStarted = activity =>
{
OpenTelemetrySdkEventSource.Log.ActivityStarted(activity);
if (string.IsNullOrEmpty(activity.Source.Name))
{
if (legacyActivityPredicate(activity))
{
// Legacy activity matches the user configured list.
// Call sampler for the legacy activity
// unless suppressed.
if (!Sdk.SuppressInstrumentation)
{
this.getRequestedDataAction!(activity);
}
else
{
activity.IsAllDataRequested = false;
}
}
else
{
// Legacy activity doesn't match the user configured list. No need to proceed further.
return;
}
}
if (!activity.IsAllDataRequested)
{
return;
}
if (SuppressInstrumentationScope.IncrementIfTriggered() == 0)
{
this.processor?.OnStart(activity);
}
};
activityListener.ActivityStopped = activity =>
{
OpenTelemetrySdkEventSource.Log.ActivityStopped(activity);
if (string.IsNullOrEmpty(activity.Source.Name) && !legacyActivityPredicate(activity))
{
// Legacy activity doesn't match the user configured list. No need to proceed further.
return;
}
if (!activity.IsAllDataRequested)
{
return;
}
// Spec says IsRecording must be false once span ends.
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#isrecording
// However, Activity has slightly different semantic
// than Span and we don't have strong reason to do this
// now, as Activity anyway allows read/write always.
// Intentionally commenting the following line.
// activity.IsAllDataRequested = false;
if (SuppressInstrumentationScope.DecrementIfTriggered() == 0)
{
this.processor?.OnEnd(activity);
}
};
}
else
{
activityListener.ActivityStarted = activity =>
{
OpenTelemetrySdkEventSource.Log.ActivityStarted(activity);
if (activity.IsAllDataRequested && SuppressInstrumentationScope.IncrementIfTriggered() == 0)
{
this.processor?.OnStart(activity);
}
};
activityListener.ActivityStopped = activity =>
{
OpenTelemetrySdkEventSource.Log.ActivityStopped(activity);
if (!activity.IsAllDataRequested)
{
return;
}
// Spec says IsRecording must be false once span ends.
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#isrecording
// However, Activity has slightly different semantic
// than Span and we don't have strong reason to do this
// now, as Activity anyway allows read/write always.
// Intentionally commenting the following line.
// activity.IsAllDataRequested = false;
if (SuppressInstrumentationScope.DecrementIfTriggered() == 0)
{
this.processor?.OnEnd(activity);
}
};
}
if (this.sampler is AlwaysOnSampler)
{
activityListener.Sample = (ref ActivityCreationOptions<ActivityContext> options) =>
!Sdk.SuppressInstrumentation ? ActivitySamplingResult.AllDataAndRecorded : ActivitySamplingResult.None;
this.getRequestedDataAction = this.RunGetRequestedDataAlwaysOnSampler;
}
else if (this.sampler is AlwaysOffSampler)
{
activityListener.Sample = (ref ActivityCreationOptions<ActivityContext> options) =>
!Sdk.SuppressInstrumentation ? PropagateOrIgnoreData(options.Parent) : ActivitySamplingResult.None;
this.getRequestedDataAction = this.RunGetRequestedDataAlwaysOffSampler;
}
else
{
// This delegate informs ActivitySource about sampling decision when the parent context is an ActivityContext.
activityListener.Sample = (ref ActivityCreationOptions<ActivityContext> options) =>
!Sdk.SuppressInstrumentation ? ComputeActivitySamplingResult(ref options, this.sampler) : ActivitySamplingResult.None;
this.getRequestedDataAction = this.RunGetRequestedDataOtherSampler;
}
// Sources can be null. This happens when user
// is only interested in InstrumentationLibraries
// which do not depend on ActivitySources.
if (state.Sources.Any())
{
// Validation of source name is already done in builder.
if (state.Sources.Any(s => WildcardHelper.ContainsWildcard(s)))
{
var regex = WildcardHelper.GetWildcardRegex(state.Sources);
// Function which takes ActivitySource and returns true/false to indicate if it should be subscribed to
// or not.
activityListener.ShouldListenTo = activitySource =>
this.supportLegacyActivity ?
string.IsNullOrEmpty(activitySource.Name) || regex.IsMatch(activitySource.Name) :
regex.IsMatch(activitySource.Name);
}
else
{
var activitySources = new HashSet<string>(state.Sources, StringComparer.OrdinalIgnoreCase);
if (this.supportLegacyActivity)
{
activitySources.Add(string.Empty);
}
// Function which takes ActivitySource and returns true/false to indicate if it should be subscribed to
// or not.
activityListener.ShouldListenTo = activitySource => activitySources.Contains(activitySource.Name);
}
}
else
{
if (this.supportLegacyActivity)
{
activityListener.ShouldListenTo = activitySource => string.IsNullOrEmpty(activitySource.Name);
}
}
ActivitySource.AddActivityListener(activityListener);
this.listener = activityListener;
OpenTelemetrySdkEventSource.Log.TracerProviderSdkEvent("TracerProvider built successfully.");
}
internal Resource Resource { get; }
internal List<object> Instrumentations => this.instrumentations;
internal BaseProcessor<Activity>? Processor => this.processor;
internal Sampler Sampler => this.sampler;
internal TracerProviderSdk AddProcessor(BaseProcessor<Activity> processor)
{
Guard.ThrowIfNull(processor);
processor.SetParentProvider(this);
if (this.processor == null)
{
this.processor = processor;
}
else if (this.processor is CompositeProcessor<Activity> compositeProcessor)
{
compositeProcessor.AddProcessor(processor);
}
else
{
var newCompositeProcessor = new CompositeProcessor<Activity>(new[]
{
this.processor,
});
newCompositeProcessor.SetParentProvider(this);
newCompositeProcessor.AddProcessor(processor);
this.processor = newCompositeProcessor;
}
return this;
}
internal bool OnForceFlush(int timeoutMilliseconds)
{
return this.processor?.ForceFlush(timeoutMilliseconds) ?? true;
}
/// <summary>
/// Called by <c>Shutdown</c>. This function should block the current
/// thread until shutdown completed or timed out.
/// </summary>
/// <param name="timeoutMilliseconds">
/// The number (non-negative) of milliseconds to wait, or
/// <c>Timeout.Infinite</c> to wait indefinitely.
/// </param>
/// <returns>
/// Returns <c>true</c> when shutdown succeeded; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// This function is called synchronously on the thread which made the
/// first call to <c>Shutdown</c>. This function should not throw
/// exceptions.
/// </remarks>
internal bool OnShutdown(int timeoutMilliseconds)
{
// TO DO Put OnShutdown logic in a task to run within the user provider timeOutMilliseconds
bool? result;
if (this.instrumentations != null)
{
foreach (var item in this.instrumentations)
{
(item as IDisposable)?.Dispose();
}
this.instrumentations.Clear();
}
result = this.processor?.Shutdown(timeoutMilliseconds);
this.listener?.Dispose();
return result ?? true;
}
protected override void Dispose(bool disposing)
{
if (!this.Disposed)
{
if (disposing)
{
if (this.instrumentations != null)
{
foreach (var item in this.instrumentations)
{
(item as IDisposable)?.Dispose();
}
this.instrumentations.Clear();
}
(this.sampler as IDisposable)?.Dispose();
// Wait for up to 5 seconds grace period
this.processor?.Shutdown(5000);
this.processor?.Dispose();
// Shutdown the listener last so that anything created while instrumentation cleans up will still be processed.
// Redis instrumentation, for example, flushes during dispose which creates Activity objects for any profiling
// sessions that were open.
this.listener?.Dispose();
this.OwnedServiceProvider?.Dispose();
}
this.Disposed = true;
OpenTelemetrySdkEventSource.Log.ProviderDisposed(nameof(TracerProvider));
}
base.Dispose(disposing);
}
private static Sampler GetSampler(IConfiguration configuration, Sampler? stateSampler)
{
var sampler = stateSampler;
if (configuration.TryGetStringValue(TracesSamplerConfigKey, out var configValue))
{
if (sampler != null)
{
OpenTelemetrySdkEventSource.Log.TracerProviderSdkEvent(
$"Trace sampler configuration value '{configValue}' has been ignored because a value '{sampler.GetType().FullName}' was set programmatically.");
return sampler;
}
switch (configValue)
{
case var _ when string.Equals(configValue, "always_on", StringComparison.OrdinalIgnoreCase):
sampler = new AlwaysOnSampler();
break;
case var _ when string.Equals(configValue, "always_off", StringComparison.OrdinalIgnoreCase):
sampler = new AlwaysOffSampler();
break;
case var _ when string.Equals(configValue, "traceidratio", StringComparison.OrdinalIgnoreCase):
{
var traceIdRatio = ReadTraceIdRatio(configuration);
sampler = new TraceIdRatioBasedSampler(traceIdRatio);
break;
}
case var _ when string.Equals(configValue, "parentbased_always_on", StringComparison.OrdinalIgnoreCase):
sampler = new ParentBasedSampler(new AlwaysOnSampler());
break;
case var _ when string.Equals(configValue, "parentbased_always_off", StringComparison.OrdinalIgnoreCase):
sampler = new ParentBasedSampler(new AlwaysOffSampler());
break;
case var _ when string.Equals(configValue, "parentbased_traceidratio", StringComparison.OrdinalIgnoreCase):
{
var traceIdRatio = ReadTraceIdRatio(configuration);
sampler = new ParentBasedSampler(new TraceIdRatioBasedSampler(traceIdRatio));
break;
}
default:
OpenTelemetrySdkEventSource.Log.TracesSamplerConfigInvalid(configValue ?? string.Empty);
break;
}
if (sampler != null)
{
OpenTelemetrySdkEventSource.Log.TracerProviderSdkEvent($"Trace sampler set to '{sampler.GetType().FullName}' from configuration.");
}
}
return sampler ?? new ParentBasedSampler(new AlwaysOnSampler());
}
private static double ReadTraceIdRatio(IConfiguration configuration)
{
if (configuration.TryGetStringValue(TracesSamplerArgConfigKey, out var configValue) &&
double.TryParse(configValue, out var traceIdRatio))
{
return traceIdRatio;
}
else
{
OpenTelemetrySdkEventSource.Log.TracesSamplerArgConfigInvalid(configValue ?? string.Empty);
}
return 1.0;
}
private static ActivitySamplingResult ComputeActivitySamplingResult(
ref ActivityCreationOptions<ActivityContext> options,
Sampler sampler)
{
var samplingParameters = new SamplingParameters(
options.Parent,
options.TraceId,
options.Name,
options.Kind,
options.Tags,
options.Links);
var samplingResult = sampler.ShouldSample(samplingParameters);
var activitySamplingResult = samplingResult.Decision switch
{
SamplingDecision.RecordAndSample => ActivitySamplingResult.AllDataAndRecorded,
SamplingDecision.RecordOnly => ActivitySamplingResult.AllData,
_ => ActivitySamplingResult.PropagationData,
};
if (activitySamplingResult != ActivitySamplingResult.PropagationData)
{
foreach (var att in samplingResult.Attributes)
{
options.SamplingTags.Add(att.Key, att.Value);
}
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#sampler
// Spec requires clearing Tracestate if empty Tracestate is returned.
// Since .NET did not have this capability, it'll break
// existing samplers if we did that. So the following is
// adopted to remain spec-compliant and backward compat.
// The behavior is:
// if sampler returns null, its treated as if it has no intend
// to change Tracestate. Existing SamplingResult ctors will put null as default TraceStateString,
// so all existing samplers will get this behavior.
// if sampler returns non-null, then it'll be used as the
// new value for Tracestate
// A sampler can return string.Empty if it intends to clear the state.
if (samplingResult.TraceStateString != null)
{
options = options with { TraceState = samplingResult.TraceStateString };
}
return activitySamplingResult;
}
return PropagateOrIgnoreData(options.Parent);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ActivitySamplingResult PropagateOrIgnoreData(in ActivityContext parentContext)
{
var isRootSpan = parentContext.TraceId == default;
// If it is the root span or the parent is remote select PropagationData so the trace ID is preserved
// even if no activity of the trace is recorded (sampled per OpenTelemetry parlance).
return (isRootSpan || parentContext.IsRemote)
? ActivitySamplingResult.PropagationData
: ActivitySamplingResult.None;
}
private void RunGetRequestedDataAlwaysOnSampler(Activity activity)
{
activity.IsAllDataRequested = true;
activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded;
}
private void RunGetRequestedDataAlwaysOffSampler(Activity activity)
{
activity.IsAllDataRequested = false;
activity.ActivityTraceFlags &= ~ActivityTraceFlags.Recorded;
}
private void RunGetRequestedDataOtherSampler(Activity activity)
{
ActivityContext parentContext;
// Check activity.ParentId alone is sufficient to normally determine if a activity is root or not. But if one uses activity.SetParentId to override the TraceId (without intending to set an actual parent), then additional check of parentspanid being empty is required to confirm if an activity is root or not.
// This checker can be removed, once Activity exposes an API to customize ID Generation (https://github.com/dotnet/runtime/issues/46704) or issue https://github.com/dotnet/runtime/issues/46706 is addressed.
if (string.IsNullOrEmpty(activity.ParentId) || activity.ParentSpanId.ToHexString() == "0000000000000000")
{
parentContext = default;
}
else if (activity.Parent != null)
{
parentContext = activity.Parent.Context;
}
else
{
parentContext = new ActivityContext(
activity.TraceId,
activity.ParentSpanId,
activity.ActivityTraceFlags,
activity.TraceStateString,
isRemote: true);
}
var samplingParameters = new SamplingParameters(
parentContext,
activity.TraceId,
activity.DisplayName,
activity.Kind,
activity.TagObjects,
activity.Links);
var samplingResult = this.sampler.ShouldSample(samplingParameters);
switch (samplingResult.Decision)
{
case SamplingDecision.Drop:
activity.IsAllDataRequested = false;
activity.ActivityTraceFlags &= ~ActivityTraceFlags.Recorded;
break;
case SamplingDecision.RecordOnly:
activity.IsAllDataRequested = true;
activity.ActivityTraceFlags &= ~ActivityTraceFlags.Recorded;
break;
case SamplingDecision.RecordAndSample:
activity.IsAllDataRequested = true;
activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded;
break;
}
if (samplingResult.Decision != SamplingDecision.Drop)
{
foreach (var att in samplingResult.Attributes)
{
activity.SetTag(att.Key, att.Value);
}
if (samplingResult.TraceStateString != null)
{
activity.TraceStateString = samplingResult.TraceStateString;
}
}
}
}