-
Notifications
You must be signed in to change notification settings - Fork 132
/
Instrumentation.cs
481 lines (426 loc) · 19.6 KB
/
Instrumentation.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
// <copyright file="Instrumentation.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Datadog.Trace.Agent;
using Datadog.Trace.Agent.DiscoveryService;
using Datadog.Trace.AppSec;
using Datadog.Trace.Ci;
using Datadog.Trace.ClrProfiler.ServerlessInstrumentation;
using Datadog.Trace.Configuration;
using Datadog.Trace.Debugger;
using Datadog.Trace.Debugger.Helpers;
using Datadog.Trace.DiagnosticListeners;
using Datadog.Trace.Logging;
using Datadog.Trace.Processors;
using Datadog.Trace.RemoteConfigurationManagement;
using Datadog.Trace.RemoteConfigurationManagement.Transport;
using Datadog.Trace.ServiceFabric;
namespace Datadog.Trace.ClrProfiler
{
/// <summary>
/// Provides access to the profiler CLSID and whether it is attached to the process.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static class Instrumentation
{
/// <summary>
/// Indicates whether we're initializing Instrumentation for the first time
/// </summary>
private static int _firstInitialization = 1;
private static int _firstNonNativePartsInitialization = 1;
/// <summary>
/// Gets the CLSID for the Datadog .NET profiler
/// </summary>
public static readonly string ProfilerClsid = "{846F5F1C-F9AE-4B07-969E-05C26BC060D8}";
private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(Instrumentation));
/// <summary>
/// Gets a value indicating whether Datadog's profiler is attached to the current process.
/// </summary>
/// <value>
/// <c>true</c> if the profiler is currently attached; <c>false</c> otherwise.
/// </value>
public static bool ProfilerAttached
{
get
{
try
{
return NativeMethods.IsProfilerAttached();
}
catch (DllNotFoundException)
{
return false;
}
}
}
/// <summary>
/// Gets a value indicating the version of the native Datadog profiler. This method
/// is rewritten by the profiler.
/// </summary>
/// <returns>In a managed-only context, where the profiler is not attached, <c>None</c>,
/// otherwise the version of the Datadog native tracer library.</returns>
public static string GetNativeTracerVersion() => "None";
/// <summary>
/// Initializes global instrumentation values.
/// </summary>
public static void Initialize()
{
if (Interlocked.Exchange(ref _firstInitialization, 0) != 1)
{
// Initialize() was already called before
return;
}
TracerDebugger.WaitForDebugger();
Log.Debug("Initialization started.");
try
{
Log.Debug("Enabling by ref instrumentation.");
NativeMethods.EnableByRefInstrumentation();
Log.Information("ByRef instrumentation enabled.");
}
catch (Exception ex)
{
Log.Error(ex, "ByRef instrumentation cannot be enabled: ");
}
try
{
Log.Debug("Enabling calltarget state by ref.");
NativeMethods.EnableCallTargetStateByRef();
Log.Information("CallTarget State ByRef enabled.");
}
catch (Exception ex)
{
Log.Error(ex, "CallTarget state ByRef cannot be enabled: ");
}
try
{
Log.Debug("Initializing TraceAttribute instrumentation.");
var payload = InstrumentationDefinitions.GetTraceAttributeDefinitions();
NativeMethods.AddTraceAttributeInstrumentation(payload.DefinitionsId, payload.AssemblyName, payload.TypeName);
Log.Information("TraceAttribute instrumentation enabled with Assembly={AssemblyName} and Type={TypeName}.", payload.AssemblyName, payload.TypeName);
}
catch (Exception ex)
{
Log.Error(ex, "Error initializing TraceAttribute instrumentation");
}
InitializeNoNativeParts();
var tracer = Tracer.Instance;
try
{
Log.Debug("Sending CallTarget integration definitions to native library.");
var payload = InstrumentationDefinitions.GetAllDefinitions();
NativeMethods.InitializeProfiler(payload.DefinitionsId, payload.Definitions);
Log.Information<int>("The profiler has been initialized with {Count} definitions.", payload.Definitions.Length);
}
catch (Exception ex)
{
Log.Error(ex, "Error sending CallTarget integration definitions to native library");
}
try
{
Serverless.InitIfNeeded();
}
catch (Exception ex)
{
Serverless.Error("Error while loading Serverless definitions", ex);
}
try
{
Log.Debug("Sending CallTarget derived integration definitions to native library.");
var payload = InstrumentationDefinitions.GetDerivedDefinitions();
NativeMethods.AddDerivedInstrumentations(payload.DefinitionsId, payload.Definitions);
Log.Information<int>("The profiler has been initialized with {Count} derived definitions.", payload.Definitions.Length);
}
catch (Exception ex)
{
Log.Error(ex, "Error sending CallTarget derived integration definitions to native library");
}
try
{
Log.Debug("Sending CallTarget interface integration definitions to native library.");
var payload = InstrumentationDefinitions.GetInterfaceDefinitions();
NativeMethods.AddInterfaceInstrumentations(payload.DefinitionsId, payload.Definitions);
Log.Information<int>("The profiler has been initialized with {Count} interface definitions.", payload.Definitions.Length);
}
catch (Exception ex)
{
Log.Error(ex, "Error sending CallTarget interface integration definitions to native library");
}
if (tracer is null)
{
Log.Debug("Skipping TraceMethods initialization because Tracer.Instance was null after InitializeNoNativeParts was invoked");
}
else
{
try
{
InitRemoteConfigurationManagement(tracer);
}
catch (Exception e)
{
Log.Error(e, "Failed to initialize Remote Configuration Management.");
}
try
{
Log.Debug("Initializing TraceMethods instrumentation.");
var traceMethodsConfiguration = tracer.Settings.TraceMethods;
var payload = InstrumentationDefinitions.GetTraceMethodDefinitions();
NativeMethods.InitializeTraceMethods(payload.DefinitionsId, payload.AssemblyName, payload.TypeName, traceMethodsConfiguration);
Log.Information("TraceMethods instrumentation enabled with Assembly={AssemblyName}, Type={TypeName}, and Configuration={Configuration}.", payload.AssemblyName, payload.TypeName, traceMethodsConfiguration);
}
catch (Exception ex)
{
Log.Error(ex, "Error initializing TraceMethods instrumentation");
}
}
if (!Iast.Iast.Instance.Settings.Enabled)
{
Log.Debug("Skipping Iast initialization because Iast is disabled");
}
else
{
try
{
int defs = 0, derived = 0;
Log.Debug("Adding CallTarget IAST integration definitions to native library.");
var payload = InstrumentationDefinitions.GetAllDefinitions(InstrumentationCategory.Iast);
NativeMethods.InitializeProfiler(payload.DefinitionsId, payload.Definitions);
defs = payload.Definitions.Length;
Log.Debug("Adding CallTarget IAST derived integration definitions to native library.");
payload = InstrumentationDefinitions.GetDerivedDefinitions(InstrumentationCategory.Iast);
NativeMethods.InitializeProfiler(payload.DefinitionsId, payload.Definitions);
derived = payload.Definitions.Length;
Log.Information<int, int>("{Defs} IAST definitions and {Derived} IAST derived definitions added to the profiler.", defs, derived);
Log.Debug("Registering IAST Callsite Dataflow Aspects into native library.");
var aspects = NativeMethods.RegisterIastAspects(AspectDefinitions.Aspects);
Log.Information<int>("{Aspects} IAST Callsite Dataflow Aspects added to the profiler.", aspects);
}
catch (Exception ex)
{
Iast.Iast.Instance.Settings.Enabled = false;
Log.Error(ex, "DDIAST-0001-01: IAST could not start because of an unexpected error. No security activities will be collected. Please contact support at https://docs.datadoghq.com/help/ for help.");
}
}
#if NETSTANDARD2_0 || NETCOREAPP3_1
try
{
// On .NET Core 2.0-3.0 we see an occasional hang caused by OpenSSL being loaded
// while the app is shutting down, which results in flaky tests due to the short-
// lived nature of our apps. This appears to be a bug in the runtime (although
// we haven't yet confirmed that). Calling the `ToUuid()` method uses an MD5
// hash which calls into the native library, triggering the load.
_ = string.Empty.ToUUID();
}
catch (Exception ex)
{
Log.Error(ex, "Error triggering eager OpenSSL load");
}
#endif
LifetimeManager.Instance.AddShutdownTask(RunShutdown);
Log.Debug("Initialization finished.");
}
private static void RunShutdown()
{
InstrumentationDefinitions.Dispose();
}
internal static void InitializeNoNativeParts()
{
if (Interlocked.Exchange(ref _firstNonNativePartsInitialization, 0) != 1)
{
// InitializeNoNativeParts() was already called before
return;
}
TracerDebugger.WaitForDebugger();
Log.Debug("Initialization of non native parts started.");
try
{
var asm = typeof(Instrumentation).Assembly;
// intentionally using string interpolation, as this is only called once, and avoids array allocation
#pragma warning disable DDLOG004 // Message templates should be constant
#if NET5_0_OR_GREATER
// Can't use asm.CodeBase or asm.GlobalAssemblyCache in .NET 5+
Log.Information($"[Assembly metadata] Location: {asm.Location}, HostContext: {asm.HostContext}, SecurityRuleSet: {asm.SecurityRuleSet}");
#else
Log.Information($"[Assembly metadata] Location: {asm.Location}, CodeBase: {asm.CodeBase}, GAC: {asm.GlobalAssemblyCache}, HostContext: {asm.HostContext}, SecurityRuleSet: {asm.SecurityRuleSet}");
#endif
#pragma warning restore DDLOG004 // Message templates should be constant
}
catch (Exception ex)
{
Log.Error(ex, "Error printing assembly metadata");
}
try
{
// ensure global instance is created if it's not already
if (CIVisibility.Enabled)
{
CIVisibility.Initialize();
}
else
{
Log.Debug("Initializing tracer singleton instance.");
}
}
catch (Exception ex)
{
Log.Error(ex, "Error initializing CIVisibility");
}
try
{
Log.Debug("Initializing security singleton instance.");
_ = Security.Instance;
}
catch (Exception ex)
{
Log.Error(ex, "Error initializing Security");
}
#if !NETFRAMEWORK
try
{
if (GlobalSettings.Instance.DiagnosticSourceEnabled)
{
// check if DiagnosticSource is available before trying to use it
var type = Type.GetType("System.Diagnostics.DiagnosticSource, System.Diagnostics.DiagnosticSource", throwOnError: false);
if (type == null)
{
Log.Warning("DiagnosticSource type could not be loaded. Skipping diagnostic observers.");
}
else
{
// don't call this method unless DiagnosticSource is available
StartDiagnosticManager();
}
}
}
catch
{
// ignore
}
// we only support Service Fabric Service Remoting instrumentation on .NET Core (including .NET 5+)
if (FrameworkDescription.Instance.IsCoreClr())
{
Log.Information("Initializing ServiceFabric instrumentation");
try
{
ServiceRemotingClient.StartTracing();
}
catch
{
// ignore
}
try
{
ServiceRemotingService.StartTracing();
}
catch
{
// ignore
}
}
#endif
try
{
if (Tracer.Instance.Settings.IsActivityListenerEnabled)
{
Log.Debug("Initializing activity listener.");
Activity.ActivityListener.Initialize();
}
}
catch (Exception ex)
{
Log.Error(ex, "Error initializing activity listener");
}
Log.Debug("Initialization of non native parts finished.");
}
#if !NETFRAMEWORK
private static void StartDiagnosticManager()
{
var observers = new List<DiagnosticObserver>();
if (Tracer.Instance.Settings.AzureAppServiceMetadata?.IsFunctionsApp is not true)
{
// Not adding the `AspNetCoreDiagnosticObserver` is particularly important for Azure Functions.
// The AspNetCoreDiagnosticObserver will be loaded in a separate Assembly Load Context, breaking the connection of AsyncLocal
// This is because user code is loaded within the functions host in a separate context
observers.Add(new AspNetCoreDiagnosticObserver());
}
var diagnosticManager = new DiagnosticManager(observers);
diagnosticManager.Start();
DiagnosticManager.Instance = diagnosticManager;
}
#endif
private static void InitRemoteConfigurationManagement(Tracer tracer)
{
// Service Name must be lowercase, otherwise the agent will not be able to find the service
var serviceName = TraceUtil.NormalizeTag(tracer.Settings.ServiceName ?? tracer.DefaultServiceName);
var discoveryService = tracer.TracerManager.DiscoveryService;
Task.Run(
async () =>
{
// TODO: RCM and LiveDebugger should be initialized in TracerManagerFactory so they can respond
// to changes in ExporterSettings etc.
var isDiscoverySuccessful = await WaitForDiscoveryService(discoveryService).ConfigureAwait(false);
if (isDiscoverySuccessful)
{
var rcmSettings = RemoteConfigurationSettings.FromDefaultSource();
var rcmApi = RemoteConfigurationApiFactory.Create(tracer.Settings.Exporter, rcmSettings, discoveryService);
var configurationManager = RemoteConfigurationManager.Create(discoveryService, rcmApi, rcmSettings, serviceName, tracer.Settings, tracer.TracerManager.GitMetadataTagsProvider);
// see comment above
configurationManager.RegisterProduct(AsmRemoteConfigurationProducts.AsmFeaturesProduct);
configurationManager.RegisterProduct(AsmRemoteConfigurationProducts.AsmDataProduct);
configurationManager.RegisterProduct(AsmRemoteConfigurationProducts.AsmDDProduct); // This should be activated by Security only when Asm is active, but there is no visibility right now
configurationManager.RegisterProduct(AsmRemoteConfigurationProducts.AsmProduct);
var liveDebugger = LiveDebuggerFactory.Create(discoveryService, configurationManager, tracer.Settings, serviceName);
Log.Debug("Initializing Remote Configuration management.");
await Task
.WhenAll(
InitializeRemoteConfigurationManager(configurationManager),
InitializeLiveDebugger(liveDebugger))
.ConfigureAwait(false);
}
});
}
private static async Task<bool> WaitForDiscoveryService(IDiscoveryService discoveryService)
{
var tc = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
// Stop waiting if we're shutting down
LifetimeManager.Instance.AddShutdownTask(() => tc.TrySetResult(false));
discoveryService.SubscribeToChanges(Callback);
return await tc.Task.ConfigureAwait(false);
void Callback(AgentConfiguration x)
{
tc.TrySetResult(true);
discoveryService.RemoveSubscription(Callback);
}
}
internal static async Task InitializeRemoteConfigurationManager(IRemoteConfigurationManager remoteConfigurationManager)
{
try
{
await remoteConfigurationManager.StartPollingAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Error(ex, "Failed to initialize Remote Configuration management.");
}
}
internal static async Task InitializeLiveDebugger(LiveDebugger liveDebugger)
{
try
{
await liveDebugger.InitializeAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Error(ex, "Failed to initialize Live Debugger");
}
}
}
}