398 lines
17 KiB
C#
398 lines
17 KiB
C#
// SPDX-License-Identifier: MPL-2.0
|
||
using System.Collections.Concurrent;
|
||
using System.Diagnostics;
|
||
using System.Net;
|
||
using System.Net.Http.Headers;
|
||
using System.Net.NetworkInformation;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using log4net;
|
||
using OpenMetaverse;
|
||
using OpenSim.Region.Framework.Interfaces;
|
||
using OpenSim.Region.Framework.Scenes;
|
||
|
||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||
|
||
/// <summary>Privileged operations, scoped to scenes hosted by this ONE simulator.</summary>
|
||
internal sealed class AdminOperations : IDisposable
|
||
{
|
||
public const long MaxUploadBytes = 2L * 1024 * 1024 * 1024;
|
||
internal sealed class OperationException(int code, string message) : Exception(message)
|
||
{
|
||
public int Status { get; } = code;
|
||
}
|
||
private sealed class Job
|
||
{
|
||
public string Id = "";
|
||
public string Region = "";
|
||
public string Kind = "";
|
||
public string State = "queued";
|
||
public string Message = "";
|
||
public DateTimeOffset Created = DateTimeOffset.UtcNow;
|
||
public long Bytes;
|
||
public long Total;
|
||
public string File = "";
|
||
}
|
||
private readonly ConcurrentDictionary<UUID, Scene> _scenes;
|
||
private readonly ConcurrentDictionary<string, Job> _jobs = new();
|
||
private readonly ConcurrentDictionary<UUID, string> _busy = new();
|
||
private readonly string _archiveDir;
|
||
private readonly string _storage;
|
||
private readonly int _retention;
|
||
private readonly List<(string Name, Uri Uri)> _services;
|
||
private readonly UpdateStager _updateStager;
|
||
private static readonly ILog Log = LogManager.GetLogger(typeof(AdminOperations));
|
||
private static readonly HttpClient GitClient = CreateGitClient();
|
||
|
||
public AdminOperations(ConcurrentDictionary<UUID, Scene> scenes, string storage, int retention, List<(string Name, Uri Uri)> services)
|
||
{
|
||
_scenes = scenes;
|
||
_storage = storage;
|
||
_retention = retention;
|
||
_services = services;
|
||
_updateStager = new UpdateStager(storage, retention);
|
||
_archiveDir = Path.Combine(storage, "archives");
|
||
Directory.CreateDirectory(_archiveDir);
|
||
}
|
||
private static HttpClient CreateGitClient()
|
||
{
|
||
var h = new HttpClientHandler { AllowAutoRedirect = false };
|
||
var client = new HttpClient(h) { Timeout = TimeSpan.FromSeconds(12) };
|
||
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("OpenGenesisLINK-Admin", "0.1"));
|
||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
|
||
return client;
|
||
}
|
||
|
||
private Scene Region(string id)
|
||
{
|
||
if (!UUID.TryParse(id, out UUID uid) || !_scenes.TryGetValue(uid, out Scene? s))
|
||
throw new OperationException(404, "Region nicht gefunden");
|
||
return s;
|
||
}
|
||
private (Scene Scene, IRegionArchiverModule Archiver) GetArchiver(string id)
|
||
{
|
||
Scene scene = Region(id);
|
||
var archive = scene.RequestModuleInterface<IRegionArchiverModule>();
|
||
if (archive is null) throw new OperationException(503, "OAR-Modul in dieser Region nicht verfügbar");
|
||
return (scene, archive);
|
||
}
|
||
private Job Begin(string id, string kind)
|
||
{
|
||
Scene scene = Region(id);
|
||
string jobId = Guid.NewGuid().ToString("N");
|
||
var job = new Job { Id = jobId, Region = scene.RegionInfo.RegionName, Kind = kind };
|
||
if (!_busy.TryAdd(scene.RegionInfo.RegionID, jobId))
|
||
throw new OperationException(409, "Diese Region führt bereits einen Archivauftrag aus");
|
||
_jobs[jobId] = job;
|
||
return job;
|
||
}
|
||
private void Complete(UUID regionId, Job job, string? error)
|
||
{
|
||
job.Message = error ?? "";
|
||
job.State = string.IsNullOrWhiteSpace(error) ? "completed" : "failed";
|
||
_busy.TryRemove(new KeyValuePair<UUID, string>(regionId, job.Id));
|
||
}
|
||
|
||
public object[] RegionSummary()
|
||
{
|
||
return _scenes.Values.OrderBy(s => s.RegionInfo.RegionName).Select(s =>
|
||
{
|
||
var r = s.RegionInfo;
|
||
return (object)new
|
||
{
|
||
id = r.RegionID.ToString(),
|
||
name = r.RegionName,
|
||
location = $"{r.RegionLocX}, {r.RegionLocY}",
|
||
size = $"{r.RegionSizeX} × {r.RegionSizeY}",
|
||
udpPort = r.InternalEndPoint?.Port,
|
||
httpPort = r.HttpPort,
|
||
serverUri = r.ServerURI,
|
||
ready = s.Ready,
|
||
agents = s.GetRootAgentCount(),
|
||
scriptsEnabled = s.ScriptsEnabled,
|
||
physicsEnabled = s.PhysicsEnabled
|
||
};
|
||
}).ToArray();
|
||
}
|
||
|
||
public object[] PortSummary()
|
||
{
|
||
IPEndPoint[] udp;
|
||
IPEndPoint[] tcp;
|
||
try
|
||
{
|
||
udp = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
|
||
tcp = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
|
||
}
|
||
catch { udp = []; tcp = []; }
|
||
var rows = new List<object>();
|
||
foreach (Scene s in _scenes.Values.OrderBy(v => v.RegionInfo.RegionName))
|
||
{
|
||
var r = s.RegionInfo;
|
||
int udpPort = r.InternalEndPoint?.Port ?? 0;
|
||
rows.Add(new
|
||
{
|
||
name = r.RegionName, protocol = "UDP", port = udpPort,
|
||
local = udpPort > 0 && udp.Any(x => x.Port == udpPort),
|
||
publicStatus = "Nicht extern geprüft – Router/NAT/Firewall unbekannt",
|
||
hint = "Fritz!Box: UDP-Port an die lokale Simulator-IP weiterleiten"
|
||
});
|
||
int httpPort = (int)r.HttpPort;
|
||
rows.Add(new
|
||
{
|
||
name = r.RegionName, protocol = "TCP", port = httpPort,
|
||
local = httpPort > 0 && tcp.Any(x => x.Port == httpPort),
|
||
publicStatus = "Nicht extern geprüft – Router/NAT/Firewall unbekannt",
|
||
hint = "Fritz!Box: TCP-Port beziehungsweise HTTPS-Proxy prüfen"
|
||
});
|
||
}
|
||
return rows.ToArray();
|
||
}
|
||
|
||
public async Task<object[]> ServiceSummaryAsync(CancellationToken stop)
|
||
{
|
||
var checks = _services.Select(async item =>
|
||
{
|
||
bool reachable = false;
|
||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(stop);
|
||
timeout.CancelAfter(TimeSpan.FromSeconds(2));
|
||
try
|
||
{
|
||
using var client = new TcpClient();
|
||
await client.ConnectAsync(item.Uri.Host, item.Uri.Port, timeout.Token);
|
||
reachable = client.Connected;
|
||
}
|
||
catch (Exception) { }
|
||
return (object)new
|
||
{
|
||
name = item.Name,
|
||
host = item.Uri.Host,
|
||
port = item.Uri.Port,
|
||
protocol = item.Uri.Scheme.ToUpperInvariant() + "/TCP",
|
||
reachable,
|
||
detail = reachable ? "TCP-Verbindung erfolgreich – Dienstfunktion nicht geprüft" :
|
||
"TCP nicht erreichbar: Dienst, DNS, Routing oder Firewall prüfen"
|
||
};
|
||
});
|
||
return await Task.WhenAll(checks);
|
||
}
|
||
|
||
public bool Restart(string id)
|
||
{
|
||
Scene s;
|
||
try { s = Region(id); }
|
||
catch (OperationException) { return false; }
|
||
_ = Task.Run(async () =>
|
||
{
|
||
await Task.Delay(500);
|
||
try { s.RestartNow(); }
|
||
catch (Exception e) { Log.Error("[OS WEBINTERFACE] Region restart failed", e); }
|
||
});
|
||
Log.Warn("[OS WEBINTERFACE] Region restart requested: " + s.RegionInfo.RegionName);
|
||
return true;
|
||
}
|
||
|
||
public string LogTail()
|
||
{
|
||
string path = Path.Combine(AppContext.BaseDirectory, "OpenSim.log");
|
||
if (!File.Exists(path))
|
||
{
|
||
string logs = Path.Combine(AppContext.BaseDirectory, "logs");
|
||
if (Directory.Exists(logs))
|
||
path = Directory.GetFiles(logs, "*.log")
|
||
.OrderByDescending(File.GetLastWriteTimeUtc).FirstOrDefault() ?? "";
|
||
}
|
||
if (string.IsNullOrEmpty(path) || !File.Exists(path)) return "Keine OpenSim.log gefunden.";
|
||
try
|
||
{
|
||
using var f = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||
long size = Math.Min(f.Length, 100 * 1024);
|
||
f.Seek(-size, SeekOrigin.End);
|
||
using var reader = new StreamReader(f, Encoding.UTF8, true, 1024);
|
||
string text = reader.ReadToEnd();
|
||
return text.Length > 90_000 ? text[^90_000..] : text;
|
||
}
|
||
catch (IOException) { return "Logdatei vorübergehend nicht lesbar."; }
|
||
}
|
||
|
||
public object[] Jobs() => _jobs.Values.OrderByDescending(x => x.Created).Take(30)
|
||
.Select(x => (object)new
|
||
{
|
||
id = x.Id, region = x.Region, kind = x.Kind, state = x.State,
|
||
message = x.Message, created = x.Created, bytes = x.Bytes, total = x.Total,
|
||
download = x.Kind == "export" && x.State == "completed"
|
||
}).ToArray();
|
||
|
||
public object Export(string regionId)
|
||
{
|
||
var (scene, archive) = GetArchiver(regionId);
|
||
Job job = Begin(regionId, "export");
|
||
job.File = Path.Combine(_archiveDir, job.Id + ".oar");
|
||
EventManager.OarFileSaved? complete = null;
|
||
complete = (requestId, message) =>
|
||
{
|
||
if (requestId != Guid.ParseExact(job.Id, "N")) return;
|
||
scene.EventManager.OnOarFileSaved -= complete;
|
||
if (string.IsNullOrWhiteSpace(message) && !File.Exists(job.File))
|
||
message = "OAR-Datei wurde nicht erstellt";
|
||
Complete(scene.RegionInfo.RegionID, job, message);
|
||
if (job.State == "completed") job.Bytes = new FileInfo(job.File).Length;
|
||
};
|
||
scene.EventManager.OnOarFileSaved += complete;
|
||
try
|
||
{
|
||
job.State = "saving";
|
||
archive.ArchiveRegion(job.File, Guid.ParseExact(job.Id, "N"), new Dictionary<string, object>());
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
scene.EventManager.OnOarFileSaved -= complete;
|
||
Complete(scene.RegionInfo.RegionID, job, e.Message);
|
||
}
|
||
return new { id = job.Id, state = job.State };
|
||
}
|
||
|
||
public async Task<object> ImportAsync(string regionId, Stream source, long contentLength, CancellationToken stop)
|
||
{
|
||
var (scene, archive) = GetArchiver(regionId);
|
||
Job job = Begin(regionId, "import");
|
||
job.File = Path.Combine(_archiveDir, job.Id + ".upload");
|
||
job.Total = contentLength;
|
||
try
|
||
{
|
||
job.State = "uploading";
|
||
using (var dst = new FileStream(job.File, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 * 1024, true))
|
||
{
|
||
byte[] buffer = new byte[64 * 1024];
|
||
int read;
|
||
while ((read = await source.ReadAsync(buffer, stop)) != 0)
|
||
{
|
||
job.Bytes += read;
|
||
if (job.Bytes > contentLength || job.Bytes > MaxUploadBytes)
|
||
throw new OperationException(413, "OAR Upload zu groß");
|
||
await dst.WriteAsync(buffer.AsMemory(0, read), stop);
|
||
}
|
||
}
|
||
if (job.Bytes != contentLength)
|
||
throw new OperationException(400, "Unvollständiger OAR-Upload");
|
||
|
||
EventManager.OarFileLoaded? complete = null;
|
||
complete = (requestId, loadedScenes, message) =>
|
||
{
|
||
if (requestId != Guid.ParseExact(job.Id, "N")) return;
|
||
scene.EventManager.OnOarFileLoaded -= complete;
|
||
Complete(scene.RegionInfo.RegionID, job, message);
|
||
try { File.Delete(job.File); } catch { }
|
||
};
|
||
scene.EventManager.OnOarFileLoaded += complete;
|
||
try
|
||
{
|
||
job.State = "importing";
|
||
archive.DearchiveRegion(job.File, Guid.ParseExact(job.Id, "N"), new Dictionary<string, object>());
|
||
}
|
||
catch
|
||
{
|
||
scene.EventManager.OnOarFileLoaded -= complete;
|
||
throw;
|
||
}
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
Complete(scene.RegionInfo.RegionID, job, e.Message);
|
||
try { File.Delete(job.File); } catch { }
|
||
if (e is OperationException) throw;
|
||
throw new OperationException(500, "OAR-Import fehlgeschlagen: " + e.Message);
|
||
}
|
||
Log.Warn("[OS WEBINTERFACE] OAR import initiated for " + scene.RegionInfo.RegionName);
|
||
return new { id = job.Id, state = job.State };
|
||
}
|
||
|
||
public string? ExportFile(string id)
|
||
{
|
||
if (!Guid.TryParseExact(id, "N", out _) ||
|
||
!_jobs.TryGetValue(id, out Job? j) ||
|
||
j.Kind != "export" || j.State != "completed")
|
||
return null;
|
||
string expected = Path.Combine(_archiveDir, id + ".oar");
|
||
return j.File == expected && File.Exists(expected) ? expected : null;
|
||
}
|
||
|
||
public async Task<object> CheckGitAsync(CancellationToken stop)
|
||
{
|
||
const string endpoint = "https://api.github.com/repos/opengenesislink/opengenesislinkserver/commits?sha=main&per_page=12";
|
||
string? local = null;
|
||
try { local = await GitShaAsync(stop); } catch { }
|
||
try
|
||
{
|
||
using var response = await GitClient.GetAsync(endpoint, stop);
|
||
response.EnsureSuccessStatusCode();
|
||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(stop));
|
||
var entries = document.RootElement.EnumerateArray().Select(c => new
|
||
{
|
||
sha = c.GetProperty("sha").GetString(),
|
||
title = (c.GetProperty("commit").GetProperty("message").GetString() ?? "").Split('\n')[0],
|
||
date = c.GetProperty("commit").GetProperty("committer").GetProperty("date").GetString()
|
||
}).ToArray();
|
||
string? remote = entries.FirstOrDefault()?.sha;
|
||
int? newCommitCount = null;
|
||
if (local is not null && remote is not null && local != remote &&
|
||
local.Length == 40 && local.All(Uri.IsHexDigit))
|
||
{
|
||
try
|
||
{
|
||
string compare = "https://api.github.com/repos/opengenesislink/opengenesislinkserver/compare/" +
|
||
local + "..." + remote;
|
||
using var compared = await GitClient.GetAsync(compare, stop);
|
||
if (compared.IsSuccessStatusCode)
|
||
{
|
||
using var detail = JsonDocument.Parse(await compared.Content.ReadAsStringAsync(stop));
|
||
newCommitCount = detail.RootElement.GetProperty("total_commits").GetInt32();
|
||
entries = detail.RootElement.GetProperty("commits").EnumerateArray().Select(c => new
|
||
{
|
||
sha = c.GetProperty("sha").GetString(),
|
||
title = (c.GetProperty("commit").GetProperty("message").GetString() ?? "").Split('\n')[0],
|
||
date = c.GetProperty("commit").GetProperty("committer").GetProperty("date").GetString()
|
||
}).ToArray();
|
||
}
|
||
}
|
||
catch (Exception e) { Log.Warn("[OS WEBINTERFACE] GitHub compare unavailable", e); }
|
||
}
|
||
return new
|
||
{
|
||
local, remote, upToDate = local is not null && local == remote,
|
||
newCommitCount, commits = entries,
|
||
note = newCommitCount > entries.Length
|
||
? "Es gibt weitere neue Commits; GitHub liefert in dieser Abfrage nur eine Teilmenge."
|
||
: "Git-Commits sind Quellcode-Stände, keine geprüften Binär-Releases. Ein Update muss gebaut und vor Aktivierung getestet werden."
|
||
};
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
return new { local, error = "GitHub nicht erreichbar: " + e.GetType().Name };
|
||
}
|
||
}
|
||
|
||
private static async Task<string?> GitShaAsync(CancellationToken stop)
|
||
{
|
||
string? root = Directory.GetParent(AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar))?.FullName;
|
||
if (root is null || !Directory.Exists(Path.Combine(root, ".git"))) return null;
|
||
var start = new ProcessStartInfo("git")
|
||
{
|
||
WorkingDirectory = root, RedirectStandardOutput = true,
|
||
RedirectStandardError = true, UseShellExecute = false
|
||
};
|
||
start.ArgumentList.Add("rev-parse");
|
||
start.ArgumentList.Add("HEAD");
|
||
using Process? p = Process.Start(start);
|
||
if (p is null) return null;
|
||
string output = (await p.StandardOutput.ReadToEndAsync(stop)).Trim();
|
||
await p.WaitForExitAsync(stop);
|
||
return p.ExitCode == 0 && output.Length == 40 ? output : null;
|
||
}
|
||
|
||
public Task<object> StageUpdateAsync(string sha, CancellationToken stop) => _updateStager.StageAsync(sha, stop);
|
||
|
||
public void Dispose() { }
|
||
}
|