prometheus-net

Форк
0
/
MetricHandler.cs 
69 строк · 2.2 Кб
1
namespace 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>
7
public abstract class MetricHandler : IMetricServer, IDisposable
8
{
9
    // The token is cancelled when the handler is instructed to stop.
10
    private CancellationTokenSource? _cts = new CancellationTokenSource();
11

12
    // This is the task started for the purpose of exporting metrics.
13
    private Task? _task;
14

15
    protected MetricHandler()
16
    {
17
    }
18

19
    public IMetricServer Start()
20
    {
21
        if (_task != null)
22
            throw new InvalidOperationException("The metric server has already been started.");
23

24
        if (_cts == null)
25
            throw 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);
28
        return this;
29
    }
30

31
    public 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

36
        try
37
        {
38
            if (_task == null)
39
                return; // 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.
44
            await _task.ConfigureAwait(false); // Issue #308
45
        }
46
        catch (OperationCanceledException)
47
        {
48
            // We'll eat this one, though, since it can easily get thrown by whatever checks the CancellationToken.
49
        }
50
        finally
51
        {
52
            _cts?.Dispose();
53
            _cts = null;
54
        }
55
    }
56

57
    public void Stop()
58
    {
59
        // This method mainly exists for API compatiblity with prometheus-net v1. But it works, so that's fine.
60
        StopAsync().GetAwaiter().GetResult();
61
    }
62

63
    public void Dispose()
64
    {
65
        Stop();
66
    }
67

68
    protected abstract Task StartServer(CancellationToken cancel);
69
}
70

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.