-
Notifications
You must be signed in to change notification settings - Fork 282
/
DiagnosticsMiddleware.cs
229 lines (196 loc) · 9 KB
/
DiagnosticsMiddleware.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.Owin;
using OpenTelemetry.Context.Propagation;
using OpenTelemetry.Instrumentation.Owin.Implementation;
using OpenTelemetry.Internal;
using OpenTelemetry.Trace;
namespace OpenTelemetry.Instrumentation.Owin;
/// <summary>
/// Instruments incoming request with <see cref="Activity"/> and notifies listeners with <see cref="ActivitySource"/>.
/// </summary>
internal sealed class DiagnosticsMiddleware : OwinMiddleware
{
private const string ContextKey = "__OpenTelemetry.Context__";
private static readonly Func<IOwinRequest, string, IEnumerable<string>> OwinRequestHeaderValuesGetter
= (request, name) => request.Headers.GetValues(name);
private static readonly RequestDataHelper RequestDataHelper = new(configureByHttpKnownMethodsEnvironmentalVariable: false);
/// <summary>
/// Initializes a new instance of the <see cref="DiagnosticsMiddleware"/> class.
/// </summary>
/// <param name="next">An optional pointer to the next component.</param>
public DiagnosticsMiddleware(OwinMiddleware next)
: base(next)
{
}
/// <inheritdoc />
public override async Task Invoke(IOwinContext owinContext)
{
long startTimestamp = -1;
try
{
BeginRequest(owinContext);
if (OwinInstrumentationMetrics.HttpServerDuration.Enabled && !owinContext.Environment.ContainsKey(ContextKey))
{
startTimestamp = Stopwatch.GetTimestamp();
}
await this.Next.Invoke(owinContext).ConfigureAwait(false);
RequestEnd(owinContext, null, startTimestamp);
}
catch (Exception ex)
{
RequestEnd(owinContext, ex, startTimestamp);
throw;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void BeginRequest(IOwinContext owinContext)
{
try
{
if (OwinInstrumentationActivitySource.Options == null || OwinInstrumentationActivitySource.Options.Filter?.Invoke(owinContext) == false)
{
OwinInstrumentationEventSource.Log.RequestIsFilteredOut();
return;
}
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
OwinInstrumentationEventSource.Log.RequestFilterException(ex);
return;
}
var textMapPropagator = Propagators.DefaultTextMapPropagator;
var ctx = textMapPropagator.Extract(default, owinContext.Request, OwinRequestHeaderValuesGetter);
Activity? activity = OwinInstrumentationActivitySource.ActivitySource.StartActivity(
OwinInstrumentationActivitySource.IncomingRequestActivityName,
ActivityKind.Server,
ctx.ActivityContext);
if (activity != null)
{
var request = owinContext.Request;
// Note: Display name is intentionally set to a low cardinality
// value because OWIN does not expose any kind of
// route/template. See:
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#name
RequestDataHelper.SetActivityDisplayName(activity, request.Method);
if (activity.IsAllDataRequested)
{
RequestDataHelper.SetHttpMethodTag(activity, request.Method);
activity.SetTag(SemanticConventions.AttributeServerAddress, request.Uri.Host);
activity.SetTag(SemanticConventions.AttributeServerPort, request.Uri.Port);
activity.SetTag(SemanticConventions.AttributeNetworkProtocolVersion, request.Protocol);
activity.SetTag(SemanticConventions.AttributeUrlPath, request.Uri.AbsolutePath);
activity.SetTag(SemanticConventions.AttributeUrlQuery, request.Query);
activity.SetTag(SemanticConventions.AttributeUrlScheme, owinContext.Request.Scheme);
if (request.Headers.TryGetValue("User-Agent", out string[] userAgent) && userAgent.Length > 0)
{
activity.SetTag(SemanticConventions.AttributeUserAgentOriginal, userAgent[0]);
}
try
{
OwinInstrumentationActivitySource.Options?.Enrich?.Invoke(
activity,
OwinEnrichEventType.BeginRequest,
owinContext,
null);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
OwinInstrumentationEventSource.Log.EnrichmentException(ex);
}
}
if (!(textMapPropagator is TraceContextPropagator))
{
Baggage.Current = ctx.Baggage;
}
owinContext.Environment[ContextKey] = activity;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void RequestEnd(IOwinContext owinContext, Exception? exception, long startTimestamp)
{
if (owinContext.Environment.TryGetValue(ContextKey, out object context)
&& context is Activity activity)
{
if (Activity.Current != activity)
{
Activity.Current = activity;
}
if (activity.IsAllDataRequested)
{
var response = owinContext.Response;
if (exception != null)
{
activity.SetStatus(Status.Error);
if (OwinInstrumentationActivitySource.Options?.RecordException == true)
{
activity.RecordException(exception);
}
}
else if (activity.GetStatus().StatusCode == StatusCode.Unset)
{
activity.SetStatus(SpanHelper.ResolveActivityStatusForHttpStatusCode(activity.Kind, response.StatusCode));
}
activity.SetTag(SemanticConventions.AttributeHttpResponseStatusCode, response.StatusCode);
try
{
OwinInstrumentationActivitySource.Options?.Enrich?.Invoke(
activity,
OwinEnrichEventType.EndRequest,
owinContext,
exception);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
OwinInstrumentationEventSource.Log.EnrichmentException(ex);
}
}
activity.Stop();
if (OwinInstrumentationMetrics.HttpServerDuration.Enabled)
{
OwinInstrumentationMetrics.HttpServerDuration.Record(
activity.Duration.TotalSeconds,
new(SemanticConventions.AttributeHttpRequestMethod, owinContext.Request.Method),
new(SemanticConventions.AttributeUrlScheme, owinContext.Request.Scheme),
new(SemanticConventions.AttributeHttpResponseStatusCode, owinContext.Response.StatusCode));
}
if (!(Propagators.DefaultTextMapPropagator is TraceContextPropagator))
{
Baggage.Current = default;
}
}
else if (OwinInstrumentationMetrics.HttpServerDuration.Enabled)
{
var endTimestamp = Stopwatch.GetTimestamp();
var duration = endTimestamp - startTimestamp;
var durationS = duration / (double)Stopwatch.Frequency;
OwinInstrumentationMetrics.HttpServerDuration.Record(
durationS,
new(SemanticConventions.AttributeHttpRequestMethod, owinContext.Request.Method),
new(SemanticConventions.AttributeUrlScheme, owinContext.Request.Scheme),
new(SemanticConventions.AttributeHttpResponseStatusCode, owinContext.Response.StatusCode));
}
}
/// <summary>
/// Gets the OpenTelemetry standard uri tag value for a span based on its request <see cref="Uri"/>.
/// </summary>
/// <param name="uri"><see cref="Uri"/>.</param>
/// <returns>Span uri value.</returns>
private static string GetUriTagValueFromRequestUri(Uri uri, bool disableQueryRedaction)
{
if (string.IsNullOrEmpty(uri.UserInfo) && disableQueryRedaction)
{
return uri.OriginalString;
}
var query = disableQueryRedaction ? uri.Query : RedactionHelper.GetRedactedQueryString(uri.Query);
return string.Concat(uri.Scheme, Uri.SchemeDelimiter, uri.Authority, uri.AbsolutePath, query, uri.Fragment);
}
}