Collect diagnostics for the analysis of a long run and package a Windows trial release (refs #95 #55)
ci / test (postgres) (push) Successful in 6m25s
ci / test (sqlite) (push) Successful in 4m1s
ci / test (postgres) (pull_request) Failing after 6m4s
ci / image (push) Canceled after 0s
ci / test (sqlite) (pull_request) Successful in 4m34s
ci / image (pull_request) Skipped
ci / test (postgres) (push) Successful in 6m25s
ci / test (sqlite) (push) Successful in 4m1s
ci / test (postgres) (pull_request) Failing after 6m4s
ci / image (push) Canceled after 0s
ci / test (sqlite) (pull_request) Successful in 4m34s
ci / image (pull_request) Skipped
The 48-hour soak run at home kept being cut short by the host, never by Anubis.
The user will instead run a release for as long as they like and paste back a
report, so the bot now records what that report needs (ADR 0013).
- Every 5 minutes and at each start, a process sample goes to diagnostic_samples:
memory, GC, threads, handles, CPU, exceptions, database size, log warnings and
errors, and outbound HTTP calls by destination with duration buckets, read from
the System.Net.Http meter without any new package.
- Every scheduled job run goes to job_runs. Both tables keep 30 days.
- The Markdown report (at most 60 KB, redacted, user folders masked) adds
findings, the soak checks, starts and silences, jobs, calls, grouped log
warnings and errors, and resources over time with their slopes. It comes from
"anubis diagnostics", GET /api/diagnostica.md and a button in Diario e sistema.
- New {long} column token: SQLite STRICT tables reject BIGINT.
- "tasks release-win" builds the trial zip with a start script, a script that
writes the report, and Italian instructions. Version 0.7.0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
32673007a2
commit
6e365673b8
26 files changed
+1678
-18
No files matched your search
@@ -4,6 +4,7 @@ using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Demo;
|
||||
using Anubis.Diagnostics;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Supervision;
|
||||
using Anubis.Trading;
|
||||
@@ -72,6 +73,7 @@ internal sealed partial class AnubisHost(
|
||||
private TradingService? _trading;
|
||||
private TelegramServices? _telegram;
|
||||
private Laboratory? _lab;
|
||||
private DiagnosticSampler? _sampler;
|
||||
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
|
||||
private volatile AppServices? _services;
|
||||
|
||||
@@ -156,6 +158,10 @@ internal sealed partial class AnubisHost(
|
||||
LogDemo(logger, Config.Data.Root);
|
||||
}
|
||||
|
||||
// From the first moment: every exception and every outbound call of the process is counted (issue #95).
|
||||
ExceptionCounter.Start();
|
||||
_ = HttpCallMeter.Shared;
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
Task wake;
|
||||
@@ -349,6 +355,9 @@ internal sealed partial class AnubisHost(
|
||||
: new TelegramServices(this, _db, clock, settings, secrets, Config.HeartbeatUrl, overrides?.TelegramHttp, logger);
|
||||
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab, _telegram);
|
||||
|
||||
// The data for the analysis of a long run (issue #95, ADR 0013); the demo has nothing to analyse.
|
||||
_sampler = options.Demo ? null : new DiagnosticSampler(_db, clock, HttpCallMeter.Shared);
|
||||
|
||||
// Before the scheduler writes its first run: how long the bot was away, and which runs it missed (SPEC 5.6).
|
||||
var lastDues = new Dictionary<string, DateTimeOffset>(StringComparer.Ordinal);
|
||||
try
|
||||
@@ -363,6 +372,11 @@ internal sealed partial class AnubisHost(
|
||||
{
|
||||
lastDues[name] = due;
|
||||
}
|
||||
|
||||
if (_sampler is not null)
|
||||
{
|
||||
await _sampler.TakeAsync(SampleKinds.Start, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
@@ -494,7 +508,7 @@ internal sealed partial class AnubisHost(
|
||||
var backup = new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
|
||||
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
|
||||
{ MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) };
|
||||
foreach (var job in new[] { backup }.Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
|
||||
foreach (var job in new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
|
||||
{
|
||||
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
|
||||
}
|
||||
@@ -618,6 +632,12 @@ internal sealed partial class AnubisHost(
|
||||
("id", Ids.NewId(clock)), ("n", run.Name), ("desc", description), ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc),
|
||||
("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Every run, for the lateness and the durations in the diagnostics report (issue #95).
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO job_runs (id, job, due_at, started_at, finished_at, outcome, missed, error, created_at) VALUES (@id, @n, @d, @s, @f, @o, @m, @e, @f)",
|
||||
("id", Ids.NewId(clock)), ("n", run.Name), ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc),
|
||||
("o", run.Outcome.ToString().ToLowerInvariant()), ("m", run.Missed), ("e", run.Error is null ? null : Redactor.Redact(run.Error))).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
|
||||
@@ -116,6 +116,8 @@
|
||||
}
|
||||
<p class="note">@s.Running</p>
|
||||
<a class="btn" href="/api/registri.zip" download><Icon Name="download" Size="18" />Scarica i registri tecnici</a>
|
||||
<a class="btn" href="/api/diagnostica.md" download><Icon Name="download" Size="18" />Scarica i dati per l'analisi</a>
|
||||
<p class="note">I dati per l'analisi sono un testo da incollare a chi segue lo sviluppo: risorse, lavori, chiamate ed errori, senza chiavi né password.</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Diagnostics;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>The diagnostics report (issue #95, ADR 0013) as the command, the download and the Diario button make it.</summary>
|
||||
internal static class DiagnosticsExport
|
||||
{
|
||||
/// <summary>Thirty days: as long as the samples are kept.</summary>
|
||||
public const double MaxHours = 720;
|
||||
|
||||
/// <summary>
|
||||
/// The report over the last <paramref name="hours"/> hours up to <paramref name="to"/>, or from
|
||||
/// <paramref name="from"/>; without either, from the first sample kept, so a run of a release is covered whole.
|
||||
/// </summary>
|
||||
public static async Task<string> BuildAsync(Database db, StartupConfig config, IReadOnlyDictionary<string, string?> environment, DateTimeOffset now,
|
||||
double? hours, DateTimeOffset? from, DateTimeOffset? to, CancellationToken cancellationToken)
|
||||
{
|
||||
var end = to ?? now;
|
||||
var start = from ?? end - TimeSpan.FromHours(Math.Clamp(hours ?? MaxHours, 0.25, MaxHours));
|
||||
if (from is null && hours is null)
|
||||
{
|
||||
var first = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(taken_at) AS t FROM diagnostic_samples", r => r.MomentOrNull("t")), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (first is { } f && f > start && f < end)
|
||||
{
|
||||
start = f;
|
||||
}
|
||||
}
|
||||
|
||||
var request = new DiagnosticsRequest(start, end, config.TimeZone)
|
||||
{
|
||||
LogsFolder = config.Data.Logs,
|
||||
Setup = Setup(config, environment),
|
||||
GeneratedAt = now,
|
||||
};
|
||||
return await DiagnosticsReporter.BuildAsync(db, request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The startup settings, and which ANUBIS_ variables are set: values only for those that cannot hold a secret.</summary>
|
||||
internal static IReadOnlyList<KeyValuePair<string, string>> Setup(StartupConfig config, IReadOnlyDictionary<string, string?> environment)
|
||||
{
|
||||
var lines = new List<KeyValuePair<string, string>>
|
||||
{
|
||||
new("Piattaforma", config.Platform.ToString().ToLowerInvariant()),
|
||||
new("Database", config.Db?.Describe() ?? "non configurato"),
|
||||
new("Cartella dei dati", config.Data.Root),
|
||||
new("Rete consentita", config.AllowNetwork ? "sì" : "no"),
|
||||
new("Ordini reali consentiti", config.AllowLive ? "sì" : "no"),
|
||||
};
|
||||
var variables = environment
|
||||
.Where(e => e.Key.StartsWith(AnubisInfo.EnvironmentPrefix, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(e.Value))
|
||||
.OrderBy(e => e.Key, StringComparer.Ordinal)
|
||||
.Select(e => e.Key + (Secretive(e.Key) ? "" : "=" + e.Value))
|
||||
.ToList();
|
||||
lines.Add(new("Variabili impostate", variables.Count == 0 ? "nessuna" : string.Join(", ", variables)));
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static readonly string[] _secretWords = ["KEY", "SECRET", "PASS", "TOKEN", "URL"];
|
||||
|
||||
private static bool Secretive(string name) => _secretWords.Any(word => name.Contains(word, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public static IReadOnlyDictionary<string, string?> ProcessEnvironment() =>
|
||||
Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "anubis diagnostics": the report to paste back after a long run of a release (issue #95, ADR 0013). It only reads,
|
||||
/// so it runs while the bot works: in Docker with <c>docker exec</c>, on desktop from a second terminal.
|
||||
/// </summary>
|
||||
internal static class DiagnosticsCommand
|
||||
{
|
||||
private const string Usage =
|
||||
"Uso: anubis diagnostics [--hours 72] [--from AAAA-MM-GGTHH:MMZ] [--to AAAA-MM-GGTHH:MMZ] [--out file.md]\n" +
|
||||
" senza --hours né --from copre tutto ciò che è stato raccolto (al massimo 30 giorni).\n" +
|
||||
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||
|
||||
/// <summary>0 when the report was made, 1 when it could not be, 2 for the usage.</summary>
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null, IClock? clock = null)
|
||||
{
|
||||
output ??= Console.Out;
|
||||
clock ??= new SystemClock();
|
||||
var own = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
var rest = new List<string>();
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
if (args[i] is "--from" or "--to" or "--hours" or "--out" && i + 1 < args.Length)
|
||||
{
|
||||
own[args[i]] = args[++i];
|
||||
}
|
||||
else if (args[i] is "--help" or "-h")
|
||||
{
|
||||
await output.WriteLineAsync(Usage).ConfigureAwait(false);
|
||||
return 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
rest.Add(args[i]);
|
||||
}
|
||||
}
|
||||
|
||||
environment ??= DiagnosticsExport.ProcessEnvironment();
|
||||
try
|
||||
{
|
||||
double? hours = own.TryGetValue("--hours", out var h) ? double.Parse(h, CultureInfo.InvariantCulture) : null;
|
||||
DateTimeOffset? to = own.TryGetValue("--to", out var t) ? DateTimeOffset.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : null;
|
||||
DateTimeOffset? from = own.TryGetValue("--from", out var f) ? DateTimeOffset.Parse(f, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : null;
|
||||
var options = ServerOptions.Parse([.. rest], environment);
|
||||
var config = options.LoadConfig(environment);
|
||||
if (!config.IsComplete)
|
||||
{
|
||||
await output.WriteLineAsync("La configurazione d'avvio non è completa: avvia prima il server una volta.").ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
|
||||
Redactor.Register(config.Db!.Password);
|
||||
await using var db = Database.Open(config.Db!, allowCreate: false);
|
||||
var text = await DiagnosticsExport.BuildAsync(db, config, environment, clock.UtcNow, hours, from, to, CancellationToken.None).ConfigureAwait(false);
|
||||
if (own.TryGetValue("--out", out var file))
|
||||
{
|
||||
await File.WriteAllTextAsync(Path.GetFullPath(file), text).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await output.WriteAsync(text).ConfigureAwait(false);
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or FormatException or ArgumentException or InvalidOperationException or SchemaException
|
||||
or System.Data.Common.DbException or UnauthorizedAccessException or TimeZoneNotFoundException)
|
||||
{
|
||||
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -183,6 +183,15 @@ internal static partial class Endpoints
|
||||
return Results.File(LogArchive(folder), "application/zip", $"anubis-registri-{day}.zip");
|
||||
});
|
||||
|
||||
// The data collected for the analysis of a long run, as one Markdown report to paste (issue #95, ADR 0013).
|
||||
api.MapGet("/diagnostica.md", async (AnubisHost host, ShellData shell, IClock clock, double? ore, CancellationToken ct) =>
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
var text = await DiagnosticsExport.BuildAsync(host.Services!.Db, host.Config, DiagnosticsExport.ProcessEnvironment(), now, ore, null, null, ct).ConfigureAwait(false);
|
||||
var day = TimeZoneInfo.ConvertTime(now, shell.Zone).ToString("yyyy-MM-dd-HHmm", System.Globalization.CultureInfo.InvariantCulture);
|
||||
return Results.File(System.Text.Encoding.UTF8.GetBytes(text), "text/markdown; charset=utf-8", $"anubis-diagnostica-{day}.md");
|
||||
});
|
||||
|
||||
// The external sources and the live feed: what is on, what is off and why (SPEC 4.4).
|
||||
api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) =>
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Anubis.Core;
|
||||
using Anubis.Diagnostics;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
@@ -33,6 +34,7 @@ internal sealed class JsonLogProvider : ILoggerProvider
|
||||
|
||||
internal void Write(string category, LogLevel level, EventId eventId, string message, Exception? exception)
|
||||
{
|
||||
LogCounter.Record(level);
|
||||
var now = _clock.UtcNow;
|
||||
using var buffer = new MemoryStream();
|
||||
using (var json = new Utf8JsonWriter(buffer))
|
||||
|
||||
@@ -24,6 +24,12 @@ if (args.Length >= 1 && args[0] == "soak")
|
||||
return await SoakCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// "anubis diagnostics": the data collected for the analysis of a long run, as one report to paste (issue #95).
|
||||
if (args.Length >= 1 && args[0] == "diagnostics")
|
||||
{
|
||||
return await DiagnosticsCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var app = ServerApp.Build(args);
|
||||
await app.RunAsync().ConfigureAwait(false);
|
||||
return 0;
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Reflection;
|
||||
|
||||
namespace Anubis;
|
||||
|
||||
/// <summary>Names fixed by ADR 0001, shared by every part of the bot.</summary>
|
||||
@@ -15,4 +17,10 @@ public static class AnubisInfo
|
||||
/// <summary>Version of the running build, for example "0.0.1".</summary>
|
||||
public static string Version { get; } =
|
||||
typeof(AnubisInfo).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
|
||||
|
||||
/// <summary>The commit the build came from (the SDK appends it to the informational version), when known.</summary>
|
||||
public static string? Commit { get; } =
|
||||
typeof(AnubisInfo).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion is { } full && full.IndexOf('+', StringComparison.Ordinal) is var plus and >= 0
|
||||
? full[(plus + 1)..][..Math.Min(12, full.Length - plus - 1)]
|
||||
: null;
|
||||
}
|
||||
@@ -91,6 +91,9 @@ public static class DbValues
|
||||
("bool", DbEngine.Sqlite) => "INTEGER",
|
||||
("bytes", DbEngine.Postgres) => "BYTEA",
|
||||
("bytes", DbEngine.Sqlite) => "BLOB",
|
||||
// A whole number beyond 2^31 (bytes of memory, counters of a long run): SQLite's INTEGER is already 64 bits.
|
||||
("long", DbEngine.Postgres) => "BIGINT",
|
||||
("long", DbEngine.Sqlite) => "INTEGER",
|
||||
("float", DbEngine.Postgres) => "DOUBLE PRECISION",
|
||||
("float", DbEngine.Sqlite) => "REAL",
|
||||
("strict", DbEngine.Postgres) => "",
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
-- Data collected for the analysis of a long run (issue #95, ADR 0013). Both tables are kept for 30 days.
|
||||
|
||||
-- One sample of the process every 5 minutes, and one at every start. The counters (collections, pauses, processor
|
||||
-- time, lock contentions, exceptions) are totals since the process started: the report takes the differences
|
||||
-- between two samples of the same process. warnings and errors are the log lines since the previous sample.
|
||||
-- calls holds the outbound HTTP calls since the previous sample, by destination, with their duration buckets.
|
||||
CREATE TABLE diagnostic_samples (
|
||||
id {uuid} PRIMARY KEY,
|
||||
taken_at {timestamp} NOT NULL,
|
||||
process_started_at {timestamp} NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
working_set {long} NOT NULL,
|
||||
private_bytes {long} NOT NULL,
|
||||
managed_heap {long} NOT NULL,
|
||||
gc_committed {long} NOT NULL,
|
||||
gc_gen0 {long} NOT NULL,
|
||||
gc_gen1 {long} NOT NULL,
|
||||
gc_gen2 {long} NOT NULL,
|
||||
gc_pause_ms {float} NOT NULL,
|
||||
threads INTEGER NOT NULL,
|
||||
handles INTEGER NOT NULL,
|
||||
cpu_ms {float} NOT NULL,
|
||||
pool_threads INTEGER NOT NULL,
|
||||
pool_pending {long} NOT NULL,
|
||||
lock_contentions {long} NOT NULL,
|
||||
exceptions {long} NOT NULL,
|
||||
db_bytes {long},
|
||||
warnings INTEGER NOT NULL,
|
||||
errors INTEGER NOT NULL,
|
||||
calls {json},
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX diagnostic_samples_taken ON diagnostic_samples (taken_at);
|
||||
|
||||
-- Every run of a scheduled job, with its lateness and duration. jobs keeps only the last one.
|
||||
CREATE TABLE job_runs (
|
||||
id {uuid} PRIMARY KEY,
|
||||
job TEXT NOT NULL,
|
||||
due_at {timestamp} NOT NULL,
|
||||
started_at {timestamp} NOT NULL,
|
||||
finished_at {timestamp} NOT NULL,
|
||||
outcome TEXT NOT NULL,
|
||||
missed {bool} NOT NULL,
|
||||
error TEXT,
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX job_runs_started ON job_runs (started_at);
|
||||
@@ -32,7 +32,7 @@ public static partial class Migrations
|
||||
{
|
||||
public const string VersionTable = "schema_versions";
|
||||
|
||||
[GeneratedRegex(@"\{(money|uuid|timestamp|json|bool|bytes|float|strict)\}")]
|
||||
[GeneratedRegex(@"\{(money|uuid|timestamp|json|bool|bytes|float|long|strict)\}")]
|
||||
internal static partial Regex Tokens();
|
||||
|
||||
[GeneratedRegex(@"^(\d{4})_([a-z0-9_]+)\.sql$")]
|
||||
|
||||
@@ -83,9 +83,10 @@ public static partial class Schema
|
||||
"{BOOL}" => ColumnKind.Bool,
|
||||
"{BYTES}" => ColumnKind.Bytes,
|
||||
"{FLOAT}" => ColumnKind.Measure,
|
||||
"{LONG}" => ColumnKind.Number,
|
||||
"TEXT" => ColumnKind.Text,
|
||||
"INTEGER" or "BIGINT" => ColumnKind.Number,
|
||||
var other => throw new InvalidOperationException($"Column type {other} is not portable: use TEXT, INTEGER, BIGINT or a token."),
|
||||
"INTEGER" => ColumnKind.Number,
|
||||
var other => throw new InvalidOperationException($"Column type {other} is not portable: use TEXT, INTEGER or a token."),
|
||||
};
|
||||
var upper = definition.ToUpperInvariant();
|
||||
var nullable = !upper.Contains("NOT NULL", StringComparison.Ordinal) && !upper.Contains("PRIMARY KEY", StringComparison.Ordinal);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Anubis.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// The warning and error lines written by the logs since the last look (issue #95). The log writer counts each line;
|
||||
/// the sampler takes the counts every 5 minutes, so the report shows when the troubles came, not only how many.
|
||||
/// </summary>
|
||||
public static class LogCounter
|
||||
{
|
||||
private static long _warnings;
|
||||
private static long _errors;
|
||||
|
||||
public static void Record(LogLevel level)
|
||||
{
|
||||
if (level == LogLevel.Warning)
|
||||
{
|
||||
Interlocked.Increment(ref _warnings);
|
||||
}
|
||||
else if (level >= LogLevel.Error && level != LogLevel.None)
|
||||
{
|
||||
Interlocked.Increment(ref _errors);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The lines since the previous call, and the counts start again from zero.</summary>
|
||||
public static (int Warnings, int Errors) Take() =>
|
||||
((int)Math.Min(int.MaxValue, Interlocked.Exchange(ref _warnings, 0)), (int)Math.Min(int.MaxValue, Interlocked.Exchange(ref _errors, 0)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every exception thrown in the process, caught or not, since the counting started. Many are normal (a cancelled
|
||||
/// wait, a lost connection retried), but a count that keeps climbing points to a loop that fails over and over.
|
||||
/// </summary>
|
||||
public static class ExceptionCounter
|
||||
{
|
||||
private static long _count;
|
||||
private static int _started;
|
||||
|
||||
public static long Count => Interlocked.Read(ref _count);
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _started, 1) == 0)
|
||||
{
|
||||
AppDomain.CurrentDomain.FirstChanceException += (_, _) => Interlocked.Increment(ref _count);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Diagnostics;
|
||||
|
||||
public static class SampleKinds
|
||||
{
|
||||
/// <summary>The first sample of a process, written as soon as the bot is ready.</summary>
|
||||
public const string Start = "start";
|
||||
|
||||
public const string Periodic = "periodic";
|
||||
}
|
||||
|
||||
/// <summary>One look at the process (issue #95). Counters are totals since the process started.</summary>
|
||||
public sealed record ProcessSample
|
||||
{
|
||||
public required DateTimeOffset TakenAt { get; init; }
|
||||
|
||||
public required DateTimeOffset ProcessStartedAt { get; init; }
|
||||
|
||||
public required string Kind { get; init; }
|
||||
|
||||
public string Version { get; init; } = AnubisInfo.Version;
|
||||
|
||||
public long WorkingSet { get; init; }
|
||||
|
||||
public long PrivateBytes { get; init; }
|
||||
|
||||
public long ManagedHeap { get; init; }
|
||||
|
||||
public long GcCommitted { get; init; }
|
||||
|
||||
public long Gen0 { get; init; }
|
||||
|
||||
public long Gen1 { get; init; }
|
||||
|
||||
public long Gen2 { get; init; }
|
||||
|
||||
public double GcPauseMs { get; init; }
|
||||
|
||||
public int Threads { get; init; }
|
||||
|
||||
public int Handles { get; init; }
|
||||
|
||||
public double CpuMs { get; init; }
|
||||
|
||||
public int PoolThreads { get; init; }
|
||||
|
||||
public long PoolPending { get; init; }
|
||||
|
||||
public long LockContentions { get; init; }
|
||||
|
||||
public long Exceptions { get; init; }
|
||||
|
||||
public long? DbBytes { get; init; }
|
||||
|
||||
public int Warnings { get; init; }
|
||||
|
||||
public int Errors { get; init; }
|
||||
|
||||
public IReadOnlyList<HttpCallStats> Calls { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every 5 minutes, and once at each start, a sample of the process goes to <c>diagnostic_samples</c>, with the log
|
||||
/// warnings and errors and the outbound calls since the previous one (issue #95, ADR 0013). Samples and job runs older
|
||||
/// than 30 days are deleted once a day. It only measures: nothing here changes what the bot does.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticSampler(Database db, IClock clock, HttpCallMeter meter)
|
||||
{
|
||||
public const string JobName = "diagnostica";
|
||||
|
||||
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(5);
|
||||
|
||||
public static readonly TimeSpan Keep = TimeSpan.FromDays(30);
|
||||
|
||||
internal static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||
|
||||
private DateTimeOffset? _lastPrune;
|
||||
|
||||
public ScheduledJob Job() => new(JobName, "Raccolta dei dati per l'analisi", Schedule.Every(Interval), ct => TakeAsync(SampleKinds.Periodic, ct))
|
||||
{
|
||||
MaxLateness = Interval,
|
||||
};
|
||||
|
||||
public async Task<ProcessSample> TakeAsync(string kind, CancellationToken cancellationToken)
|
||||
{
|
||||
var (warnings, errors) = LogCounter.Take();
|
||||
var sample = Probe(clock.UtcNow, kind) with
|
||||
{
|
||||
DbBytes = await DatabaseBytesAsync(db, cancellationToken).ConfigureAwait(false),
|
||||
Warnings = warnings,
|
||||
Errors = errors,
|
||||
Calls = meter.Take(),
|
||||
};
|
||||
var prune = _lastPrune is not { } last || sample.TakenAt - last >= TimeSpan.FromDays(1);
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await WriteAsync(s, clock, sample, cancellationToken).ConfigureAwait(false);
|
||||
if (prune)
|
||||
{
|
||||
var before = sample.TakenAt - Keep;
|
||||
await s.ExecuteAsync("DELETE FROM diagnostic_samples WHERE taken_at < @t", cancellationToken, ("t", before)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("DELETE FROM job_runs WHERE started_at < @t", cancellationToken, ("t", before)).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
if (prune)
|
||||
{
|
||||
_lastPrune = sample.TakenAt;
|
||||
}
|
||||
|
||||
return sample;
|
||||
}
|
||||
|
||||
/// <summary>The process as it is now. Process times come from the system clock: they measure the machine, not the market.</summary>
|
||||
public static ProcessSample Probe(DateTimeOffset now, string kind)
|
||||
{
|
||||
using var process = Process.GetCurrentProcess();
|
||||
var gc = GC.GetGCMemoryInfo();
|
||||
return new ProcessSample
|
||||
{
|
||||
TakenAt = now,
|
||||
ProcessStartedAt = new DateTimeOffset(process.StartTime.ToUniversalTime(), TimeSpan.Zero),
|
||||
Kind = kind,
|
||||
WorkingSet = process.WorkingSet64,
|
||||
PrivateBytes = process.PrivateMemorySize64,
|
||||
ManagedHeap = GC.GetTotalMemory(forceFullCollection: false),
|
||||
GcCommitted = gc.TotalCommittedBytes,
|
||||
Gen0 = GC.CollectionCount(0),
|
||||
Gen1 = GC.CollectionCount(1),
|
||||
Gen2 = GC.CollectionCount(2),
|
||||
GcPauseMs = Math.Round(GC.GetTotalPauseDuration().TotalMilliseconds, 1),
|
||||
Threads = process.Threads.Count,
|
||||
Handles = process.HandleCount,
|
||||
CpuMs = Math.Round(process.TotalProcessorTime.TotalMilliseconds, 1),
|
||||
PoolThreads = ThreadPool.ThreadCount,
|
||||
PoolPending = ThreadPool.PendingWorkItemCount,
|
||||
LockContentions = Monitor.LockContentionCount,
|
||||
Exceptions = ExceptionCounter.Count,
|
||||
};
|
||||
}
|
||||
|
||||
public static async Task WriteAsync(DbSession s, IClock clock, ProcessSample sample, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(s);
|
||||
ArgumentNullException.ThrowIfNull(sample);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO diagnostic_samples (id, taken_at, process_started_at, kind, version, working_set, private_bytes, managed_heap, gc_committed, gc_gen0, gc_gen1, gc_gen2, " +
|
||||
"gc_pause_ms, threads, handles, cpu_ms, pool_threads, pool_pending, lock_contentions, exceptions, db_bytes, warnings, errors, calls, created_at) VALUES " +
|
||||
"(@id, @t, @ps, @k, @v, @ws, @pb, @mh, @gcc, @g0, @g1, @g2, @gp, @th, @h, @cpu, @pt, @pp, @lc, @ex, @db, @w, @e, @calls, @now)",
|
||||
cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("t", sample.TakenAt), ("ps", sample.ProcessStartedAt), ("k", sample.Kind), ("v", sample.Version), ("ws", sample.WorkingSet),
|
||||
("pb", sample.PrivateBytes), ("mh", sample.ManagedHeap), ("gcc", sample.GcCommitted), ("g0", sample.Gen0), ("g1", sample.Gen1), ("g2", sample.Gen2),
|
||||
("gp", sample.GcPauseMs), ("th", sample.Threads), ("h", sample.Handles), ("cpu", sample.CpuMs), ("pt", sample.PoolThreads), ("pp", sample.PoolPending),
|
||||
("lc", sample.LockContentions), ("ex", sample.Exceptions), ("db", sample.DbBytes), ("w", sample.Warnings), ("e", sample.Errors),
|
||||
("calls", sample.Calls.Count == 0 ? null : new DbJson(JsonSerializer.Serialize(sample.Calls, Json))), ("now", clock.UtcNow)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The size of the database: its files on SQLite (with the journal), what PostgreSQL reports for it.</summary>
|
||||
public static async Task<long?> DatabaseBytesAsync(Database db, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
try
|
||||
{
|
||||
if (db.Engine == DbEngine.Sqlite)
|
||||
{
|
||||
return db.SqlitePath is not { } path ? null
|
||||
: new[] { path, path + "-wal", path + "-shm" }.Where(File.Exists).Sum(f => new FileInfo(f).Length);
|
||||
}
|
||||
|
||||
return await db.ReadAsync(s => s.CountAsync("SELECT pg_database_size(current_database())"), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Data.Common.DbException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,595 @@
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Supervision;
|
||||
|
||||
namespace Anubis.Diagnostics;
|
||||
|
||||
/// <summary>What the report covers and the facts about the installation that only the caller knows.</summary>
|
||||
public sealed record DiagnosticsRequest(DateTimeOffset From, DateTimeOffset To, TimeZoneInfo Zone)
|
||||
{
|
||||
/// <summary>The folder of the technical logs (<c>anubis-yyyyMMdd.log</c>); without it the report skips them.</summary>
|
||||
public string? LogsFolder { get; init; }
|
||||
|
||||
/// <summary>Startup settings with nothing secret in them, shown as they are.</summary>
|
||||
public IReadOnlyList<KeyValuePair<string, string>> Setup { get; init; } = [];
|
||||
|
||||
public DateTimeOffset GeneratedAt { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The report the user pastes back after a long run of a release (issue #95, ADR 0013): in Markdown, at most 60 KB,
|
||||
/// with everything passed through <see cref="Redactor"/> and the user's folders masked. It only reads.
|
||||
/// </summary>
|
||||
public static partial class DiagnosticsReporter
|
||||
{
|
||||
public const int MaxBytes = 60 * 1024;
|
||||
|
||||
private const int MaxLogGroups = 40;
|
||||
private const long MaxLogBytes = 256L * 1024 * 1024;
|
||||
|
||||
/// <summary>Two missed samples in a row: the process lived but did not sample (sleep, a stuck scheduler).</summary>
|
||||
private static readonly TimeSpan Silence = DiagnosticSampler.Interval * 2 + TimeSpan.FromMinutes(1);
|
||||
|
||||
private static readonly TimeSpan[] Steps =
|
||||
[TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(30), TimeSpan.FromHours(1), TimeSpan.FromHours(2), TimeSpan.FromHours(3),
|
||||
TimeSpan.FromHours(6), TimeSpan.FromHours(12), TimeSpan.FromDays(1)];
|
||||
|
||||
public static async Task<string> BuildAsync(Database db, DiagnosticsRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (request.To <= request.From)
|
||||
{
|
||||
throw new ArgumentException("La fine del periodo deve venire dopo l'inizio.", nameof(request));
|
||||
}
|
||||
|
||||
var zone = request.Zone;
|
||||
var findings = new List<string>();
|
||||
var soak = await SoakReporter.BuildAsync(db, request.From, request.To, request.To - request.From, zone, cancellationToken).ConfigureAwait(false);
|
||||
var data = await db.ReadAsync(async s =>
|
||||
{
|
||||
(string Name, object? Value)[] window = [("from", request.From), ("to", request.To)];
|
||||
var engine = await s.FirstOrDefaultAsync(s.Engine == DbEngine.Sqlite ? "SELECT sqlite_version() AS v" : "SELECT version() AS v", r => r.Text("v")).ConfigureAwait(false);
|
||||
var samples = await s.QueryAsync("SELECT * FROM diagnostic_samples WHERE taken_at >= @from AND taken_at <= @to ORDER BY taken_at", ReadSample, window).ConfigureAwait(false);
|
||||
var runs = await s.QueryAsync("SELECT job, due_at, started_at, finished_at, outcome, missed, error FROM job_runs WHERE started_at >= @from AND started_at <= @to",
|
||||
r => new Run(r.Text("job"), r.Moment("due_at"), r.Moment("started_at"), r.Moment("finished_at"), r.Text("outcome"), r.Bool("missed"), r.TextOrNull("error")), window)
|
||||
.ConfigureAwait(false);
|
||||
var absences = await s.QueryAsync("SELECT started_at, ended_at FROM absences WHERE ended_at >= @from AND started_at <= @to ORDER BY started_at",
|
||||
r => (Start: r.Moment("started_at"), End: r.Moment("ended_at")), window).ConfigureAwait(false);
|
||||
return (Engine: engine, Samples: samples, Runs: runs, Absences: absences);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var logs = request.LogsFolder is { } folder ? ReadLogs(folder, request.From, request.To) : null;
|
||||
|
||||
var sections = new List<string>
|
||||
{
|
||||
Setup(request, data.Engine, data.Samples),
|
||||
Soak(soak, findings),
|
||||
Starts(data.Samples, data.Absences, zone, findings),
|
||||
Jobs(data.Runs, findings),
|
||||
Calls(data.Samples, findings),
|
||||
Logs(logs, zone, findings),
|
||||
Resources(data.Samples, request, findings),
|
||||
};
|
||||
|
||||
var text = new StringBuilder()
|
||||
.AppendLine("# Anubis · dati per l'analisi")
|
||||
.AppendLine()
|
||||
.AppendLine(CultureInfo.InvariantCulture, $"Versione {AnubisInfo.Version} (commit {AnubisInfo.Commit ?? "non noto"}). Dal {SoakReport.Moment(request.From, zone)} al " +
|
||||
$"{SoakReport.Moment(request.To, zone)} ({SoakReport.Hours(request.To - request.From)}), ora di {zone.Id}. Fatto il {SoakReport.Moment(request.GeneratedAt, zone)}.")
|
||||
.AppendLine()
|
||||
.AppendLine("## In breve")
|
||||
.AppendLine();
|
||||
foreach (var finding in findings.Count == 0 ? ["Nessun segnale di problema nei dati raccolti."] : findings)
|
||||
{
|
||||
text.AppendLine("- " + finding);
|
||||
}
|
||||
|
||||
foreach (var section in sections)
|
||||
{
|
||||
text.AppendLine().Append(section);
|
||||
}
|
||||
|
||||
return Fit(Mask(text.ToString()));
|
||||
}
|
||||
|
||||
/// <summary>The user's folders and name out, the secrets out, and no more than <see cref="MaxBytes"/>.</summary>
|
||||
internal static string Mask(string text)
|
||||
{
|
||||
var profile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
if (profile.Length > 3)
|
||||
{
|
||||
text = text.Replace(profile, "%USERPROFILE%", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
var user = Environment.UserName;
|
||||
if (user.Length >= 3)
|
||||
{
|
||||
text = text.Replace("\\" + user + "\\", "\\‹utente›\\", StringComparison.OrdinalIgnoreCase)
|
||||
.Replace("/" + user + "/", "/‹utente›/", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
return Redactor.Redact(text);
|
||||
}
|
||||
|
||||
internal static string Fit(string text)
|
||||
{
|
||||
if (Encoding.UTF8.GetByteCount(text) <= MaxBytes)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
|
||||
const string note = "\n\n_Rapporto tagliato a 60 KB: le righe più vecchie delle risorse mancano._\n";
|
||||
var limit = MaxBytes - Encoding.UTF8.GetByteCount(note);
|
||||
var cut = text.Length;
|
||||
while (cut > 0 && Encoding.UTF8.GetByteCount(text.AsSpan(0, cut)) > limit)
|
||||
{
|
||||
cut = text.LastIndexOf('\n', cut - 1);
|
||||
}
|
||||
|
||||
return text[..Math.Max(0, cut)] + note;
|
||||
}
|
||||
|
||||
private static string Setup(DiagnosticsRequest request, string? engine, List<ProcessSample> samples)
|
||||
{
|
||||
var text = new StringBuilder("## Installazione\n\n");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"- Sistema: {RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture}), {Environment.ProcessorCount} processori")
|
||||
.AppendLine(CultureInfo.InvariantCulture, $"- Runtime: {RuntimeInformation.FrameworkDescription}")
|
||||
.AppendLine(CultureInfo.InvariantCulture, $"- Motore del database: {engine ?? "non noto"}");
|
||||
if (samples.LastOrDefault(s => s.DbBytes is not null) is { DbBytes: { } bytes })
|
||||
{
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"- Dimensione del database: {Mb(bytes)} MB");
|
||||
}
|
||||
|
||||
foreach (var (name, value) in request.Setup)
|
||||
{
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"- {name}: {value}");
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Soak(SoakReport soak, List<string> findings)
|
||||
{
|
||||
var failed = soak.Checks.Where(c => !c.Ok).ToList();
|
||||
if (failed.Count > 0)
|
||||
{
|
||||
findings.Add($"Controlli del lavoro da guardare: {failed.Count} (sezione «Controlli del lavoro»).");
|
||||
}
|
||||
|
||||
var text = new StringBuilder("## Controlli del lavoro\n\n");
|
||||
foreach (var check in soak.Checks)
|
||||
{
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"- {(check.Ok ? "✓" : "✗")} {check.Text}");
|
||||
}
|
||||
|
||||
foreach (var fact in soak.Facts)
|
||||
{
|
||||
text.AppendLine("- " + fact);
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Starts(List<ProcessSample> samples, List<(DateTimeOffset Start, DateTimeOffset End)> absences, TimeZoneInfo zone, List<string> findings)
|
||||
{
|
||||
var text = new StringBuilder("## Avvii, spegnimenti e silenzi\n\n");
|
||||
var processes = Processes(samples);
|
||||
if (processes.Count == 0)
|
||||
{
|
||||
findings.Add("Nessun campione nel periodo: la raccolta dei dati non ha girato (versione senza raccolta, o bot spento).");
|
||||
return text.AppendLine("Nessun campione nel periodo.").ToString();
|
||||
}
|
||||
|
||||
text.AppendLine("| Avviato | Versione | Primo campione | Ultimo campione | Campioni |").AppendLine("|---|---|---|---|---|");
|
||||
foreach (var p in processes)
|
||||
{
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"| {SoakReport.Moment(p[0].ProcessStartedAt, zone)} | {p[0].Version} | {SoakReport.Moment(p[0].TakenAt, zone)} | {SoakReport.Moment(p[^1].TakenAt, zone)} | {p.Count} |");
|
||||
}
|
||||
|
||||
if (processes.Count > 1)
|
||||
{
|
||||
findings.Add($"Il bot è ripartito {processes.Count - 1} volte nel periodo.");
|
||||
}
|
||||
|
||||
text.AppendLine();
|
||||
if (absences.Count > 0)
|
||||
{
|
||||
var total = absences.Aggregate(TimeSpan.Zero, (sum, a) => sum + (a.End - a.Start));
|
||||
findings.Add($"Spento {absences.Count} volte, in tutto {Duration(total)}.");
|
||||
text.AppendLine("Spento: " + string.Join(", ", absences.Select(a => $"dal {SoakReport.Moment(a.Start, zone)} per {Duration(a.End - a.Start)}")) + ".");
|
||||
}
|
||||
else
|
||||
{
|
||||
text.AppendLine("Nessuno spegnimento registrato.");
|
||||
}
|
||||
|
||||
var silences = processes.SelectMany(p => p.Zip(p.Skip(1)).Where(x => x.Second.TakenAt - x.First.TakenAt > Silence)).ToList();
|
||||
if (silences.Count > 0)
|
||||
{
|
||||
var total = silences.Aggregate(TimeSpan.Zero, (sum, x) => sum + (x.Second.TakenAt - x.First.TakenAt));
|
||||
findings.Add($"Silenzi a processo acceso: {silences.Count}, in tutto {Duration(total)} (computer in sospensione, o lavori bloccati).");
|
||||
text.AppendLine().AppendLine("Silenzi a processo acceso (nessun campione per più di 11 minuti): " +
|
||||
string.Join(", ", silences.Take(30).Select(x => $"dal {SoakReport.Moment(x.First.TakenAt, zone)} per {Duration(x.Second.TakenAt - x.First.TakenAt)}")) +
|
||||
(silences.Count > 30 ? $" e altri {silences.Count - 30}" : "") + ".");
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Jobs(List<Run> runs, List<string> findings)
|
||||
{
|
||||
var text = new StringBuilder("## Lavori pianificati\n\n");
|
||||
if (runs.Count == 0)
|
||||
{
|
||||
return text.AppendLine("Nessuna esecuzione registrata nel periodo.").ToString();
|
||||
}
|
||||
|
||||
text.AppendLine("| Lavoro | Esecuzioni | Fallite | Saltate | Recuperate | Ritardo medio · massimo | Durata mediana · 95% · massima | Ultimo errore |")
|
||||
.AppendLine("|---|---|---|---|---|---|---|---|");
|
||||
foreach (var job in runs.GroupBy(r => r.Job, StringComparer.Ordinal).OrderBy(g => g.Key, StringComparer.Ordinal))
|
||||
{
|
||||
var list = job.OrderBy(r => r.Started).ToList();
|
||||
var failed = list.Count(r => r.Outcome == "failed");
|
||||
var skipped = list.Count(r => r.Outcome == "skipped");
|
||||
var late = list.Where(r => r.Outcome != "skipped" && !r.Missed).Select(r => (r.Started - r.Due).TotalSeconds).DefaultIfEmpty(0).ToList();
|
||||
var took = list.Where(r => r.Outcome != "skipped").Select(r => (r.Finished - r.Started).TotalSeconds).Order().ToList();
|
||||
var error = list.LastOrDefault(r => r.Error is not null)?.Error;
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"| {job.Key} | {list.Count} | {failed} | {skipped} | {list.Count(r => r.Missed)} | {Seconds(late.Average())} · {Seconds(late.Max())} | " +
|
||||
$"{Seconds(Rank(took, 0.5))} · {Seconds(Rank(took, 0.95))} · {Seconds(took.LastOrDefault())} | {Cell(error, 160)} |");
|
||||
if (failed > 0)
|
||||
{
|
||||
findings.Add($"Il lavoro «{job.Key}» è fallito {failed} volte su {list.Count}.");
|
||||
}
|
||||
|
||||
if (skipped > 0)
|
||||
{
|
||||
findings.Add($"Il lavoro «{job.Key}» è stato saltato {skipped} volte (troppo in ritardo).");
|
||||
}
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Calls(List<ProcessSample> samples, List<string> findings)
|
||||
{
|
||||
var text = new StringBuilder("## Chiamate esterne\n\n");
|
||||
var calls = HttpCallStats.Merge(samples.SelectMany(s => s.Calls));
|
||||
if (calls.Count == 0)
|
||||
{
|
||||
return text.AppendLine("Nessuna chiamata registrata nel periodo.").ToString();
|
||||
}
|
||||
|
||||
text.AppendLine("| Destinazione | Chiamate | Fallite | Esiti | Media ms | 50% ms | 95% ms | Massimo ms |").AppendLine("|---|---|---|---|---|---|---|---|");
|
||||
foreach (var c in calls)
|
||||
{
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"| {Cell(c.Host, 80)} | {c.Calls} | {c.Failures} | {Cell(string.Join(", ", c.Outcomes.Select(o => o.Key + "×" + o.Value)), 160)} | {Ms(c.AverageMs)} | " +
|
||||
$"{Ms(c.Percentile(0.5))} | {Ms(c.Percentile(0.95))} | {Ms(c.MaxMs)} |");
|
||||
if (c.Calls >= 20 && c.Failures * 20 > c.Calls)
|
||||
{
|
||||
findings.Add($"Le chiamate a {c.Host} falliscono spesso: {c.Failures} su {c.Calls}.");
|
||||
}
|
||||
|
||||
if (c.Calls >= 20 && c.Percentile(0.95) >= 5000)
|
||||
{
|
||||
findings.Add($"Le chiamate a {c.Host} sono lente: il 95% sta sotto {Ms(c.Percentile(0.95))} ms.");
|
||||
}
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Logs(LogSummary? logs, TimeZoneInfo zone, List<string> findings)
|
||||
{
|
||||
var text = new StringBuilder("## Registri tecnici: avvisi ed errori\n\n");
|
||||
if (logs is null)
|
||||
{
|
||||
return text.AppendLine("Cartella dei registri non disponibile.").ToString();
|
||||
}
|
||||
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"Letti {logs.Files} file, {logs.Lines} righe nel periodo: {logs.Warnings} avvisi e {logs.Errors} errori{(logs.Truncated ? " (lettura fermata a 256 MB)" : "")}.").AppendLine();
|
||||
if (logs.Errors > 0)
|
||||
{
|
||||
findings.Add($"Errori nei registri tecnici: {logs.Errors}, di {logs.Groups.Count(g => g.Level != "warning")} tipi.");
|
||||
}
|
||||
|
||||
if (logs.Groups.Count == 0)
|
||||
{
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
text.AppendLine("| Livello | Volte | Prima | Ultima | Origine | Messaggio |").AppendLine("|---|---|---|---|---|---|");
|
||||
foreach (var g in logs.Groups.OrderBy(g => g.Level == "warning" ? 1 : 0).ThenByDescending(g => g.Count).Take(MaxLogGroups))
|
||||
{
|
||||
var message = g.Error is null ? g.Sample : g.Sample + " — " + g.Error;
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"| {g.Level} | {g.Count} | {SoakReport.Moment(g.First, zone)} | {SoakReport.Moment(g.Last, zone)} | {Cell(g.Category, 60)} | {Cell(message, 300)} |");
|
||||
}
|
||||
|
||||
if (logs.Groups.Count > MaxLogGroups)
|
||||
{
|
||||
text.AppendLine().AppendLine(CultureInfo.InvariantCulture, $"Altri {logs.Groups.Count - MaxLogGroups} tipi di messaggio non mostrati.");
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Resources(List<ProcessSample> samples, DiagnosticsRequest request, List<string> findings)
|
||||
{
|
||||
var text = new StringBuilder("## Risorse nel tempo\n\n");
|
||||
var processes = Processes(samples);
|
||||
if (processes.Count == 0)
|
||||
{
|
||||
return text.AppendLine("Nessun campione.").ToString();
|
||||
}
|
||||
|
||||
foreach (var p in processes)
|
||||
{
|
||||
var settled = p.Where(s => s.TakenAt - s.ProcessStartedAt >= TimeSpan.FromMinutes(30)).ToList();
|
||||
var line = $"Processo avviato il {SoakReport.Moment(p[0].ProcessStartedAt, request.Zone)}: memoria da {Mb(p[0].WorkingSet)} a {Mb(p[^1].WorkingSet)} MB, " +
|
||||
$"memoria gestita da {Mb(p[0].ManagedHeap)} a {Mb(p[^1].ManagedHeap)} MB, handle da {p[0].Handles} a {p[^1].Handles}, thread da {p[0].Threads} a {p[^1].Threads}";
|
||||
if (settled.Count >= 12 && settled[^1].TakenAt - settled[0].TakenAt >= TimeSpan.FromHours(3))
|
||||
{
|
||||
var ws = Slope(settled, s => s.WorkingSet / 1048576.0);
|
||||
var heap = Slope(settled, s => s.GcCommitted / 1048576.0);
|
||||
var handles = Slope(settled, s => s.Handles);
|
||||
var threads = Slope(settled, s => s.Threads);
|
||||
line += $"; pendenza dopo la prima mezz'ora: memoria {Signed(ws)} MB/ora, memoria del GC {Signed(heap)} MB/ora, handle {Signed(handles)}/ora, thread {Signed(threads)}/ora";
|
||||
var hours = (settled[^1].TakenAt - settled[0].TakenAt).TotalHours;
|
||||
if (ws > 2 && ws * hours > settled[0].WorkingSet / 1048576.0 * 0.2)
|
||||
{
|
||||
findings.Add($"La memoria cresce di {Signed(ws)} MB l'ora da {Duration(TimeSpan.FromHours(hours))}: possibile perdita.");
|
||||
}
|
||||
|
||||
if (handles > 10 && handles * hours > settled[0].Handles * 0.2)
|
||||
{
|
||||
findings.Add($"Gli handle crescono di {Signed(handles)} l'ora: possibile perdita di connessioni o file.");
|
||||
}
|
||||
|
||||
if (threads > 1 && threads * hours > settled[0].Threads * 0.3)
|
||||
{
|
||||
findings.Add($"I thread crescono di {Signed(threads)} l'ora.");
|
||||
}
|
||||
}
|
||||
|
||||
var hoursAlive = (p[^1].TakenAt - p[0].ProcessStartedAt).TotalHours;
|
||||
if (hoursAlive >= 1 && (p[^1].Exceptions / hoursAlive) > 2000)
|
||||
{
|
||||
findings.Add($"Molte eccezioni: {Format.Number((decimal)(p[^1].Exceptions / hoursAlive))} l'ora nel processo avviato il {SoakReport.Moment(p[0].ProcessStartedAt, request.Zone)}.");
|
||||
}
|
||||
|
||||
text.AppendLine(line + ".");
|
||||
}
|
||||
|
||||
var dbFirst = samples.FirstOrDefault(s => s.DbBytes is not null);
|
||||
var dbLast = samples.LastOrDefault(s => s.DbBytes is not null);
|
||||
if (dbFirst is { DbBytes: { } a } && dbLast is { DbBytes: { } b } && dbLast.TakenAt - dbFirst.TakenAt >= TimeSpan.FromHours(6))
|
||||
{
|
||||
var perDay = (b - a) / (dbLast.TakenAt - dbFirst.TakenAt).TotalDays;
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"Il database è passato da {Mb(a)} a {Mb(b)} MB ({Signed(perDay / 1048576.0)} MB al giorno).");
|
||||
}
|
||||
|
||||
var span = request.To - request.From;
|
||||
var step = Steps.FirstOrDefault(s => span / s <= 48, Steps[^1]);
|
||||
text.AppendLine()
|
||||
.AppendLine(CultureInfo.InvariantCulture, $"Un campione ogni {Duration(step)}; i conteggi sono dal campione della riga prima. Memorie in MB, CPU in % di un processore.")
|
||||
.AppendLine()
|
||||
.AppendLine("| Ora | Memoria | Gestita | GC | Thread | Handle | Coda | CPU % | GC2 | Pause ms | Eccezioni | Avvisi | Errori | DB | |")
|
||||
.AppendLine("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|");
|
||||
ProcessSample? previous = null;
|
||||
foreach (var bucket in samples.GroupBy(s => s.TakenAt.UtcTicks / step.Ticks).OrderBy(g => g.Key))
|
||||
{
|
||||
var last = bucket.Last();
|
||||
var same = previous is not null && previous.ProcessStartedAt == last.ProcessStartedAt;
|
||||
var basis = same ? previous! : null;
|
||||
var wall = (last.TakenAt - (basis?.TakenAt ?? last.ProcessStartedAt)).TotalMilliseconds;
|
||||
var cpu = wall <= 0 ? 0 : (last.CpuMs - (basis?.CpuMs ?? 0)) / wall * 100;
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"| {SoakReport.Moment(last.TakenAt, request.Zone)} | {Mb(last.WorkingSet)} | {Mb(last.ManagedHeap)} | {Mb(last.GcCommitted)} | {last.Threads} | {last.Handles} | " +
|
||||
$"{last.PoolPending} | {Format.Number((decimal)cpu, 1)} | {last.Gen2 - (basis?.Gen2 ?? 0)} | {Format.Number((decimal)(last.GcPauseMs - (basis?.GcPauseMs ?? 0)))} | " +
|
||||
$"{last.Exceptions - (basis?.Exceptions ?? 0)} | {bucket.Sum(s => s.Warnings)} | {bucket.Sum(s => s.Errors)} | {(last.DbBytes is { } db ? Mb(db) : "")} | " +
|
||||
$"{(previous is not null && !same ? "riavvio" : "")} |");
|
||||
previous = last;
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static List<List<ProcessSample>> Processes(List<ProcessSample> samples) =>
|
||||
samples.GroupBy(s => s.ProcessStartedAt).Select(g => g.OrderBy(s => s.TakenAt).ToList()).OrderBy(p => p[0].TakenAt).ToList();
|
||||
|
||||
private static ProcessSample ReadSample(DbRow r) => new()
|
||||
{
|
||||
TakenAt = r.Moment("taken_at"),
|
||||
ProcessStartedAt = r.Moment("process_started_at"),
|
||||
Kind = r.Text("kind"),
|
||||
Version = r.Text("version"),
|
||||
WorkingSet = r.Number("working_set"),
|
||||
PrivateBytes = r.Number("private_bytes"),
|
||||
ManagedHeap = r.Number("managed_heap"),
|
||||
GcCommitted = r.Number("gc_committed"),
|
||||
Gen0 = r.Number("gc_gen0"),
|
||||
Gen1 = r.Number("gc_gen1"),
|
||||
Gen2 = r.Number("gc_gen2"),
|
||||
GcPauseMs = r.Measure("gc_pause_ms"),
|
||||
Threads = (int)r.Number("threads"),
|
||||
Handles = (int)r.Number("handles"),
|
||||
CpuMs = r.Measure("cpu_ms"),
|
||||
PoolThreads = (int)r.Number("pool_threads"),
|
||||
PoolPending = r.Number("pool_pending"),
|
||||
LockContentions = r.Number("lock_contentions"),
|
||||
Exceptions = r.Number("exceptions"),
|
||||
DbBytes = r.IsNull("db_bytes") ? null : r.Number("db_bytes"),
|
||||
Warnings = (int)r.Number("warnings"),
|
||||
Errors = (int)r.Number("errors"),
|
||||
Calls = r.TextOrNull("calls") is { } json ? JsonSerializer.Deserialize<List<HttpCallStats>>(json, DiagnosticSampler.Json) ?? [] : [],
|
||||
};
|
||||
|
||||
/// <summary>The warning and error lines of the technical logs in the window, grouped by what they say.</summary>
|
||||
internal static LogSummary ReadLogs(string folder, DateTimeOffset from, DateTimeOffset to)
|
||||
{
|
||||
var groups = new Dictionary<string, LogGroup>(StringComparer.Ordinal);
|
||||
int files = 0, warnings = 0, errors = 0;
|
||||
long lines = 0, read = 0;
|
||||
var truncated = false;
|
||||
if (!Directory.Exists(folder))
|
||||
{
|
||||
return new LogSummary(0, 0, 0, 0, false, []);
|
||||
}
|
||||
|
||||
var first = DateOnly.FromDateTime(from.UtcDateTime).AddDays(-1);
|
||||
var last = DateOnly.FromDateTime(to.UtcDateTime).AddDays(1);
|
||||
foreach (var file in Directory.EnumerateFiles(folder, "anubis-*.log").Order(StringComparer.Ordinal))
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(file);
|
||||
if (!DateOnly.TryParseExact(name["anubis-".Length..], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) || day < first || day > last)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (read >= MaxLogBytes)
|
||||
{
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
|
||||
files++;
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
while (reader.ReadLine() is { } line)
|
||||
{
|
||||
read += line.Length + 1;
|
||||
if (read > MaxLogBytes)
|
||||
{
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!TryParse(line, out var entry) || entry.At < from || entry.At > to)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
lines++;
|
||||
if (entry.Level is not ("warning" or "error" or "critical"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.Level == "warning")
|
||||
{
|
||||
warnings++;
|
||||
}
|
||||
else
|
||||
{
|
||||
errors++;
|
||||
}
|
||||
|
||||
var category = entry.Category[(entry.Category.LastIndexOf('.') + 1)..];
|
||||
var key = entry.Level + "|" + category + "|" + Normalize(entry.Message);
|
||||
if (groups.TryGetValue(key, out var group))
|
||||
{
|
||||
groups[key] = group with { Count = group.Count + 1, Last = entry.At > group.Last ? entry.At : group.Last, Error = group.Error ?? entry.Error };
|
||||
}
|
||||
else
|
||||
{
|
||||
groups[key] = new LogGroup(entry.Level, category, entry.Message, entry.Error, 1, entry.At, entry.At);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return new LogSummary(files, lines, warnings, errors, truncated, [.. groups.Values]);
|
||||
}
|
||||
|
||||
private static bool TryParse(string line, out (DateTimeOffset At, string Level, string Category, string Message, string? Error) entry)
|
||||
{
|
||||
entry = default;
|
||||
try
|
||||
{
|
||||
using var json = JsonDocument.Parse(line);
|
||||
var root = json.RootElement;
|
||||
if (!root.TryGetProperty("at", out var at) || !DateTimeOffset.TryParse(at.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var moment))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
entry = (moment, root.TryGetProperty("level", out var l) ? l.GetString() ?? "" : "", root.TryGetProperty("category", out var c) ? c.GetString() ?? "" : "",
|
||||
root.TryGetProperty("message", out var m) ? m.GetString() ?? "" : "", root.TryGetProperty("error", out var e) ? e.GetString() : null);
|
||||
return true;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The message with ids and numbers taken out, so the same trouble with other values counts once.</summary>
|
||||
internal static string Normalize(string message) => Numbers().Replace(Guids().Replace(message, "‹id›"), "#");
|
||||
|
||||
private static double Slope(List<ProcessSample> samples, Func<ProcessSample, double> value)
|
||||
{
|
||||
var t0 = samples[0].TakenAt;
|
||||
var xs = samples.Select(s => (s.TakenAt - t0).TotalHours).ToList();
|
||||
var ys = samples.Select(value).ToList();
|
||||
var mx = xs.Average();
|
||||
var my = ys.Average();
|
||||
var den = xs.Sum(x => (x - mx) * (x - mx));
|
||||
return den == 0 ? 0 : xs.Zip(ys).Sum(p => (p.First - mx) * (p.Second - my)) / den;
|
||||
}
|
||||
|
||||
private static double Rank(List<double> sorted, double q) => sorted.Count == 0 ? 0 : sorted[Math.Clamp((int)Math.Ceiling(q * sorted.Count) - 1, 0, sorted.Count - 1)];
|
||||
|
||||
private static string Mb(long bytes) => Format.Number((decimal)Math.Round(bytes / 1048576.0, 1), 1);
|
||||
|
||||
private static string Ms(double ms) => Format.Number((decimal)Math.Round(ms));
|
||||
|
||||
private static string Seconds(double seconds) => seconds < 10 ? Format.Number((decimal)Math.Round(seconds, 2), 2) + " s" : Format.Number((decimal)Math.Round(seconds)) + " s";
|
||||
|
||||
private static string Signed(double value) => Format.Number((decimal)Math.Round(value, 2), 2, withSign: true);
|
||||
|
||||
private static string Duration(TimeSpan span) => span.TotalMinutes < 90
|
||||
? Format.Number((decimal)Math.Round(span.TotalMinutes)) + " minuti"
|
||||
: span.TotalHours < 48 ? SoakReport.Hours(TimeSpan.FromHours(Math.Round(span.TotalHours, 1))) : Format.Number((decimal)Math.Round(span.TotalDays, 1), 1) + " giorni";
|
||||
|
||||
private static string Cell(string? text, int max)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
var flat = text.ReplaceLineEndings(" ").Replace("|", "\\|", StringComparison.Ordinal);
|
||||
return flat.Length <= max ? flat : flat[..max] + "…";
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b")]
|
||||
private static partial Regex Guids();
|
||||
|
||||
[GeneratedRegex(@"\d+(?:[.,:]\d+)*")]
|
||||
private static partial Regex Numbers();
|
||||
|
||||
private sealed record Run(string Job, DateTimeOffset Due, DateTimeOffset Started, DateTimeOffset Finished, string Outcome, bool Missed, string? Error);
|
||||
|
||||
internal sealed record LogGroup(string Level, string Category, string Sample, string? Error, int Count, DateTimeOffset First, DateTimeOffset Last);
|
||||
|
||||
internal sealed record LogSummary(int Files, long Lines, int Warnings, int Errors, bool Truncated, IReadOnlyList<LogGroup> Groups);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
using System.Diagnostics.Metrics;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Anubis.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// The outbound HTTP calls of one destination over a stretch of time (issue #95): how many, how many failed and how,
|
||||
/// and how long they took, in fixed buckets so that stretches can be added together without keeping every call.
|
||||
/// </summary>
|
||||
public sealed record HttpCallStats(string Host, long Calls, long Failures, IReadOnlyDictionary<string, long> Outcomes, long[] Buckets, double MaxMs, double TotalMs)
|
||||
{
|
||||
/// <summary>Upper bounds in milliseconds of the duration buckets; one more bucket holds everything slower.</summary>
|
||||
public static IReadOnlyList<double> Bounds { get; } = [5, 10, 20, 50, 100, 200, 300, 500, 750, 1000, 1500, 2000, 3000, 5000, 10000, 20000, 30000, 60000];
|
||||
|
||||
public double AverageMs => Calls == 0 ? 0 : TotalMs / Calls;
|
||||
|
||||
/// <summary>
|
||||
/// The duration under which a share <paramref name="q"/> of the calls finished, read from the buckets: the upper
|
||||
/// bound of the bucket where that share is reached, never more than the slowest call.
|
||||
/// </summary>
|
||||
public double Percentile(double q)
|
||||
{
|
||||
var total = Buckets.Sum();
|
||||
if (total == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var rank = Math.Max(1, (long)Math.Ceiling(q * total));
|
||||
long seen = 0;
|
||||
for (var i = 0; i < Buckets.Length; i++)
|
||||
{
|
||||
seen += Buckets[i];
|
||||
if (seen >= rank)
|
||||
{
|
||||
return i < Bounds.Count ? Math.Min(Bounds[i], MaxMs) : MaxMs;
|
||||
}
|
||||
}
|
||||
|
||||
return MaxMs;
|
||||
}
|
||||
|
||||
public static IReadOnlyList<HttpCallStats> Merge(IEnumerable<HttpCallStats> stats)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stats);
|
||||
return stats.GroupBy(s => s.Host, StringComparer.Ordinal).Select(g =>
|
||||
{
|
||||
var buckets = new long[Bounds.Count + 1];
|
||||
var outcomes = new SortedDictionary<string, long>(StringComparer.Ordinal);
|
||||
foreach (var s in g)
|
||||
{
|
||||
for (var i = 0; i < Math.Min(buckets.Length, s.Buckets.Length); i++)
|
||||
{
|
||||
buckets[i] += s.Buckets[i];
|
||||
}
|
||||
|
||||
foreach (var (outcome, count) in s.Outcomes)
|
||||
{
|
||||
outcomes[outcome] = outcomes.GetValueOrDefault(outcome) + count;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpCallStats(g.Key, g.Sum(s => s.Calls), g.Sum(s => s.Failures), outcomes, buckets, g.Max(s => s.MaxMs), g.Sum(s => s.TotalMs));
|
||||
}).OrderByDescending(s => s.Calls).ThenBy(s => s.Host, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
internal static int Bucket(double milliseconds)
|
||||
{
|
||||
for (var i = 0; i < Bounds.Count; i++)
|
||||
{
|
||||
if (milliseconds <= Bounds[i])
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return Bounds.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Listens to the duration that .NET records for every outbound HTTP request (meter <c>System.Net.Http</c>,
|
||||
/// instrument <c>http.client.request.duration</c>) and adds it up by destination until <see cref="Take"/>. No
|
||||
/// package and no change to the brokers' clients: every <see cref="HttpClient"/> of the process is measured.
|
||||
/// </summary>
|
||||
public sealed class HttpCallMeter : IDisposable
|
||||
{
|
||||
public const string MeterName = "System.Net.Http";
|
||||
public const string InstrumentName = "http.client.request.duration";
|
||||
|
||||
private static readonly Lazy<HttpCallMeter> _shared = new(() => new HttpCallMeter());
|
||||
|
||||
private readonly MeterListener _listener = new();
|
||||
private readonly Lock _gate = new();
|
||||
private Dictionary<string, Tally> _tallies = new(StringComparer.Ordinal);
|
||||
|
||||
public HttpCallMeter()
|
||||
{
|
||||
_listener.InstrumentPublished = (instrument, listener) =>
|
||||
{
|
||||
if (instrument.Meter.Name == MeterName && instrument.Name == InstrumentName)
|
||||
{
|
||||
listener.EnableMeasurementEvents(instrument);
|
||||
}
|
||||
};
|
||||
_listener.SetMeasurementEventCallback<double>(OnMeasurement);
|
||||
_listener.Start();
|
||||
}
|
||||
|
||||
/// <summary>The one meter of the running bot, started at the first use.</summary>
|
||||
public static HttpCallMeter Shared => _shared.Value;
|
||||
|
||||
/// <summary>The calls since the previous call to this method, by destination; the counts start again from zero.</summary>
|
||||
public IReadOnlyList<HttpCallStats> Take()
|
||||
{
|
||||
Dictionary<string, Tally> taken;
|
||||
lock (_gate)
|
||||
{
|
||||
taken = _tallies;
|
||||
_tallies = new Dictionary<string, Tally>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
return taken.Select(t => t.Value.Stats(t.Key)).OrderBy(s => s.Host, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
public void Dispose() => _listener.Dispose();
|
||||
|
||||
private void OnMeasurement(Instrument instrument, double seconds, ReadOnlySpan<KeyValuePair<string, object?>> tags, object? state)
|
||||
{
|
||||
string? host = null;
|
||||
int? port = null;
|
||||
int? status = null;
|
||||
string? error = null;
|
||||
foreach (var tag in tags)
|
||||
{
|
||||
switch (tag.Key)
|
||||
{
|
||||
case "server.address":
|
||||
host = tag.Value?.ToString();
|
||||
break;
|
||||
case "server.port":
|
||||
port = tag.Value is null ? null : Convert.ToInt32(tag.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case "http.response.status_code":
|
||||
status = tag.Value is null ? null : Convert.ToInt32(tag.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case "error.type":
|
||||
error = tag.Value?.ToString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var key = (host ?? "?") + (port is { } p and not (80 or 443) ? ":" + p.ToString(CultureInfo.InvariantCulture) : "");
|
||||
var outcome = status?.ToString(CultureInfo.InvariantCulture) ?? error ?? "?";
|
||||
var failed = status is not (>= 200 and < 400);
|
||||
var milliseconds = Math.Max(0, seconds * 1000);
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_tallies.TryGetValue(key, out var tally))
|
||||
{
|
||||
tally = new Tally();
|
||||
_tallies[key] = tally;
|
||||
}
|
||||
|
||||
tally.Add(outcome, failed, milliseconds);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Tally
|
||||
{
|
||||
private readonly long[] _buckets = new long[HttpCallStats.Bounds.Count + 1];
|
||||
private readonly SortedDictionary<string, long> _outcomes = new(StringComparer.Ordinal);
|
||||
private long _calls;
|
||||
private long _failures;
|
||||
private double _max;
|
||||
private double _total;
|
||||
|
||||
public void Add(string outcome, bool failed, double milliseconds)
|
||||
{
|
||||
_calls++;
|
||||
if (failed)
|
||||
{
|
||||
_failures++;
|
||||
}
|
||||
|
||||
_outcomes[outcome] = _outcomes.GetValueOrDefault(outcome) + 1;
|
||||
_buckets[HttpCallStats.Bucket(milliseconds)]++;
|
||||
_max = Math.Max(_max, milliseconds);
|
||||
_total += milliseconds;
|
||||
}
|
||||
|
||||
public HttpCallStats Stats(string host) => new(host, _calls, _failures, new SortedDictionary<string, long>(_outcomes, StringComparer.Ordinal),
|
||||
(long[])_buckets.Clone(), Math.Round(_max, 1), Math.Round(_total, 1));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user