-
Notifications
You must be signed in to change notification settings - Fork 773
/
TracerProviderSdk.cs
317 lines (271 loc) · 11.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
// <copyright file="TracerProviderSdk.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using OpenTelemetry.Internal;
using OpenTelemetry.Resources;
namespace OpenTelemetry.Trace
{
internal class TracerProviderSdk : TracerProvider
{
internal int ShutdownCount;
private readonly List<object> instrumentations = new List<object>();
private readonly ActivityListener listener;
private readonly Sampler sampler;
private readonly ActivitySourceAdapter adapter;
private BaseProcessor<Activity> processor;
internal TracerProviderSdk(
Resource resource,
IEnumerable<string> sources,
IEnumerable<TracerProviderBuilderSdk.DiagnosticSourceInstrumentationFactory> diagnosticSourceInstrumentationFactories,
IEnumerable<TracerProviderBuilderSdk.InstrumentationFactory> instrumentationFactories,
Sampler sampler,
List<BaseProcessor<Activity>> processors)
{
this.Resource = resource;
this.sampler = sampler;
foreach (var processor in processors)
{
this.AddProcessor(processor);
}
if (diagnosticSourceInstrumentationFactories.Any())
{
this.adapter = new ActivitySourceAdapter(sampler, this.processor);
foreach (var instrumentationFactory in diagnosticSourceInstrumentationFactories)
{
this.instrumentations.Add(instrumentationFactory.Factory(this.adapter));
}
}
if (instrumentationFactories.Any())
{
foreach (var instrumentationFactory in instrumentationFactories)
{
this.instrumentations.Add(instrumentationFactory.Factory());
}
}
var listener = new ActivityListener
{
// Callback when Activity is started.
ActivityStarted = (activity) =>
{
OpenTelemetrySdkEventSource.Log.ActivityStarted(activity);
if (!activity.IsAllDataRequested)
{
return;
}
if (SuppressInstrumentationScope.IncrementIfTriggered() == 0)
{
this.processor?.OnStart(activity);
}
},
// Callback when Activity is stopped.
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 (sampler is AlwaysOnSampler)
{
listener.Sample = (ref ActivityCreationOptions<ActivityContext> options) =>
!Sdk.SuppressInstrumentation ? ActivitySamplingResult.AllDataAndRecorded : ActivitySamplingResult.None;
}
else if (sampler is AlwaysOffSampler)
{
listener.Sample = (ref ActivityCreationOptions<ActivityContext> options) =>
!Sdk.SuppressInstrumentation ? PropagateOrIgnoreData(options.Parent.TraceId) : ActivitySamplingResult.None;
}
else
{
// This delegate informs ActivitySource about sampling decision when the parent context is an ActivityContext.
listener.Sample = (ref ActivityCreationOptions<ActivityContext> options) =>
!Sdk.SuppressInstrumentation ? ComputeActivitySamplingResult(options, sampler) : ActivitySamplingResult.None;
}
if (sources.Any())
{
// Sources can be null. This happens when user
// is only interested in InstrumentationLibraries
// which do not depend on ActivitySources.
var wildcardMode = false;
// Validation of source name is already done in builder.
foreach (var name in sources)
{
if (name.Contains('*'))
{
wildcardMode = true;
}
}
if (wildcardMode)
{
var pattern = "^(" + string.Join("|", from name in sources select '(' + Regex.Escape(name).Replace("\\*", ".*") + ')') + ")$";
var regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Function which takes ActivitySource and returns true/false to indicate if it should be subscribed to
// or not.
listener.ShouldListenTo = (activitySource) => regex.IsMatch(activitySource.Name);
}
else
{
var activitySources = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
foreach (var name in sources)
{
activitySources[name] = true;
}
// Function which takes ActivitySource and returns true/false to indicate if it should be subscribed to
// or not.
listener.ShouldListenTo = (activitySource) => activitySources.ContainsKey(activitySource.Name);
}
}
ActivitySource.AddActivityListener(listener);
this.listener = listener;
}
internal Resource Resource { get; }
internal TracerProviderSdk AddProcessor(BaseProcessor<Activity> processor)
{
if (processor == null)
{
throw new ArgumentNullException(nameof(processor));
}
processor.SetParentProvider(this);
if (this.processor == null)
{
this.processor = processor;
}
else if (this.processor is CompositeProcessor<Activity> compositeProcessor)
{
compositeProcessor.AddProcessor(processor);
}
else
{
this.processor = new CompositeProcessor<Activity>(new[]
{
this.processor,
processor,
});
}
this.adapter?.UpdateProcessor(this.processor);
return this;
}
/// <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 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.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();
base.Dispose(disposing);
}
private static ActivitySamplingResult ComputeActivitySamplingResult(
in ActivityCreationOptions<ActivityContext> options,
Sampler sampler)
{
var samplingParameters = new SamplingParameters(
options.Parent,
options.TraceId,
options.Name,
options.Kind,
options.Tags,
options.Links);
var shouldSample = sampler.ShouldSample(samplingParameters);
var activitySamplingResult = shouldSample.Decision switch
{
SamplingDecision.RecordAndSample => ActivitySamplingResult.AllDataAndRecorded,
SamplingDecision.RecordOnly => ActivitySamplingResult.AllData,
_ => ActivitySamplingResult.PropagationData
};
if (activitySamplingResult != ActivitySamplingResult.PropagationData)
{
foreach (var att in shouldSample.Attributes)
{
options.SamplingTags.Add(att.Key, att.Value);
}
return activitySamplingResult;
}
return PropagateOrIgnoreData(options.Parent.TraceId);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ActivitySamplingResult PropagateOrIgnoreData(ActivityTraceId traceId)
{
var isRootSpan = traceId == default;
// If it is the root span select PropagationData so the trace ID is preserved
// even if no activity of the trace is recorded (sampled per OpenTelemetry parlance).
return isRootSpan
? ActivitySamplingResult.PropagationData
: ActivitySamplingResult.None;
}
}
}