-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Activity.cs
1731 lines (1527 loc) · 67.1 KB
/
Activity.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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
/// <summary>
/// Activity represents operation with context to be used for logging.
/// Activity has operation name, Id, start time and duration, tags and baggage.
///
/// Current activity can be accessed with static AsyncLocal variable Activity.Current.
///
/// Activities should be created with constructor, configured as necessary
/// and then started with Activity.Start method which maintains parent-child
/// relationships for the activities and sets Activity.Current.
///
/// When activity is finished, it should be stopped with static Activity.Stop method.
///
/// No methods on Activity allow exceptions to escape as a response to bad inputs.
/// They are thrown and caught (that allows Debuggers and Monitors to see the error)
/// but the exception is suppressed, and the operation does something reasonable (typically
/// doing nothing).
/// </summary>
public partial class Activity : IDisposable
{
#pragma warning disable CA1825 // Array.Empty<T>() doesn't exist in all configurations
private static readonly IEnumerable<KeyValuePair<string, string?>> s_emptyBaggageTags = new KeyValuePair<string, string?>[0];
private static readonly IEnumerable<ActivityLink> s_emptyLinks = new ActivityLink[0];
private static readonly IEnumerable<ActivityEvent> s_emptyEvents = new ActivityEvent[0];
#pragma warning restore CA1825
private static readonly ActivitySource s_defaultSource = new ActivitySource(string.Empty);
private const byte ActivityTraceFlagsIsSet = 0b_1_0000000; // Internal flag to indicate if flags have been set
private const int RequestIdMaxLength = 1024;
// Used to generate an ID it represents the machine and process we are in.
private static readonly string s_uniqSuffix = "-" + GetRandomNumber().ToString("x") + ".";
// A unique number inside the appdomain, randomized between appdomains.
// Int gives enough randomization and keeps hex-encoded s_currentRootId 8 chars long for most applications
private static long s_currentRootId = (uint)GetRandomNumber();
private static ActivityIdFormat s_defaultIdFormat;
/// <summary>
/// Normally if the ParentID is defined, the format of that is used to determine the
/// format used by the Activity. However if ForceDefaultFormat is set to true, the
/// ID format will always be the DefaultIdFormat even if the ParentID is define and is
/// a different format.
/// </summary>
public static bool ForceDefaultIdFormat { get; set; }
private string? _traceState;
private State _state;
private int _currentChildId; // A unique number for all children of this activity.
// State associated with ID.
private string? _id;
private string? _rootId;
// State associated with ParentId.
private string? _parentId;
// W3C formats
private string? _parentSpanId;
private string? _traceId;
private string? _spanId;
private byte _w3CIdFlags;
private TagsLinkedList? _tags;
private LinkedList<KeyValuePair<string, string?>>? _baggage;
private LinkedList<ActivityLink>? _links;
private LinkedList<ActivityEvent>? _events;
private ConcurrentDictionary<string, object>? _customProperties;
private string? _displayName;
/// <summary>
/// Gets the relationship between the Activity, its parents, and its children in a Trace.
/// </summary>
public ActivityKind Kind { get; private set; } = ActivityKind.Internal;
/// <summary>
/// An operation name is a COARSEST name that is useful grouping/filtering.
/// The name is typically a compile-time constant. Names of Rest APIs are
/// reasonable, but arguments (e.g. specific accounts etc), should not be in
/// the name but rather in the tags.
/// </summary>
public string OperationName { get; }
/// <summary>Gets or sets the display name of the Activity</summary>
/// <remarks>
/// DisplayName is intended to be used in a user interface and need not be the same as OperationName.
/// </remarks>
public string DisplayName
{
get => _displayName ?? OperationName;
set => _displayName = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>Get the ActivitySource object associated with this Activity.</summary>
/// <remarks>
/// All Activities created from public constructors will have a singleton source where the source name is an empty string.
/// Otherwise, the source will hold the object that created the Activity through ActivitySource.StartActivity.
/// </remarks>
public ActivitySource Source { get; private set; }
/// <summary>
/// If the Activity that created this activity is from the same process you can get
/// that Activity with Parent. However, this can be null if the Activity has no
/// parent (a root activity) or if the Parent is from outside the process.
/// </summary>
/// <seealso cref="ParentId"/>
public Activity? Parent { get; private set; }
/// <summary>
/// If the Activity has ended (<see cref="Stop"/> or <see cref="SetEndTime"/> was called) then this is the delta
/// between <see cref="StartTimeUtc"/> and end. If Activity is not ended and <see cref="SetEndTime"/> was not called then this is
/// <see cref="TimeSpan.Zero"/>.
/// </summary>
public TimeSpan Duration { get; private set; }
/// <summary>
/// The time that operation started. It will typically be initialized when <see cref="Start"/>
/// is called, but you can set at any time via <see cref="SetStartTime(DateTime)"/>.
/// </summary>
public DateTime StartTimeUtc { get; private set; }
/// <summary>
/// This is an ID that is specific to a particular request. Filtering
/// to a particular ID insures that you get only one request that matches.
/// Id has a hierarchical structure: '|root-id.id1_id2.id3_' Id is generated when
/// <see cref="Start"/> is called by appending suffix to Parent.Id
/// or ParentId; Activity has no Id until it started
/// <para/>
/// See <see href="https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md#id-format"/> for more details
/// </summary>
/// <example>
/// Id looks like '|a000b421-5d183ab6.1.8e2d4c28_1.':<para />
/// - '|a000b421-5d183ab6.' - Id of the first, top-most, Activity created<para />
/// - '|a000b421-5d183ab6.1.' - Id of a child activity. It was started in the same process as the first activity and ends with '.'<para />
/// - '|a000b421-5d183ab6.1.8e2d4c28_' - Id of the grand child activity. It was started in another process and ends with '_'<para />
/// 'a000b421-5d183ab6' is a <see cref="RootId"/> for the first Activity and all its children
/// </example>
public string? Id
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get
{
// if we represented it as a traceId-spanId, convert it to a string.
// We can do this concatenation with a stackalloced Span<char> if we actually used Id a lot.
if (_id == null && _spanId != null)
{
// Convert flags to binary.
Span<char> flagsChars = stackalloc char[2];
HexConverter.ToCharsBuffer((byte)((~ActivityTraceFlagsIsSet) & _w3CIdFlags), flagsChars, 0, HexConverter.Casing.Lower);
string id = "00-" + _traceId + "-" + _spanId + "-" + flagsChars.ToString();
Interlocked.CompareExchange(ref _id, id, null);
}
return _id;
}
}
/// <summary>
/// If the parent for this activity comes from outside the process, the activity
/// does not have a Parent Activity but MAY have a ParentId (which was deserialized from
/// from the parent). This accessor fetches the parent ID if it exists at all.
/// Note this can be null if this is a root Activity (it has no parent)
/// <para/>
/// See <see href="https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md#id-format"/> for more details
/// </summary>
public string? ParentId
{
get
{
// if we represented it as a traceId-spanId, convert it to a string.
if (_parentId == null)
{
if (_parentSpanId != null)
{
string parentId = "00-" + _traceId + "-" + _parentSpanId + "-00";
Interlocked.CompareExchange(ref _parentId, parentId, null);
}
else if (Parent != null)
{
Interlocked.CompareExchange(ref _parentId, Parent.Id, null);
}
}
return _parentId;
}
}
/// <summary>
/// Root Id is substring from Activity.Id (or ParentId) between '|' (or beginning) and first '.'.
/// Filtering by root Id allows to find all Activities involved in operation processing.
/// RootId may be null if Activity has neither ParentId nor Id.
/// See <see href="https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md#id-format"/> for more details
/// </summary>
public string? RootId
{
get
{
//we expect RootId to be requested at any time after activity is created,
//possibly even before it was started for sampling or logging purposes
//Presumably, it will be called by logging systems for every log record, so we cache it.
if (_rootId == null)
{
string? rootId = null;
if (Id != null)
{
rootId = GetRootId(Id);
}
else if (ParentId != null)
{
rootId = GetRootId(ParentId);
}
if (rootId != null)
{
Interlocked.CompareExchange(ref _rootId, rootId, null);
}
}
return _rootId;
}
}
/// <summary>
/// Tags are string-string key-value pairs that represent information that will
/// be logged along with the Activity to the logging system. This information
/// however is NOT passed on to the children of this activity.
/// </summary>
/// <seealso cref="Baggage"/>
public IEnumerable<KeyValuePair<string, string?>> Tags
{
get => _tags?.EnumerateStringValues() ?? s_emptyBaggageTags;
}
/// <summary>
/// List of the tags which represent information that will be logged along with the Activity to the logging system.
/// This information however is NOT passed on to the children of this activity.
/// </summary>
public IEnumerable<KeyValuePair<string, object?>> TagObjects
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get => _tags?.Enumerate() ?? Unsafe.As<IEnumerable<KeyValuePair<string, object?>>>(s_emptyBaggageTags);
}
/// <summary>
/// Events is the list of all <see cref="ActivityEvent" /> objects attached to this Activity object.
/// If there is not any <see cref="ActivityEvent" /> object attached to the Activity object, Events will return empty list.
/// </summary>
public IEnumerable<ActivityEvent> Events
{
get => _events != null ? _events.Enumerate() : s_emptyEvents;
}
/// <summary>
/// Links is the list of all <see cref="ActivityLink" /> objects attached to this Activity object.
/// If there is no any <see cref="ActivityLink" /> object attached to the Activity object, Links will return empty list.
/// </summary>
public IEnumerable<ActivityLink> Links
{
get => _links != null ? _links.Enumerate() : s_emptyLinks;
}
/// <summary>
/// Baggage is string-string key-value pairs that represent information that will
/// be passed along to children of this activity. Baggage is serialized
/// when requests leave the process (along with the ID). Typically Baggage is
/// used to do fine-grained control over logging of the activity and any children.
/// In general, if you are not using the data at runtime, you should be using Tags
/// instead.
/// </summary>
public IEnumerable<KeyValuePair<string, string?>> Baggage
{
get
{
for (Activity? activity = this; activity != null; activity = activity.Parent)
{
if (activity._baggage != null)
{
return Iterate(activity);
}
}
return s_emptyBaggageTags;
static IEnumerable<KeyValuePair<string, string?>> Iterate(Activity? activity)
{
Debug.Assert(activity != null);
do
{
if (activity._baggage != null)
{
for (LinkedListNode<KeyValuePair<string, string?>>? current = activity._baggage.First; current != null; current = current.Next)
{
yield return current.Value;
}
}
activity = activity.Parent;
} while (activity != null);
}
}
}
/// <summary>
/// Returns the value of the key-value pair added to the activity with <see cref="AddBaggage(string, string)"/>.
/// Returns null if that key does not exist.
/// </summary>
public string? GetBaggageItem(string key)
{
foreach (KeyValuePair<string, string?> keyValue in Baggage)
if (key == keyValue.Key)
return keyValue.Value;
return null;
}
/* Constructors Builder methods */
/// <summary>
/// Note that Activity has a 'builder' pattern, where you call the constructor, a number of 'Set*' and 'Add*' APIs and then
/// call <see cref="Start"/> to build the activity. You MUST call <see cref="Start"/> before using it.
/// </summary>
/// <param name="operationName">Operation's name <see cref="OperationName"/></param>
public Activity(string operationName)
{
Source = s_defaultSource;
// Allow data by default in the constructor to keep the compatability.
IsAllDataRequested = true;
if (string.IsNullOrEmpty(operationName))
{
NotifyError(new ArgumentException(SR.OperationNameInvalid));
}
OperationName = operationName;
}
/// <summary>
/// Update the Activity to have a tag with an additional 'key' and value 'value'.
/// This shows up in the <see cref="Tags"/> enumeration. It is meant for information that
/// is useful to log but not needed for runtime control (for the latter, <see cref="Baggage"/>)
/// </summary>
/// <returns>'this' for convenient chaining</returns>
/// <param name="key">The tag key name</param>
/// <param name="value">The tag value mapped to the input key</param>
public Activity AddTag(string key, string? value) => AddTag(key, (object?) value);
/// <summary>
/// Update the Activity to have a tag with an additional 'key' and value 'value'.
/// This shows up in the <see cref="TagObjects"/> enumeration. It is meant for information that
/// is useful to log but not needed for runtime control (for the latter, <see cref="Baggage"/>)
/// </summary>
/// <returns>'this' for convenient chaining</returns>
/// <param name="key">The tag key name</param>
/// <param name="value">The tag value mapped to the input key</param>
public Activity AddTag(string key, object? value)
{
KeyValuePair<string, object?> kvp = new KeyValuePair<string, object?>(key, value);
if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(kvp), null) != null)
{
_tags.Add(kvp);
}
return this;
}
/// <summary>
/// Add or update the Activity tag with the input key and value.
/// If the input value is null
/// - if the collection has any tag with the same key, then this tag will get removed from the collection.
/// - otherwise, nothing will happen and the collection will not change.
/// If the input value is not null
/// - if the collection has any tag with the same key, then the value mapped to this key will get updated with the new input value.
/// - otherwise, the key and value will get added as a new tag to the collection.
/// </summary>
/// <param name="key">The tag key name</param>
/// <param name="value">The tag value mapped to the input key</param>
/// <returns>'this' for convenient chaining</returns>
public Activity SetTag(string key, object value)
{
KeyValuePair<string, object?> kvp = new KeyValuePair<string, object?>(key, value);
if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(kvp, set: true), null) != null)
{
_tags.Set(kvp);
}
return this;
}
/// <summary>
/// Add <see cref="ActivityEvent" /> object to the <see cref="Events" /> list.
/// </summary>
/// <param name="e"> object of <see cref="ActivityEvent"/> to add to the attached events list.</param>
/// <returns>'this' for convenient chaining</returns>
public Activity AddEvent(ActivityEvent e)
{
if (_events != null || Interlocked.CompareExchange(ref _events, new LinkedList<ActivityEvent>(e), null) != null)
{
_events.Add(e);
}
return this;
}
/// <summary>
/// Update the Activity to have baggage with an additional 'key' and value 'value'.
/// This shows up in the <see cref="Baggage"/> enumeration as well as the <see cref="GetBaggageItem(string)"/>
/// method.
/// Baggage is meant for information that is needed for runtime control. For information
/// that is simply useful to show up in the log with the activity use <see cref="Tags"/>.
/// Returns 'this' for convenient chaining.
/// </summary>
/// <returns>'this' for convenient chaining</returns>
public Activity AddBaggage(string key, string? value)
{
KeyValuePair<string, string?> kvp = new KeyValuePair<string, string?>(key, value);
if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new LinkedList<KeyValuePair<string, string?>>(kvp), null) != null)
{
_baggage.Add(kvp);
}
return this;
}
/// <summary>
/// Updates the Activity To indicate that the activity with ID <paramref name="parentId"/>
/// caused this activity. This is intended to be used only at 'boundary'
/// scenarios where an activity from another process logically started
/// this activity. The Parent ID shows up the Tags (as well as the ParentID
/// property), and can be used to reconstruct the causal tree.
/// Returns 'this' for convenient chaining.
/// </summary>
/// <param name="parentId">The id of the parent operation.</param>
public Activity SetParentId(string parentId)
{
if (Parent != null)
{
NotifyError(new InvalidOperationException(SR.SetParentIdOnActivityWithParent));
}
else if (ParentId != null || _parentSpanId != null)
{
NotifyError(new InvalidOperationException(SR.ParentIdAlreadySet));
}
else if (string.IsNullOrEmpty(parentId))
{
NotifyError(new ArgumentException(SR.ParentIdInvalid));
}
else
{
_parentId = parentId;
}
return this;
}
/// <summary>
/// Set the parent ID using the W3C convention using a TraceId and a SpanId. This
/// constructor has the advantage that no string manipulation is needed to set the ID.
/// </summary>
public Activity SetParentId(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags activityTraceFlags = ActivityTraceFlags.None)
{
if (Parent != null)
{
NotifyError(new InvalidOperationException(SR.SetParentIdOnActivityWithParent));
}
else if (ParentId != null || _parentSpanId != null)
{
NotifyError(new InvalidOperationException(SR.ParentIdAlreadySet));
}
else
{
_traceId = traceId.ToHexString(); // The child will share the parent's traceId.
_parentSpanId = spanId.ToHexString();
ActivityTraceFlags = activityTraceFlags;
}
return this;
}
/// <summary>
/// Update the Activity to set start time
/// </summary>
/// <param name="startTimeUtc">Activity start time in UTC (Greenwich Mean Time)</param>
/// <returns>'this' for convenient chaining</returns>
public Activity SetStartTime(DateTime startTimeUtc)
{
if (startTimeUtc.Kind != DateTimeKind.Utc)
{
NotifyError(new InvalidOperationException(SR.StartTimeNotUtc));
}
else
{
StartTimeUtc = startTimeUtc;
}
return this;
}
/// <summary>
/// Update the Activity to set <see cref="Duration"/>
/// as a difference between <see cref="StartTimeUtc"/>
/// and <paramref name="endTimeUtc"/>.
/// </summary>
/// <param name="endTimeUtc">Activity stop time in UTC (Greenwich Mean Time)</param>
/// <returns>'this' for convenient chaining</returns>
public Activity SetEndTime(DateTime endTimeUtc)
{
if (endTimeUtc.Kind != DateTimeKind.Utc)
{
NotifyError(new InvalidOperationException(SR.EndTimeNotUtc));
}
else
{
Duration = endTimeUtc - StartTimeUtc;
if (Duration.Ticks <= 0)
Duration = new TimeSpan(1); // We want Duration of 0 to mean 'EndTime not set)
}
return this;
}
/// <summary>
/// Get the context of the activity. Context becomes valid only if the activity has been started.
/// otherwise will default context.
/// </summary>
public ActivityContext Context => new ActivityContext(TraceId, SpanId, ActivityTraceFlags, TraceStateString);
/// <summary>
/// Starts activity
/// <list type="bullet">
/// <item>Sets <see cref="Parent"/> to hold <see cref="Current"/>.</item>
/// <item>Sets <see cref="Current"/> to this activity.</item>
/// <item>If <see cref="StartTimeUtc"/> was not set previously, sets it to <see cref="DateTime.UtcNow"/>.</item>
/// <item>Generates a unique <see cref="Id"/> for this activity.</item>
/// </list>
/// Use <see cref="DiagnosticSource.StartActivity(Activity, object)"/> to start activity and write start event.
/// </summary>
/// <seealso cref="DiagnosticSource.StartActivity(Activity, object)"/>
/// <seealso cref="SetStartTime(DateTime)"/>
public Activity Start()
{
// Has the ID already been set (have we called Start()).
if (_id != null || _spanId != null)
{
NotifyError(new InvalidOperationException(SR.ActivityStartAlreadyStarted));
}
else
{
if (_parentId == null && _parentSpanId is null)
{
Activity? parent = Current;
if (parent != null)
{
// The parent change should not form a loop. We are actually guaranteed this because
// 1. Un-started activities can't be 'Current' (thus can't be 'parent'), we throw if you try.
// 2. All started activities have a finite parent change (by inductive reasoning).
Parent = parent;
}
}
if (StartTimeUtc == default)
StartTimeUtc = GetUtcNow();
if (IdFormat == ActivityIdFormat.Unknown)
{
// Figure out what format to use.
IdFormat =
ForceDefaultIdFormat ? DefaultIdFormat :
Parent != null ? Parent.IdFormat :
_parentSpanId != null ? ActivityIdFormat.W3C :
_parentId == null ? DefaultIdFormat :
IsW3CId(_parentId) ? ActivityIdFormat.W3C :
ActivityIdFormat.Hierarchical;
}
// Generate the ID in the appropriate format.
if (IdFormat == ActivityIdFormat.W3C)
GenerateW3CId();
else
_id = GenerateHierarchicalId();
SetCurrent(this);
Source.NotifyActivityStart(this);
}
return this;
}
/// <summary>
/// Stops activity: sets <see cref="Current"/> to <see cref="Parent"/>.
/// If end time was not set previously, sets <see cref="Duration"/> as a difference between <see cref="DateTime.UtcNow"/> and <see cref="StartTimeUtc"/>
/// Use <see cref="DiagnosticSource.StopActivity(Activity, object)"/> to stop activity and write stop event.
/// </summary>
/// <seealso cref="DiagnosticSource.StopActivity(Activity, object)"/>
/// <seealso cref="SetEndTime(DateTime)"/>
public void Stop()
{
if (Id == null)
{
NotifyError(new InvalidOperationException(SR.ActivityNotStarted));
return;
}
if (!IsFinished)
{
IsFinished = true;
if (Duration == TimeSpan.Zero)
{
SetEndTime(GetUtcNow());
}
Source.NotifyActivityStop(this);
SetCurrent(Parent);
}
}
/* W3C support functionality (see https://w3c.github.io/trace-context) */
/// <summary>
/// Holds the W3C 'tracestate' header as a string.
///
/// Tracestate is intended to carry information supplemental to trace identity contained
/// in traceparent. List of key value pairs carried by tracestate convey information
/// about request position in multiple distributed tracing graphs. It is typically used
/// by distributed tracing systems and should not be used as a general purpose baggage
/// as this use may break correlation of a distributed trace.
///
/// Logically it is just a kind of baggage (if flows just like baggage), but because
/// it is expected to be special cased (it has its own HTTP header), it is more
/// convenient/efficient if it is not lumped in with other baggage.
/// </summary>
public string? TraceStateString
{
get
{
for (Activity? activity = this; activity != null; activity = activity.Parent)
{
string? val = activity._traceState;
if (val != null)
return val;
}
return null;
}
set
{
_traceState = value;
}
}
/// <summary>
/// If the Activity has the W3C format, this returns the ID for the SPAN part of the Id.
/// Otherwise it returns a zero SpanId.
/// </summary>
public ActivitySpanId SpanId
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get
{
if (_spanId is null)
{
if (_id != null && IdFormat == ActivityIdFormat.W3C)
{
ActivitySpanId activitySpanId = ActivitySpanId.CreateFromString(_id.AsSpan(36, 16));
string spanId = activitySpanId.ToHexString();
Interlocked.CompareExchange(ref _spanId, spanId, null);
}
}
return new ActivitySpanId(_spanId);
}
}
/// <summary>
/// If the Activity has the W3C format, this returns the ID for the TraceId part of the Id.
/// Otherwise it returns a zero TraceId.
/// </summary>
public ActivityTraceId TraceId
{
get
{
if (_traceId is null)
{
TrySetTraceIdFromParent();
}
return new ActivityTraceId(_traceId);
}
}
/// <summary>
/// True if the W3CIdFlags.Recorded flag is set.
/// </summary>
public bool Recorded { get => (ActivityTraceFlags & ActivityTraceFlags.Recorded) != 0; }
/// <summary>
/// Indicate if the this Activity object should be populated with all the propagation info and also all other
/// properties such as Links, Tags, and Events.
/// </summary>
public bool IsAllDataRequested { get; set;}
/// <summary>
/// Return the flags (defined by the W3C ID specification) associated with the activity.
/// </summary>
public ActivityTraceFlags ActivityTraceFlags
{
get
{
if (!W3CIdFlagsSet)
{
TrySetTraceFlagsFromParent();
}
return (ActivityTraceFlags)((~ActivityTraceFlagsIsSet) & _w3CIdFlags);
}
set
{
_w3CIdFlags = (byte)(ActivityTraceFlagsIsSet | (byte)value);
}
}
/// <summary>
/// If the parent Activity ID has the W3C format, this returns the ID for the SpanId part of the ParentId.
/// Otherwise it returns a zero SpanId.
/// </summary>
public ActivitySpanId ParentSpanId
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get
{
if (_parentSpanId is null)
{
string? parentSpanId = null;
if (_parentId != null && IsW3CId(_parentId))
{
try
{
parentSpanId = ActivitySpanId.CreateFromString(_parentId.AsSpan(36, 16)).ToHexString();
}
catch { }
}
else if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C)
{
parentSpanId = Parent.SpanId.ToHexString();
}
if (parentSpanId != null)
{
Interlocked.CompareExchange(ref _parentSpanId, parentSpanId, null);
}
}
return new ActivitySpanId(_parentSpanId);
}
}
/* static state (configuration) */
/// <summary>
/// Activity tries to use the same format for IDs as its parent.
/// However if the activity has no parent, it has to do something.
/// This determines the default format we use.
/// </summary>
public static ActivityIdFormat DefaultIdFormat
{
get
{
if (s_defaultIdFormat == ActivityIdFormat.Unknown)
{
#if W3C_DEFAULT_ID_FORMAT
s_defaultIdFormat = LocalAppContextSwitches.DefaultActivityIdFormatIsHierarchial ? ActivityIdFormat.Hierarchical : ActivityIdFormat.W3C;
#else
s_defaultIdFormat = ActivityIdFormat.Hierarchical;
#endif // W3C_DEFAULT_ID_FORMAT
}
return s_defaultIdFormat;
}
set
{
if (!(ActivityIdFormat.Hierarchical <= value && value <= ActivityIdFormat.W3C))
throw new ArgumentException(SR.ActivityIdFormatInvalid);
s_defaultIdFormat = value;
}
}
/// <summary>
/// Sets IdFormat on the Activity before it is started. It takes precedence over
/// Parent.IdFormat, ParentId format, DefaultIdFormat and ForceDefaultIdFormat.
/// </summary>
public Activity SetIdFormat(ActivityIdFormat format)
{
if (_id != null || _spanId != null)
{
NotifyError(new InvalidOperationException(SR.SetFormatOnStartedActivity));
}
else
{
IdFormat = format;
}
return this;
}
/// <summary>
/// Returns true if 'id' has the format of a WC3 id see https://w3c.github.io/trace-context
/// </summary>
private static bool IsW3CId(string id)
{
// A W3CId is
// * 2 hex chars Version (ff is invalid)
// * 1 char - char
// * 32 hex chars traceId
// * 1 char - char
// * 16 hex chars spanId
// * 1 char - char
// * 2 hex chars flags
// = 55 chars (see https://w3c.github.io/trace-context)
// The version (00-fe) is used to indicate that this is a WC3 ID.
return id.Length == 55 &&
('0' <= id[0] && id[0] <= '9' || 'a' <= id[0] && id[0] <= 'f') &&
('0' <= id[1] && id[1] <= '9' || 'a' <= id[1] && id[1] <= 'e');
}
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
internal static bool TryConvertIdToContext(string id, out ActivityContext context)
{
context = default;
if (!IsW3CId(id))
{
return false;
}
ReadOnlySpan<char> traceIdSpan = id.AsSpan(3, 32);
ReadOnlySpan<char> spanIdSpan = id.AsSpan(36, 16);
if (!ActivityTraceId.IsLowerCaseHexAndNotAllZeros(traceIdSpan) || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(spanIdSpan) ||
!HexConverter.IsHexLowerChar(id[53]) || !HexConverter.IsHexLowerChar(id[54]))
{
return false;
}
context = new ActivityContext(new ActivityTraceId(traceIdSpan.ToString()), new ActivitySpanId(spanIdSpan.ToString()), (ActivityTraceFlags) ActivityTraceId.HexByteFromChars(id[53], id[54]));
return true;
}
/// <summary>
/// Dispose will stop the Activity if it is already started and notify any event listeners. Nothing will happen otherwise.
/// </summary>
public void Dispose()
{
if (!IsFinished)
{
Stop();
}
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
/// <summary>
/// SetCustomProperty allow attaching any custom object to this Activity object.
/// If the property name was previously associated with other object, SetCustomProperty will update to use the new propert value instead.
/// </summary>
/// <param name="propertyName"> The name to associate the value with.<see cref="OperationName"/></param>
/// <param name="propertyValue">The object to attach and map to the property name.</param>
public void SetCustomProperty(string propertyName, object? propertyValue)
{
if (_customProperties == null)
{
Interlocked.CompareExchange(ref _customProperties, new ConcurrentDictionary<string, object>(), null);
}
if (propertyValue == null)
{
_customProperties.TryRemove(propertyName, out object _);
}
else
{
_customProperties[propertyName] = propertyValue!;
}
}
/// <summary>
/// GetCustomProperty retrieve previously attached object mapped to the property name.
/// </summary>
/// <param name="propertyName"> The name to get the associated object with.</param>
/// <returns>The object mapped to the property name. Or null if there is no mapping previously done with this property name.</returns>
public object? GetCustomProperty(string propertyName)
{
// We don't check null name here as the dictionary is performing this check anyway.
if (_customProperties == null)
{
return null;
}
return _customProperties.TryGetValue(propertyName, out object? o) ? o! : null;
}
internal static Activity CreateAndStart(ActivitySource source, string name, ActivityKind kind, string? parentId, ActivityContext parentContext,
IEnumerable<KeyValuePair<string, object?>>? tags, IEnumerable<ActivityLink>? links,
DateTimeOffset startTime, ActivityDataRequest request)
{
Activity activity = new Activity(name);
activity.Source = source;
activity.Kind = kind;
if (parentId != null)
{
activity._parentId = parentId;
}
else if (parentContext != default)
{
activity._traceId = parentContext.TraceId.ToString();
activity._parentSpanId = parentContext.SpanId.ToString();
activity.ActivityTraceFlags = parentContext.TraceFlags;
activity._traceState = parentContext.TraceState;
}
else
{
Activity? parent = Current;
if (parent != null)
{
// The parent change should not form a loop. We are actually guaranteed this because
// 1. Un-started activities can't be 'Current' (thus can't be 'parent'), we throw if you try.
// 2. All started activities have a finite parent change (by inductive reasoning).
activity.Parent = parent;
}
}
activity.IdFormat =
ForceDefaultIdFormat ? DefaultIdFormat :
activity.Parent != null ? activity.Parent.IdFormat :
activity._parentSpanId != null ? ActivityIdFormat.W3C :
activity._parentId == null ? DefaultIdFormat :
IsW3CId(activity._parentId) ? ActivityIdFormat.W3C :
ActivityIdFormat.Hierarchical;
if (activity.IdFormat == ActivityIdFormat.W3C)
activity.GenerateW3CId();
else
activity._id = activity.GenerateHierarchicalId();
if (links != null)
{
using (IEnumerator<ActivityLink> enumerator = links.GetEnumerator())
{
if (enumerator.MoveNext())
{
activity._links = new LinkedList<ActivityLink>(enumerator);
}
}
}
if (tags != null)
{
using (IEnumerator<KeyValuePair<string, object?>> enumerator = tags.GetEnumerator())
{
if (enumerator.MoveNext())
{
activity._tags = new TagsLinkedList(enumerator);
}
}
}
activity.StartTimeUtc = startTime == default ? DateTime.UtcNow : startTime.UtcDateTime;
activity.IsAllDataRequested = request == ActivityDataRequest.AllData || request == ActivityDataRequest.AllDataAndRecorded;
if (request == ActivityDataRequest.AllDataAndRecorded)
{
activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded;
}
SetCurrent(activity);
return activity;