-
Notifications
You must be signed in to change notification settings - Fork 820
/
Copy pathOtlpExportClient.cs
347 lines (290 loc) · 11.9 KB
/
OtlpExportClient.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#if NETFRAMEWORK
using System.Net.Http;
#endif
using System.Net;
using System.Net.Http.Headers;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient;
internal abstract class OtlpExportClient : IExportClient
{
private static readonly Version Http2RequestVersion = new(2, 0);
#if NET
private static readonly bool SynchronousSendSupportedByCurrentPlatform;
static OtlpExportClient()
{
#if NET
// See: https://github.com/dotnet/runtime/blob/280f2a0c60ce0378b8db49adc0eecc463d00fe5d/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs#L767
SynchronousSendSupportedByCurrentPlatform = !OperatingSystem.IsAndroid()
&& !OperatingSystem.IsIOS()
&& !OperatingSystem.IsTvOS()
&& !OperatingSystem.IsBrowser();
#endif
}
#endif
protected OtlpExportClient(OtlpExporterOptions options, HttpClient httpClient, string signalPath)
{
Guard.ThrowIfNull(options);
Guard.ThrowIfNull(httpClient);
Guard.ThrowIfNull(signalPath);
Uri exporterEndpoint;
if (options.Protocol == OtlpExportProtocol.Grpc)
{
exporterEndpoint = options.Endpoint.AppendPathIfNotPresent(signalPath);
}
else
{
exporterEndpoint = options.AppendSignalPathToEndpoint
? options.Endpoint.AppendPathIfNotPresent(signalPath)
: options.Endpoint;
}
this.Endpoint = new UriBuilder(exporterEndpoint).Uri;
this.Headers = options.GetHeaders<Dictionary<string, string>>((d, k, v) => d.Add(k, v));
this.HttpClient = httpClient;
}
internal HttpClient HttpClient { get; }
internal Uri Endpoint { get; }
internal IReadOnlyDictionary<string, string> Headers { get; }
internal abstract MediaTypeHeaderValue MediaTypeHeader { get; }
internal virtual bool RequireHttp2 => false;
public abstract ExportClientResponse SendExportRequest(byte[] buffer, int contentLength, DateTime deadlineUtc, CancellationToken cancellationToken = default);
/// <inheritdoc/>
public bool Shutdown(int timeoutMilliseconds)
{
this.HttpClient.CancelPendingRequests();
return true;
}
protected HttpRequestMessage CreateHttpRequest(byte[] buffer, int contentLength)
{
var request = new HttpRequestMessage(HttpMethod.Post, this.Endpoint);
if (this.RequireHttp2)
{
request.Version = Http2RequestVersion;
#if NET6_0_OR_GREATER
request.VersionPolicy = HttpVersionPolicy.RequestVersionExact;
#endif
}
foreach (var header in this.Headers)
{
request.Headers.Add(header.Key, header.Value);
}
// TODO: Support compression.
request.Content = new ByteArrayContent(buffer, 0, contentLength);
request.Content.Headers.ContentType = this.MediaTypeHeader;
return request;
}
protected (Uri Uri, HttpMethod Method, Dictionary<string, string> Headers, byte[] Content, string ContentType)
CreateSynchronousRequestParams(byte[] buffer, int contentLength)
{
Uri uri = this.Endpoint;
HttpMethod method = HttpMethod.Post;
var headers = new Dictionary<string, string>();
foreach (var header in this.Headers)
{
headers[header.Key] = header.Value;
}
byte[] content;
if (contentLength < buffer.Length)
{
content = new byte[contentLength];
Array.Copy(buffer, 0, content, 0, contentLength);
}
else
{
content = buffer;
}
string contentType = this.MediaTypeHeader.ToString();
return (uri, method, headers, content, contentType);
}
protected HttpResponseMessage SendHttpRequest(HttpRequestMessage request, CancellationToken cancellationToken)
{
#if NET
// Note: SendAsync must be used with HTTP/2 because synchronous send is
// not supported.
return this.RequireHttp2 || !SynchronousSendSupportedByCurrentPlatform
? this.HttpClient.SendAsync(request, cancellationToken).GetAwaiter().GetResult()
: this.HttpClient.Send(request, cancellationToken);
#else
return this.HttpClient.SendAsync(request, cancellationToken).GetAwaiter().GetResult();
#endif
}
protected HttpResponseMessage SendHttpRequestSynchronous(Uri uri, HttpMethod method, Dictionary<string, string> headers = null, byte[] content = null, string contentType = null, CancellationToken cancellationToken = default)
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = method.ToString();
webRequest.AllowAutoRedirect = true;
if (headers != null)
{
foreach (var header in headers)
{
if (WebHeaderCollection.IsRestricted(header.Key))
{
switch (header.Key.ToLowerInvariant())
{
case "accept":
webRequest.Accept = header.Value;
break;
case "connection":
webRequest.Connection = header.Value;
break;
case "content-type":
break;
case "user-agent":
webRequest.UserAgent = header.Value;
break;
case "content-length":
break;
case "expect":
webRequest.Expect = header.Value;
break;
case "date":
webRequest.Date = DateTime.Parse(header.Value);
break;
case "host":
break;
case "if-modified-since":
webRequest.IfModifiedSince = DateTime.Parse(header.Value);
break;
case "range":
string[] range = header.Value.Split('=', ',');
if (range.Length >= 2 && range[0].Trim().Equals("bytes"))
{
string[] startEnd = range[1].Split('-');
if (startEnd.Length >= 2)
{
long start = long.Parse(startEnd[0]);
long end = long.Parse(startEnd[1]);
webRequest.AddRange(start, end);
}
}
break;
case "referer":
webRequest.Referer = header.Value;
break;
case "transfer-encoding":
webRequest.TransferEncoding = header.Value;
break;
}
}
else
{
webRequest.Headers.Add(header.Key, header.Value);
}
}
}
if (!string.IsNullOrEmpty(contentType))
{
webRequest.ContentType = contentType;
}
if (content != null && content.Length > 0)
{
webRequest.ContentLength = content.Length;
using (var requestStream = webRequest.GetRequestStream())
{
requestStream.Write(content, 0, content.Length);
}
}
else
{
webRequest.ContentLength = 0;
}
cancellationToken.Register(webRequest.Abort);
try
{
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
return CreateResponseFromWebResponse(webResponse);
}
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse errorResponse)
{
return CreateResponseFromWebResponse(errorResponse);
}
// For cases where there's no response (timeout, etc.)
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
ReasonPhrase = ex.Message,
};
return response;
}
catch (Exception ex)
{
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
ReasonPhrase = ex.Message,
};
return response;
}
}
private static HttpResponseMessage CreateResponseFromWebResponse(HttpWebResponse webResponse)
{
var response = new HttpResponseMessage(webResponse.StatusCode)
{
ReasonPhrase = webResponse.StatusDescription,
Version = new Version(webResponse.ProtocolVersion.ToString()),
};
foreach (string headerName in webResponse.Headers.AllKeys)
{
if (headerName.Equals("Content-Length", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Type", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Encoding", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Language", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Location", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-MD5", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Range", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Disposition", StringComparison.OrdinalIgnoreCase))
{
continue;
}
response.Headers.TryAddWithoutValidation(headerName, webResponse.Headers[headerName]);
}
if (webResponse.ContentLength != 0)
{
var responseStream = webResponse.GetResponseStream();
var memoryStream = new MemoryStream();
if (responseStream != null)
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
}
memoryStream.Position = 0;
}
response.Content = new ByteArrayContent(memoryStream.ToArray());
if (!string.IsNullOrEmpty(webResponse.ContentType))
{
response.Content.Headers.ContentType = new MediaTypeHeaderValue(webResponse.ContentType);
}
if (webResponse.ContentLength > 0)
{
response.Content.Headers.ContentLength = webResponse.ContentLength;
}
var contentEncoding = webResponse.Headers["Content-Encoding"];
if (!string.IsNullOrEmpty(contentEncoding))
{
response.Content.Headers.TryAddWithoutValidation("Content-Encoding", contentEncoding);
}
var contentLanguage = webResponse.Headers["Content-Language"];
if (!string.IsNullOrEmpty(contentLanguage))
{
response.Content.Headers.TryAddWithoutValidation("Content-Language", contentLanguage);
}
// Add other content headers if needed
var contentDisposition = webResponse.Headers["Content-Disposition"];
if (!string.IsNullOrEmpty(contentDisposition))
{
response.Content.Headers.TryAddWithoutValidation("Content-Disposition", contentDisposition);
}
}
else
{
response.Content = new ByteArrayContent([]);
}
return response;
}
}