ci / test (postgres) (pull_request) Successful in 9m14s
ci / test (sqlite) (push) Successful in 4m11s
ci / test (sqlite) (pull_request) Successful in 4m12s
ci / test (postgres) (push) Successful in 9m40s
ci / image (pull_request) Successful in 2m14s
ci / image (push) Successful in 54s
Trying the packaged release showed three things to fix: a 101 answer that opens a WebSocket was counted as a failure, the duration buckets were too coarse around the usual 200-500 ms of the brokers, and the report mixed CRLF and LF lines and named SQLite only by its version. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
140 lines
6.8 KiB
C#
140 lines
6.8 KiB
C#
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("Raggiungibile da altri computer", 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;
|
|
}
|
|
}
|
|
}
|