prometheus-net
69 строк · 2.2 Кб
1namespace Prometheus;
2
3/// <summary>
4/// Base class for various metric server implementations that start an independent exporter in the background.
5/// The expoters may either be pull-based (exposing the Prometheus API) or push-based (actively pushing to PushGateway).
6/// </summary>
7public abstract class MetricHandler : IMetricServer, IDisposable
8{
9// The token is cancelled when the handler is instructed to stop.
10private CancellationTokenSource? _cts = new CancellationTokenSource();
11
12// This is the task started for the purpose of exporting metrics.
13private Task? _task;
14
15protected MetricHandler()
16{
17}
18
19public IMetricServer Start()
20{
21if (_task != null)
22throw new InvalidOperationException("The metric server has already been started.");
23
24if (_cts == null)
25throw new InvalidOperationException("The metric server has already been started and stopped. Create a new server if you want to start it again.");
26
27_task = StartServer(_cts.Token);
28return this;
29}
30
31public async Task StopAsync()
32{
33// Signal the CTS to give a hint to the server thread that it is time to close up shop.
34_cts?.Cancel();
35
36try
37{
38if (_task == null)
39return; // Never started.
40
41// This will re-throw any exception that was caught on the StartServerAsync thread.
42// Perhaps not ideal behavior but hey, if the implementation does not want this to happen
43// it should have caught it itself in the background processing thread.
44await _task.ConfigureAwait(false); // Issue #308
45}
46catch (OperationCanceledException)
47{
48// We'll eat this one, though, since it can easily get thrown by whatever checks the CancellationToken.
49}
50finally
51{
52_cts?.Dispose();
53_cts = null;
54}
55}
56
57public void Stop()
58{
59// This method mainly exists for API compatiblity with prometheus-net v1. But it works, so that's fine.
60StopAsync().GetAwaiter().GetResult();
61}
62
63public void Dispose()
64{
65Stop();
66}
67
68protected abstract Task StartServer(CancellationToken cancel);
69}
70