// 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;
/// Privileged operations, scoped to scenes hosted by this ONE simulator.
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 = "";
public DateTimeOffset? Finished;
public bool FileObserved;
public List<(DateTimeOffset Time, string Text)> Events = new();
}
private readonly ConcurrentDictionary _scenes;
private readonly ConcurrentDictionary _jobs = new();
private readonly ConcurrentDictionary _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));
public AdminOperations(ConcurrentDictionary 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 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();
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;
Record(job, "Archivauftrag angelegt");
return job;
}
private static void Record(Job job, string message)
{
lock (job)
{
job.Events.Add((DateTimeOffset.UtcNow, message));
if (job.Events.Count > 12) job.Events.RemoveAt(0);
}
}
private void Complete(UUID regionId, Job job, string? error)
{
lock (job)
{
if (job.State is "completed" or "failed") return;
if (string.IsNullOrWhiteSpace(error) && job.Kind == "export")
{
try
{
if (!File.Exists(job.File))
error = "OAR-Datei wurde nicht erstellt.";
else
{
job.Bytes = new FileInfo(job.File).Length;
if (job.Bytes == 0) error = "OAR-Datei ist leer.";
}
}
catch (IOException e) { error = "OAR-Datei konnte nicht geprüft werden: " + e.Message; }
}
job.Message = error ?? "";
job.State = string.IsNullOrWhiteSpace(error) ? "completed" : "failed";
job.Finished = DateTimeOffset.UtcNow;
job.Events.Add((job.Finished.Value, job.State == "completed"
? (job.Kind == "export" ? "OAR-Datei vollständig erstellt" : "Import abgeschlossen")
: "Archivauftrag fehlgeschlagen: " + job.Message));
}
_busy.TryRemove(new KeyValuePair(regionId, job.Id));
}
// Status is derived from the actual archive file and the archiver
// completion event. A percent value cannot be determined by this API.
private object Snapshot(Job job)
{
lock (job)
{
if (job.Kind == "export" && job.State == "saving")
{
try
{
if (File.Exists(job.File))
{
long bytes = new FileInfo(job.File).Length;
if (bytes > job.Bytes) job.Bytes = bytes;
if (bytes > 0 && !job.FileObserved)
{
job.FileObserved = true;
job.Events.Add((DateTimeOffset.UtcNow,
"OAR-Datei wird geschrieben"));
}
}
}
catch (IOException) { /* Transient write; next poll retries. */ }
}
string stage = job.State switch
{
"queued" => "Auftrag angenommen",
"saving" => job.Bytes > 0 ? "Archivdaten werden geschrieben"
: "Region wird für das OAR gesichert",
"uploading" => "OAR-Datei wird hochgeladen",
"importing" => "OAR-Datei wird importiert",
"completed" => "OAR-Auftrag abgeschlossen",
"failed" => "OAR-Auftrag fehlgeschlagen",
_ => "Archivauftrag wird bearbeitet"
};
var now = DateTimeOffset.UtcNow;
return new
{
id=job.Id,region=job.Region,kind=job.Kind,state=job.State,
stage,message=job.Message,created=job.Created,
finishedAtUtc=job.Finished,
elapsedSeconds=Math.Max(0,(long)((job.Finished??now)-job.Created).TotalSeconds),
bytes=job.Bytes,bytesWritten=job.Bytes,total=job.Total,
percent=job.Kind=="import" && job.Total>0
? (int?)Math.Min(100,100*job.Bytes/job.Total) : null,
download=job.Kind=="export" && job.State=="completed",
events=job.Events.Select(e=>new{timeUtc=e.Time,message=e.Text}).ToArray()
};
}
}
public object? OarStatus(string id)
{
if (!Guid.TryParseExact(id, "N", out _) ||
!_jobs.TryGetValue(id, out Job? job) || job.Kind != "export")
return null;
return Snapshot(job);
}
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