OpenGenesisLINK main - .NET 10 Build Gate / .NET 10 Windows x64 build (push) Waiting to run
Generation 1.1 .NET 10 ARM64 Server Runtime / ROBUST and Simulator .NET 10 ARM64 build + boot (push) Canceled after 0s
NexVerse CI / NV dollar live database matrix (push) Failing after 15s
OpenGenesisLINK main - .NET 10 Build Gate / .NET 10 generated-project and server build (push) Successful in 1m33s
OpenGenesisLINK Generation 1 - Abgeschlossene Branches bereinigen / Abgeschlossene und nicht mehr benoetigte Branches entfernen (push) Successful in 30s
Generation 1 Stable and Updates source policy / release-policy (push) Successful in 17s
NexVerse CI / Build NexVerse (push) Failing after 57s
629 lines
27 KiB
C#
629 lines
27 KiB
C#
// SPDX-License-Identifier: MPL-2.0
|
||
using System.Collections.Concurrent;
|
||
using System.Diagnostics;
|
||
using System.IO.Compression;
|
||
using OpenSim.Services.Interfaces;
|
||
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 = "";
|
||
public string RemoteName = "";
|
||
public string BackupKind = "";
|
||
public DateTimeOffset? Finished;
|
||
public bool FileObserved;
|
||
public List<(DateTimeOffset Time, string Text)> Events = new();
|
||
}
|
||
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 WebDavBackupStore _backups = new();
|
||
private readonly ConcurrentDictionary<UUID, FileStream> _iarBusy = new();
|
||
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<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);
|
||
if (OperatingSystem.IsLinux()) File.SetUnixFileMode(_archiveDir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||
}
|
||
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;
|
||
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.BackupKind.Length != 0)
|
||
{
|
||
try
|
||
{
|
||
if (!File.Exists(job.File))
|
||
error = "Archivdatei wurde nicht erstellt.";
|
||
else
|
||
{
|
||
job.Bytes = new FileInfo(job.File).Length;
|
||
if (job.Bytes == 0) error = "Archivdatei ist leer.";
|
||
}
|
||
}
|
||
catch (IOException) { error = "Archivdatei konnte nicht geprüft werden."; }
|
||
}
|
||
job.Message = error ?? "";
|
||
job.State = string.IsNullOrWhiteSpace(error) ? "completed" : "failed";
|
||
job.Finished = DateTimeOffset.UtcNow;
|
||
job.Events.Add((job.Finished.Value, job.State == "completed"
|
||
? (job.BackupKind.Length != 0 ? "WebDAV-Sicherung vollständig übertragen und geprüft" : "Import abgeschlossen")
|
||
: "Archivauftrag fehlgeschlagen: " + job.Message));
|
||
}
|
||
_busy.TryRemove(new KeyValuePair<UUID, string>(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.BackupKind.Length != 0 && 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",
|
||
"webdav" => "Archiv wird zum NAS übertragen und geprüft",
|
||
"importing" => "OAR-Datei wird importiert",
|
||
"completed" => job.BackupKind.Length != 0 ? "WebDAV-Backup erfolgreich" : "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.BackupKind.Length != 0 && job.State=="completed",
|
||
downloadUrl=job.BackupKind.Length != 0 && job.State=="completed"
|
||
? "/api/backups/download?kind="+job.BackupKind+"&name="+Uri.EscapeDataString(job.RemoteName) : null,
|
||
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<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 = "UDP: kein externer Protokoll-Handshake geprüft",
|
||
hint = "Ein TCP-Verbindungstest bestätigt keine UDP-Erreichbarkeit."
|
||
});
|
||
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 = "Externe TCP-Prüfung wird geladen",
|
||
hint = "Messung erfolgt von einem unabhängigen Standort."
|
||
});
|
||
}
|
||
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(Snapshot).ToArray();
|
||
|
||
public object Export(string regionId)
|
||
{
|
||
_backups.EnsureConfigured();
|
||
var (scene, archive) = GetArchiver(regionId);
|
||
Job job = Begin(regionId, "export");
|
||
job.File = Path.Combine(_archiveDir, job.Id + ".oar");
|
||
job.BackupKind = "oar";
|
||
job.RemoteName = WebDavBackupStore.RegionName(job.Region,
|
||
scene.RegionInfo.RegionID.Guid, Guid.ParseExact(job.Id, "N"), job.Created);
|
||
int terminal = 0;
|
||
Guid requestId = Guid.ParseExact(job.Id, "N");
|
||
EventManager.OarFileSaved? complete = null;
|
||
complete = (id, message) =>
|
||
{
|
||
if (id != requestId || Interlocked.Exchange(ref terminal, 1) != 0) return;
|
||
scene.EventManager.OnOarFileSaved -= complete;
|
||
_ = Task.Run(() => FinishBackupAsync(scene.RegionInfo.RegionID, job, message));
|
||
};
|
||
scene.EventManager.OnOarFileSaved += complete;
|
||
// Return the identifier immediately: writing the archive can take
|
||
// minutes, and the UI must be able to poll while it is running.
|
||
_ = Task.Run(() =>
|
||
{
|
||
try
|
||
{
|
||
lock (job) job.State = "saving";
|
||
Record(job, "Archivierung für " + job.Region + " gestartet");
|
||
archive.ArchiveRegion(job.File, requestId, new Dictionary<string, object>());
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
scene.EventManager.OnOarFileSaved -= complete;
|
||
if (Interlocked.Exchange(ref terminal, 1) == 0)
|
||
{
|
||
Log.Error("[OS WEBINTERFACE] OAR export failed for " + job.Region, e);
|
||
Complete(scene.RegionInfo.RegionID, job, "OAR-Archivierung fehlgeschlagen.");
|
||
}
|
||
}
|
||
});
|
||
return new { id = job.Id, state = "queued" };
|
||
}
|
||
|
||
private async Task FinishBackupAsync(UUID regionId, Job job, string? error, UUID? avatar = null)
|
||
{
|
||
try
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(error))
|
||
{
|
||
Complete(regionId, job, "Archivierung fehlgeschlagen. Lokale Zwischendatei bleibt zur Prüfung erhalten.");
|
||
return;
|
||
}
|
||
if (!File.Exists(job.File) || new FileInfo(job.File).Length <= 0)
|
||
throw new WebDavBackupStore.BackupException(500, "Archiv fehlt oder ist leer.");
|
||
lock (job)
|
||
{
|
||
job.Bytes = new FileInfo(job.File).Length;
|
||
job.State = "webdav";
|
||
}
|
||
Record(job, "Archiv abgeschlossen; WebDAV-Übertragung gestartet");
|
||
if (OperatingSystem.IsLinux())
|
||
File.SetUnixFileMode(job.File, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||
using (var file = File.OpenRead(job.File))
|
||
{
|
||
if (file.ReadByte() != 0x1f || file.ReadByte() != 0x8b)
|
||
throw new WebDavBackupStore.BackupException(500, "Archiv ist kein GZip-Archiv.");
|
||
file.Position = 0;
|
||
using var gzip = new GZipStream(file, CompressionMode.Decompress);
|
||
await gzip.CopyToAsync(Stream.Null);
|
||
}
|
||
await _backups.SaveAsync(job.BackupKind, job.RemoteName, job.File);
|
||
Complete(regionId, job, null);
|
||
// A successful archive stays on the NAS only. On any failure keep
|
||
// the private local spool for operator recovery.
|
||
try { File.Delete(job.File); }
|
||
catch (IOException) { Log.Warn("[OS WEBINTERFACE] Backup spool cleanup failed"); }
|
||
catch (UnauthorizedAccessException) { Log.Warn("[OS WEBINTERFACE] Backup spool cleanup denied"); }
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string reason = e is WebDavBackupStore.BackupException be ? be.Message :
|
||
"WebDAV-Sicherung fehlgeschlagen oder Zeitlimit überschritten.";
|
||
Complete(regionId, job, reason + " Lokale Zwischendatei bleibt zur Wiederherstellung erhalten.");
|
||
Log.Warn("[OS WEBINTERFACE] WebDAV backup job failed: " + job.Id + " (" + e.GetType().Name + ")");
|
||
}
|
||
finally
|
||
{
|
||
if (avatar is UUID user) ReleaseInventoryLock(user);
|
||
}
|
||
}
|
||
|
||
// Both local simulator processes use the same persistent lock directory.
|
||
// Keep the lock file in place: deleting it could create a second inode and
|
||
// allow two concurrent writers. OS locks are released on process exit.
|
||
private void AcquireInventoryLock(UUID avatar)
|
||
{
|
||
FileStream? lease = null;
|
||
try
|
||
{
|
||
string root = Path.Combine(Path.GetDirectoryName(WebDavBackupStore.CredentialPath)!, "iar-locks");
|
||
Directory.CreateDirectory(root);
|
||
if (OperatingSystem.IsLinux())
|
||
File.SetUnixFileMode(root, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||
lease = new FileStream(Path.Combine(root, avatar.Guid.ToString("N") + ".lock"),
|
||
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
|
||
if (!_iarBusy.TryAdd(avatar, lease))
|
||
throw new IOException("IAR job already running");
|
||
lease = null;
|
||
}
|
||
catch (IOException)
|
||
{
|
||
throw new OperationException(409, "IAR-Sicherung für diesen Avatar läuft bereits oder Sperre ist nicht verfügbar.");
|
||
}
|
||
finally { lease?.Dispose(); }
|
||
}
|
||
|
||
private void ReleaseInventoryLock(UUID avatar)
|
||
{
|
||
if (_iarBusy.TryRemove(avatar, out var lease)) lease.Dispose();
|
||
}
|
||
|
||
public object ExportInventory(string regionId, string avatar)
|
||
{
|
||
_backups.EnsureConfigured();
|
||
Scene scene = Region(regionId);
|
||
var archiver = scene.RequestModuleInterface<IInventoryArchiverModule>();
|
||
if (archiver == null) throw new OperationException(503, "IAR-Modul nicht verfügbar.");
|
||
avatar = avatar?.Trim() ?? "";
|
||
if (avatar.Length == 0 || avatar.Length > 120)
|
||
throw new OperationException(400, "Avatarname oder UUID fehlt.");
|
||
UserAccount? user;
|
||
if (UUID.TryParse(avatar, out UUID avatarId))
|
||
user = scene.UserAccountService.GetUserAccount(UUID.Zero, avatarId);
|
||
else
|
||
{
|
||
string[] name = avatar.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||
if (name.Length != 2) throw new OperationException(400, "Vor- und Nachname oder UUID angeben.");
|
||
user = scene.UserAccountService.GetUserAccount(UUID.Zero, name[0], name[1]);
|
||
}
|
||
// Only local account records; no Hypergrid foreign-avatar export.
|
||
if (user == null || !user.LocalToGrid || user.PrincipalID == UUID.Zero)
|
||
throw new OperationException(404, "Lokaler Avatar nicht gefunden.");
|
||
AcquireInventoryLock(user.PrincipalID);
|
||
Job job;
|
||
try { job = Begin(regionId, "iar-export"); }
|
||
catch { ReleaseInventoryLock(user.PrincipalID); throw; }
|
||
job.Region = user.Name;
|
||
job.BackupKind = "iar";
|
||
job.RemoteName = WebDavBackupStore.AvatarName(user.PrincipalID.Guid);
|
||
job.File = Path.Combine(_archiveDir, job.Id + ".iar");
|
||
UUID requestId = new UUID(Guid.ParseExact(job.Id, "N"));
|
||
int terminal = 0;
|
||
InventoryArchiveSaved? saved = null;
|
||
saved = (id, success, account, path, stream, exception, count, filtered) =>
|
||
{
|
||
if (id != requestId || Interlocked.Exchange(ref terminal, 1) != 0) return;
|
||
archiver.OnInventoryArchiveSaved -= saved;
|
||
string? error = success && account?.PrincipalID == user.PrincipalID ? null : "IAR-Archivierung fehlgeschlagen.";
|
||
_ = Task.Run(async () =>
|
||
{
|
||
if (error == null)
|
||
{
|
||
// Reuse the simulator's bounded archive preflight where available.
|
||
try
|
||
{
|
||
var inspector = scene.RequestModuleInterface<IInventoryArchiveInspector>();
|
||
if (inspector != null && !inspector.TryInspect(job.File, out _, out _))
|
||
error = "IAR-Integritätsprüfung fehlgeschlagen.";
|
||
}
|
||
catch { error = "IAR-Integritätsprüfung fehlgeschlagen."; }
|
||
}
|
||
await FinishBackupAsync(scene.RegionInfo.RegionID, job, error, user.PrincipalID);
|
||
});
|
||
};
|
||
archiver.OnInventoryArchiveSaved += saved;
|
||
_ = Task.Run(async () =>
|
||
{
|
||
GZipStream? output = null;
|
||
try
|
||
{
|
||
lock (job) job.State = "saving";
|
||
Record(job, "Vollständiges Inventar einschließlich Assets wird gesichert");
|
||
output = new GZipStream(new FileStream(job.File, FileMode.CreateNew,
|
||
FileAccess.Write, FileShare.None), CompressionLevel.Optimal);
|
||
// Existing server-authorized overload, already protected by the
|
||
// UserLevel >= 200 session and CSRF checks in AdminHttpServer.
|
||
if (!archiver.ArchiveInventory(requestId, user, "/", output, new Dictionary<string, object>()))
|
||
throw new InvalidOperationException("IAR rejected");
|
||
// The archiver owns and closes the stream on completion.
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
archiver.OnInventoryArchiveSaved -= saved;
|
||
if (Interlocked.Exchange(ref terminal, 1) == 0)
|
||
{
|
||
try { output?.Dispose(); } catch { }
|
||
Log.Warn("[OS WEBINTERFACE] IAR export failed: " + e.GetType().Name);
|
||
await FinishBackupAsync(scene.RegionInfo.RegionID, job, "IAR-Archivierung fehlgeschlagen.", user.PrincipalID);
|
||
}
|
||
}
|
||
});
|
||
return new { id = job.Id, state = "queued", avatar = user.Name };
|
||
}
|
||
|
||
public async Task<object> ListBackupsAsync(CancellationToken stop)
|
||
{
|
||
var entries = await _backups.ListAsync(stop);
|
||
var labels = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||
var accountService = _scenes.Values.FirstOrDefault(x => x.UserAccountService != null)?.UserAccountService;
|
||
if (accountService != null)
|
||
{
|
||
var ids = entries.Where(x => x.Kind == "iar")
|
||
.Select(x => Guid.ParseExact(x.Name[7..^4], "N").ToString()).Distinct().ToArray();
|
||
foreach (var batch in ids.Chunk(50))
|
||
{
|
||
try
|
||
{
|
||
foreach (var account in accountService.GetUserAccounts(UUID.Zero, batch.ToList()))
|
||
if (account.LocalToGrid)
|
||
labels[WebDavBackupStore.AvatarName(account.PrincipalID.Guid)] = account.Name;
|
||
}
|
||
catch { break; } // UUID filenames remain usable without name lookup.
|
||
}
|
||
}
|
||
return new { entries = entries.Select(x => new
|
||
{
|
||
x.Kind, x.Name, x.Bytes, x.Modified,
|
||
label = labels.TryGetValue(x.Name, out var label) ? label : x.Name
|
||
}).ToArray() };
|
||
}
|
||
|
||
public Task DownloadBackupAsync(string kind, string name, HttpListenerRequest request,
|
||
HttpListenerResponse response, CancellationToken stop) =>
|
||
_backups.DownloadAsync(kind, name, request, response, stop);
|
||
|
||
public string? RemoteOarName(string id) =>
|
||
Guid.TryParseExact(id, "N", out _) && _jobs.TryGetValue(id, out var job) &&
|
||
job.Kind == "export" && job.State == "completed" ? job.RemoteName : null;
|
||
|
||
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");
|
||
lock (j)
|
||
return j.File == expected && File.Exists(expected) ? expected : null;
|
||
}
|
||
|
||
public Task<object> CheckUpdatesAsync(CancellationToken stop) =>
|
||
_updateStager.CheckAsync(stop);
|
||
|
||
public Task<object> StageUpdateAsync(string sha, CancellationToken stop) => _updateStager.StageAsync(sha, stop);
|
||
|
||
public void Dispose() => _backups.Dispose();
|
||
}
|