using System.Collections; using System.Globalization; using Anubis.Core; using Anubis.Db; using Anubis.Diagnostics; using Anubis.Platform; namespace Anubis.Server; /// The diagnostics report (issue #95, ADR 0013) as the command, the download and the Diario button make it. internal static class DiagnosticsExport { /// Thirty days: as long as the samples are kept. public const double MaxHours = 720; /// /// The report over the last hours up to , or from /// ; without either, from the first sample kept, so a run of a release is covered whole. /// public static async Task BuildAsync(Database db, StartupConfig config, IReadOnlyDictionary 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); } /// The startup settings, and which ANUBIS_ variables are set: values only for those that cannot hold a secret. internal static IReadOnlyList> Setup(StartupConfig config, IReadOnlyDictionary environment) { var lines = new List> { 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 ProcessEnvironment() => Environment.GetEnvironmentVariables().Cast().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); } /// /// "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 docker exec, on desktop from a second terminal. /// 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 ]"; /// 0 when the report was made, 1 when it could not be, 2 for the usage. public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null, IClock? clock = null) { output ??= Console.Out; clock ??= new SystemClock(); var own = new Dictionary(StringComparer.Ordinal); var rest = new List(); 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; } } }