-
Notifications
You must be signed in to change notification settings - Fork 773
/
MeterProviderSdk.cs
549 lines (464 loc) · 22.7 KB
/
MeterProviderSdk.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OpenTelemetry.Internal;
using OpenTelemetry.Resources;
namespace OpenTelemetry.Metrics;
internal sealed class MeterProviderSdk : MeterProvider
{
internal const string ExemplarFilterConfigKey = "OTEL_METRICS_EXEMPLAR_FILTER";
internal const string ExemplarFilterHistogramsConfigKey = "OTEL_DOTNET_EXPERIMENTAL_METRICS_EXEMPLAR_FILTER_HISTOGRAMS";
internal readonly IServiceProvider ServiceProvider;
internal readonly IDisposable? OwnedServiceProvider;
internal int ShutdownCount;
internal bool Disposed;
internal ExemplarFilterType? ExemplarFilter;
internal ExemplarFilterType? ExemplarFilterForHistograms;
internal Action? OnCollectObservableInstruments;
private readonly List<object> instrumentations = new();
private readonly List<Func<Instrument, MetricStreamConfiguration?>> viewConfigs;
private readonly Lock collectLock = new();
private readonly MeterListener listener;
private readonly MetricReader? reader;
private readonly CompositeMetricReader? compositeMetricReader;
private readonly Func<Instrument, bool> shouldListenTo = instrument => false;
internal MeterProviderSdk(
IServiceProvider serviceProvider,
bool ownsServiceProvider)
{
Debug.Assert(serviceProvider != null, "serviceProvider was null");
var state = serviceProvider!.GetRequiredService<MeterProviderBuilderSdk>();
state.RegisterProvider(this);
this.ServiceProvider = serviceProvider!;
if (ownsServiceProvider)
{
this.OwnedServiceProvider = serviceProvider as IDisposable;
Debug.Assert(this.OwnedServiceProvider != null, "serviceProvider was not IDisposable");
}
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent("Building MeterProvider.");
var configureProviderBuilders = serviceProvider!.GetServices<IConfigureMeterProviderBuilder>();
foreach (var configureProviderBuilder in configureProviderBuilders)
{
configureProviderBuilder.ConfigureBuilder(serviceProvider!, state);
}
this.ExemplarFilter = state.ExemplarFilter;
this.ApplySpecificationConfigurationKeys(serviceProvider!.GetRequiredService<IConfiguration>());
StringBuilder exportersAdded = new StringBuilder();
StringBuilder instrumentationFactoriesAdded = new StringBuilder();
var resourceBuilder = state.ResourceBuilder ?? ResourceBuilder.CreateDefault();
resourceBuilder.ServiceProvider = serviceProvider;
this.Resource = resourceBuilder.Build();
this.viewConfigs = state.ViewConfigs;
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent(
$"MeterProvider configuration: {{MetricLimit={state.MetricLimit}, CardinalityLimit={state.CardinalityLimit}, ExemplarFilter={this.ExemplarFilter}, ExemplarFilterForHistograms={this.ExemplarFilterForHistograms}}}.");
foreach (var reader in state.Readers)
{
Guard.ThrowIfNull(reader);
reader.SetParentProvider(this);
reader.ApplyParentProviderSettings(
state.MetricLimit,
state.CardinalityLimit,
this.ExemplarFilter,
this.ExemplarFilterForHistograms);
if (this.reader == null)
{
this.reader = reader;
}
else if (this.reader is CompositeMetricReader compositeReader)
{
compositeReader.AddReader(reader);
}
else
{
this.reader = new CompositeMetricReader(new[] { this.reader, reader });
}
if (reader is PeriodicExportingMetricReader periodicExportingMetricReader)
{
exportersAdded.Append(periodicExportingMetricReader.Exporter);
exportersAdded.Append(" (Paired with PeriodicExportingMetricReader exporting at ");
exportersAdded.Append(periodicExportingMetricReader.ExportIntervalMilliseconds);
exportersAdded.Append(" milliseconds intervals.)");
exportersAdded.Append(';');
}
else if (reader is BaseExportingMetricReader baseExportingMetricReader)
{
exportersAdded.Append(baseExportingMetricReader.Exporter);
exportersAdded.Append(" (Paired with a MetricReader requiring manual trigger to export.)");
exportersAdded.Append(';');
}
}
if (exportersAdded.Length != 0)
{
exportersAdded.Remove(exportersAdded.Length - 1, 1);
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Exporters added = \"{exportersAdded}\".");
}
this.compositeMetricReader = this.reader as CompositeMetricReader;
if (state.Instrumentation.Any())
{
foreach (var instrumentation in state.Instrumentation)
{
if (instrumentation.Instance is not null)
{
this.instrumentations.Add(instrumentation.Instance);
}
instrumentationFactoriesAdded.Append(instrumentation.Name);
instrumentationFactoriesAdded.Append(';');
}
}
if (instrumentationFactoriesAdded.Length != 0)
{
instrumentationFactoriesAdded.Remove(instrumentationFactoriesAdded.Length - 1, 1);
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Instrumentations added = \"{instrumentationFactoriesAdded}\".");
}
// Setup Listener
if (state.MeterSources.Any(s => WildcardHelper.ContainsWildcard(s)))
{
var regex = WildcardHelper.GetWildcardRegex(state.MeterSources);
this.shouldListenTo = instrument => regex.IsMatch(instrument.Meter.Name);
}
else if (state.MeterSources.Any())
{
var meterSourcesToSubscribe = new HashSet<string>(state.MeterSources, StringComparer.OrdinalIgnoreCase);
this.shouldListenTo = instrument => meterSourcesToSubscribe.Contains(instrument.Meter.Name);
}
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Listening to following meters = \"{string.Join(";", state.MeterSources)}\".");
this.listener = new MeterListener();
var viewConfigCount = this.viewConfigs.Count;
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Number of views configured = {viewConfigCount}.");
this.listener.InstrumentPublished = (instrument, listener) =>
{
object? state = this.InstrumentPublished(instrument, listeningIsManagedExternally: false);
if (state != null)
{
listener.EnableMeasurementEvents(instrument, state);
}
};
// Everything double
this.listener.SetMeasurementEventCallback<double>(MeasurementRecordedDouble);
this.listener.SetMeasurementEventCallback<float>(static (instrument, value, tags, state) => MeasurementRecordedDouble(instrument, value, tags, state));
// Everything long
this.listener.SetMeasurementEventCallback<long>(MeasurementRecordedLong);
this.listener.SetMeasurementEventCallback<int>(static (instrument, value, tags, state) => MeasurementRecordedLong(instrument, value, tags, state));
this.listener.SetMeasurementEventCallback<short>(static (instrument, value, tags, state) => MeasurementRecordedLong(instrument, value, tags, state));
this.listener.SetMeasurementEventCallback<byte>(static (instrument, value, tags, state) => MeasurementRecordedLong(instrument, value, tags, state));
this.listener.MeasurementsCompleted = MeasurementsCompleted;
this.listener.Start();
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent("MeterProvider built successfully.");
}
internal Resource Resource { get; }
internal List<object> Instrumentations => this.instrumentations;
internal MetricReader? Reader => this.reader;
internal int ViewCount => this.viewConfigs.Count;
internal static void MeasurementsCompleted(Instrument instrument, object? state)
{
if (state is not MetricState metricState)
{
// todo: Log
return;
}
metricState.CompleteMeasurement();
}
internal static void MeasurementRecordedLong(Instrument instrument, long value, ReadOnlySpan<KeyValuePair<string, object?>> tags, object? state)
{
if (state is not MetricState metricState)
{
OpenTelemetrySdkEventSource.Log.MeasurementDropped(instrument?.Name ?? "UnknownInstrument", "SDK internal error occurred.", "Contact SDK owners.");
return;
}
metricState.RecordMeasurementLong(value, tags);
}
internal static void MeasurementRecordedDouble(Instrument instrument, double value, ReadOnlySpan<KeyValuePair<string, object?>> tags, object? state)
{
if (state is not MetricState metricState)
{
OpenTelemetrySdkEventSource.Log.MeasurementDropped(instrument?.Name ?? "UnknownInstrument", "SDK internal error occurred.", "Contact SDK owners.");
return;
}
metricState.RecordMeasurementDouble(value, tags);
}
internal object? InstrumentPublished(Instrument instrument, bool listeningIsManagedExternally)
{
var listenToInstrumentUsingSdkConfiguration = this.shouldListenTo(instrument);
if (listeningIsManagedExternally && listenToInstrumentUsingSdkConfiguration)
{
OpenTelemetrySdkEventSource.Log.MetricInstrumentIgnored(
instrument.Name,
instrument.Meter.Name,
"Instrument belongs to a Meter which has been enabled both externally and via a subscription on the provider. External subscription will be ignored in favor of the provider subscription.",
"Programmatic calls adding meters to the SDK (either by calling AddMeter directly or indirectly through helpers such as 'AddInstrumentation' extensions) are always favored over external registrations. When also using external management (typically IMetricsBuilder or IMetricsListener) remove programmatic calls to the SDK to allow registrations to be added and removed dynamically.");
return null;
}
else if (!listenToInstrumentUsingSdkConfiguration && !listeningIsManagedExternally)
{
OpenTelemetrySdkEventSource.Log.MetricInstrumentIgnored(
instrument.Name,
instrument.Meter.Name,
"Instrument belongs to a Meter not subscribed by the provider.",
"Use AddMeter to add the Meter to the provider.");
return null;
}
object? state = null;
var viewConfigCount = this.viewConfigs.Count;
try
{
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Started publishing Instrument = \"{instrument.Name}\" of Meter = \"{instrument.Meter.Name}\".");
if (viewConfigCount <= 0)
{
if (!MeterProviderBuilderSdk.IsValidInstrumentName(instrument.Name))
{
OpenTelemetrySdkEventSource.Log.MetricInstrumentIgnored(
instrument.Name,
instrument.Meter.Name,
"Instrument name is invalid.",
"The name must comply with the OpenTelemetry specification");
return null;
}
if (this.reader != null)
{
var metrics = this.reader.AddMetricWithNoViews(instrument);
if (metrics.Count == 1)
{
state = MetricState.BuildForSingleMetric(metrics[0]);
}
else if (metrics.Count > 0)
{
state = MetricState.BuildForMetricList(metrics);
}
}
}
else
{
// Creating list with initial capacity as the maximum
// possible size, to avoid any array resize/copy internally.
// There may be excess space wasted, but it'll eligible for
// GC right after this method.
var metricStreamConfigs = new List<MetricStreamConfiguration?>(viewConfigCount);
for (var i = 0; i < viewConfigCount; ++i)
{
var viewConfig = this.viewConfigs[i];
MetricStreamConfiguration? metricStreamConfig = null;
try
{
metricStreamConfig = viewConfig(instrument);
// The SDK provides some static MetricStreamConfigurations.
// For example, the Drop configuration. The static ViewId
// should not be changed for these configurations.
if (metricStreamConfig != null && !metricStreamConfig.ViewId.HasValue)
{
metricStreamConfig.ViewId = i;
}
if (metricStreamConfig is HistogramConfiguration
&& instrument.GetType().GetGenericTypeDefinition() != typeof(Histogram<>))
{
metricStreamConfig = null;
OpenTelemetrySdkEventSource.Log.MetricViewIgnored(
instrument.Name,
instrument.Meter.Name,
"The current SDK does not allow aggregating non-Histogram instruments as Histograms.",
"Fix the view configuration.");
}
}
catch (Exception ex)
{
OpenTelemetrySdkEventSource.Log.MetricViewIgnored(instrument.Name, instrument.Meter.Name, ex.Message, "Fix the view configuration.");
}
if (metricStreamConfig != null)
{
metricStreamConfigs.Add(metricStreamConfig);
}
}
if (metricStreamConfigs.Count == 0)
{
// No views matched. Add null
// which will apply defaults.
// Users can turn off this default
// by adding a view like below as the last view.
// .AddView(instrumentName: "*", MetricStreamConfiguration.Drop)
metricStreamConfigs.Add(null);
}
if (this.reader != null)
{
var metrics = this.reader.AddMetricWithViews(instrument, metricStreamConfigs);
if (metrics.Count == 1)
{
state = MetricState.BuildForSingleMetric(metrics[0]);
}
else if (metrics.Count > 0)
{
state = MetricState.BuildForMetricList(metrics);
}
}
}
if (state != null)
{
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Measurements for Instrument = \"{instrument.Name}\" of Meter = \"{instrument.Meter.Name}\" will be processed and aggregated by the SDK.");
return state;
}
else
{
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Measurements for Instrument = \"{instrument.Name}\" of Meter = \"{instrument.Meter.Name}\" will be dropped by the SDK.");
return null;
}
}
#if DEBUG
catch (Exception ex)
{
throw new InvalidOperationException("SDK internal error occurred.", ex);
}
#else
catch (Exception)
{
OpenTelemetrySdkEventSource.Log.MetricInstrumentIgnored(instrument.Name, instrument.Meter.Name, "SDK internal error occurred.", "Contact SDK owners.");
return null;
}
#endif
}
internal void CollectObservableInstruments()
{
lock (this.collectLock)
{
// Record all observable instruments
try
{
this.listener.RecordObservableInstruments();
this.OnCollectObservableInstruments?.Invoke();
}
catch (Exception exception)
{
// TODO:
// It doesn't looks like we can find which instrument callback
// threw.
OpenTelemetrySdkEventSource.Log.MetricObserverCallbackException(exception);
}
}
}
/// <summary>
/// Called by <c>ForceFlush</c>. This function should block the current
/// thread until flush 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 flush succeeded; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// This function is called synchronously on the thread which made the
/// first call to <c>ForceFlush</c>. This function should not throw
/// exceptions.
/// </remarks>
internal bool OnForceFlush(int timeoutMilliseconds)
{
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"{nameof(MeterProviderSdk)}.{nameof(this.OnForceFlush)} called with {nameof(timeoutMilliseconds)} = {timeoutMilliseconds}.");
return this.reader?.Collect(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)
{
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"{nameof(MeterProviderSdk)}.{nameof(this.OnShutdown)} called with {nameof(timeoutMilliseconds)} = {timeoutMilliseconds}.");
return this.reader?.Shutdown(timeoutMilliseconds) ?? true;
}
protected override void Dispose(bool disposing)
{
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"{nameof(MeterProviderSdk)}.{nameof(this.Dispose)} started.");
if (!this.Disposed)
{
if (disposing)
{
if (this.instrumentations != null)
{
foreach (var item in this.instrumentations)
{
(item as IDisposable)?.Dispose();
}
this.instrumentations.Clear();
}
// Wait for up to 5 seconds grace period
this.reader?.Shutdown(5000);
this.reader?.Dispose();
this.compositeMetricReader?.Dispose();
this.listener?.Dispose();
this.OwnedServiceProvider?.Dispose();
}
this.Disposed = true;
OpenTelemetrySdkEventSource.Log.ProviderDisposed(nameof(MeterProvider));
}
base.Dispose(disposing);
}
private void ApplySpecificationConfigurationKeys(IConfiguration configuration)
{
var hasProgrammaticExemplarFilterValue = this.ExemplarFilter.HasValue;
if (configuration.TryGetStringValue(ExemplarFilterConfigKey, out var configValue))
{
if (hasProgrammaticExemplarFilterValue)
{
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent(
$"Exemplar filter configuration value '{configValue}' has been ignored because a value '{this.ExemplarFilter}' was set programmatically.");
return;
}
if (!TryParseExemplarFilterFromConfigurationValue(configValue, out var exemplarFilter))
{
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Exemplar filter configuration was found but the value '{configValue}' is invalid and will be ignored.");
return;
}
this.ExemplarFilter = exemplarFilter;
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Exemplar filter set to '{exemplarFilter}' from configuration.");
}
if (configuration.TryGetStringValue(ExemplarFilterHistogramsConfigKey, out configValue))
{
if (hasProgrammaticExemplarFilterValue)
{
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent(
$"Exemplar filter histogram configuration value '{configValue}' has been ignored because a value '{this.ExemplarFilter}' was set programmatically.");
return;
}
if (!TryParseExemplarFilterFromConfigurationValue(configValue, out var exemplarFilter))
{
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Exemplar filter histogram configuration was found but the value '{configValue}' is invalid and will be ignored.");
return;
}
this.ExemplarFilterForHistograms = exemplarFilter;
OpenTelemetrySdkEventSource.Log.MeterProviderSdkEvent($"Exemplar filter for histograms set to '{exemplarFilter}' from configuration.");
}
static bool TryParseExemplarFilterFromConfigurationValue(string? configValue, out ExemplarFilterType? exemplarFilter)
{
if (string.Equals("always_off", configValue, StringComparison.OrdinalIgnoreCase))
{
exemplarFilter = ExemplarFilterType.AlwaysOff;
return true;
}
if (string.Equals("always_on", configValue, StringComparison.OrdinalIgnoreCase))
{
exemplarFilter = ExemplarFilterType.AlwaysOn;
return true;
}
if (string.Equals("trace_based", configValue, StringComparison.OrdinalIgnoreCase))
{
exemplarFilter = ExemplarFilterType.TraceBased;
return true;
}
exemplarFilter = null;
return false;
}
}
}