-
Notifications
You must be signed in to change notification settings - Fork 760
/
TextMapPropagator.cs
265 lines (222 loc) · 9.57 KB
/
TextMapPropagator.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
// <copyright file="TextMapPropagator.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.Text;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Context.Propagation
{
/// <summary>
/// W3C trace context text wire protocol formatter. See https://github.com/w3c/distributed-tracing/.
/// </summary>
public class TextMapPropagator : IPropagator
{
private const string TraceParent = "traceparent";
private const string TraceState = "tracestate";
private static readonly int VersionPrefixIdLength = "00-".Length;
private static readonly int TraceIdLength = "0af7651916cd43dd8448eb211c80319c".Length;
private static readonly int VersionAndTraceIdLength = "00-0af7651916cd43dd8448eb211c80319c-".Length;
private static readonly int SpanIdLength = "00f067aa0ba902b7".Length;
private static readonly int VersionAndTraceIdAndSpanIdLength = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-".Length;
private static readonly int OptionsLength = "00".Length;
private static readonly int TraceparentLengthV0 = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-00".Length;
/// <inheritdoc/>
public ISet<string> Fields => new HashSet<string> { TraceState, TraceParent };
/// <inheritdoc/>
public PropagationContext Extract<T>(PropagationContext context, T carrier, Func<T, string, IEnumerable<string>> getter)
{
if (context.ActivityContext.IsValid())
{
// If a valid context has already been extracted, perform a noop.
return context;
}
if (carrier == null)
{
OpenTelemetryApiEventSource.Log.FailedToExtractActivityContext(nameof(TextMapPropagator), "null carrier");
return context;
}
if (getter == null)
{
OpenTelemetryApiEventSource.Log.FailedToExtractActivityContext(nameof(TextMapPropagator), "null getter");
return context;
}
try
{
var traceparentCollection = getter(carrier, TraceParent);
// There must be a single traceparent
if (traceparentCollection == null || traceparentCollection.Count() != 1)
{
return context;
}
var traceparent = traceparentCollection.First();
var traceparentParsed = TryExtractTraceparent(traceparent, out var traceId, out var spanId, out var traceoptions);
if (!traceparentParsed)
{
return context;
}
string tracestate = null;
var tracestateCollection = getter(carrier, TraceState);
if (tracestateCollection?.Any() ?? false)
{
TryExtractTracestate(tracestateCollection.ToArray(), out tracestate);
}
return new PropagationContext(
new ActivityContext(traceId, spanId, traceoptions, tracestate, isRemote: true),
context.Baggage);
}
catch (Exception ex)
{
OpenTelemetryApiEventSource.Log.ActivityContextExtractException(nameof(TextMapPropagator), ex);
}
// in case of exception indicate to upstream that there is no parseable context from the top
return context;
}
/// <inheritdoc/>
public void Inject<T>(PropagationContext context, T carrier, Action<T, string, string> setter)
{
if (context.ActivityContext.TraceId == default || context.ActivityContext.SpanId == default)
{
OpenTelemetryApiEventSource.Log.FailedToInjectActivityContext(nameof(TextMapPropagator), "Invalid context");
return;
}
if (carrier == null)
{
OpenTelemetryApiEventSource.Log.FailedToInjectActivityContext(nameof(TextMapPropagator), "null carrier");
return;
}
if (setter == null)
{
OpenTelemetryApiEventSource.Log.FailedToInjectActivityContext(nameof(TextMapPropagator), "null setter");
return;
}
var traceparent = string.Concat("00-", context.ActivityContext.TraceId.ToHexString(), "-", context.ActivityContext.SpanId.ToHexString());
traceparent = string.Concat(traceparent, (context.ActivityContext.TraceFlags & ActivityTraceFlags.Recorded) != 0 ? "-01" : "-00");
setter(carrier, TraceParent, traceparent);
string tracestateStr = context.ActivityContext.TraceState;
if (tracestateStr?.Length > 0)
{
setter(carrier, TraceState, tracestateStr);
}
}
internal static bool TryExtractTraceparent(string traceparent, out ActivityTraceId traceId, out ActivitySpanId spanId, out ActivityTraceFlags traceOptions)
{
// from https://github.com/w3c/distributed-tracing/blob/master/trace_context/HTTP_HEADER_FORMAT.md
// traceparent: 00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-01
traceId = default;
spanId = default;
traceOptions = default;
var bestAttempt = false;
if (string.IsNullOrWhiteSpace(traceparent) || traceparent.Length < TraceparentLengthV0)
{
return false;
}
// if version does not end with delimiter
if (traceparent[VersionPrefixIdLength - 1] != '-')
{
return false;
}
// or version is not a hex (will throw)
var version0 = HexCharToByte(traceparent[0]);
var version1 = HexCharToByte(traceparent[1]);
if (version0 == 0xf && version1 == 0xf)
{
return false;
}
if (version0 > 0)
{
// expected version is 00
// for higher versions - best attempt parsing of trace id, span id, etc.
bestAttempt = true;
}
if (traceparent[VersionAndTraceIdLength - 1] != '-')
{
return false;
}
try
{
traceId = ActivityTraceId.CreateFromString(traceparent.AsSpan().Slice(VersionPrefixIdLength, TraceIdLength));
}
catch (ArgumentOutOfRangeException)
{
// it's ok to still parse tracestate
return false;
}
if (traceparent[VersionAndTraceIdAndSpanIdLength - 1] != '-')
{
return false;
}
byte options1;
try
{
spanId = ActivitySpanId.CreateFromString(traceparent.AsSpan().Slice(VersionAndTraceIdLength, SpanIdLength));
options1 = HexCharToByte(traceparent[VersionAndTraceIdAndSpanIdLength + 1]);
}
catch (ArgumentOutOfRangeException)
{
// it's ok to still parse tracestate
return false;
}
if ((options1 & 1) == 1)
{
traceOptions |= ActivityTraceFlags.Recorded;
}
if ((!bestAttempt) && (traceparent.Length != VersionAndTraceIdAndSpanIdLength + OptionsLength))
{
return false;
}
if (bestAttempt)
{
if ((traceparent.Length > TraceparentLengthV0) && (traceparent[TraceparentLengthV0] != '-'))
{
return false;
}
}
return true;
}
internal static bool TryExtractTracestate(string[] tracestateCollection, out string tracestateResult)
{
tracestateResult = string.Empty;
if (tracestateCollection != null)
{
var result = new StringBuilder();
// Iterate in reverse order because when call builder set the elements is added in the
// front of the list.
for (int i = tracestateCollection.Length - 1; i >= 0; i--)
{
if (string.IsNullOrEmpty(tracestateCollection[i]))
{
return false;
}
result.Append(tracestateCollection[i]);
}
tracestateResult = result.ToString();
}
return true;
}
private static byte HexCharToByte(char c)
{
if (((c >= '0') && (c <= '9'))
|| ((c >= 'a') && (c <= 'f'))
|| ((c >= 'A') && (c <= 'F')))
{
return Convert.ToByte(c);
}
throw new ArgumentOutOfRangeException(nameof(c), $"Invalid character: {c}.");
}
}
}