forked from open-telemetry/opentelemetry-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrometheusExporterMiddlewareTests.cs
More file actions
446 lines (380 loc) · 16.6 KB
/
PrometheusExporterMiddlewareTests.cs
File metadata and controls
446 lines (380 loc) · 16.6 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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#if !NETFRAMEWORK
using System.Diagnostics.Metrics;
using System.Net;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Tests;
using Xunit;
namespace OpenTelemetry.Exporter.Prometheus.AspNetCore.Tests;
public sealed class PrometheusExporterMiddlewareTests
{
private const string MeterVersion = "1.0.1";
private static readonly string MeterName = Utils.GetCurrentMethodName();
[Fact]
public Task PrometheusExporterMiddlewareIntegration()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint());
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_Options()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics_options",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(),
services => services.Configure<PrometheusAspNetCoreOptions>(o => o.ScrapeEndpointPath = "metrics_options"));
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_OptionsFallback()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(),
services => services.Configure<PrometheusAspNetCoreOptions>(o => o.ScrapeEndpointPath = null));
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_OptionsViaAddPrometheusExporter()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics_from_AddPrometheusExporter",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(),
configureOptions: o => o.ScrapeEndpointPath = "/metrics_from_AddPrometheusExporter");
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_PathOverride()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics_override",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint("/metrics_override"));
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_WithPathNamedOptionsOverride()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics_override",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(
meterProvider: null,
predicate: null,
path: null,
configureBranchedPipeline: null,
optionsName: "myOptions"),
services =>
{
services.Configure<PrometheusAspNetCoreOptions>("myOptions", o => o.ScrapeEndpointPath = "/metrics_override");
});
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_Predicate()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics_predicate?enabled=true",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(httpcontext => httpcontext.Request.Path == "/metrics_predicate" && httpcontext.Request.Query["enabled"] == "true"));
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_MixedPredicateAndPath()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics_predicate",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(
meterProvider: null,
predicate: httpcontext => httpcontext.Request.Path == "/metrics_predicate",
path: "/metrics_path",
configureBranchedPipeline: branch => branch.Use((context, next) =>
{
context.Response.Headers.Append("X-MiddlewareExecuted", "true");
return next();
}),
optionsName: null),
services => services.Configure<PrometheusAspNetCoreOptions>(o => o.ScrapeEndpointPath = "/metrics_options"),
validateResponse: rsp =>
{
if (!rsp.Headers.TryGetValues("X-MiddlewareExecuted", out IEnumerable<string> headers))
{
headers = Array.Empty<string>();
}
Assert.Equal("true", headers.FirstOrDefault());
});
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_MixedPath()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics_path",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(
meterProvider: null,
predicate: null,
path: "/metrics_path",
configureBranchedPipeline: branch => branch.Use((context, next) =>
{
context.Response.Headers.Append("X-MiddlewareExecuted", "true");
return next();
}),
optionsName: null),
services => services.Configure<PrometheusAspNetCoreOptions>(o => o.ScrapeEndpointPath = "/metrics_options"),
validateResponse: rsp =>
{
if (!rsp.Headers.TryGetValues("X-MiddlewareExecuted", out IEnumerable<string> headers))
{
headers = Array.Empty<string>();
}
Assert.Equal("true", headers.FirstOrDefault());
});
}
[Fact]
public async Task PrometheusExporterMiddlewareIntegration_MeterProvider()
{
using MeterProvider meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(MeterName)
.ConfigureResource(x => x.Clear().AddService("my_service", serviceInstanceId: "id1"))
.AddPrometheusExporter()
.Build();
await RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(
meterProvider: meterProvider,
predicate: null,
path: null,
configureBranchedPipeline: null,
optionsName: null),
registerMeterProvider: false);
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_NoMetrics()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(),
skipMetrics: true);
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_MapEndpoint()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics",
app => app.UseRouting().UseEndpoints(builder => builder.MapPrometheusScrapingEndpoint()),
services => services.AddRouting());
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_MapEndpoint_WithPathOverride()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics_path",
app => app.UseRouting().UseEndpoints(builder => builder.MapPrometheusScrapingEndpoint("metrics_path")),
services => services.AddRouting());
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_MapEndpoint_WithPathNamedOptionsOverride()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics_path",
app => app.UseRouting().UseEndpoints(builder => builder.MapPrometheusScrapingEndpoint(
path: null,
meterProvider: null,
configureBranchedPipeline: null,
optionsName: "myOptions")),
services =>
{
services.AddRouting();
services.Configure<PrometheusAspNetCoreOptions>("myOptions", o => o.ScrapeEndpointPath = "/metrics_path");
});
}
[Fact]
public async Task PrometheusExporterMiddlewareIntegration_MapEndpoint_WithMeterProvider()
{
using MeterProvider meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(MeterName)
.ConfigureResource(x => x.Clear().AddService("my_service", serviceInstanceId: "id1"))
.AddPrometheusExporter()
.Build();
await RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics",
app => app.UseRouting().UseEndpoints(builder => builder.MapPrometheusScrapingEndpoint(
path: null,
meterProvider: meterProvider,
configureBranchedPipeline: null,
optionsName: null)),
services => services.AddRouting(),
registerMeterProvider: false);
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_TextPlainResponse()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(),
acceptHeader: "text/plain");
}
[Fact]
public Task PrometheusExporterMiddlewareIntegration_UseOpenMetricsVersionHeader()
{
return RunPrometheusExporterMiddlewareIntegrationTest(
"/metrics",
app => app.UseOpenTelemetryPrometheusScrapingEndpoint(),
acceptHeader: "application/openmetrics-text; version=1.0.0");
}
[Fact]
public async Task PrometheusExporterMiddlewareIntegration_CanServeOpenMetricsAndPlainFormats()
{
using var host = await StartTestHostAsync(
app => app.UseOpenTelemetryPrometheusScrapingEndpoint());
var tags = new KeyValuePair<string, object>[]
{
new KeyValuePair<string, object>("key1", "value1"),
new KeyValuePair<string, object>("key2", "value2"),
};
using var meter = new Meter(MeterName, MeterVersion);
var beginTimestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
var counter = meter.CreateCounter<double>("counter_double", unit: "By");
counter.Add(100.18D, tags);
counter.Add(0.99D, tags);
var testCases = new bool[] { true, false, true, true, false };
using var client = host.GetTestClient();
foreach (var testCase in testCases)
{
using var request = new HttpRequestMessage
{
Headers = { { "Accept", testCase ? "application/openmetrics-text" : "text/plain" } },
RequestUri = new Uri("/metrics", UriKind.Relative),
Method = HttpMethod.Get,
};
using var response = await client.SendAsync(request);
var endTimestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
await VerifyAsync(beginTimestamp, endTimestamp, response, testCase);
}
await host.StopAsync();
}
[Fact]
public async Task PrometheusExporterMiddlewareIntegration_ALotOfMetrics()
{
using var host = await StartTestHostAsync(
app => app.UseOpenTelemetryPrometheusScrapingEndpoint());
using var meter = new Meter(MeterName, MeterVersion);
for (var x = 0; x < 1000; x++)
{
var counter = meter.CreateCounter<double>("counter_double_" + x, unit: "By");
counter.Add(1);
}
using var client = host.GetTestClient();
using var response = await client.GetAsync("/metrics");
var text = await response.Content.ReadAsStringAsync();
Assert.NotEmpty(text);
await host.StopAsync();
}
private static async Task RunPrometheusExporterMiddlewareIntegrationTest(
string path,
Action<IApplicationBuilder> configure,
Action<IServiceCollection> configureServices = null,
Action<HttpResponseMessage> validateResponse = null,
bool registerMeterProvider = true,
Action<PrometheusAspNetCoreOptions> configureOptions = null,
bool skipMetrics = false,
string acceptHeader = "application/openmetrics-text")
{
var requestOpenMetrics = acceptHeader.StartsWith("application/openmetrics-text");
using var host = await StartTestHostAsync(configure, configureServices, registerMeterProvider, configureOptions);
var tags = new KeyValuePair<string, object>[]
{
new KeyValuePair<string, object>("key1", "value1"),
new KeyValuePair<string, object>("key2", "value2"),
};
using var meter = new Meter(MeterName, MeterVersion);
var beginTimestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
var counter = meter.CreateCounter<double>("counter_double", unit: "By");
if (!skipMetrics)
{
counter.Add(100.18D, tags);
counter.Add(0.99D, tags);
}
using var client = host.GetTestClient();
if (!string.IsNullOrEmpty(acceptHeader))
{
client.DefaultRequestHeaders.Add("Accept", acceptHeader);
}
using var response = await client.GetAsync(path);
var endTimestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
if (!skipMetrics)
{
await VerifyAsync(beginTimestamp, endTimestamp, response, requestOpenMetrics);
}
else
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
validateResponse?.Invoke(response);
await host.StopAsync();
}
private static async Task VerifyAsync(long beginTimestamp, long endTimestamp, HttpResponseMessage response, bool requestOpenMetrics)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(response.Content.Headers.Contains("Last-Modified"));
if (requestOpenMetrics)
{
Assert.Equal("application/openmetrics-text; version=1.0.0; charset=utf-8", response.Content.Headers.ContentType.ToString());
}
else
{
Assert.Equal("text/plain; charset=utf-8; version=0.0.4", response.Content.Headers.ContentType.ToString());
}
string content = (await response.Content.ReadAsStringAsync()).ReplaceLineEndings();
string expected = requestOpenMetrics
? $$"""
# TYPE target info
# HELP target Target metadata
target_info{service_name="my_service",service_instance_id="id1"} 1
# TYPE otel_scope_info info
# HELP otel_scope_info Scope metadata
otel_scope_info{otel_scope_name="{{MeterName}}"} 1
# TYPE counter_double_bytes counter
# UNIT counter_double_bytes bytes
counter_double_bytes_total{otel_scope_name="{{MeterName}}",otel_scope_version="{{MeterVersion}}",key1="value1",key2="value2"} 101.17 (\d+\.\d{3})
# EOF
""".ReplaceLineEndings()
: $$"""
# TYPE counter_double_bytes_total counter
# UNIT counter_double_bytes_total bytes
counter_double_bytes_total{otel_scope_name="{{MeterName}}",otel_scope_version="{{MeterVersion}}",key1="value1",key2="value2"} 101.17 (\d+)
# EOF
""".ReplaceLineEndings();
var matches = Regex.Matches(content, "^" + expected + "$");
Assert.True(matches.Count == 1, content);
var timestamp = long.Parse(matches[0].Groups[1].Value.Replace(".", string.Empty));
Assert.True(beginTimestamp <= timestamp && timestamp <= endTimestamp, $"{beginTimestamp} {timestamp} {endTimestamp}");
}
private static Task<IHost> StartTestHostAsync(
Action<IApplicationBuilder> configure,
Action<IServiceCollection> configureServices = null,
bool registerMeterProvider = true,
Action<PrometheusAspNetCoreOptions> configureOptions = null)
{
return new HostBuilder()
.ConfigureWebHost(webBuilder => webBuilder
.UseTestServer()
.ConfigureServices(services =>
{
if (registerMeterProvider)
{
services.AddOpenTelemetry().WithMetrics(builder => builder
.ConfigureResource(x => x.Clear().AddService("my_service", serviceInstanceId: "id1"))
.AddMeter(MeterName)
.AddPrometheusExporter(o =>
{
configureOptions?.Invoke(o);
}));
}
configureServices?.Invoke(services);
})
.Configure(configure))
.StartAsync();
}
}
#endif