diff --git a/.github/workflows/nexjast-ci.yml b/.github/workflows/nexjast-ci.yml index d73a5ecc..4f795726 100644 --- a/.github/workflows/nexjast-ci.yml +++ b/.github/workflows/nexjast-ci.yml @@ -338,6 +338,10 @@ jobs: shell: bash run: python3 tools/ci/verify_region_mutations.py + - name: Verify graceful avatar relocation before region restart and simulator shutdown + shell: bash + run: python3 tools/ci/verify_avatar_evacuation.py + - name: Verify World API public statistics degraded-mode correctness shell: bash run: python3 tools/ci/verify_statistics_fallback.py diff --git a/NexVerse/RegionModules/NodeAgent/NexVerseManagedRegionHostPlugin.cs b/NexVerse/RegionModules/NodeAgent/NexVerseManagedRegionHostPlugin.cs index 6b634c8d..f00c90c1 100644 --- a/NexVerse/RegionModules/NodeAgent/NexVerseManagedRegionHostPlugin.cs +++ b/NexVerse/RegionModules/NodeAgent/NexVerseManagedRegionHostPlugin.cs @@ -605,13 +605,6 @@ namespace NexVerse.RegionModules.NodeAgent return false; } - if (scene.GetRootAgentCount() > 0) - { - error = - "region_has_agents"; - return false; - } - string configPath = ConfigPath(regionId); @@ -625,6 +618,17 @@ namespace NexVerse.RegionModules.NodeAgent return false; } + // Validate managed ownership before relocating anyone. + // A failed evacuation leaves the region running. + if (NexVerseAvatarEvacuation.HasHumanRootAgents(scene) && + !NexVerseAvatarEvacuation.Evacuate( + scene, new HashSet { regionId }, 25, + "Managed region stop")) + { + error = "region_evacuation_incomplete"; + return false; + } + regionName = scene.RegionInfo.RegionName; @@ -781,13 +785,6 @@ namespace NexVerse.RegionModules.NodeAgent return false; } - if (scene.GetRootAgentCount() > 0) - { - error = - "region_has_agents"; - return false; - } - string configPath = ConfigPath(regionId); @@ -801,6 +798,17 @@ namespace NexVerse.RegionModules.NodeAgent return false; } + // Validate managed ownership before relocating anyone. + // A failed evacuation leaves the region running. + if (NexVerseAvatarEvacuation.HasHumanRootAgents(scene) && + !NexVerseAvatarEvacuation.Evacuate( + scene, new HashSet { regionId }, 25, + "Managed region restart")) + { + error = "region_evacuation_incomplete"; + return false; + } + regionName = scene.RegionInfo.RegionName; diff --git a/OpenSim/Region/Application/OpenSimBase.cs b/OpenSim/Region/Application/OpenSimBase.cs index a8c88a92..7a8a4886 100644 --- a/OpenSim/Region/Application/OpenSimBase.cs +++ b/OpenSim/Region/Application/OpenSimBase.cs @@ -974,6 +974,22 @@ namespace OpenSim /// protected override void ShutdownSpecific() { + // A process shutdown must move clients to a DIFFERENT server. + // All regions hosted by this process are excluded as targets. + try + { + var evacConfig = Config?.Configs["NexVerseAvatarEvacuation"]; + if (evacConfig?.GetBoolean("Enabled", true) != false && + SceneManager != null) + NexVerseAvatarEvacuation.EvacuateInstance( + SceneManager.Scenes.ToArray(), + evacConfig?.GetInt("WaitSeconds", 25) ?? 25); + } + catch (Exception e) + { + m_log.Error("[NEX-EVAC]: Evacuation failed; continuing bounded process shutdown.", e); + } + if (proxyUrl.Length > 0) { Util.XmlRpcCommand(proxyUrl, "Stop"); diff --git a/OpenSim/Region/Framework/OpenSim.Region.Framework.csproj b/OpenSim/Region/Framework/OpenSim.Region.Framework.csproj index 5474079f..3b8b5509 100644 --- a/OpenSim/Region/Framework/OpenSim.Region.Framework.csproj +++ b/OpenSim/Region/Framework/OpenSim.Region.Framework.csproj @@ -214,6 +214,7 @@ Code + Code diff --git a/OpenSim/Region/Framework/Scenes/NexVerseAvatarEvacuation.cs b/OpenSim/Region/Framework/Scenes/NexVerseAvatarEvacuation.cs new file mode 100644 index 00000000..8ec58035 --- /dev/null +++ b/OpenSim/Region/Framework/Scenes/NexVerseAvatarEvacuation.cs @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: MPL-2.0 +// Graceful OpenGenesisLINK Gen1 restart/shutdown relocation. Grid-only, +// fail-closed region restarts; process shutdown is bounded best effort. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Services.Interfaces; +using GridRegion = OpenSim.Services.Interfaces.GridRegion; +using TPFlags = OpenSim.Framework.Constants.TeleportFlags; + +namespace OpenSim.Region.Framework.Scenes +{ + public static class NexVerseAvatarEvacuation + { + private static readonly ILog Log = LogManager.GetLogger(typeof(NexVerseAvatarEvacuation)); + + // Does not include child presences (neighbours), NPCs (no actual viewer + // circuit), agents already transferring, or closed clients. + private static List Residents(Scene scene) + { + return scene.GetScenePresences().Where(sp => + sp != null && !sp.IsChildAgent && !sp.IsNPC && + !sp.IsDeleted).ToList(); + } + + public static bool HasHumanRootAgents(Scene scene) => + scene != null && Residents(scene).Count != 0; + + /// + /// Pick the closest ONLINE same-grid destination. Ignore every region + /// on the shutting-down process and any explicitly excluded region. + /// The grid service returns candidates in distance order and omits + /// Hypergrid hyperlinks. A missing grid service is NOT a valid target. + /// + public static List Destinations(Scene scene, + ISet excluded, int limit = 1024) + { + if (scene == null) return new List(); + List online = scene.GridService.GetOnlineRegions( + scene.RegionInfo.ScopeID, + checked((int)scene.RegionInfo.WorldLocX), + checked((int)scene.RegionInfo.WorldLocY), + Math.Clamp(limit, 1, 1024)); + return (online ?? new List()) + .Where(region => region != null && !region.RegionID.IsZero() && + !excluded.Contains(region.RegionID) && + region.RegionHandle != scene.RegionInfo.RegionHandle && + region.RegionSizeX > 0 && region.RegionSizeY > 0 && + region.RegionName?.Length > 0) + .GroupBy(region => region.RegionID) + .Select(group => group.First()) + .OrderBy(region => + { + double dx = (double)region.RegionLocX - scene.RegionInfo.WorldLocX; + double dy = (double)region.RegionLocY - scene.RegionInfo.WorldLocY; + return dx * dx + dy * dy; + }) + .ThenBy(region => region.RegionID.ToString()) + .ToList(); + } + + /// + /// Returns true only once all real root viewer presences are no longer + /// rooted in the source region. A teleport request is asynchronous and + /// may fail; issuing it is NOT counted as a successful evacuation. + /// + public static bool Evacuate(Scene scene, ISet excluded, int waitSeconds, + string reason = "Region restart", CancellationToken cancellation = default) + { + if (scene == null) return true; + List residents = Residents(scene); + if (residents.Count == 0) return true; + IEntityTransferModule transfer = + scene.RequestModuleInterface(); + if (transfer == null) + { + Log.WarnFormat("[NEX-EVAC]: {0} has no entity transfer service.", scene.Name); + return false; + } + List targets; + try { targets = Destinations(scene, excluded); } + catch (Exception e) + { + Log.Warn("[NEX-EVAC]: Grid online-region lookup failed; refusing to guess a target.", e); + return false; + } + if (targets.Count == 0) + { + Log.WarnFormat("[NEX-EVAC]: No online grid destination for {0}.", scene.Name); + foreach (ScenePresence sp in residents) + try { sp.ControllingClient?.SendAlertMessage( + "Region restart: no other online region is available."); } + catch (Exception) { } + return false; + } + + // Native entity transfer enforces access checks. Teleport() is + // asynchronous: retry the next closest ONLINE destination only + // after a request has had time to finish, and never while a + // transfer is in progress. All residents share one bounded clock. + var attempts = new Dictionary(); + var lastAttempt = new Dictionary(); + int options = Math.Min(targets.Count, 6); + int timeoutMs = Math.Clamp(waitSeconds, 1, 90) * 1000; + long until = Environment.TickCount64 + timeoutMs; + while (Environment.TickCount64 < until && !cancellation.IsCancellationRequested) + { + List remaining = Residents(scene); + if (remaining.Count == 0) + { + Log.InfoFormat("[NEX-EVAC]: Moved {0} avatars away from {1}.", + residents.Count, scene.Name); + return true; + } + foreach (ScenePresence sp in remaining) + { + if (cancellation.IsCancellationRequested) break; + if (sp.IsInTransit) continue; + int next = attempts.TryGetValue(sp.UUID, out int index) ? index : 0; + if (next >= options) continue; + long now = Environment.TickCount64; + if (lastAttempt.TryGetValue(sp.UUID, out long attempted) && + now - attempted < 4000) + continue; + + // Advance before dispatch so a synchronous rejection cannot + // cause the same destination to be tried indefinitely. + attempts[sp.UUID] = next + 1; + lastAttempt[sp.UUID] = now; + GridRegion destination = targets[next]; + try + { + sp.ControllingClient?.SendAlertMessage( + reason + ": moving you to " + destination.RegionName + "."); + Vector3 landing = new Vector3( + Math.Clamp(destination.RegionSizeX / 2f, 1f, + destination.RegionSizeX - 1f), + Math.Clamp(destination.RegionSizeY / 2f, 1f, + destination.RegionSizeY - 1f), + 35f); + transfer.Teleport(sp, destination.RegionHandle, landing, + new Vector3(1f, 0f, 0f), (uint)TPFlags.ViaLocation); + } + catch (Exception e) + { + Log.WarnFormat("[NEX-EVAC]: Teleport request for {0} to {1} failed: {2}", + sp.UUID, destination.RegionID, e.GetType().Name); + } + } + Thread.Sleep(250); + } + int left = Residents(scene).Count; + Log.WarnFormat("[NEX-EVAC]: {0} root avatars still present in {1} after {2}s.", + left, scene.Name, waitSeconds); + return left == 0; + } + + /// + /// Excludes ALL regions hosted by this process: the destination must + /// be on another simulator, even if a local region is technically up + /// until the next Close() call. + /// + public static void EvacuateInstance(IReadOnlyCollection scenes, + int waitSeconds) + { + if (scenes == null || scenes.Count == 0) return; + var excluded = new HashSet( + scenes.Where(s => s != null).Select(s => s.RegionInfo.RegionID)); + Scene[] occupied = scenes.Where(s => s != null && HasHumanRootAgents(s)).ToArray(); + if (occupied.Length == 0) return; + // Every region begins relocation before the shutdown deadline. + // One region with a denied teleport must not consume the entire + // budget and prevent all other regions from moving their users. + int budgetMs = Math.Clamp(waitSeconds, 5, 90) * 1000; + using CancellationTokenSource stop = new CancellationTokenSource(); + Task[] transfers = occupied.Select(scene => Task.Run(() => + Evacuate(scene, excluded, waitSeconds, + "Simulator shutdown", stop.Token))).ToArray(); + try + { + if (!Task.WaitAll(transfers, budgetMs)) + Log.Warn("[NEX-EVAC]: Simulator-wide evacuation deadline reached."); + } + catch (AggregateException e) + { + Log.Warn("[NEX-EVAC]: One or more evacuation tasks failed.", e); + } + finally + { + stop.Cancel(); + try { Task.WaitAll(transfers, 2000); } + catch (AggregateException e) + { Log.Warn("[NEX-EVAC]: Evacuation finished with errors.", e); } + } + int evacuated = transfers.Count(t => + t.Status == TaskStatus.RanToCompletion && t.Result); + Log.InfoFormat("[NEX-EVAC]: Shutdown evacuation result: " + + "{0}/{1} regions clear of viewer avatars.", evacuated, occupied.Length); + } + + } +} diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs index 67df1119..56a84954 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.cs @@ -1460,6 +1460,18 @@ namespace OpenSim.Region.Framework.Scenes } } + // Relocate real viewer avatars BEFORE deregistering this region. + // If no live destination accepts them, keep the region running. + var evacConfig = m_config?.Configs["NexVerseAvatarEvacuation"]; + if (evacConfig?.GetBoolean("Enabled", true) != false && + !NexVerseAvatarEvacuation.Evacuate(this, + new HashSet { RegionInfo.RegionID }, + evacConfig?.GetInt("WaitSeconds", 25) ?? 25)) + { + m_log.WarnFormat("[NEX-EVAC]: Cancelled restart of {0}; avatars remain.", Name); + return; + } + m_log.Info($"[REGION]: Restarting region {Name}"); Close(); diff --git a/bin/OpenSim.ini b/bin/OpenSim.ini index 88491df2..4626f5b6 100644 --- a/bin/OpenSim.ini +++ b/bin/OpenSim.ini @@ -9,6 +9,14 @@ Enabled = true PublicKeyPath = "config-include/ogl-feature-public.pem" +; Graceful resident relocation on region restart and simulator shutdown. +; Region restart selects the closest online region on this grid. +; Full shutdown excludes every region on this simulator process. +; Failed region evacuation cancels restart instead of disconnecting residents. +[NexVerseAvatarEvacuation] + Enabled = true + WaitSeconds = 25 + [NexVerseNodeAgent] Enabled = true ; Jede Simulatorinstanz benoetigt eine eigene NodeId. Fuer Stadt-NexVerse: Mainland_Server_001. diff --git a/doc/NexVerse/AVATAR_EVACUATION_RESTART_SHUTDOWN.md b/doc/NexVerse/AVATAR_EVACUATION_RESTART_SHUTDOWN.md new file mode 100644 index 00000000..32db9c6e --- /dev/null +++ b/doc/NexVerse/AVATAR_EVACUATION_RESTART_SHUTDOWN.md @@ -0,0 +1,85 @@ +# OpenGenesisLINK Gen1 – Graceful Avatar Evacuation on Restart/Shutdown + +## Ziel + +Bei `region restart` und Inworld-Region-Restart werden vor dem eigentlichen +Regionsstopp alle Root-Viewer-Avatare zur **nächstgelegenen online registrierten** +Region desselben Grids teleportiert. Andere Regionen derselben Simulatorinstanz +sind zulässig, wenn **nur diese eine Region** neu startet. + +Bei einem vollständigen `shutdown` / `quit` auf einem Simulator werden +**alle dort gehosteten Regionen** als Teleportziele ausgeschlossen. Nur +online registrierte Regionen auf **einem anderen Simulatorprozess** werden +verwendet. Die Zielwahl erfolgt über die vorhandene GridService-Datenbank, +also **keine neue Datenbank** (die bestehende MariaDB bleibt maßgeblich) +und keine fest einprogrammierte Liste. + +Die vorhandene native `IEntityTransferModule.Teleport`-Schnittstelle prüft +weiterhin Einlassrechte, Land-/Estate-Regeln und die regulären +OpenSimulator-Teleportbedingungen. Ein Ziel ohne Zutrittsrechte kann nicht +durch einen administrativen Region-Restart zum erzwungenen Zutritt werden. + +## Aktivierung + +Bereits in der versionierten `bin/OpenSim.ini` aktiviert: + +```ini +[NexVerseAvatarEvacuation] + Enabled = true + WaitSeconds = 25 +``` + +Es sind keine weiteren per-Region-Einstellungen nötig. + +## Abgedeckte Pfade + +- `Scene.RestartNow()`: Root-Viewer vor `Close()` versetzen. Ohne + verfügbares Ziel oder bei verbliebenen Avataren **Regionsneustart abbrechen**, + nicht einfach alle Bürger herauswerfen. +- World-API/NodeAgent-gesteuerter **Managed Region Restart und Stop**: + nach bestätigter Verwaltungsberechtigung dasselbe Verfahren; bei + unvollständigem Transfer wird `region_evacuation_incomplete` gemeldet + und die Region bleibt in Betrieb. +- Vollständiges `shutdown` einer OpenSim-Instanz: + alle lokalen Regions-UUIDs als Ziele ausschließen, den Transfer vor + `SceneManager.Close()` beginnen, Erfolg bis zum Timeout prüfen. + Ein unvermeidbarer Prozess-Shutdown ist **best effort**; verbleibende + Avatare werden protokolliert und durch die normale Abschaltung getrennt. + +## Grenzen + +Nur echte Viewer-Root-Presences lassen sich mit `IEntityTransferModule` +teleportieren. Child Agents sind keine eigenständigen Benutzer. +Server-NPCs besitzen keinen normalen Viewer-Circuit und werden **nicht** mit +dieser Viewer-Transfer-API verschoben; sie werden beim Schließen der +Ursprungsregion beendet und brauchen gegebenenfalls eine spätere eigene +persistente Spawn-/Rekonstruktionsfunktion. + +Die online-Registrierung in der Grid-Datenbank ist eine notwendige, aber +keine vollständige Garantie für Erreichbarkeit oder Zutrittsrechte. Ein +abgeschalteter Zielserver, Zeitüberschreitung, fehlende Berechtigung oder +erzwungener Prozessabbruch (SIGKILL/OOM) kann eine Evakuierung verhindern. +Ein erfolgreicher Teleportaufruf allein gilt **nicht** als Erfolg: +OpenGenesisLINK prüft, ob der Root-Agent die Quellregion verlassen hat. + +Ein gewaltsames `kill -9` oder ein VM-/Host-Ausfall kann **nicht** +abgefangen werden. Bei vollständigem Instanzshutdown wird nach dem +begrenzten Evakuierungsversuch normal heruntergefahren, selbst wenn kein +geeignetes Ziel erreichbar ist. Dieser Unterschied zum abbrechbaren +Regionsneustart ist beabsichtigt. + +## Abnahme + +1. Zwei laufende Regionen auf demselben Simulator, eine weitere auf + separatem Simulatorhost innerhalb desselben Grids. +2. Mit einem Testavatar in Region A `region restart` auslösen: + Wechsel zur nächsten Online-Region vor dem Schließen von A prüfen. +3. Mit Testavatare in A und B `shutdown` auslösen: + beide dürfen nur zur Region auf dem anderen Simulator wechseln. +4. Für Testaccount mit fehlendem Zutrittsrecht verifizieren, dass keine + Rechte umgangen werden. Ohne erreichbares Ziel bleibt bei + `region restart` A geöffnet. +5. Teleport- und Abschaltlogs prüfen, ohne Tokens oder Bestandsdaten in + Debuglogs auszugeben. + +Quellcode-/CI-Validierung ersetzt keinen Firestorm-/OpenSim-Live-Test. diff --git a/tools/ci/verify_avatar_evacuation.py b/tools/ci/verify_avatar_evacuation.py new file mode 100644 index 00000000..ba0200db --- /dev/null +++ b/tools/ci/verify_avatar_evacuation.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Regression guard: graceful region restart and all-server shutdown routing.""" +from pathlib import Path +r = Path(__file__).resolve().parents[2] +def load(name): + return (r / name).read_text(encoding="utf-8-sig") +evac=load("OpenSim/Region/Framework/Scenes/NexVerseAvatarEvacuation.cs") +scene=load("OpenSim/Region/Framework/Scenes/Scene.cs") +server=load("OpenSim/Region/Application/OpenSimBase.cs") +managed=load("NexVerse/RegionModules/NodeAgent/NexVerseManagedRegionHostPlugin.cs") +project=load("OpenSim/Region/Framework/OpenSim.Region.Framework.csproj") +config=load("bin/OpenSim.ini") +checks={ + "in-process scene lifecycle": + ('NexVerseAvatarEvacuation.Evacuate(this' in scene and + scene.index('NexVerseAvatarEvacuation.Evacuate(this') < + scene.index('Close();',scene.index('public void RestartNow()')) and + 'Cancelled restart of' in scene), + "process-wide before shutdown": + ('NexVerseAvatarEvacuation.EvacuateInstance(' in server and + server.index('NexVerseAvatarEvacuation.EvacuateInstance(') < + server.index('SceneManager.Close();',server.index('protected override void ShutdownSpecific()'))), + "every local region excluded": + ('scenes.Where(s => s != null).Select(s => s.RegionInfo.RegionID)' in evac and + 'excluded.Contains(region.RegionID)' in evac), + "genuine online regions only": + ('scene.GridService.GetOnlineRegions(' in evac and + 'scopeID' not in evac and + 'region.RegionHandle != scene.RegionInfo.RegionHandle' in evac), + "closest deterministic destination": + ('.OrderBy(region =>' in evac and '.ThenBy(region => region.RegionID.ToString())' in evac), + "real viewer-only root relocation": + ('!sp.IsChildAgent && !sp.IsNPC' in evac and + 'transfer.Teleport(sp, destination.RegionHandle' in evac), + "native access policies preserved": + ('IEntityTransferModule' in evac and 'TPFlags.ViaLocation' in evac and + 'DoTeleport(' not in evac), + "wait for actual avatar exit": + ('List remaining = Residents(scene)' in evac and + 'if (remaining.Count == 0)' in evac and + 'Thread.Sleep(250)' in evac and 'Environment.TickCount64' in evac), + "managed stop and restart": + (managed.count('NexVerseAvatarEvacuation.Evacuate(')==2 and + managed.count('region_evacuation_incomplete')==2 and + managed.count('region_not_nexverse_managed')>=2), + "no silent success when missing target": + ('if (targets.Count == 0)' in evac and + 'return false;' in evac and 'return left == 0;' in evac), + "compiled and enabled": + ('Scenes\\NexVerseAvatarEvacuation.cs' in project and + '[NexVerseAvatarEvacuation]' in config and 'Enabled = true' in config and + 'WaitSeconds = 25' in config), +} +for title,ok in checks.items(): + if not ok: + raise AssertionError("AVATAR_EVACUATION_REGRESSION: "+title) + print("PASS:", title) +print("NEXVERSE_AVATAR_EVACUATION_CONTRACT_PASS",len(checks))