-
Notifications
You must be signed in to change notification settings - Fork 25
/
SignalFxMetricHandler.cs
373 lines (327 loc) · 14.2 KB
/
SignalFxMetricHandler.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
using StackExchange.Metrics.Infrastructure;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace StackExchange.Metrics.Handlers
{
/// <summary>
/// Implements <see cref="IMetricHandler"/> by sending data to SignalFx
/// </summary>
public class SignalFxMetricHandler : IMetricHandler
{
IMetricHandler _activeHandler;
Uri _baseUri;
string _accessToken;
/// <summary>
/// Constructs a new <see cref="SignalFxMetricHandler" /> pointing at the specified <see cref="Uri" />.
/// </summary>
/// <param name="baseUri">
/// <see cref="Uri" /> of a SignalFx endpoint.
/// </param>
/// <remarks>
/// If the URI points at a UDP endpoint then a StatsD endpoint is assumed, otherwise if the URI
/// is HTTP or HTTPS then a REST endpoint is assumed
/// </remarks>
public SignalFxMetricHandler(Uri baseUri)
{
_baseUri = baseUri;
_activeHandler = GetHandler();
}
/// <summary>
/// Constructs a new <see cref="SignalFxMetricHandler" /> pointing at the specified <see cref="Uri" />
/// and using the specified access token.
/// </summary>
/// <param name="baseUri">
/// <see cref="Uri" /> of a SignalFx endpoint.
/// </param>
/// <param name="accessToken">
/// An access token.
/// </param>
/// <remarks>
/// If the URI points at a UDP endpoint then a StatsD endpoint is assumed, otherwise if the URI
/// is HTTP or HTTPS then a REST endpoint is assumed
/// </remarks>
public SignalFxMetricHandler(Uri baseUri, string accessToken)
{
_accessToken = accessToken ?? throw new ArgumentNullException(nameof(accessToken));
_baseUri = baseUri;
_activeHandler = GetHandler();
}
/// <summary>
/// Gets or sets the maximum number of payloads we can keep before we consider our buffers full.
/// </summary>
public long MaxPayloadCount
{
get
{
if (_activeHandler is BufferedMetricHandler bufferedHandler)
{
return bufferedHandler.MaxPayloadCount;
}
return 0;
}
set
{
if (_activeHandler is BufferedMetricHandler bufferedHandler)
{
bufferedHandler.MaxPayloadCount = value;
}
}
}
/// <summary>
/// Gets or sets the base URI used by the handler.
/// </summary>
public Uri BaseUri
{
get => _baseUri;
set
{
_baseUri = value;
var oldHandler = _activeHandler;
if (oldHandler != null)
{
oldHandler.Dispose();
}
_activeHandler = GetHandler();
}
}
/// <inheritdoc />
public IMetricReadingBatch BeginBatch() => _activeHandler.BeginBatch();
/// <inheritdoc />
public void Dispose() => _activeHandler.Dispose();
/// <inheritdoc />
public ValueTask FlushAsync(TimeSpan delayBetweenRetries, int maxRetries, Action<AfterSendInfo> afterSend, Action<Exception> exceptionHandler)
=> _activeHandler?.FlushAsync(delayBetweenRetries, maxRetries, afterSend, exceptionHandler) ?? default(ValueTask);
/// <inheritdoc />
public void SerializeMetadata(IEnumerable<Metadata> metadata) => _activeHandler.SerializeMetadata(metadata);
/// <inheritdoc />
public void SerializeMetric(in MetricReading reading) => _activeHandler.SerializeMetric(reading);
private IMetricHandler GetHandler()
{
if (_baseUri == null)
{
return NoOpMetricHandler.Instance;
}
if (_baseUri.Scheme == "udp")
{
return new BufferedStatsdMetricHandler(_baseUri.Host, (ushort)_baseUri.Port);
}
if (_baseUri.Scheme == Uri.UriSchemeHttp || _baseUri.Scheme == Uri.UriSchemeHttps)
{
if (_accessToken != null)
{
return new JsonMetricHandler(_baseUri, _accessToken);
}
return new JsonMetricHandler(_baseUri);
}
throw new ArgumentOutOfRangeException(nameof(_baseUri), $"URI scheme {_baseUri.Scheme} is not supported.");
}
/// <summary>
/// Implements <see cref="BufferedHttpMetricHandler" /> by sending data to the SignalFX REST API.
/// </summary>
private class JsonMetricHandler : BufferedHttpMetricHandler
{
Uri _baseUri;
Uri _metricUri;
readonly string _accessToken;
static readonly JsonSerializerOptions s_jsonOptions = new JsonSerializerOptions
{
Converters =
{
new JsonEpochMillisecondsConverter(),
new JsonMetricReadingConverter()
}
};
static readonly byte[] s_comma = Encoding.UTF8.GetBytes(",");
static readonly byte[] s_counterPreamble = Encoding.UTF8.GetBytes(@"{""counter"":[");
static readonly byte[] s_cumulativeCounterPreamble = Encoding.UTF8.GetBytes(@"{""cumulative_counter"":[");
static readonly byte[] s_gaugePreamble = Encoding.UTF8.GetBytes(@"{""gauge"":[");
static readonly byte[] s_postamble = Encoding.UTF8.GetBytes("]}");
/// <summary>
/// Constructs a new <see cref="JsonMetricHandler" /> pointing at the specified <see cref="Uri" />.
/// </summary>
/// <param name="baseUri">
/// <see cref="Uri" /> of a SignalFx endpoint.
/// </param>
public JsonMetricHandler(Uri baseUri)
{
BaseUri = baseUri;
}
/// <summary>
/// Constructs a new <see cref="JsonMetricHandler" /> pointing at the specified URL
/// and using the given API key.
/// </summary>
/// <param name="baseUri">
/// <see cref="Uri" /> of a SignalFx endpoint.
/// </param>
/// <param name="accessToken">
/// An access token.
/// </param>
public JsonMetricHandler(Uri baseUri, string accessToken) : this(baseUri)
{
_accessToken = accessToken ?? throw new ArgumentNullException(nameof(accessToken));
}
/// <summary>
/// Gets or sets the base URI used by the handler.
/// </summary>
public Uri BaseUri
{
get => _baseUri;
set
{
_baseUri = value;
_metricUri = value != null ? new Uri(value, "/v2/datapoint") : null;
}
}
/// <inheritdoc />
protected override HttpClient CreateHttpClient()
{
var httpClient = base.CreateHttpClient();
if (_accessToken != null)
{
httpClient.DefaultRequestHeaders.Add("X-SF-TOKEN", _accessToken);
}
return httpClient;
}
/// <inheritdoc />
protected override int GetPreambleLength(PayloadType payloadType)
{
switch (payloadType)
{
case PayloadType.Counter:
return s_counterPreamble.Length;
case PayloadType.CumulativeCounter:
return s_cumulativeCounterPreamble.Length;
case PayloadType.Gauge:
return s_gaugePreamble.Length;
default:
return 0;
}
}
/// <inheritdoc />
protected override int GetPostambleLength(PayloadType payloadType) => payloadType == PayloadType.Metadata ? 0 : s_postamble.Length;
/// <inheritdoc />
protected override void SerializeMetric(IBufferWriter<byte> writer, in MetricReading reading)
{
if (_metricUri == null)
{
// no endpoint to write to, don't bother
return;
}
writer.Write(s_comma);
using (var utfWriter = new Utf8JsonWriter(writer))
{
JsonSerializer.Serialize(utfWriter, reading, s_jsonOptions);
}
}
/// <inheritdoc />
protected override void SerializeMetadata(IBufferWriter<byte> writer, IEnumerable<Metadata> metadata)
{
// this particular implementation doesn't understand metadata
}
/// <inheritdoc />
protected override ValueTask SendCounterAsync(ReadOnlySequence<byte> sequence) => SendAsync(_metricUri, HttpMethod.Post, PayloadType.Counter, MediaTypes.Json, sequence);
/// <inheritdoc />
protected override ValueTask SendCumulativeCounterAsync(ReadOnlySequence<byte> sequence) => SendAsync(_metricUri, HttpMethod.Post, PayloadType.CumulativeCounter, MediaTypes.Json, sequence);
/// <inheritdoc />
protected override ValueTask SendGaugeAsync(ReadOnlySequence<byte> sequence) => SendAsync(_metricUri, HttpMethod.Post, PayloadType.Gauge, MediaTypes.Json, sequence);
/// <inheritdoc />
protected override ValueTask SendMetadataAsync(ReadOnlySequence<byte> sequence)
{
// this particular implementation doesn't understand metadata
return default;
}
/// <inheritdoc />
protected override Task WritePreambleAsync(Stream stream, PayloadType payloadType)
{
if (payloadType == PayloadType.Metadata)
{
return Task.CompletedTask;
}
// SignalFX needs a different preamble depending upon the
// type of metric we're writing...
var preamble = Array.Empty<byte>();
switch (payloadType)
{
case PayloadType.Counter:
preamble = s_counterPreamble;
break;
case PayloadType.CumulativeCounter:
preamble = s_cumulativeCounterPreamble;
break;
case PayloadType.Gauge:
preamble = s_gaugePreamble;
break;
}
return stream.WriteAsync(preamble, 0, preamble.Length);
}
/// <inheritdoc />
protected override Task WritePostambleAsync(Stream stream, PayloadType payloadType)
{
if (payloadType == PayloadType.Metadata)
{
return Task.CompletedTask;
}
return stream.WriteAsync(s_postamble, 0, s_postamble.Length);
}
/// <inheritdoc />
protected override void PrepareSequence(ref ReadOnlySequence<byte> sequence, PayloadType payloadType)
{
if (payloadType == PayloadType.Metadata)
{
return;
}
sequence = sequence.Trim(',');
}
class JsonMetricReadingConverter : JsonConverter<MetricReading>
{
public override MetricReading Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotSupportedException();
}
static readonly JsonEncodedText s_metricProperty = JsonEncodedText.Encode("metric");
static readonly JsonEncodedText s_valueProperty = JsonEncodedText.Encode("value");
static readonly JsonEncodedText s_dimensionsProperty = JsonEncodedText.Encode("dimensions");
static readonly JsonEncodedText s_timestampProperty = JsonEncodedText.Encode("timestamp");
public override void Write(Utf8JsonWriter writer, MetricReading reading, JsonSerializerOptions options)
{
var epochConverter = (JsonConverter<DateTime>)options.GetConverter(typeof(DateTime));
writer.WriteStartObject(); // {
writer.WriteString(s_metricProperty, reading.Name); // "metric": "name"
writer.WriteNumber(s_valueProperty, reading.Value); // ,"value": 1.23
if (reading.Tags.Count > 0)
{
writer.WritePropertyName(s_dimensionsProperty); // ,"dimensions":
writer.WriteStartObject(); // {
foreach (var tag in reading.Tags)
{
writer.WriteString(tag.Key, tag.Value); // ,"tag": "value"
}
writer.WriteEndObject(); // }
}
writer.WritePropertyName(s_timestampProperty);
epochConverter.Write(writer, reading.Timestamp, options); // ,"timestamp": 1234567
writer.WriteEndObject(); // }
}
}
class JsonEpochMillisecondsConverter : JsonConverter<DateTime>
{
static readonly DateTime s_epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return s_epoch.AddMilliseconds(reader.GetInt64());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteNumberValue((long)(value - s_epoch).TotalMilliseconds);
}
}
}
}
}