forked from open-telemetry/opentelemetry-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZipkinExporter.cs
More file actions
276 lines (232 loc) · 8.27 KB
/
ZipkinExporter.cs
File metadata and controls
276 lines (232 loc) · 8.27 KB
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
// <copyright file="ZipkinExporter.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.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
#if NET452
using Newtonsoft.Json;
#else
using System.Text.Json;
#endif
using System.Threading;
using System.Threading.Tasks;
using OpenTelemetry.Exporter.Zipkin.Implementation;
using OpenTelemetry.Resources;
namespace OpenTelemetry.Exporter.Zipkin
{
/// <summary>
/// Zipkin exporter.
/// </summary>
public class ZipkinExporter : BaseExporter<Activity>
{
private readonly ZipkinExporterOptions options;
#if !NET452
private readonly int maxPayloadSizeInBytes;
#endif
private readonly HttpClient httpClient;
/// <summary>
/// Initializes a new instance of the <see cref="ZipkinExporter"/> class.
/// </summary>
/// <param name="options">Configuration options.</param>
/// <param name="client">Http client to use to upload telemetry.</param>
internal ZipkinExporter(ZipkinExporterOptions options, HttpClient client = null)
{
this.options = options ?? throw new ArgumentNullException(nameof(options));
#if !NET452
this.maxPayloadSizeInBytes = (!options.MaxPayloadSizeInBytes.HasValue || options.MaxPayloadSizeInBytes <= 0) ? ZipkinExporterOptions.DefaultMaxPayloadSizeInBytes : options.MaxPayloadSizeInBytes.Value;
#endif
this.httpClient = client ?? new HttpClient();
}
internal ZipkinEndpoint LocalEndpoint { get; private set; }
/// <inheritdoc/>
public override ExportResult Export(in Batch<Activity> batch)
{
if (this.LocalEndpoint == null)
{
this.SetLocalEndpointFromResource(this.ParentProvider.GetResource());
}
// Prevent Zipkin's HTTP operations from being instrumented.
using var scope = SuppressInstrumentationScope.Begin();
try
{
var requestUri = this.options.Endpoint;
using var request = new HttpRequestMessage(HttpMethod.Post, requestUri)
{
Content = new JsonContent(this, batch),
};
using var response = this.httpClient.SendAsync(request, CancellationToken.None).GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
return ExportResult.Success;
}
catch (Exception ex)
{
ZipkinExporterEventSource.Log.FailedExport(ex);
return ExportResult.Failure;
}
}
internal void SetLocalEndpointFromResource(Resource resource)
{
var hostName = ResolveHostName();
string ipv4 = null;
string ipv6 = null;
if (!string.IsNullOrEmpty(hostName))
{
ipv4 = ResolveHostAddress(hostName, AddressFamily.InterNetwork);
ipv6 = ResolveHostAddress(hostName, AddressFamily.InterNetworkV6);
}
string serviceName = null;
Dictionary<string, object> tags = null;
foreach (var label in resource.Attributes)
{
string key = label.Key;
switch (key)
{
case ResourceSemanticConventions.AttributeServiceName:
serviceName = label.Value as string;
continue;
}
if (tags == null)
{
tags = new Dictionary<string, object>();
}
tags[key] = label.Value;
}
if (string.IsNullOrEmpty(serviceName))
{
serviceName = this.options.ServiceName;
}
this.LocalEndpoint = new ZipkinEndpoint(
serviceName,
ipv4,
ipv6,
port: null,
tags);
}
private static string ResolveHostAddress(string hostName, AddressFamily family)
{
string result = null;
try
{
var results = Dns.GetHostAddresses(hostName);
if (results != null && results.Length > 0)
{
foreach (var addr in results)
{
if (addr.AddressFamily.Equals(family))
{
var sanitizedAddress = new IPAddress(addr.GetAddressBytes()); // Construct address sans ScopeID
result = sanitizedAddress.ToString();
break;
}
}
}
}
catch (Exception)
{
// Ignore
}
return result;
}
private static string ResolveHostName()
{
string result = null;
try
{
result = Dns.GetHostName();
if (!string.IsNullOrEmpty(result))
{
var response = Dns.GetHostEntry(result);
if (response != null)
{
return response.HostName;
}
}
}
catch (Exception)
{
// Ignore
}
return result;
}
private class JsonContent : HttpContent
{
private static readonly MediaTypeHeaderValue JsonHeader = new MediaTypeHeaderValue("application/json")
{
CharSet = "utf-8",
};
private readonly ZipkinExporter exporter;
private readonly Batch<Activity> batch;
#if NET452
private JsonWriter writer;
#else
private Utf8JsonWriter writer;
#endif
public JsonContent(ZipkinExporter exporter, in Batch<Activity> batch)
{
this.exporter = exporter;
this.batch = batch;
this.Headers.ContentType = JsonHeader;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
#if NET452
StreamWriter streamWriter = new StreamWriter(stream);
this.writer = new JsonTextWriter(streamWriter);
#else
if (this.writer == null)
{
this.writer = new Utf8JsonWriter(stream);
}
else
{
this.writer.Reset(stream);
}
#endif
this.writer.WriteStartArray();
foreach (var activity in this.batch)
{
var zipkinSpan = activity.ToZipkinSpan(this.exporter.LocalEndpoint, this.exporter.options.UseShortTraceIds);
zipkinSpan.Write(this.writer);
zipkinSpan.Return();
#if !NET452
if (this.writer.BytesPending >= this.exporter.maxPayloadSizeInBytes)
{
this.writer.Flush();
}
#endif
}
this.writer.WriteEndArray();
this.writer.Flush();
#if NET452
return Task.FromResult(true);
#else
return Task.CompletedTask;
#endif
}
protected override bool TryComputeLength(out long length)
{
// We can't know the length of the content being pushed to the output stream.
length = -1;
return false;
}
}
}
}