-
Notifications
You must be signed in to change notification settings - Fork 770
/
HttpHandlerDiagnosticListener.cs
181 lines (156 loc) · 7.64 KB
/
HttpHandlerDiagnosticListener.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
// <copyright file="HttpHandlerDiagnosticListener.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.Net.Http;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using OpenTelemetry.Context.Propagation;
using OpenTelemetry.Trace;
namespace OpenTelemetry.Instrumentation.Dependencies.Implementation
{
internal class HttpHandlerDiagnosticListener : ListenerHandler
{
private static readonly Func<HttpRequestMessage, string, IEnumerable<string>> HttpRequestMessageHeaderValuesGetter = (request, name) =>
{
if (request.Headers.TryGetValues(name, out var values))
{
return values;
}
return null;
};
private static readonly Action<HttpRequestMessage, string, string> HttpRequestMessageHeaderValueSetter = (request, name, value) => request.Headers.Add(name, value);
private static readonly Regex CoreAppMajorVersionCheckRegex = new Regex("^\\.NETCoreApp,Version=v(\\d+)\\.", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly ActivitySourceAdapter activitySource;
private readonly PropertyFetcher startRequestFetcher = new PropertyFetcher("Request");
private readonly PropertyFetcher stopResponseFetcher = new PropertyFetcher("Response");
private readonly PropertyFetcher stopExceptionFetcher = new PropertyFetcher("Exception");
private readonly PropertyFetcher stopRequestStatusFetcher = new PropertyFetcher("RequestTaskStatus");
private readonly bool httpClientSupportsW3C = false;
private readonly HttpClientInstrumentationOptions options;
public HttpHandlerDiagnosticListener(HttpClientInstrumentationOptions options, ActivitySourceAdapter activitySource)
: base("HttpHandlerDiagnosticListener")
{
var framework = Assembly
.GetEntryAssembly()?
.GetCustomAttribute<TargetFrameworkAttribute>()?
.FrameworkName;
// Depending on the .NET version/flavor this will look like
// '.NETCoreApp,Version=v3.0', '.NETCoreApp,Version = v2.2' or '.NETFramework,Version = v4.7.1'
if (framework != null)
{
var match = CoreAppMajorVersionCheckRegex.Match(framework);
this.httpClientSupportsW3C = match.Success && int.Parse(match.Groups[1].Value) >= 3;
}
this.options = options;
this.activitySource = activitySource;
}
public override void OnStartActivity(Activity activity, object payload)
{
if (!(this.startRequestFetcher.Fetch(payload) is HttpRequestMessage request))
{
InstrumentationEventSource.Log.NullPayload(nameof(HttpHandlerDiagnosticListener), nameof(this.OnStartActivity));
return;
}
if (this.options.TextFormat.IsInjected(request, HttpRequestMessageHeaderValuesGetter))
{
// this request is already instrumented, we should back off
activity.IsAllDataRequested = false;
return;
}
activity.SetKind(ActivityKind.Client);
activity.DisplayName = HttpTagHelper.GetOperationNameForHttpMethod(request.Method);
this.activitySource.Start(activity);
if (activity.IsAllDataRequested)
{
activity.AddTag(SemanticConventions.AttributeHTTPMethod, HttpTagHelper.GetNameForHttpMethod(request.Method));
activity.AddTag(SemanticConventions.AttributeHTTPHost, HttpTagHelper.GetHostTagValueFromRequestUri(request.RequestUri));
activity.AddTag(SemanticConventions.AttributeHTTPURL, request.RequestUri.OriginalString);
if (this.options.SetHttpFlavor)
{
activity.AddTag(SemanticConventions.AttributeHTTPFlavor, HttpTagHelper.GetFlavorTagValueFromProtocolVersion(request.Version));
}
}
if (!(this.httpClientSupportsW3C && this.options.TextFormat is TraceContextFormatActivity))
{
this.options.TextFormat.Inject(activity.Context, request, HttpRequestMessageHeaderValueSetter);
}
}
public override void OnStopActivity(Activity activity, object payload)
{
if (activity.IsAllDataRequested)
{
var requestTaskStatus = this.stopRequestStatusFetcher.Fetch(payload) as TaskStatus?;
if (requestTaskStatus.HasValue)
{
if (requestTaskStatus != TaskStatus.RanToCompletion)
{
if (requestTaskStatus == TaskStatus.Canceled)
{
activity.SetStatus(Status.Cancelled);
}
else if (requestTaskStatus != TaskStatus.Faulted)
{
// Faults are handled in OnException and should already have a span.Status of Unknown w/ Description.
activity.SetStatus(Status.Unknown);
}
}
}
if (this.stopResponseFetcher.Fetch(payload) is HttpResponseMessage response)
{
// response could be null for DNS issues, timeouts, etc...
activity.AddTag(SemanticConventions.AttributeHTTPStatusCode, response.StatusCode.ToString());
activity.SetStatus(
SpanHelper
.ResolveSpanStatusForHttpStatusCode((int)response.StatusCode)
.WithDescription(response.ReasonPhrase));
}
}
this.activitySource.Stop(activity);
}
public override void OnException(Activity activity, object payload)
{
if (activity.IsAllDataRequested)
{
if (!(this.stopExceptionFetcher.Fetch(payload) is Exception exc))
{
InstrumentationEventSource.Log.NullPayload(nameof(HttpHandlerDiagnosticListener), nameof(this.OnException));
return;
}
if (exc is HttpRequestException)
{
if (exc.InnerException is SocketException exception)
{
switch (exception.SocketErrorCode)
{
case SocketError.HostNotFound:
activity.SetStatus(Status.InvalidArgument.WithDescription(exc.Message));
return;
}
}
if (exc.InnerException != null)
{
activity.SetStatus(Status.Unknown.WithDescription(exc.Message));
}
}
}
}
}
}