Integrates administrator-only health endpoints, privacy-preserving ROBUST login diagnostics, validated DLL preflight sources, WebInterface runtime UI and required assets. Verified with .NET 10 builds, synthetic log tests and responsive browser tests. Live rollout on NexTopia; main simulator awaits its next controlled restart.
348 lines
18 KiB
C#
348 lines
18 KiB
C#
// SPDX-License-Identifier: LicenseRef-OpenGenesisLINK-EULA
|
|
// OpenGenesisLINK Gen1 Health Center and privacy-preserving grid login diagnostics.
|
|
using System.Globalization;
|
|
using System.Net.Http;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
|
|
|
/// <summary>
|
|
/// Read-only diagnostics for administrator sessions. No avatar names, UUIDs,
|
|
/// passwords, IP addresses, raw log lines or private node tokens leave this class.
|
|
/// </summary>
|
|
internal static class OglHealthDiagnostics
|
|
{
|
|
private const int MaxLogBytes = 2 * 1024 * 1024;
|
|
private const int WindowMinutes = 60;
|
|
private static readonly HttpClient ProbeClient = new(
|
|
new HttpClientHandler { AllowAutoRedirect = false })
|
|
{ Timeout = TimeSpan.FromSeconds(4) };
|
|
|
|
private sealed record Finding(string Code, string Label, string Severity,
|
|
string Explanation, string Action, DateTimeOffset Time);
|
|
private sealed record Component(string Id, string Title, string Status,
|
|
string Detail, string Action);
|
|
private sealed record CauseInfo(string Code, string Label, string Severity,
|
|
string Explanation, string Action);
|
|
private static readonly CauseInfo[] Causes =
|
|
[
|
|
new("missing_dll_type", "Fehlende Kernkomponente", "critical",
|
|
"Das Loginmodul erwartet eine Klasse, die in der geladenen DLL nicht vorhanden ist.",
|
|
"DLL-Startschutz prüfen und zusammengehörige OGL-Binärdateien bereitstellen."),
|
|
new("incompatible_dll_method", "Inkompatible DLL-Schnittstelle", "critical",
|
|
"Eine erforderliche Login- oder Framework-Methode ist nicht vorhanden.",
|
|
"DLL-Startschutz prüfen; Framework und Loginmodul aus demselben Build bereitstellen."),
|
|
new("destination_not_found", "Ankunftsregion nicht verfügbar", "warning",
|
|
"Die angeforderte Zielregion konnte nicht aufgelöst oder erreicht werden.",
|
|
"Home-Region, Regionseintrag, Grid-Service und Ziel-Simulator prüfen."),
|
|
new("credentials_rejected", "Zugangsdaten abgelehnt", "warning",
|
|
"Das Grid hat die Anmeldung mit den angegebenen Zugangsdaten abgewiesen.",
|
|
"Konto- und Authentifizierungsdienst prüfen, ohne Passwörter zu protokollieren."),
|
|
new("viewer_rejected", "Viewer abgewiesen", "warning",
|
|
"Die Viewer-Zugangsprüfung hat eine Anmeldung zurückgewiesen.",
|
|
"Viewer-Freigabeliste und OGL-Zugangsrichtlinien kontrollieren."),
|
|
new("access_policy", "Zugangsrichtlinie", "warning",
|
|
"Eine serverseitige Zugangs- oder Bürgerordnungsrichtlinie verhindert den Login.",
|
|
"Aktive Richtlinie und notwendige Zustimmung kontrollieren."),
|
|
new("login_timeout", "Zeitüberschreitung beim Login", "warning",
|
|
"Ein notwendiger Grid-/Simulator-Dienst hat nicht rechtzeitig geantwortet.",
|
|
"Netzwerkpfad, Grid-Dienste, Logs und Auslastung kontrollieren."),
|
|
new("login_exception", "Interner Loginfehler", "critical",
|
|
"Bei der Verarbeitung der Login-Anfrage ist eine Serverausnahme aufgetreten.",
|
|
"ROBUST-Loginmodul und aktuelle Serverprotokolle untersuchen."),
|
|
new("login_rejected_other", "Anmeldung abgewiesen", "warning",
|
|
"Das Loginmodul hat die Anmeldung abgelehnt; weitere Details bleiben im geschützten ROBUST-Protokoll.",
|
|
"ROBUST-Logdatei mit Zugriff für Serveradministratoren prüfen.")
|
|
];
|
|
|
|
private static CauseInfo Lookup(string code) =>
|
|
Causes.First(x => x.Code == code);
|
|
|
|
private static string? LatestRobustLog()
|
|
{
|
|
// Only the local operator can configure the directory.
|
|
// Foreign nodes without shared ROBUST logs display "not available".
|
|
string? configured = Environment.GetEnvironmentVariable("OGL_HEALTH_ROBUST_LOG_DIR");
|
|
string folder = !string.IsNullOrWhiteSpace(configured)
|
|
? configured : Path.Combine(AppContext.BaseDirectory, "logs");
|
|
if (!Path.IsPathFullyQualified(folder) || !Directory.Exists(folder))
|
|
return null;
|
|
try
|
|
{
|
|
return Directory.EnumerateFiles(folder,"Robust_*.log",SearchOption.TopDirectoryOnly)
|
|
.OrderByDescending(File.GetLastWriteTimeUtc)
|
|
.FirstOrDefault();
|
|
}
|
|
catch (Exception e) when(e is IOException or UnauthorizedAccessException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static string LastLogChunk(string file)
|
|
{
|
|
using var stream = new FileStream(file, FileMode.Open, FileAccess.Read,
|
|
FileShare.ReadWrite|FileShare.Delete);
|
|
long count = Math.Min(stream.Length, MaxLogBytes);
|
|
stream.Seek(-count,SeekOrigin.End);
|
|
byte[] buffer = new byte[(int)count];
|
|
int read = 0;
|
|
while (read < buffer.Length)
|
|
{
|
|
int n = stream.Read(buffer,read,buffer.Length-read);
|
|
if (n == 0) break;
|
|
read += n;
|
|
}
|
|
// The first line might be truncated when reading the tail.
|
|
string content=Encoding.UTF8.GetString(buffer,0,read);
|
|
if (stream.Length > MaxLogBytes)
|
|
{
|
|
int newline=content.IndexOf('\n');
|
|
if (newline>=0) content=content[(newline+1)..];
|
|
}
|
|
return content;
|
|
}
|
|
|
|
private static bool TryLogTime(string line,out DateTimeOffset time)
|
|
{
|
|
time=default;
|
|
if (line.Length<23) return false;
|
|
if (!DateTime.TryParseExact(line[..23],"yyyy-MM-dd HH:mm:ss,fff",
|
|
CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal,out DateTime date))
|
|
return false;
|
|
time=new DateTimeOffset(date.ToUniversalTime(),TimeSpan.Zero);
|
|
return true;
|
|
}
|
|
|
|
private static string? Classify(string line,out bool success)
|
|
{
|
|
success=false;
|
|
// Match only known login-specific events; never return the raw line.
|
|
bool exception=line.Contains("login_to_simulator",StringComparison.OrdinalIgnoreCase)
|
|
&& line.Contains("threw exception",StringComparison.OrdinalIgnoreCase);
|
|
bool loginFailure=line.Contains("[LLOGIN SERVICE]",StringComparison.OrdinalIgnoreCase) &&
|
|
line.Contains("Login failed",StringComparison.OrdinalIgnoreCase);
|
|
bool passed=line.Contains("[LLOGIN SERVICE]",StringComparison.OrdinalIgnoreCase) &&
|
|
line.Contains("All clear. Sending login response",StringComparison.OrdinalIgnoreCase);
|
|
if(passed){success=true;return null;}
|
|
if(!exception&&!loginFailure)return null;
|
|
if(line.Contains("Could not load type",StringComparison.OrdinalIgnoreCase))
|
|
return "missing_dll_type";
|
|
if(line.Contains("Method not found",StringComparison.OrdinalIgnoreCase)||
|
|
line.Contains("MissingMethodException",StringComparison.OrdinalIgnoreCase))
|
|
return "incompatible_dll_method";
|
|
if(line.Contains("destination not found",StringComparison.OrdinalIgnoreCase)||
|
|
line.Contains("region not found",StringComparison.OrdinalIgnoreCase))
|
|
return "destination_not_found";
|
|
if(line.Contains("password",StringComparison.OrdinalIgnoreCase)||
|
|
line.Contains("authentication failed",StringComparison.OrdinalIgnoreCase)||
|
|
line.Contains("incorrect credentials",StringComparison.OrdinalIgnoreCase))
|
|
return "credentials_rejected";
|
|
if(line.Contains("viewer",StringComparison.OrdinalIgnoreCase)||
|
|
line.Contains("channel not allowed",StringComparison.OrdinalIgnoreCase))
|
|
return "viewer_rejected";
|
|
if(line.Contains("citizen rules",StringComparison.OrdinalIgnoreCase)||
|
|
line.Contains("access policy",StringComparison.OrdinalIgnoreCase)||
|
|
line.Contains("terms",StringComparison.OrdinalIgnoreCase)||
|
|
line.Contains("blocked",StringComparison.OrdinalIgnoreCase))
|
|
return "access_policy";
|
|
if(line.Contains("timed out",StringComparison.OrdinalIgnoreCase)||
|
|
line.Contains("timeout",StringComparison.OrdinalIgnoreCase))
|
|
return "login_timeout";
|
|
return exception?"login_exception":"login_rejected_other";
|
|
}
|
|
|
|
public static object LoginDiagnostics()
|
|
{
|
|
var now=DateTimeOffset.UtcNow;
|
|
var findings=new List<Finding>();
|
|
string? path=LatestRobustLog();
|
|
if (path is null)
|
|
{
|
|
return new {
|
|
available=false, status="unknown", checkedAtUtc=now, lookbackMinutes=WindowMinutes,
|
|
source="ROBUST-Protokoll hier nicht verfügbar", sampleLimited=true,
|
|
successes=0, failures=0, critical=0,
|
|
causes=Array.Empty<object>(), recent=Array.Empty<object>(),
|
|
message="Die ROBUST-Logdatei ist für diese Simulatorinstanz nicht eingebunden.",
|
|
note="Ein fehlender Diagnosebericht bedeutet nicht, dass Avatar-Logins fehlschlagen."
|
|
};
|
|
}
|
|
try
|
|
{
|
|
var info=new FileInfo(path);
|
|
string text=LastLogChunk(path);
|
|
int successes=0;
|
|
foreach(string line in text.Split('\n'))
|
|
{
|
|
if(!TryLogTime(line,out var timestamp) ||
|
|
timestamp<now.AddMinutes(-WindowMinutes) ||
|
|
timestamp>now.AddMinutes(5)) continue;
|
|
string? code=Classify(line,out bool passed);
|
|
if(passed){successes++;continue;}
|
|
if(code is null)continue;
|
|
CauseInfo c=Lookup(code);
|
|
findings.Add(new(c.Code,c.Label,c.Severity,c.Explanation,c.Action,timestamp));
|
|
}
|
|
int severe=findings.Count(x=>x.Severity=="critical");
|
|
string status=severe>0?"critical":findings.Count>0?"warning":
|
|
successes>0?"ok":"unknown";
|
|
var summaries=findings.GroupBy(x=>x.Code)
|
|
.OrderByDescending(g=>g.Count())
|
|
.Select(g=>new{
|
|
code=g.Key,label=g.First().Label,severity=g.First().Severity,
|
|
count=g.Count(),lastSeenUtc=g.Max(x=>x.Time),
|
|
explanation=g.First().Explanation,action=g.First().Action
|
|
}).ToArray();
|
|
var recent=findings.OrderByDescending(x=>x.Time).Take(18)
|
|
.Select(x=>new{timeUtc=x.Time,code=x.Code,label=x.Label,
|
|
severity=x.Severity,explanation=x.Explanation,
|
|
action=x.Action}).ToArray();
|
|
long age=Math.Max(0,(long)(now-info.LastWriteTimeUtc).TotalSeconds);
|
|
return new{
|
|
available=true,status,checkedAtUtc=now,lookbackMinutes=WindowMinutes,
|
|
source="Lokales ROBUST-Protokoll (anonymisierte Ereignisse)",
|
|
sampleLimited=info.Length>MaxLogBytes,logAgeSeconds=age,
|
|
successes,failures=findings.Count,critical=severe,
|
|
causes=summaries,recent,
|
|
message=severe>0?"Kritischer Loginfehler im ausgewerteten Zeitraum erkannt.":
|
|
findings.Count>0?"Einzelne abgewiesene Loginversuche protokolliert.":
|
|
successes>0?"Erfolgreiche Loginantworten im Protokoll erkannt.":
|
|
"Keine auswertbaren Loginereignisse im aktuellen Protokollausschnitt.",
|
|
note="Nur der letzte Protokollausschnitt (höchstens 2 MiB) wird für die letzten "+
|
|
WindowMinutes+" Minuten ausgewertet. Keine Namen, IDs, IP-Adressen oder Rohprotokolle "+
|
|
"in dieser Ansicht. Ein protokollierter Erfolg ist kein vollständiger Viewer-End-to-End-Test."
|
|
};
|
|
}
|
|
catch(Exception e) when(e is IOException or UnauthorizedAccessException or ArgumentException)
|
|
{
|
|
return new {
|
|
available=false,status="unknown",checkedAtUtc=now,
|
|
lookbackMinutes=WindowMinutes,source="ROBUST-Protokoll nicht lesbar",
|
|
sampleLimited=true,successes=0,failures=0,critical=0,
|
|
causes=Array.Empty<object>(),recent=Array.Empty<object>(),
|
|
message="Die lokale ROBUST-Protokollauswertung ist derzeit nicht möglich.",
|
|
note="Logzugriff prüfen; es wurden keine Zugangsdaten offengelegt."
|
|
};
|
|
}
|
|
}
|
|
|
|
private static async Task<Component> Probe(string id,string title,string? address,
|
|
CancellationToken stop)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(address))
|
|
return new(id,title,"unknown","Auf dieser Node nicht konfiguriert.",
|
|
"Dienstkonfiguration prüfen, falls dieser Dienst verwendet werden soll.");
|
|
if (!Uri.TryCreate(address,UriKind.Absolute,out Uri? uri) ||
|
|
uri.Scheme!=Uri.UriSchemeHttps||uri.UserInfo.Length>0 ||
|
|
uri.Query.Length>0 ||uri.Fragment.Length>0)
|
|
return new(id,title,"unknown","Keine gültige HTTPS-Dienstadresse konfiguriert.",
|
|
"HTTPS-Ziel der Node prüfen.");
|
|
try
|
|
{
|
|
// Only site owners can set this environment variable. No user-provided URLs.
|
|
using var cancel=CancellationTokenSource.CreateLinkedTokenSource(stop);
|
|
cancel.CancelAfter(TimeSpan.FromSeconds(3));
|
|
using var response=await ProbeClient.GetAsync(new Uri(uri,"/v1/health"),cancel.Token);
|
|
return response.IsSuccessStatusCode?
|
|
new(id,title,"ok","HTTPS-Healthcheck erfolgreich.",
|
|
"Keine Maßnahme erforderlich."):
|
|
new(id,title,"warning","Zentrale antwortet mit HTTP "+(int)response.StatusCode+".",
|
|
"Dienststatus und HTTPS-Reverse-Proxy prüfen.");
|
|
}
|
|
catch(Exception ex) when(ex is HttpRequestException or OperationCanceledException)
|
|
{
|
|
return new(id,title,"warning","Zentraler Dienst reagiert nicht auf die HTTPS-Prüfung.",
|
|
"Netzwerkverbindung und zentralen Dienst kontrollieren.");
|
|
}
|
|
}
|
|
|
|
public static async Task<object> SummaryAsync(AdminOperations operations,CancellationToken stop)
|
|
{
|
|
var now=DateTimeOffset.UtcNow;
|
|
var components=new List<Component>();
|
|
object[] regions=operations.RegionSummary();
|
|
int notReady=0;
|
|
int avatars=0;
|
|
foreach(var obj in regions)
|
|
{
|
|
JsonElement value=JsonSerializer.SerializeToElement(obj);
|
|
if(!value.GetProperty("ready").GetBoolean())notReady++;
|
|
avatars+=value.GetProperty("agents").GetInt32();
|
|
}
|
|
components.Add(new("regions","Simulator und Regionen",
|
|
regions.Length==0?"warning":notReady>0?"critical":"ok",
|
|
regions.Length+" lokal geladene Regionen, "+(regions.Length-notReady)+
|
|
" bereit, "+avatars+" Root-Avatare online.",
|
|
regions.Length==0?"Simulatorstart und Regionskonfiguration prüfen.":
|
|
notReady>0?"Nicht bereite Regionen im Regionsmenü untersuchen.":
|
|
"Keine Maßnahme erforderlich."));
|
|
object[] services=await operations.ServiceSummaryAsync(stop);
|
|
int down=0;
|
|
foreach(object item in services)
|
|
{
|
|
var value=JsonSerializer.SerializeToElement(item);
|
|
bool reachable=value.GetProperty("reachable").GetBoolean();
|
|
if(!reachable)down++;
|
|
}
|
|
components.Add(new("grid_services","ROBUST-/Grid-Service-Endpunkte",
|
|
services.Length==0?"unknown":down>0?"warning":"ok",
|
|
services.Length==0?"Keine Grid-Service-Ports konfiguriert.":
|
|
(services.Length-down)+" von "+services.Length+
|
|
" konfigurierten TCP-Endpunkten erreichbar.",
|
|
down>0?"Routing, DNS, Firewall und Dienstports prüfen.":
|
|
"TCP bestätigt nur die Erreichbarkeit; keine Login-Funktionsgarantie."));
|
|
var baseDir=Path.Combine(AppContext.BaseDirectory,"ops-data");
|
|
var preflight=Path.Combine(baseDir,"compatibility-simulator.json");
|
|
bool loaded=File.Exists(preflight);
|
|
string preflightStatus="unknown",preflightDetail="Kein aktueller DLL-Prüfbericht.";
|
|
if(loaded)
|
|
{
|
|
try
|
|
{
|
|
using var json=JsonDocument.Parse(File.ReadAllText(preflight));
|
|
preflightStatus=json.RootElement.GetProperty("status").GetString()=="ok"?"ok":"critical";
|
|
preflightDetail=preflightStatus=="ok"?
|
|
"Kern-DLLs auf dem Datenträger als kompatibel geprüft.":
|
|
"DLL-Kompatibilitätsproblem auf dem Datenträger erkannt.";
|
|
}
|
|
catch(Exception e) when(e is IOException or JsonException or UnauthorizedAccessException)
|
|
{
|
|
preflightDetail="Prüfbericht ist derzeit nicht lesbar.";
|
|
}
|
|
}
|
|
components.Add(new("preflight","DLL-Startschutz",preflightStatus,
|
|
preflightDetail,"Einzelheiten unter System & Integrität ansehen."));
|
|
// Never infer login success from healthy TCP ports or process uptime.
|
|
JsonElement login=JsonSerializer.SerializeToElement(LoginDiagnostics());
|
|
string loginStatus=login.GetProperty("status").GetString()??"unknown";
|
|
components.Add(new("login","Avatar-Loginprotokoll",loginStatus,
|
|
login.GetProperty("message").GetString()??"Keine Daten.",
|
|
"Für genaue Ursachen die anonymisierte Login-Diagnose öffnen."));
|
|
string? updates=Environment.GetEnvironmentVariable("OGL_UPDATE_CENTRAL_URL");
|
|
string? translator=Environment.GetEnvironmentVariable("OGL_TRANSLATOR_CENTRAL_URL");
|
|
var probes=await Task.WhenAll(
|
|
Probe("update_center","OGL Update Center",updates,stop),
|
|
Probe("translator","OGL Global Translater",translator,stop));
|
|
components.AddRange(probes);
|
|
var active=components.Where(x=>x.Status!="unknown").ToArray();
|
|
string state=active.Any(x=>x.Status=="critical")?"critical":
|
|
active.Any(x=>x.Status=="warning")?"warning":
|
|
active.Length==0?"unknown":"ok";
|
|
return new {
|
|
status=state,
|
|
checkedAtUtc=now,
|
|
components=components.Select(x=>new{
|
|
id=x.Id,title=x.Title,status=x.Status,
|
|
detail=x.Detail,action=x.Action
|
|
}).ToArray(),
|
|
evaluated=active.Length,
|
|
attention=components.Count(x=>x.Status is "critical" or "warning"),
|
|
note="Live-Checks der lokalen Simulatorinstanz und konfigurierter Endpunkte. "+
|
|
"TCP-/HTTPS-Erreichbarkeit und Logauswertung ersetzen keine echte Avatar-Anmeldung."
|
|
};
|
|
}
|
|
}
|