feat: evacuate avatars before region restart and full simulator shutdown (#362)

* feat: move root viewer avatars to nearest online grid region before restart or shutdown

* feat: evacuate avatars before normal region restart, abort if transfers remain

* feat: evacuate full simulator to other online host before closing scenes

* build: include simulator avatar evacuation service

* feat: safely evacuate residents before managed region stop or restart

* config: enable graceful region and instance avatar evacuation by default

* test: guard nearest online region evacuation before restart and full-instance shutdown

* ci: run avatar evacuation safety contracts with region-control validation

* docs: define graceful region and instance avatar relocation and operational limitations

* fix: retry next nearest online region on rejected or timed-out teleport without racing transfers

* fix: enforce one process-wide shutdown evacuation timeout across all hosted regions

* test: recognize verified root-presence polling in multi-target evacuation loop

* feat: launch instance-wide avatar evacuations concurrently within one bounded shutdown deadline
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-11-02 01:16:23 +01:00
1 parent 3e0e13b47a
commit bac8e86d0d
9 files changed
+414 -14

No files matched your search

+4
View File
@@ -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
@@ -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<UUID> { 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<UUID> { regionId }, 25,
"Managed region restart"))
{
error = "region_evacuation_incomplete";
return false;
}
regionName =
scene.RegionInfo.RegionName;
+16
View File
@@ -974,6 +974,22 @@ namespace OpenSim
/// </summary>
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");
@@ -214,6 +214,7 @@
<Compile Include="Scenes\GodController.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Scenes\NexVerseAvatarEvacuation.cs" />
<Compile Include="Scenes\Scene.cs">
<Compile Include="Scenes\OglFastMapStartupQueue.cs" />
<SubType>Code</SubType>
@@ -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<ScenePresence> 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;
/// <summary>
/// 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.
/// </summary>
public static List<GridRegion> Destinations(Scene scene,
ISet<UUID> excluded, int limit = 1024)
{
if (scene == null) return new List<GridRegion>();
List<GridRegion> 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<GridRegion>())
.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();
}
/// <summary>
/// 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.
/// </summary>
public static bool Evacuate(Scene scene, ISet<UUID> excluded, int waitSeconds,
string reason = "Region restart", CancellationToken cancellation = default)
{
if (scene == null) return true;
List<ScenePresence> residents = Residents(scene);
if (residents.Count == 0) return true;
IEntityTransferModule transfer =
scene.RequestModuleInterface<IEntityTransferModule>();
if (transfer == null)
{
Log.WarnFormat("[NEX-EVAC]: {0} has no entity transfer service.", scene.Name);
return false;
}
List<GridRegion> 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<UUID, int>();
var lastAttempt = new Dictionary<UUID, long>();
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<ScenePresence> 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;
}
/// <summary>
/// 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.
/// </summary>
public static void EvacuateInstance(IReadOnlyCollection<Scene> scenes,
int waitSeconds)
{
if (scenes == null || scenes.Count == 0) return;
var excluded = new HashSet<UUID>(
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<bool>[] 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);
}
}
}
+12
View File
@@ -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<UUID> { 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();
+8
View File
@@ -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.
@@ -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.
+58
View File
@@ -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<ScenePresence> 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))