-
Notifications
You must be signed in to change notification settings - Fork 769
/
TelemetryHeaderHandler.cs
301 lines (263 loc) · 12.3 KB
/
TelemetryHeaderHandler.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
#region Copyright notice and license
// Copyright 2019 The gRPC 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.
#endregion
#if NET5_0
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
// Copied with permission from https://github.com/dotnet/runtime/blob/7565d60891e43415f5e81b59e50c52dba46ee0d7/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs
namespace Grpc.Shared
{
/// <summary>
/// This handler:
/// 1. Propagates trace headers.
/// 2. Starts and stops System.Net.Http.HttpRequestOut activity.
/// 3. Writes to diagnostics listener.
///
/// These actions are required for OpenTelemetry and for AppInsights to detect HTTP requests.
/// Note: Deprecated diagnostics listener events are still used by AppInsights.
///
/// Usually this logic is handled by https://github.com/dotnet/runtime/blob/7565d60891e43415f5e81b59e50c52dba46ee0d7/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs.
/// DiagnosticsHandler is only run when HttpClientHandler is used.
/// If SocketsHttpHandler is used directly then this handler is added as a subsitute.
/// </summary>
internal sealed class TelemetryHeaderHandler : DelegatingHandler
{
public TelemetryHeaderHandler(HttpMessageHandler innerHandler) : base(innerHandler)
{
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (Activity.Current != null || DiagnosticListener.IsEnabled())
{
return SendAsyncCore(request, cancellationToken);
}
return base.SendAsync(request, cancellationToken);
}
private async Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
{
Activity? activity = null;
var diagnosticListener = DiagnosticListener;
// if there is no listener, but propagation is enabled (with previous IsEnabled() check)
// do not write any events just start/stop Activity and propagate Ids
if (!diagnosticListener.IsEnabled())
{
activity = new Activity(ActivityName);
activity.Start();
InjectHeaders(activity, request);
try
{
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
finally
{
activity.Stop();
}
}
var loggingRequestId = Guid.Empty;
// There is a listener. Check if listener wants to be notified about HttpClient Activities
if (diagnosticListener.IsEnabled(ActivityName, request))
{
activity = new Activity(ActivityName);
// Only send start event to users who subscribed for it, but start activity anyway
if (diagnosticListener.IsEnabled(ActivityStartName))
{
diagnosticListener.StartActivity(activity, new ActivityStartData(request));
}
else
{
activity.Start();
}
}
// try to write System.Net.Http.Request event (deprecated)
if (diagnosticListener.IsEnabled(RequestWriteNameDeprecated))
{
var timestamp = Stopwatch.GetTimestamp();
loggingRequestId = Guid.NewGuid();
diagnosticListener.Write(RequestWriteNameDeprecated, new RequestData(request, loggingRequestId, timestamp));
}
// If we are on at all, we propagate current activity information
var currentActivity = Activity.Current;
if (currentActivity != null)
{
InjectHeaders(currentActivity, request);
}
HttpResponseMessage? response = null;
var taskStatus = TaskStatus.RanToCompletion;
try
{
response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
return response;
}
catch (OperationCanceledException)
{
taskStatus = TaskStatus.Canceled;
// we'll report task status in HttpRequestOut.Stop
throw;
}
catch (Exception ex)
{
taskStatus = TaskStatus.Faulted;
if (diagnosticListener.IsEnabled(ExceptionEventName))
{
// If request was initially instrumented, Activity.Current has all necessary context for logging
// Request is passed to provide some context if instrumentation was disabled and to avoid
// extensive Activity.Tags usage to tunnel request properties
diagnosticListener.Write(ExceptionEventName, new ExceptionData(ex, request));
}
throw;
}
finally
{
// always stop activity if it was started
if (activity != null)
{
diagnosticListener.StopActivity(activity, new ActivityStopData(
response,
// If request is failed or cancelled, there is no response, therefore no information about request;
// pass the request in the payload, so consumers can have it in Stop for failed/canceled requests
// and not retain all requests in Start
request,
taskStatus));
}
// Try to write System.Net.Http.Response event (deprecated)
if (diagnosticListener.IsEnabled(ResponseWriteNameDeprecated))
{
var timestamp = Stopwatch.GetTimestamp();
diagnosticListener.Write(ResponseWriteNameDeprecated,
new ResponseData(
response,
loggingRequestId,
timestamp,
taskStatus));
}
}
}
public static readonly DiagnosticListener DiagnosticListener = new DiagnosticListener(DiagnosticListenerName);
private const string DiagnosticListenerName = "HttpHandlerDiagnosticListener";
private const string RequestWriteNameDeprecated = "System.Net.Http.Request";
private const string ResponseWriteNameDeprecated = "System.Net.Http.Response";
private const string ExceptionEventName = "System.Net.Http.Exception";
private const string ActivityName = "System.Net.Http.HttpRequestOut";
private const string ActivityStartName = "System.Net.Http.HttpRequestOut.Start";
private const string RequestIdHeaderName = "Request-Id";
private const string CorrelationContextHeaderName = "Correlation-Context";
private const string TraceParentHeaderName = "traceparent";
private const string TraceStateHeaderName = "tracestate";
private sealed class ActivityStartData
{
internal ActivityStartData(HttpRequestMessage request)
{
Request = request;
}
public HttpRequestMessage Request { get; }
public override string ToString() => $"{{ {nameof(Request)} = {Request} }}";
}
private sealed class ActivityStopData
{
internal ActivityStopData(HttpResponseMessage? response, HttpRequestMessage request, TaskStatus requestTaskStatus)
{
Response = response;
Request = request;
RequestTaskStatus = requestTaskStatus;
}
public HttpResponseMessage? Response { get; }
public HttpRequestMessage Request { get; }
public TaskStatus RequestTaskStatus { get; }
public override string ToString() => $"{{ {nameof(Response)} = {Response}, {nameof(Request)} = {Request}, {nameof(RequestTaskStatus)} = {RequestTaskStatus} }}";
}
private sealed class ExceptionData
{
internal ExceptionData(Exception exception, HttpRequestMessage request)
{
Exception = exception;
Request = request;
}
public Exception Exception { get; }
public HttpRequestMessage Request { get; }
public override string ToString() => $"{{ {nameof(Exception)} = {Exception}, {nameof(Request)} = {Request} }}";
}
private sealed class RequestData
{
internal RequestData(HttpRequestMessage request, Guid loggingRequestId, long timestamp)
{
Request = request;
LoggingRequestId = loggingRequestId;
Timestamp = timestamp;
}
public HttpRequestMessage Request { get; }
public Guid LoggingRequestId { get; }
public long Timestamp { get; }
public override string ToString() => $"{{ {nameof(Request)} = {Request}, {nameof(LoggingRequestId)} = {LoggingRequestId}, {nameof(Timestamp)} = {Timestamp} }}";
}
private sealed class ResponseData
{
internal ResponseData(HttpResponseMessage? response, Guid loggingRequestId, long timestamp, TaskStatus requestTaskStatus)
{
Response = response;
LoggingRequestId = loggingRequestId;
Timestamp = timestamp;
RequestTaskStatus = requestTaskStatus;
}
public HttpResponseMessage? Response { get; }
public Guid LoggingRequestId { get; }
public long Timestamp { get; }
public TaskStatus RequestTaskStatus { get; }
public override string ToString() => $"{{ {nameof(Response)} = {Response}, {nameof(LoggingRequestId)} = {LoggingRequestId}, {nameof(Timestamp)} = {Timestamp}, {nameof(RequestTaskStatus)} = {RequestTaskStatus} }}";
}
private static void InjectHeaders(Activity currentActivity, HttpRequestMessage request)
{
if (currentActivity.IdFormat == ActivityIdFormat.W3C)
{
if (!request.Headers.Contains(TraceParentHeaderName))
{
request.Headers.TryAddWithoutValidation(TraceParentHeaderName, currentActivity.Id);
if (currentActivity.TraceStateString != null)
{
request.Headers.TryAddWithoutValidation(TraceStateHeaderName, currentActivity.TraceStateString);
}
}
}
else
{
if (!request.Headers.Contains(RequestIdHeaderName))
{
request.Headers.TryAddWithoutValidation(RequestIdHeaderName, currentActivity.Id);
}
}
// we expect baggage to be empty or contain a few items
using (IEnumerator<KeyValuePair<string, string?>> e = currentActivity.Baggage.GetEnumerator())
{
if (e.MoveNext())
{
var baggage = new List<string>();
do
{
KeyValuePair<string, string?> item = e.Current;
baggage.Add(new NameValueHeaderValue(WebUtility.UrlEncode(item.Key), WebUtility.UrlEncode(item.Value)).ToString());
}
while (e.MoveNext());
request.Headers.TryAddWithoutValidation(CorrelationContextHeaderName, baggage);
}
}
}
}
}
#endif