This repository has been archived by the owner on Mar 26, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
ReportSchedulerHostedService.cs
162 lines (135 loc) · 6.2 KB
/
ReportSchedulerHostedService.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
// <copyright file="ReportSchedulerHostedService.cs" company="Allan Hardy">
// Copyright (c) Allan Hardy. All rights reserved.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using App.Metrics.Counter;
using App.Metrics.Logging;
using App.Metrics.Reporting;
using Microsoft.Extensions.Hosting;
namespace App.Metrics.AspNetCore.Reporting
{
public class ReportSchedulerHostedService : HostedService
{
private static readonly ILog Logger = LogProvider.For<ReportSchedulerHostedService>();
private static readonly TimeSpan WaitBetweenReportRunChecks = TimeSpan.FromMilliseconds(500);
private readonly IMetrics _metrics;
private readonly CounterOptions _successCounter;
private readonly CounterOptions _failedCounter;
private readonly MetricsOptions _options;
private readonly List<SchedulerTaskWrapper> _scheduledReporters = new List<SchedulerTaskWrapper>();
public ReportSchedulerHostedService(
IMetrics metrics,
MetricsOptions options,
IEnumerable<IReportMetrics> reporters)
{
_metrics = metrics;
_options = options;
var referenceTime = DateTime.UtcNow;
_successCounter = new CounterOptions
{
Context = AppMetricsConstants.InternalMetricsContext,
MeasurementUnit = Unit.Items,
ResetOnReporting = true,
Name = "report_success"
};
_failedCounter = new CounterOptions
{
Context = AppMetricsConstants.InternalMetricsContext,
MeasurementUnit = Unit.Items,
ResetOnReporting = true,
Name = "report_failed"
};
foreach (var reporter in reporters)
{
_scheduledReporters.Add(
new SchedulerTaskWrapper
{
Interval = reporter.FlushInterval,
Reporter = reporter,
NextRunTime = referenceTime
});
}
}
public event EventHandler<UnobservedTaskExceptionEventArgs> UnobservedTaskException;
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
if (!_scheduledReporters.Any())
{
await Task.CompletedTask;
}
while (!cancellationToken.IsCancellationRequested
&& _options.Enabled
&& _options.ReportingEnabled)
{
await ExecuteOnceAsync(cancellationToken);
Logger.Trace($"Delaying for {WaitBetweenReportRunChecks}");
await Task.Delay(WaitBetweenReportRunChecks, cancellationToken);
}
}
private async Task ExecuteOnceAsync(CancellationToken cancellationToken)
{
var taskFactory = new TaskFactory(TaskScheduler.Current);
var referenceTime = DateTime.UtcNow;
foreach (var flushTask in _scheduledReporters)
{
if (!flushTask.ShouldRun(referenceTime))
{
Logger.Trace($"Skipping {flushTask.Reporter.GetType().FullName}, next run in {flushTask.NextRunTime.Subtract(referenceTime).Milliseconds} ms");
continue;
}
flushTask.Increment();
await taskFactory.StartNew(
async () =>
{
try
{
Logger.Trace($"Executing reporter {flushTask.Reporter.GetType().FullName} FlushAsync");
var result = await flushTask.Reporter.FlushAsync(
_metrics.Snapshot.Get(flushTask.Reporter.Filter),
cancellationToken);
if (result)
{
_metrics.Measure.Counter.Increment(_successCounter, flushTask.Reporter.GetType().FullName);
Logger.Trace($"Reporter {flushTask.Reporter.GetType().FullName} FlushAsync executed successfully");
}
else
{
_metrics.Measure.Counter.Increment(_failedCounter, flushTask.Reporter.GetType().FullName);
Logger.Warn($"Reporter {flushTask.Reporter.GetType().FullName} FlushAsync failed");
}
}
catch (Exception ex)
{
_metrics.Measure.Counter.Increment(_failedCounter, flushTask.Reporter.GetType().FullName);
var args = new UnobservedTaskExceptionEventArgs(
ex as AggregateException ?? new AggregateException(ex));
Logger.Error($"Reporter {flushTask.Reporter.GetType().FullName} FlushAsync failed", ex);
UnobservedTaskException?.Invoke(this, args);
if (!args.Observed)
{
throw;
}
}
},
cancellationToken);
}
}
private class SchedulerTaskWrapper
{
public TimeSpan Interval { get; set; }
public DateTime LastRunTime { get; set; }
public DateTime NextRunTime { get; set; }
public IReportMetrics Reporter { get; set; }
public void Increment()
{
LastRunTime = NextRunTime;
NextRunTime = DateTime.UtcNow.Add(Interval);
}
public bool ShouldRun(DateTime currentTime) { return NextRunTime < currentTime && LastRunTime != NextRunTime; }
}
}
}