Files
opengenesislinkserver/NexVerse/RegionModules/NodeAgent/NexVerseNodeAgentModule.cs
T
OpenGenesis (MPL 2.0) 73cf90eb30 feat(perf): OGLPerformance 1.2 advanced ROBUST node diagnostics (#424)
* feat(perf): bounded Linux host per-core CPU measurement in opt-in sampler

* feat(perf): shared read-only asset cache metrics interface

* feat(perf): read-only Flotsam cache hit, LRU, writer and byte-budget snapshot

* feat(perf): attach read-only asset cache diagnostics to signed heartbeat

* feat(perf): bounded per-region and Linux host-core telemetry projection

* feat(perf): read-only API projection of regional frame and host core diagnostics

* feat(perf): ROBUST diagnostic panel, curves, core meters, region and asset cache views

* feat(perf): browser-session trend charts, Linux core meters, per-region frame table and Flotsam analytics

* fix(perf): keep missing heap and allocation telemetry as gaps, not zero

* test(perf): Linux host CPU parser and bounded per-core sampling

* test(perf): node registry parses bounded signed host, region and asset samples

* feat(perf): bound telemetry to 64 regions so 42-region nodes are fully represented

* feat(perf): bound telemetry to 64 regions so 42-region nodes are fully represented

* feat(perf): bound telemetry to 64 regions so 42-region nodes are fully represented

* test(perf): read-only Flotsam cache diagnostic interface

* docs(perf): operator guide for bounded CPU/core, region, GC and asset diagnostics

* test(perf): retain all 42 regions with expanded bounded heartbeat cap

* feat(perf): reboot-aware browser trends and Flotsam cache hit ratios

* fix(perf): account for host cores omitted and document 64-region telemetry cap

* fix(perf): account for host cores omitted and document 64-region telemetry cap
2026-11-10 21:30:13 +01:00

3095 lines
129 KiB
C#

// SPDX-License-Identifier: MPL-2.0
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using Mono.Addins;
using NexVerse.Core.Archives;
using NexVerse.Core.Messaging;
using NexVerse.Core.Observability;
using NexVerse.RegionModules.Archives;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace NexVerse.RegionModules.NodeAgent
{
[Extension(
Path = "/OpenSim/RegionModules",
NodeName = "RegionModule",
Id = "NexVerseNodeAgentModule")]
public sealed class NexVerseNodeAgentModule :
ISharedRegionModule,
INexVerseEventBusModule,
ICrossRegionObjectMessageRouter,
IEstateScriptMessageRouter,
IGridScriptMessageRouter
{
private const int DebugChannel = 0x7fffffff;
private const int ObjectMessageRateEntryLimit = 8192;
private static readonly ILog m_Log =
LogManager.GetLogger(typeof(NexVerseNodeAgentModule));
private readonly ConcurrentDictionary<UUID, Scene> m_Scenes =
new ConcurrentDictionary<UUID, Scene>();
private readonly ConcurrentDictionary<UUID, ObjectMessageRateState> m_ObjectMessageOutboundRates =
new ConcurrentDictionary<UUID, ObjectMessageRateState>();
private readonly ConcurrentDictionary<UUID, ObjectMessageRateState> m_ObjectMessageInboundRates =
new ConcurrentDictionary<UUID, ObjectMessageRateState>();
private bool m_Enabled;
// Inbound HTTP may finish after Close starts and the bus is disposed.
// Reject new events during shutdown instead of logging a spurious 500.
private int m_Stopping;
private string m_NodeId = string.Empty;
private string m_SharedKey = string.Empty;
private string m_InboundPath = "/internal/nexbus/v1/events";
private int m_HeartbeatSeconds = 30;
// Opt-in read-only G1 resource sampler; no direct mutation of region threads.
private OglPerformanceSampler m_PerformanceSampler;
private bool m_ObjectMessagingEnabled;
private bool m_EstateScriptMessagingEnabled = true;
// An opt-in, manager/owner-only cross-estate channel; never public by default.
private bool m_GridScriptMessagingEnabled;
private bool m_CrossRegionChatMessaging;
private int m_ChatWhisperDistance = 10;
private int m_ChatSayDistance = 20;
private int m_ChatShoutDistance = 100;
private readonly ConcurrentDictionary<UUID, ObjectMessageRateState> m_ChatOutboundRates = new();
private readonly ConcurrentDictionary<UUID, ObjectMessageRateState> m_ChatInboundRates = new();
private bool m_AllowCrossOwnerObjectMessages;
private int m_ObjectMessagesPerSecond = 20;
private int m_ObjectMessageMaxAgeSeconds = 30;
private string m_MigrationStorageId = string.Empty;
private SimulatorNexEventTransport m_Transport;
private DistributedNexEventBus m_Bus;
private Timer m_HeartbeatTimer;
// Secure, cursor-based export to the existing HMAC-authenticated
// NexBus peer. Never transport plain files via a public HTTP upload.
private Timer m_LogForwardTimer;
private HttpClient m_LogForwardClient;
private Uri m_LogForwardPeer;
private bool m_LogForwardEnabled;
private int m_LogForwardRunning;
private readonly Dictionary<string, long> m_LogForwardOffsets = new();
private readonly object m_LogForwardSync = new();
private IDisposable m_CreateRegionSubscription;
private IDisposable m_MoveRegionSubscription;
private IDisposable m_RegionLifecycleSubscription;
private IDisposable m_NodeControlSubscription;
private IDisposable m_NodeUpdateSubscription;
private IDisposable m_NodeLiveUpdateSubscription;
private bool m_LiveUpdaterEnabled;
private string m_LiveUpdaterUrl = string.Empty;
private string m_LiveUpdaterToken = string.Empty;
private bool m_UpdateStagingEnabled;
private bool m_UpdateStagingBuild = true;
private string m_UpdateStagingRoot = string.Empty;
private int m_NodeUpdateRunning;
private string m_UpdateControlKey = string.Empty;
private readonly ConcurrentDictionary<string, long> m_NodeUpdateReplay = new();
private IDisposable m_OarControlSubscription;
private IDisposable m_IarControlSubscription;
// IAR export/import is synchronous in the native OpenSim archiver.
// Never perform it on the authenticated NexBus HTTP request thread.
// One active archive per simulator node avoids competing large I/O jobs;
// reserve at most eight queued/running requests to bound memory.
private const int MaxPendingIarCommands = 8;
private readonly SemaphoreSlim m_IarCommandSlot = new(1, 1);
private int m_IarCommandsPending;
private OglIarWebDavStorage m_IarWebDav;
private long m_IarWebDavMaximumBytes = 10240L * 1024 * 1024;
private IDisposable m_ObjectMessageSubscription;
private IDisposable m_EstateScriptMessageSubscription;
private IDisposable m_GridScriptMessageSubscription;
private IDisposable m_CrossRegionChatSubscription;
private IDisposable m_FeaturePolicySubscription;
// Robust republishes signed policies on each heartbeat to refresh expiry.
// Only report an initial or genuinely changed policy, never renewals.
private readonly object m_FeaturePolicyLogSync = new();
private long m_LastLoggedFeaturePolicyRevision = -1;
private int m_LastLoggedFeaturePolicyFlags = -1;
// A malformed own-node policy must remain visible without flooding the log.
private long m_LastOwnFeaturePolicyWarningSeconds;
private volatile bool m_MaintenanceMode;
private volatile bool m_Draining;
private DateTimeOffset m_StartedAt;
public string NodeId => m_NodeId;
public bool Enabled => m_Enabled && m_ObjectMessagingEnabled;
public string Name => "NexVerseNodeAgentModule";
public Type ReplaceableInterface => null;
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["NexVerseNodeAgent"];
if (config == null || !config.GetBoolean("Enabled", false))
return;
string peerUrl = config.GetString("PeerUrl", string.Empty).Trim();
string sharedKey = config.GetString("SharedKey", string.Empty);
if (!Uri.TryCreate(peerUrl, UriKind.Absolute, out Uri peer))
{
m_Log.Error("[NEX-NODE]: NexVerseNodeAgent PeerUrl is missing or invalid; module disabled.");
return;
}
try
{
NexBusProtocol.ValidateSharedKey(sharedKey);
}
catch (Exception e)
{
m_Log.Error("[NEX-NODE]: NexVerseNodeAgent SharedKey is invalid; module disabled.", e);
return;
}
m_NodeId = OglArchiveFeatureGate.ResolveNodeId(
config.GetString("NodeId", Environment.MachineName),
Environment.MachineName);
// Log files can contain personally identifiable information or
// credentials. Forward only over TLS (or loopback for local tests).
m_LogForwardEnabled = config.GetBoolean("LogForwardingEnabled", true) &&
System.Text.RegularExpressions.Regex.IsMatch(m_NodeId,
@"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") &&
(peer.Scheme == Uri.UriSchemeHttps || peer.IsLoopback);
if (config.GetBoolean("LogForwardingEnabled", true) && !m_LogForwardEnabled)
m_Log.Warn("[NEX-NODE]: Automatic OpenSim log forwarding disabled: " +
"NexBus peer must use HTTPS and NodeId must contain safe filename characters.");
m_LogForwardPeer = peer;
m_SharedKey = sharedKey;
m_UpdateStagingEnabled = config.GetBoolean("UpdateStagingEnabled", false);
m_UpdateStagingRoot = config.GetString("UpdateStagingRoot", string.Empty).Trim();
m_UpdateStagingBuild = config.GetBoolean("UpdateStagingBuild", true);
m_UpdateControlKey = Environment.GetEnvironmentVariable("NEXVERSE_UPDATE_CONTROL_KEY") ?? string.Empty;
m_LiveUpdaterEnabled = config.GetBoolean("LiveUpdateEnabled", false);
m_LiveUpdaterUrl = config.GetString("LiveUpdateServiceUrl",
"http://127.0.0.1:19090").Trim().TrimEnd('/');
// Never place local service credentials in repository INI files.
m_LiveUpdaterToken = Environment.GetEnvironmentVariable("OGL_NODE_UPDATER_TOKEN") ?? string.Empty;
m_InboundPath = config.GetString(
"InboundPath",
"/internal/nexbus/v1/events").Trim();
m_HeartbeatSeconds = Math.Max(5, config.GetInt("HeartbeatSeconds", 30));
IConfig performanceConfig = source.Configs["OGLPerformance"];
if (performanceConfig?.GetBoolean("Enabled", false) == true)
m_PerformanceSampler = new OglPerformanceSampler();
m_ObjectMessagingEnabled =
config.GetBoolean(
"CrossRegionObjectMessaging",
false);
m_EstateScriptMessagingEnabled =
config.GetBoolean(
"EstateScriptMessaging",
true);
m_GridScriptMessagingEnabled =
config.GetBoolean("GridScriptMessaging", false);
m_CrossRegionChatMessaging = config.GetBoolean(
"CrossRegionChatMessaging", false);
IConfig chatConfig = source.Configs["Chat"];
m_ChatWhisperDistance = chatConfig?.GetInt("whisper_distance", 10) ?? 10;
m_ChatSayDistance = chatConfig?.GetInt("say_distance", 20) ?? 20;
m_ChatShoutDistance = chatConfig?.GetInt("shout_distance", 100) ?? 100;
m_AllowCrossOwnerObjectMessages =
config.GetBoolean(
"AllowCrossOwnerObjectMessages",
false);
m_ObjectMessagesPerSecond =
Math.Clamp(
config.GetInt(
"ObjectMessagesPerSecond",
20),
1,
200);
m_ObjectMessageMaxAgeSeconds =
Math.Clamp(
config.GetInt(
"ObjectMessageMaxAgeSeconds",
30),
5,
300);
IConfig iarConfig = source.Configs["OpenGenesisLINKIAR"];
// Separate per-node NAS credentials. Never distribute passwords
// or client authentication material through NexBus.
if ((iarConfig?.GetString("StorageBackend", "WebDAV") ?? "WebDAV")
.Equals("WebDAV", StringComparison.OrdinalIgnoreCase) &&
iarConfig?.GetBoolean("Enabled", false) == true &&
!string.IsNullOrWhiteSpace(iarConfig.GetString("WebDavBaseUrl", "")))
{
try
{
m_IarWebDav = new OglIarWebDavStorage(
iarConfig.GetString("WebDavBaseUrl", ""),
iarConfig.GetString("NasHost", "10.78.0.4"),
iarConfig.GetString("WebDavUsername", ""),
iarConfig.GetString("WebDavPasswordFile", ""));
long mib = iarConfig.GetLong("MaximumArchiveMiB", 10240);
if (mib < 101 || mib > 10240)
throw new ArgumentException("Invalid WebDAV IAR archive size cap.");
m_IarWebDavMaximumBytes = mib * 1024L * 1024;
}
catch (Exception e) when (e is IOException or ArgumentException or
UnauthorizedAccessException or System.Security.SecurityException)
{
m_IarWebDav?.Dispose();
m_IarWebDav = null;
m_Log.Error("[OGL-IAR]: WebDAV archive transport disabled.", e);
}
}
IConfig oarConfig = source.Configs["OpenGenesisLINKOAR"];
m_MigrationStorageId =
(oarConfig?.GetString("MigrationStorageId", string.Empty) ?? string.Empty)
.Trim();
int queueCapacity = Math.Max(128, config.GetInt("QueueCapacity", 2048));
int timeoutMs = Math.Max(250, config.GetInt("RequestTimeoutMilliseconds", 2000));
int deduplicationWindow = Math.Max(128, config.GetInt("DeduplicationWindow", 10000));
m_Transport = new SimulatorNexEventTransport(
m_NodeId,
peer,
m_SharedKey,
queueCapacity,
timeoutMs);
m_Bus = new DistributedNexEventBus(m_Transport, deduplicationWindow);
Interlocked.Exchange(ref m_Stopping, 0);
m_StartedAt = DateTimeOffset.UtcNow;
m_Enabled = true;
m_Log.InfoFormat(
"[NEX-NODE]: NodeAgent enabled for node {0}; NexBus peer {1}",
m_NodeId,
peer);
}
public void AddRegion(Scene scene)
{
if (!m_Enabled || scene == null)
return;
m_Scenes[scene.RegionInfo.RegionID] = scene;
scene.RegisterModuleInterface<INexVerseEventBusModule>(this);
scene.RegisterModuleInterface<ICrossRegionObjectMessageRouter>(this);
scene.RegisterModuleInterface<IEstateScriptMessageRouter>(this);
scene.RegisterModuleInterface<IGridScriptMessageRouter>(this);
if (m_CrossRegionChatMessaging)
scene.EventManager.OnChatFromClient += PublishNeighbourAvatarChat;
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled || scene == null)
return;
PublishRegionEvent("region.online", scene);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled || scene == null)
return;
PublishRegionEvent("region.offline", scene);
if (m_CrossRegionChatMessaging)
scene.EventManager.OnChatFromClient -= PublishNeighbourAvatarChat;
scene.UnregisterModuleInterface<IGridScriptMessageRouter>(this);
scene.UnregisterModuleInterface<IEstateScriptMessageRouter>(this);
scene.UnregisterModuleInterface<ICrossRegionObjectMessageRouter>(this);
scene.UnregisterModuleInterface<INexVerseEventBusModule>(this);
m_Scenes.TryRemove(scene.RegionInfo.RegionID, out _);
}
public void PostInitialise()
{
if (!m_Enabled)
return;
if (MainServer.Instance == null)
{
m_Log.Error("[NEX-NODE]: MainServer is unavailable; NodeAgent inbound NexBus disabled.");
return;
}
MainServer.Instance.AddSimpleStreamHandler(
new SimpleStreamHandler(
m_InboundPath,
HandleInbound,
"NexVerse Simulator NexBus"));
m_CreateRegionSubscription =
m_Bus.Subscribe(
"region.control.create.requested",
HandleCreateRegionCommand);
m_MoveRegionSubscription =
m_Bus.Subscribe(
"region.control.move.requested",
HandleMoveRegionCommand);
m_RegionLifecycleSubscription =
m_Bus.Subscribe(
"region.control.lifecycle.requested",
HandleRegionLifecycleCommand);
m_NodeControlSubscription = m_Bus.Subscribe("node.control.requested", HandleNodeControlCommand);
m_NodeUpdateSubscription = m_Bus.Subscribe("node.update.stage.requested", HandleStageUpdateCommand);
m_NodeLiveUpdateSubscription = m_Bus.Subscribe("node.update.live.requested", HandleLiveUpdateCommand);
m_OarControlSubscription = m_Bus.Subscribe("archive.oar.requested", HandleOarCommand);
m_IarControlSubscription = m_Bus.Subscribe("archive.iar.requested", HandleIarCommand);
if (m_ObjectMessagingEnabled)
{
m_ObjectMessageSubscription =
m_Bus.Subscribe(
"object.message.requested",
HandleObjectMessage);
}
if (m_CrossRegionChatMessaging)
m_CrossRegionChatSubscription = m_Bus.Subscribe(
"chat.neighbor.requested", HandleNeighbourAvatarChat);
if (OglArchiveFeatureGate.Enabled)
{
m_FeaturePolicySubscription = m_Bus.Subscribe(
"feature.policy.updated", HandleFeaturePolicy);
Publish(new NexEvent("feature.policy.requested",
"nexverse.simulator", new Dictionary<string, string>
{ ["node_id"] = m_NodeId }));
}
if (m_EstateScriptMessagingEnabled)
{
m_EstateScriptMessageSubscription =
m_Bus.Subscribe(
"estate.script.message.requested",
HandleEstateScriptMessage);
}
if (m_GridScriptMessagingEnabled)
{
m_GridScriptMessageSubscription =
m_Bus.Subscribe(
"grid.script.message.requested",
HandleGridScriptMessage);
}
m_HeartbeatTimer = new Timer(
_ => PublishHeartbeatSafe(),
null,
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(m_HeartbeatSeconds));
if (m_LogForwardEnabled)
{
m_LogForwardClient = new HttpClient {
Timeout = TimeSpan.FromSeconds(8)
};
m_LogForwardTimer = new Timer(
_ => _ = ForwardDailyLogsSafeAsync(),
null, TimeSpan.FromSeconds(8), TimeSpan.FromSeconds(15));
}
Publish(new NexEvent(
"node.online",
"nexverse.simulator",
NodeData()));
}
public void Close()
{
if (!m_Enabled || Interlocked.Exchange(ref m_Stopping, 1) != 0)
return;
try
{
Publish(new NexEvent(
"node.offline",
"nexverse.simulator",
NodeData()));
}
catch
{
}
m_CreateRegionSubscription?.Dispose();
m_CreateRegionSubscription = null;
m_MoveRegionSubscription?.Dispose();
m_MoveRegionSubscription = null;
m_RegionLifecycleSubscription?.Dispose();
m_RegionLifecycleSubscription = null;
m_NodeControlSubscription?.Dispose();
m_NodeControlSubscription = null;
m_NodeUpdateSubscription?.Dispose();
m_NodeUpdateSubscription = null;
m_NodeLiveUpdateSubscription?.Dispose();
m_NodeLiveUpdateSubscription = null;
m_OarControlSubscription?.Dispose();
m_OarControlSubscription = null;
m_IarControlSubscription?.Dispose();
m_IarControlSubscription = null;
m_ObjectMessageSubscription?.Dispose();
m_ObjectMessageSubscription = null;
m_EstateScriptMessageSubscription?.Dispose();
m_EstateScriptMessageSubscription = null;
m_GridScriptMessageSubscription?.Dispose();
m_GridScriptMessageSubscription = null;
m_CrossRegionChatSubscription?.Dispose();
m_CrossRegionChatSubscription = null;
m_FeaturePolicySubscription?.Dispose();
m_FeaturePolicySubscription = null;
foreach (Scene scene in m_Scenes.Values)
scene.EventManager.OnChatFromClient -= PublishNeighbourAvatarChat;
m_ChatOutboundRates.Clear();
m_ChatInboundRates.Clear();
m_ObjectMessageOutboundRates.Clear();
m_ObjectMessageInboundRates.Clear();
m_HeartbeatTimer?.Dispose();
m_LogForwardTimer?.Dispose();
m_LogForwardClient?.Dispose();
m_IarWebDav?.Dispose();
m_IarWebDav = null;
m_Bus?.Dispose();
m_Transport = null;
m_Bus = null;
m_Enabled = false;
}
public IDisposable Subscribe(
string eventName,
Action<NexEvent> handler)
{
if (!m_Enabled || m_Bus == null)
throw new InvalidOperationException("NexVerse NodeAgent is not enabled.");
return m_Bus.Subscribe(eventName, handler);
}
public void Publish(NexEvent nexEvent)
{
if (!m_Enabled || m_Bus == null)
return;
m_Bus.Publish(nexEvent);
}
// Signed NexBus messages carry the original viewer's world position.
// Do not use ordinary viewer chat broadcasts here: these would be
// shown twice by child-agent viewers and do not reach llListen.
private void PublishNeighbourAvatarChat(object sender, OSChatMessage chat)
{
if (!m_Enabled || !m_CrossRegionChatMessaging || m_Bus == null ||
chat?.Sender == null || string.IsNullOrEmpty(chat.Message) ||
chat.Channel == DebugChannel)
return;
float range = CrossRegionChatGeometry.ChatRange(
chat.Type, m_ChatWhisperDistance, m_ChatSayDistance, m_ChatShoutDistance);
if (range <= 0 || chat.Scene is not Scene source ||
!m_Scenes.ContainsKey(source.RegionInfo.RegionID))
return;
ScenePresence avatar = source.GetScenePresence(chat.Sender.AgentId);
if (avatar == null || avatar.IsChildAgent || avatar.IsDeleted)
return;
Vector3 position = avatar.AbsolutePosition;
if (!float.IsFinite(position.X) || !float.IsFinite(position.Y) ||
!float.IsFinite(position.Z))
return;
// Skip network broadcast when no other region can be within range.
if (position.X >= range && position.Y >= range &&
position.X <= source.RegionInfo.RegionSizeX - range &&
position.Y <= source.RegionInfo.RegionSizeY - range)
return;
if (!TryTakeObjectMessageRateSlot(m_ChatOutboundRates, avatar.UUID))
return;
string message = chat.Message.Length > 1023 ? chat.Message[..1023] : chat.Message;
Dictionary<string, string> data = new()
{
["source_node_id"] = m_NodeId,
["source_region_id"] = source.RegionInfo.RegionID.ToString(),
["source_avatar_id"] = avatar.UUID.ToString(),
["source_name"] = avatar.Name,
["world_x"] = (source.RegionInfo.WorldLocX + position.X).ToString(
"R", System.Globalization.CultureInfo.InvariantCulture),
["world_y"] = (source.RegionInfo.WorldLocY + position.Y).ToString(
"R", System.Globalization.CultureInfo.InvariantCulture),
["world_z"] = position.Z.ToString(
"R", System.Globalization.CultureInfo.InvariantCulture),
["channel"] = chat.Channel.ToString(
System.Globalization.CultureInfo.InvariantCulture),
["chat_type"] = ((int)chat.Type).ToString(
System.Globalization.CultureInfo.InvariantCulture),
["message"] = message
};
Publish(new NexEvent("chat.neighbor.requested", "nexverse.simulator", data));
}
private static bool TryChatFloat(NexEvent ev, string key, out float value)
{
value = 0;
return TryCommandData(ev, key, out string raw) &&
float.TryParse(raw, System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out value) &&
float.IsFinite(value);
}
private void HandleNeighbourAvatarChat(NexEvent ev)
{
if (!m_Enabled || !m_CrossRegionChatMessaging ||
ev == null || Math.Abs((DateTimeOffset.UtcNow - ev.Timestamp).TotalSeconds) > 5 ||
!string.Equals(ev.Source, "nexverse.simulator", StringComparison.Ordinal) ||
!TryCommandData(ev, "source_node_id", out string sourceNode) ||
// A second simulator on the same machine may share the
// default NodeId; source-region ownership prevents loops.
!TryCommandData(ev, "source_region_id", out string rawRegion) ||
!UUID.TryParse(rawRegion, out UUID sourceRegion) ||
sourceRegion.IsZero() || m_Scenes.ContainsKey(sourceRegion) ||
!TryCommandData(ev, "source_avatar_id", out string rawAvatar) ||
!UUID.TryParse(rawAvatar, out UUID sourceAvatar) ||
sourceAvatar.IsZero() ||
!TryCommandData(ev, "source_name", out string sourceName) ||
(ev.Data == null || !ev.Data.TryGetValue("message", out string message) ||
message == null || message.Length == 0 || message.Length > 1023) ||
!TryCommandInt(ev, "chat_type", out int rawType) ||
!TryCommandInt(ev, "channel", out int channel) ||
channel == DebugChannel ||
!TryChatFloat(ev, "world_x", out float worldX) ||
!TryChatFloat(ev, "world_y", out float worldY) ||
!TryChatFloat(ev, "world_z", out float worldZ))
return;
ChatTypeEnum type = (ChatTypeEnum)rawType;
float range = CrossRegionChatGeometry.ChatRange(
type, m_ChatWhisperDistance, m_ChatSayDistance, m_ChatShoutDistance);
if (range <= 0 || !TryTakeObjectMessageRateSlot(m_ChatInboundRates, sourceAvatar))
return;
foreach (Scene target in m_Scenes.Values)
{
if (!CrossRegionChatGeometry.CanReachRegion(
worldX, worldY, target.RegionInfo.WorldLocX, target.RegionInfo.WorldLocY,
target.RegionInfo.RegionSizeX, target.RegionInfo.RegionSizeY, range))
continue;
IWorldComm worldComm = target.RequestModuleInterface<IWorldComm>();
if (worldComm == null || worldComm.ListenerCount == 0)
continue;
Vector3 localPos = new(
worldX - target.RegionInfo.WorldLocX,
worldY - target.RegionInfo.WorldLocY, worldZ);
worldComm.DeliverMessage(type, channel, sourceName, sourceAvatar,
message, localPos);
}
}
public bool TryRoute(
UUID sourceRegionId,
UUID sourceObjectId,
UUID sourceOwnerId,
string sourceName,
Vector3 sourcePosition,
UUID targetObjectId,
int channel,
string message)
{
if (!Enabled ||
m_Bus == null ||
sourceRegionId.IsZero() ||
sourceObjectId.IsZero() ||
sourceOwnerId.IsZero() ||
targetObjectId.IsZero() ||
channel == DebugChannel)
{
return false;
}
if (!m_Scenes.TryGetValue(
sourceRegionId,
out Scene sourceScene))
{
return false;
}
SceneObjectPart sourcePart =
sourceScene.GetSceneObjectPart(
sourceObjectId);
if (sourcePart == null ||
sourcePart.IsDeleted ||
sourcePart.OwnerID != sourceOwnerId)
{
return false;
}
string payload =
message ?? string.Empty;
if (payload.Length > 1023)
payload = payload[..1023];
if (!TryTakeObjectMessageRateSlot(
m_ObjectMessageOutboundRates,
sourceObjectId))
{
m_Log.WarnFormat(
"[NEX-OBJECT]: Rate limit reached for source object {0} in region {1}.",
sourceObjectId,
sourceScene.RegionInfo.RegionName);
return false;
}
Dictionary<string, string> data =
new Dictionary<string, string>
{
["source_node_id"] =
m_NodeId,
["source_region_id"] =
sourceRegionId.ToString(),
["source_object_id"] =
sourceObjectId.ToString(),
["source_owner_id"] =
sourceOwnerId.ToString(),
["source_name"] =
string.IsNullOrWhiteSpace(sourceName)
? sourcePart.Name ?? string.Empty
: sourceName.Trim(),
["source_position"] =
string.Format(
System.Globalization.CultureInfo.InvariantCulture,
"{0:R},{1:R},{2:R}",
sourcePosition.X,
sourcePosition.Y,
sourcePosition.Z),
["target_object_id"] =
targetObjectId.ToString(),
["channel"] =
channel.ToString(
System.Globalization.CultureInfo.InvariantCulture),
["message"] =
payload
};
Publish(new NexEvent(
"object.message.requested",
"nexverse.simulator",
data));
return true;
}
public bool TryRouteEstateMessage(
UUID sourceRegionId,
UUID sourceObjectId,
UUID sourceOwnerId,
string sourceName,
uint estateId,
int channel,
string message)
{
if (!m_Enabled ||
!m_EstateScriptMessagingEnabled ||
m_Bus == null ||
sourceRegionId.IsZero() ||
sourceObjectId.IsZero() ||
sourceOwnerId.IsZero() ||
estateId == 0 ||
channel == 0 ||
channel == DebugChannel)
{
return false;
}
if (!m_Scenes.TryGetValue(
sourceRegionId,
out Scene sourceScene))
{
return false;
}
SceneObjectPart sourcePart =
sourceScene.GetSceneObjectPart(
sourceObjectId);
if (sourcePart == null ||
sourcePart.IsDeleted ||
sourcePart.OwnerID != sourceOwnerId)
{
return false;
}
EstateSettings sourceEstate =
sourceScene.RegionInfo.EstateSettings;
if (sourceEstate == null ||
sourceEstate.EstateID != estateId ||
!sourceEstate.IsEstateManagerOrOwner(sourceOwnerId))
{
m_Log.WarnFormat(
"[NEX-ESTATE-SAY]: Nicht autorisierter Routing-Versuch von Objekt {0}, Besitzer {1}, Estate {2}.",
sourceObjectId,
sourceOwnerId,
estateId);
return false;
}
if (!TryTakeObjectMessageRateSlot(
m_ObjectMessageOutboundRates,
sourceObjectId))
{
m_Log.WarnFormat(
"[NEX-ESTATE-SAY]: Ratenlimit fuer Quellobjekt {0} erreicht.",
sourceObjectId);
return false;
}
string payload =
message ?? string.Empty;
if (payload.Length > 1023)
payload = payload[..1023];
Publish(new NexEvent(
"estate.script.message.requested",
"nexverse.simulator",
new Dictionary<string, string>
{
["source_node_id"] =
m_NodeId,
["source_region_id"] =
sourceRegionId.ToString(),
["source_object_id"] =
sourceObjectId.ToString(),
["source_owner_id"] =
sourceOwnerId.ToString(),
["source_name"] =
string.IsNullOrWhiteSpace(sourceName)
? sourcePart.Name ?? string.Empty
: sourceName.Trim(),
["estate_id"] =
estateId.ToString(
System.Globalization.CultureInfo.InvariantCulture),
["channel"] =
channel.ToString(
System.Globalization.CultureInfo.InvariantCulture),
["message"] =
payload
}));
return true;
}
// Grid-wide script messages are opt-in and limited to source objects
// owned by an Estate Manager/Owner. They are not emitted to viewer chat.
// The trusted NexBus layer authenticates remote simulator messages.
public bool TryBroadcastGridMessage(
UUID sourceRegionId,
UUID sourceObjectId,
UUID sourceOwnerId,
string sourceName,
int channel,
string message)
{
if (!m_Enabled || !m_GridScriptMessagingEnabled || m_Bus == null ||
sourceRegionId.IsZero() || sourceObjectId.IsZero() ||
sourceOwnerId.IsZero() || channel == 0 || channel == DebugChannel ||
!m_Scenes.TryGetValue(sourceRegionId, out Scene sourceScene))
return false;
SceneObjectPart sourcePart = sourceScene.GetSceneObjectPart(sourceObjectId);
EstateSettings sourceEstate = sourceScene.RegionInfo.EstateSettings;
if (sourcePart == null || sourcePart.IsDeleted ||
sourcePart.OwnerID != sourceOwnerId || sourceEstate == null ||
!sourceEstate.IsEstateManagerOrOwner(sourceOwnerId))
{
m_Log.WarnFormat("[NEX-GRID-SAY]: Unauthorisierter Sender {0}, Besitzer {1}.",
sourceObjectId, sourceOwnerId);
return false;
}
if (!TryTakeObjectMessageRateSlot(m_ObjectMessageOutboundRates, sourceObjectId))
return false;
string payload = message ?? string.Empty;
if (payload.Length > 1023)
payload = payload[..1023];
string name = string.IsNullOrWhiteSpace(sourceName)
? sourcePart.Name ?? string.Empty
: sourceName.Trim();
// All locally loaded scenes, regardless of EstateID. This happens
// exactly once on the source node; the bus receiver skips this node.
foreach (Scene scene in m_Scenes.Values)
{
IWorldComm comm = scene.RequestModuleInterface<IWorldComm>();
comm?.DeliverMessage(ChatTypeEnum.Region, channel, name,
sourceObjectId, payload);
}
Publish(new NexEvent(
"grid.script.message.requested",
"nexverse.simulator",
new Dictionary<string, string>
{
["source_node_id"] = m_NodeId,
["source_region_id"] = sourceRegionId.ToString(),
["source_object_id"] = sourceObjectId.ToString(),
["source_owner_id"] = sourceOwnerId.ToString(),
["source_name"] = name,
["channel"] = channel.ToString(
System.Globalization.CultureInfo.InvariantCulture),
["message"] = payload
}));
return true;
}
private void HandleGridScriptMessage(NexEvent nexEvent)
{
if (!m_Enabled || !m_GridScriptMessagingEnabled ||
nexEvent == null || nexEvent.Data == null ||
!string.Equals(nexEvent.Source, "nexverse.simulator",
StringComparison.Ordinal))
return;
TimeSpan age = DateTimeOffset.UtcNow - nexEvent.Timestamp;
if (age > TimeSpan.FromSeconds(m_ObjectMessageMaxAgeSeconds) ||
age < TimeSpan.FromSeconds(-5))
return;
if (!TryCommandData(nexEvent, "source_node_id", out string sourceNodeId) ||
string.Equals(sourceNodeId, m_NodeId, StringComparison.Ordinal) ||
!TryCommandData(nexEvent, "source_region_id", out string rawSourceRegion) ||
!UUID.TryParse(rawSourceRegion, out UUID sourceRegionId) ||
sourceRegionId.IsZero() ||
!TryCommandData(nexEvent, "source_object_id", out string rawSourceObject) ||
!UUID.TryParse(rawSourceObject, out UUID sourceObjectId) ||
sourceObjectId.IsZero() ||
!TryCommandData(nexEvent, "source_owner_id", out string rawSourceOwner) ||
!UUID.TryParse(rawSourceOwner, out UUID sourceOwnerId) ||
sourceOwnerId.IsZero() ||
!TryCommandInt(nexEvent, "channel", out int channel) ||
channel == 0 || channel == DebugChannel)
return;
// The originating authenticated simulator validated object ownership
// and Estate Manager/Owner rights; never rely on viewer-reported data.
if (!TryTakeObjectMessageRateSlot(m_ObjectMessageInboundRates,
sourceObjectId))
return;
string sourceName = nexEvent.Data.TryGetValue("source_name", out string name)
? name ?? string.Empty : string.Empty;
string payload = nexEvent.Data.TryGetValue("message", out string message)
? message ?? string.Empty : string.Empty;
if (payload.Length > 1023)
payload = payload[..1023];
foreach (Scene scene in m_Scenes.Values)
{
IWorldComm comm = scene.RequestModuleInterface<IWorldComm>();
comm?.DeliverMessage(ChatTypeEnum.Region, channel, sourceName,
sourceObjectId, payload);
}
}
private void HandleEstateScriptMessage(
NexEvent nexEvent)
{
if (!m_Enabled ||
!m_EstateScriptMessagingEnabled ||
nexEvent == null ||
nexEvent.Data == null ||
!string.Equals(
nexEvent.Source,
"nexverse.simulator",
StringComparison.Ordinal))
{
return;
}
TimeSpan age =
DateTimeOffset.UtcNow -
nexEvent.Timestamp;
if (age >
TimeSpan.FromSeconds(
m_ObjectMessageMaxAgeSeconds) ||
age <
TimeSpan.FromSeconds(-5))
{
return;
}
if (!TryCommandData(
nexEvent,
"source_node_id",
out string sourceNodeId) ||
string.Equals(
sourceNodeId,
m_NodeId,
StringComparison.Ordinal) ||
!TryCommandData(
nexEvent,
"source_object_id",
out string rawSourceObject) ||
!UUID.TryParse(
rawSourceObject,
out UUID sourceObjectId) ||
sourceObjectId.IsZero() ||
!TryCommandData(
nexEvent,
"source_owner_id",
out string rawSourceOwner) ||
!UUID.TryParse(
rawSourceOwner,
out UUID sourceOwnerId) ||
sourceOwnerId.IsZero() ||
!TryCommandData(
nexEvent,
"estate_id",
out string rawEstateId) ||
!uint.TryParse(
rawEstateId,
System.Globalization.NumberStyles.Integer,
System.Globalization.CultureInfo.InvariantCulture,
out uint estateId) ||
estateId == 0 ||
!TryCommandInt(
nexEvent,
"channel",
out int channel) ||
channel == 0 ||
channel == DebugChannel)
{
return;
}
if (!TryTakeObjectMessageRateSlot(
m_ObjectMessageInboundRates,
sourceObjectId))
{
m_Log.WarnFormat(
"[NEX-ESTATE-SAY]: Eingehendes Ratenlimit fuer Quellobjekt {0} erreicht.",
sourceObjectId);
return;
}
string sourceName =
nexEvent.Data.TryGetValue(
"source_name",
out string rawName)
? rawName ?? string.Empty
: string.Empty;
string message =
nexEvent.Data.TryGetValue(
"message",
out string rawMessage)
? rawMessage ?? string.Empty
: string.Empty;
if (message.Length > 1023)
message = message[..1023];
foreach (Scene scene in
m_Scenes.Values)
{
EstateSettings targetEstate =
scene.RegionInfo.EstateSettings;
if (targetEstate == null ||
targetEstate.EstateID != estateId ||
!targetEstate.IsEstateManagerOrOwner(sourceOwnerId))
{
continue;
}
IWorldComm worldComm =
scene.RequestModuleInterface<IWorldComm>();
worldComm?.DeliverMessage(
ChatTypeEnum.Region,
channel,
sourceName,
sourceObjectId,
message);
}
}
private void HandleObjectMessage(
NexEvent nexEvent)
{
if (!Enabled ||
nexEvent == null ||
nexEvent.Data == null ||
!string.Equals(
nexEvent.Source,
"nexverse.simulator",
StringComparison.Ordinal))
{
return;
}
TimeSpan age =
DateTimeOffset.UtcNow -
nexEvent.Timestamp;
if (age >
TimeSpan.FromSeconds(
m_ObjectMessageMaxAgeSeconds) ||
age <
TimeSpan.FromSeconds(-5))
{
return;
}
if (!TryCommandData(
nexEvent,
"source_object_id",
out string rawSourceObject) ||
!UUID.TryParse(
rawSourceObject,
out UUID sourceObjectId) ||
sourceObjectId.IsZero() ||
!TryCommandData(
nexEvent,
"source_owner_id",
out string rawSourceOwner) ||
!UUID.TryParse(
rawSourceOwner,
out UUID sourceOwnerId) ||
sourceOwnerId.IsZero() ||
!TryCommandData(
nexEvent,
"target_object_id",
out string rawTarget) ||
!UUID.TryParse(
rawTarget,
out UUID targetObjectId) ||
targetObjectId.IsZero() ||
!TryCommandInt(
nexEvent,
"channel",
out int channel) ||
channel ==
DebugChannel)
{
return;
}
string sourceName =
nexEvent.Data.TryGetValue(
"source_name",
out string rawName)
? rawName ?? string.Empty
: string.Empty;
string message =
nexEvent.Data.TryGetValue(
"message",
out string rawMessage)
? rawMessage ?? string.Empty
: string.Empty;
if (message.Length > 1023)
message = message[..1023];
foreach (Scene scene in
m_Scenes.Values)
{
SceneObjectPart targetPart =
scene.GetSceneObjectPart(
targetObjectId);
if (targetPart == null ||
targetPart.IsDeleted)
{
continue;
}
if (!m_AllowCrossOwnerObjectMessages &&
targetPart.OwnerID !=
sourceOwnerId)
{
m_Log.DebugFormat(
"[NEX-OBJECT]: Cross-owner object message rejected from {0} to {1}.",
sourceObjectId,
targetObjectId);
return;
}
if (!TryTakeObjectMessageRateSlot(
m_ObjectMessageInboundRates,
sourceObjectId))
{
m_Log.WarnFormat(
"[NEX-OBJECT]: Inbound rate limit reached for source object {0}.",
sourceObjectId);
return;
}
IWorldComm worldComm =
scene.RequestModuleInterface<IWorldComm>();
if (worldComm == null)
return;
worldComm.DeliverMessageTo(
targetObjectId,
channel,
Vector3.Zero,
sourceName,
sourceObjectId,
message);
Publish(new NexEvent(
"object.message.received",
"nexverse.simulator",
new Dictionary<string, string>
{
["source_object_id"] =
sourceObjectId.ToString(),
["source_owner_id"] =
sourceOwnerId.ToString(),
["target_object_id"] =
targetObjectId.ToString(),
["target_region_id"] =
scene.RegionInfo.RegionID.ToString(),
["target_node_id"] =
m_NodeId,
["channel"] =
channel.ToString(
System.Globalization.CultureInfo.InvariantCulture),
["request_event_id"] =
nexEvent.EventId.ToString()
},
nexEvent.CorrelationId));
return;
}
}
private bool TryTakeObjectMessageRateSlot(
ConcurrentDictionary<UUID, ObjectMessageRateState> rates,
UUID sourceObjectId)
{
long currentSecond =
DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (!rates.ContainsKey(sourceObjectId) &&
rates.Count >= ObjectMessageRateEntryLimit)
{
PruneObjectMessageRateStates(
rates,
currentSecond);
if (rates.Count >= ObjectMessageRateEntryLimit)
return false;
}
ObjectMessageRateState state =
rates.GetOrAdd(
sourceObjectId,
_ => new ObjectMessageRateState());
lock (state.SyncRoot)
{
if (state.WindowSecond !=
currentSecond)
{
state.WindowSecond =
currentSecond;
state.Count = 0;
}
state.LastSeenSecond =
currentSecond;
if (state.Count >=
m_ObjectMessagesPerSecond)
{
return false;
}
state.Count++;
}
if (rates.Count > ObjectMessageRateEntryLimit / 2)
PruneObjectMessageRateStates(
rates,
currentSecond);
return true;
}
private static void PruneObjectMessageRateStates(
ConcurrentDictionary<UUID, ObjectMessageRateState> rates,
long currentSecond)
{
foreach (KeyValuePair<UUID, ObjectMessageRateState> item in rates)
{
if (currentSecond -
item.Value.LastSeenSecond >
60)
{
rates.TryRemove(
item.Key,
out _);
}
}
}
private void HandleFeaturePolicy(NexEvent ev)
{
if (!OglArchiveFeatureGate.Enabled || ev?.Data == null ||
!string.Equals(ev.Source, "opengenesislink.world-api", StringComparison.Ordinal) ||
!ev.Data.TryGetValue("node_id", out string node) ||
!ev.Data.TryGetValue("revision", out string revisionRaw) ||
!long.TryParse(revisionRaw, out long revision) ||
!ev.Data.TryGetValue("expires", out string expiryRaw) ||
!long.TryParse(expiryRaw, out long expires) ||
!ev.Data.TryGetValue("flags", out string flagsRaw) ||
!int.TryParse(flagsRaw, out int flags) ||
!ev.Data.TryGetValue("signature", out string signature))
return;
// NexBus broadcasts every node's renewal. Ignore policies addressed
// to another node WITHOUT attempting signature verification or
// treating them as security incidents on this simulator.
if (!OglArchiveFeatureGate.IsForConfiguredNode(node))
return;
if (OglArchiveFeatureGate.Apply(node, revision, expires, flags, signature))
{
Interlocked.Exchange(ref m_LastOwnFeaturePolicyWarningSeconds, 0);
// Every heartbeat carries a newly signed expiry even when the
// revision and access flags are unchanged. Keep applying it so
// archive permissions do not expire, but log only real changes.
bool policyChanged;
lock (m_FeaturePolicyLogSync)
{
policyChanged = revision != m_LastLoggedFeaturePolicyRevision ||
flags != m_LastLoggedFeaturePolicyFlags;
if (policyChanged)
{
m_LastLoggedFeaturePolicyRevision = revision;
m_LastLoggedFeaturePolicyFlags = flags;
}
}
if (policyChanged)
m_Log.InfoFormat(
"[OGL FEATURE CONTROL]: Eigene Richtlinie gesetzt/geändert: Node {0}, Revision {1}, Flags {2}.",
node, revision, flags);
}
else
{
// Bad own-node signatures/expiry remain fail-closed. Warn at
// most once per 120 seconds, without disclosing signatures.
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
long previous = Interlocked.Read(ref m_LastOwnFeaturePolicyWarningSeconds);
if (now - previous >= 120 &&
Interlocked.CompareExchange(
ref m_LastOwnFeaturePolicyWarningSeconds, now, previous) == previous)
m_Log.WarnFormat(
"[OGL FEATURE CONTROL]: Richtlinie für eigene Node {0} abgewiesen " +
"(Revision {1}, Ablauf UTC {2}). NodeId, ES256-Public-Key, " +
"ROBUST-Signing-Key und Systemzeit prüfen. Archivfreigaben bleiben gesperrt.",
node, revision, expires);
}
}
/// <summary>
/// Keep source offsets only after NexBus HTTP 202 acceptance. Each
/// message is signed using the existing NodeAgent HMAC transport key.
/// A retry starts at the same offset, so Robust de-duplicates content.
/// Read at most 4 * 32 KiB per timer cycle to avoid starving the sim.
/// The previous 7 daily archives remain eligible for catch-up.
/// </summary>
private async Task ForwardDailyLogsSafeAsync()
{
if (!m_Enabled || !m_LogForwardEnabled ||
Interlocked.CompareExchange(ref m_LogForwardRunning, 1, 0) != 0)
return;
try
{
int remaining = 4;
// An oldest-first replay also synchronizes yesterday's tail
// after reconnection, restart or temporary network failure.
for (int back = 7; back >= 0 && remaining > 0; --back)
{
DateTime day = DateTime.Today.AddDays(-back);
string dayId = day.ToString("yyyy-MM-dd",
System.Globalization.CultureInfo.InvariantCulture);
string local = Path.Combine(AppContext.BaseDirectory, "logs",
"OpenSim_" + day.ToString("dd_MM_yyyy",
System.Globalization.CultureInfo.InvariantCulture) + ".log");
if (!File.Exists(local)) continue;
long cursor;
lock (m_LogForwardSync)
cursor = m_LogForwardOffsets.TryGetValue(dayId, out long pos) ? pos : 0L;
while (remaining > 0)
{
byte[] bytes = new byte[32 * 1024];
int count;
try
{
using var input = new FileStream(local, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete);
if (cursor > input.Length) cursor = 0L;
input.Position = cursor;
count = await input.ReadAsync(bytes.AsMemory(0, bytes.Length))
.ConfigureAwait(false);
}
catch (IOException) { break; }
catch (UnauthorizedAccessException) { break; }
if (count == 0) break;
if (count != bytes.Length) Array.Resize(ref bytes, count);
var envelope = new NexEvent("node.log.chunk", "nexverse.simulator",
new Dictionary<string, string> {
["node_id"] = m_NodeId,
["date"] = dayId,
["offset"] = cursor.ToString(
System.Globalization.CultureInfo.InvariantCulture),
["bytes_base64"] = Convert.ToBase64String(bytes)
});
byte[] payload = NexBusProtocol.Serialize(envelope);
using var outgoing = new HttpRequestMessage(HttpMethod.Post, m_LogForwardPeer);
outgoing.Headers.TryAddWithoutValidation("X-NexBus-Node", m_NodeId);
outgoing.Headers.TryAddWithoutValidation("X-NexBus-Schema",
NexVerse.Core.NexVersePlatform.NexBusSchemaVersion);
outgoing.Headers.TryAddWithoutValidation("X-NexBus-Signature",
"sha256=" + NexBusProtocol.Sign(payload, m_SharedKey));
outgoing.Content = new ByteArrayContent(payload);
outgoing.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using HttpResponseMessage result = await m_LogForwardClient.SendAsync(outgoing)
.ConfigureAwait(false);
if (result.StatusCode != HttpStatusCode.Accepted) return;
// 'accepted=false' means the NexBus replay/dedup gate
// rejected this particular event; never lose the cursor.
byte[] reply = await result.Content.ReadAsByteArrayAsync()
.ConfigureAwait(false);
using JsonDocument ack = JsonDocument.Parse(reply);
if (!ack.RootElement.TryGetProperty("accepted", out JsonElement accepted) ||
accepted.ValueKind != JsonValueKind.True)
return;
cursor += count;
lock (m_LogForwardSync) m_LogForwardOffsets[dayId] = cursor;
--remaining;
}
}
}
catch (Exception error)
{
if (error is not OperationCanceledException)
m_Log.Debug("[NEX-NODE]: Signed log sync will retry: " + error.GetType().Name);
}
finally { Volatile.Write(ref m_LogForwardRunning, 0); }
}
private void PublishHeartbeatSafe()
{
try
{
Publish(new NexEvent(
"node.heartbeat",
"nexverse.simulator",
NodeData()));
// Keep per-region NPC and total avatar presence fresh rather than
// relying on the count captured at region startup.
foreach (Scene scene in m_Scenes.Values.ToArray())
PublishRegionEvent("region.presence", scene);
}
catch (Exception e)
{
m_Log.Warn("[NEX-NODE]: Failed to publish heartbeat.", e);
}
}
private Dictionary<string, string> NodeData()
{
Scene[] scenes = m_Scenes.Values.ToArray();
int agents = scenes.Sum(x => x.GetRootAgentCount());
int npcs = scenes.Sum(x => x.GetRootNPCCount());
LunaTextureNodeSummary lunaTexture =
CollectLunaTextureDiagnostics(scenes);
using Process process = Process.GetCurrentProcess();
DriveInfo drive = new DriveInfo(Path.GetPathRoot(AppContext.BaseDirectory) ?? "/");
Dictionary<string, string> data = new Dictionary<string, string>
{
["node_id"] = m_NodeId,
["hostname"] = Environment.MachineName,
["server_version"] = OpenSim.VersionInfo.Version.Trim(),
["uptime_seconds"] = Math.Max(
0,
(long)(DateTimeOffset.UtcNow - m_StartedAt).TotalSeconds).ToString(),
["process_id"] = Environment.ProcessId.ToString(),
["working_set_bytes"] = process.WorkingSet64.ToString(),
["cpu_seconds"] = process.TotalProcessorTime.TotalSeconds.ToString("F3", System.Globalization.CultureInfo.InvariantCulture),
["disk_free_bytes"] = drive.AvailableFreeSpace.ToString(),
["disk_total_bytes"] = drive.TotalSize.ToString(),
["region_count"] = scenes.Length.ToString(),
["agent_count"] = agents.ToString(),
["npc_count"] = npcs.ToString(),
["maintenance_mode"] = m_MaintenanceMode.ToString(),
["draining"] = m_Draining.ToString(),
["update_staging_enabled"] = m_UpdateStagingEnabled.ToString(),
["update_staging_running"] = (Volatile.Read(ref m_NodeUpdateRunning) != 0).ToString(),
["update_live_enabled"] = m_LiveUpdaterEnabled.ToString(),
["managed_region_commands"] =
(NexVerseManagedRegionHostPlugin.Current?.Enabled == true)
.ToString(),
["cross_region_object_messaging"] =
m_ObjectMessagingEnabled.ToString(),
["cross_owner_object_messaging"] =
m_AllowCrossOwnerObjectMessages.ToString(),
["object_messages_per_second"] =
m_ObjectMessagesPerSecond.ToString(
System.Globalization.CultureInfo.InvariantCulture),
["object_message_max_age_seconds"] =
m_ObjectMessageMaxAgeSeconds.ToString(
System.Globalization.CultureInfo.InvariantCulture),
["migration_storage_id"] =
m_MigrationStorageId,
["luna_texture_diagnostic_count"] =
lunaTexture.DiagnosticCount.ToString(),
["luna_texture_occurrence_count"] =
lunaTexture.OccurrenceCount.ToString(),
["luna_texture_regions_affected"] =
lunaTexture.RegionsAffected.ToString(),
["luna_texture_last_seen_utc"] =
lunaTexture.LastSeenUtc?.ToString("O") ?? string.Empty,
["luna_texture_classifications_json"] =
JsonSerializer.Serialize(lunaTexture.Classifications),
["regions"] = string.Join(
";",
scenes
.OrderBy(x => x.RegionInfo.RegionName, StringComparer.OrdinalIgnoreCase)
.Select(x => x.RegionInfo.RegionID + "|" + x.RegionInfo.RegionName))
};
if (m_PerformanceSampler != null)
{
try
{
OglRegionFrame[] frames = scenes
.OrderBy(x => x.RegionInfo.RegionID.ToString(), StringComparer.Ordinal)
.Select(x =>
{
// Per-region window is drained only on the signed
// NodeAgent heartbeat (never on every scene frame).
OglRegionTimingSample? timings =
x.OglPerformanceTiming?.TakeSnapshotAndReset();
return new OglRegionFrame(
x.RegionInfo.RegionID.ToString(), x.Frame, x.FrameTime,
timings?.Frames ?? 0,
timings?.WorkAverageMs ?? 0,
timings?.FrameAverageMs ?? 0,
timings?.WorkP95Ms ?? 0,
timings?.FrameP95Ms ?? 0,
timings?.FrameP99Ms ?? 0,
timings?.WorkOverBudgetPercent ?? 0,
timings?.FrameOverBudgetPercent ?? 0);
})
.ToArray();
foreach (KeyValuePair<string, string> sample in m_PerformanceSampler.Capture(frames))
data[sample.Key] = sample.Value;
// The active shared cache is discovered through its existing
// region interface; NodeAgent remains decoupled from Flotsam.
if (scenes.Length > 0 &&
scenes[0].RequestModuleInterface<IAssetCache>()
is IOglAssetCacheMetricsProvider assetMetrics)
{
foreach (KeyValuePair<string, long> metric in assetMetrics.CaptureAssetCacheMetrics())
data[metric.Key] = metric.Value.ToString(
System.Globalization.CultureInfo.InvariantCulture);
}
}
catch (Exception error)
{
// Never let optional diagnostics interrupt the signed NexBus heartbeat.
m_Log.Warn("[OGL PERFORMANCE]: Resource sample unavailable: " +
error.GetType().Name);
}
}
return data;
}
private LunaTextureNodeSummary CollectLunaTextureDiagnostics(
Scene[] scenes)
{
LunaTextureNodeSummary summary =
new LunaTextureNodeSummary();
foreach (Scene scene in scenes)
{
try
{
ILunaTextureDiagnostics diagnostics =
scene.RequestModuleInterface<ILunaTextureDiagnostics>();
if (diagnostics == null)
continue;
IReadOnlyList<LunaTextureDiagnosticInfo> records =
diagnostics.GetDiagnostics();
if (records == null || records.Count == 0)
continue;
summary.RegionsAffected++;
foreach (LunaTextureDiagnosticInfo record in records)
{
if (record == null)
continue;
summary.DiagnosticCount++;
long occurrences =
Math.Max(1, record.Count);
summary.OccurrenceCount += occurrences;
string classification =
string.IsNullOrWhiteSpace(record.Classification)
? "unknown"
: record.Classification.Trim().ToLowerInvariant();
if (!summary.Classifications.TryGetValue(
classification,
out long current))
{
current = 0;
}
summary.Classifications[classification] =
current + occurrences;
DateTime seen =
record.LastSeenUtc.Kind == DateTimeKind.Utc
? record.LastSeenUtc
: record.LastSeenUtc.ToUniversalTime();
if (!summary.LastSeenUtc.HasValue ||
seen > summary.LastSeenUtc.Value)
{
summary.LastSeenUtc = seen;
}
}
}
catch (Exception e)
{
m_Log.DebugFormat(
"[NEX-NODE]: LunaTexture diagnostics unavailable for region {0}: {1}",
scene?.RegionInfo.RegionName ?? "<unknown>",
e.Message);
}
}
return summary;
}
private sealed class LunaTextureNodeSummary
{
public int DiagnosticCount;
public long OccurrenceCount;
public int RegionsAffected;
public DateTime? LastSeenUtc;
public Dictionary<string, long> Classifications { get; } =
new Dictionary<string, long>(
StringComparer.OrdinalIgnoreCase);
}
private void PublishRegionEvent(string name, Scene scene)
{
Publish(new NexEvent(
name,
"nexverse.simulator",
new Dictionary<string, string>
{
["node_id"] = m_NodeId,
["region_id"] = scene.RegionInfo.RegionID.ToString(),
["region_name"] = scene.RegionInfo.RegionName,
["server_uri"] = scene.RegionInfo.ServerURI ?? string.Empty,
["size_x"] = scene.RegionInfo.RegionSizeX.ToString(),
["size_y"] = scene.RegionInfo.RegionSizeY.ToString(),
["agent_count"] = scene.GetRootAgentCount().ToString(),
["npc_count"] = scene.GetRootNPCCount().ToString()
}));
}
private void HandleCreateRegionCommand(
NexEvent nexEvent)
{
if (!IsCommandForThisNode(
nexEvent) ||
!TryCommandData(
nexEvent,
"operation_id",
out string operationId))
{
return;
}
PublishOperationState(
"region.control.operation.accepted",
nexEvent,
operationId,
"create",
"accepted");
_ = Task.Run(() =>
{
try
{
if (!TryCommandData(
nexEvent,
"region_id",
out string regionIdRaw) ||
!UUID.TryParse(
regionIdRaw,
out UUID regionId) ||
!TryCommandData(
nexEvent,
"region_name",
out string regionName) ||
!TryCommandInt(
nexEvent,
"grid_x",
out int gridX) ||
!TryCommandInt(
nexEvent,
"grid_y",
out int gridY) ||
!TryCommandInt(
nexEvent,
"size_x",
out int sizeX) ||
!TryCommandInt(
nexEvent,
"size_y",
out int sizeY) ||
!TryCommandInt(
nexEvent,
"estate_id",
out int estateId))
{
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
"create",
"invalid_command_payload");
return;
}
NexVerseManagedRegionHostPlugin host =
NexVerseManagedRegionHostPlugin.Current;
if (host == null ||
!host.Enabled)
{
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
"create",
"managed_region_commands_disabled");
return;
}
if (!host.TryCreateRegion(
regionId,
regionName,
gridX,
gridY,
sizeX,
sizeY,
estateId,
out string error,
out int internalPort,
out string _))
{
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
"create",
error);
return;
}
PublishOperationState(
"region.control.operation.completed",
nexEvent,
operationId,
"create",
"region_created",
new Dictionary<string, string>
{
["region_id"] =
regionId.ToString(),
["region_name"] =
regionName,
["grid_x"] =
gridX.ToString(),
["grid_y"] =
gridY.ToString(),
["size_x"] =
sizeX.ToString(),
["size_y"] =
sizeY.ToString(),
["internal_port"] =
internalPort.ToString()
});
}
catch (Exception e)
{
m_Log.Error(
"[NEX-NODE]: Managed create-region command failed.",
e);
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
"create",
"region_create_unhandled_failure");
}
});
}
private void HandleMoveRegionCommand(
NexEvent nexEvent)
{
if (!IsCommandForThisNode(
nexEvent) ||
!TryCommandData(
nexEvent,
"operation_id",
out string operationId))
{
return;
}
PublishOperationState(
"region.control.operation.accepted",
nexEvent,
operationId,
"move",
"accepted");
_ = Task.Run(() =>
{
try
{
if (!TryCommandData(
nexEvent,
"region_id",
out string regionIdRaw) ||
!UUID.TryParse(
regionIdRaw,
out UUID regionId) ||
!TryCommandInt(
nexEvent,
"grid_x",
out int gridX) ||
!TryCommandInt(
nexEvent,
"grid_y",
out int gridY))
{
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
"move",
"invalid_command_payload");
return;
}
NexVerseManagedRegionHostPlugin host =
NexVerseManagedRegionHostPlugin.Current;
if (host == null ||
!host.Enabled)
{
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
"move",
"managed_region_commands_disabled");
return;
}
if (!host.TryMoveRegion(
regionId,
gridX,
gridY,
out string error,
out int oldGridX,
out int oldGridY))
{
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
"move",
error);
return;
}
PublishOperationState(
"region.control.operation.completed",
nexEvent,
operationId,
"move",
"region_moved",
new Dictionary<string, string>
{
["region_id"] =
regionId.ToString(),
["old_grid_x"] =
oldGridX.ToString(),
["old_grid_y"] =
oldGridY.ToString(),
["grid_x"] =
gridX.ToString(),
["grid_y"] =
gridY.ToString()
});
}
catch (Exception e)
{
m_Log.Error(
"[NEX-NODE]: Managed move-region command failed.",
e);
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
"move",
"region_move_unhandled_failure");
}
});
}
private void HandleRegionLifecycleCommand(
NexEvent nexEvent)
{
if (!IsCommandForThisNode(
nexEvent) ||
!TryCommandData(
nexEvent,
"operation_id",
out string operationId) ||
!TryCommandData(
nexEvent,
"action",
out string action))
{
return;
}
action =
action.Trim()
.ToLowerInvariant();
if (action != "start" &&
action != "stop" &&
action != "restart" &&
action != "retire")
{
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
"lifecycle",
"invalid_lifecycle_action");
return;
}
PublishOperationState(
"region.control.operation.accepted",
nexEvent,
operationId,
action,
"accepted");
_ = Task.Run(() =>
{
try
{
if (!TryCommandData(
nexEvent,
"region_id",
out string regionIdRaw) ||
!UUID.TryParse(
regionIdRaw,
out UUID regionId) ||
regionId.IsZero())
{
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
action,
"invalid_command_payload");
return;
}
NexVerseManagedRegionHostPlugin host =
NexVerseManagedRegionHostPlugin.Current;
if (host == null ||
!host.Enabled)
{
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
action,
"managed_region_commands_disabled");
return;
}
bool success;
string error;
string regionName;
switch (action)
{
case "start":
success =
host.TryStartRegion(
regionId,
out error,
out regionName);
break;
case "stop":
success =
host.TryStopRegion(
regionId,
out error,
out regionName);
break;
case "restart":
success =
host.TryRestartRegion(
regionId,
out error,
out regionName);
break;
default:
success =
host.TryRetireRegion(
regionId,
out error,
out regionName);
break;
}
if (!success)
{
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
action,
error);
return;
}
string completedMessage =
action switch
{
"start" => "region_started",
"stop" => "region_stopped",
"restart" => "region_restarted",
_ => "region_retired"
};
PublishOperationState(
"region.control.operation.completed",
nexEvent,
operationId,
action,
completedMessage,
new Dictionary<string, string>
{
["region_id"] =
regionId.ToString(),
["region_name"] =
regionName ?? string.Empty,
["action"] =
action
});
}
catch (Exception e)
{
m_Log.Error(
"[NEX-NODE]: Managed region lifecycle command failed.",
e);
PublishOperationState(
"region.control.operation.failed",
nexEvent,
operationId,
action,
"region_lifecycle_unhandled_failure");
}
});
}
private void HandleIarCommand(NexEvent nexEvent)
{
if (!IsCommandForThisNode(nexEvent)
|| !TryCommandData(nexEvent, "operation_id", out string operationRaw)
|| !UUID.TryParse(operationRaw, out UUID operationId)
|| !TryCommandData(nexEvent, "region_id", out string regionRaw)
|| !UUID.TryParse(regionRaw, out UUID regionId)
|| !TryCommandData(nexEvent, "user_id", out string userRaw)
|| !UUID.TryParse(userRaw, out UUID userId)
|| !TryCommandData(nexEvent, "action", out string action)
|| !TryCommandData(nexEvent, "file_name", out string fileName)
|| !TryCommandData(nexEvent, "inventory_path", out string inventoryPath))
return;
// The shared event bus dispatches handlers synchronously. Native
// ArchiveInventory/AssetService/Get and GZip + WebDAV can take
// minutes; executing them here would block the NexBus POST.
if (Volatile.Read(ref m_Stopping) != 0)
return;
if (Interlocked.Increment(ref m_IarCommandsPending) > MaxPendingIarCommands)
{
Interlocked.Decrement(ref m_IarCommandsPending);
m_Log.WarnFormat("[OGL-IAR]: IAR request {0} rejected: the node's bounded archive queue is full.",
operationId);
PublishIarState(nexEvent, operationId, regionId, action,
"failed", "iar_node_busy", 0, 0);
return;
}
try
{
_ = Task.Run(async () =>
{
bool acquired = false;
try
{
await m_IarCommandSlot.WaitAsync().ConfigureAwait(false);
acquired = true;
if (Volatile.Read(ref m_Stopping) != 0)
return;
ProcessIarCommand(nexEvent, operationId, regionId, userId,
action, fileName, inventoryPath);
}
catch (Exception e)
{
m_Log.Error("[OGL-IAR]: Background IAR command failed for " + operationId + ".", e);
if (Volatile.Read(ref m_Stopping) == 0)
{
try
{
PublishIarState(nexEvent, operationId, regionId, action,
"failed", "iar_worker_failed", 0, 0);
}
catch (Exception report)
{
m_Log.Error("[OGL-IAR]: Could not publish terminal IAR worker failure.", report);
}
}
}
finally
{
if (acquired)
m_IarCommandSlot.Release();
Interlocked.Decrement(ref m_IarCommandsPending);
}
});
}
catch (Exception e)
{
Interlocked.Decrement(ref m_IarCommandsPending);
m_Log.Error("[OGL-IAR]: Could not schedule background IAR command.", e);
PublishIarState(nexEvent, operationId, regionId, action,
"failed", "iar_worker_unavailable", 0, 0);
}
}
private void ProcessIarCommand(NexEvent nexEvent, UUID operationId, UUID regionId,
UUID userId, string action, string fileName, string inventoryPath)
{
if (!m_Scenes.TryGetValue(regionId, out Scene scene))
{
PublishIarState(nexEvent, operationId, regionId, action, "failed", "region_not_loaded", 0, 0);
return;
}
IOglIarOperations operations = scene.RequestModuleInterface<IOglIarOperations>();
UserAccount user = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, userId);
if (operations == null || user == null)
{
PublishIarState(nexEvent, operationId, regionId, action, "failed",
operations == null ? "iar_management_unavailable" : "user_not_found", 0, 0);
return;
}
bool selfService = nexEvent.Data.TryGetValue("self_service", out string self) &&
string.Equals(self, "true", StringComparison.OrdinalIgnoreCase);
bool webdav = selfService &&
nexEvent.Data.TryGetValue("storage_backend", out string storageBackend) &&
string.Equals(storageBackend, "WebDAV", StringComparison.OrdinalIgnoreCase);
string stage = string.Empty;
if (selfService)
{
try
{
if (!nexEvent.Data.TryGetValue("nas_host", out string nasHost) ||
!string.Equals(nasHost, "10.78.0.4", StringComparison.Ordinal) ||
!string.Equals(fileName, operationId.ToString() + ".iar",
StringComparison.OrdinalIgnoreCase))
throw new IOException("Unapproved IAR NAS command.");
if (webdav)
{
if (m_IarWebDav == null)
throw new IOException("IAR WebDAV transport not configured.");
Guid reg = Guid.Parse(regionId.ToString());
Guid id = Guid.Parse(operationId.ToString());
stage = OglIarTransferPolicy.Resolve(
Path.GetDirectoryName(operations.StorageRoot), reg, id);
if (!string.Equals(stage, Path.Combine(operations.StorageRoot, fileName),
StringComparison.OrdinalIgnoreCase))
throw new IOException("IAR WebDAV stage mismatch.");
Directory.CreateDirectory(operations.StorageRoot);
if (string.Equals(action, "import", StringComparison.OrdinalIgnoreCase))
{
if (File.Exists(stage)) throw new IOException("IAR work file already exists.");
m_IarWebDav.Download(reg, id, stage, m_IarWebDavMaximumBytes);
}
}
else if (!nexEvent.Data.TryGetValue("storage_backend", out string backend) ||
string.Equals(backend, "NFS", StringComparison.OrdinalIgnoreCase))
{
OglIarNasStorage.RequireMounted(
Path.GetDirectoryName(operations.StorageRoot), nasHost);
}
else throw new IOException("Unknown IAR backend.");
}
catch (Exception ex) when (ex is IOException or ArgumentException or
UnauthorizedAccessException)
{
// Distinguish missing simulator configuration from a
// reachable WebDAV client failing during transfer or staging.
string reason = webdav && m_IarWebDav == null
? "iar_webdav_not_configured" : "iar_nas_storage_unavailable";
m_Log.Error("[OGL-IAR]: Archive staging failed for operation " +
operationId + ", region " + regionId + ", action " + action +
" (" + reason + ").", ex);
PublishIarState(nexEvent, operationId, regionId, action,
"failed", reason, 0, 0);
return;
}
}
void Changed(OglIarOperation operation)
{
if (operation.RequestId != operationId) return;
string state = operation.State.ToString().ToLowerInvariant();
if (webdav && operation.State is OglIarOperationState.Completed or
OglIarOperationState.Failed)
{
// The simulator's native archiver works on a temporary
// file. Report export success only after PUT to WebDAV.
// A native archiver failure is NOT a WebDAV transfer error.
bool remoteUploadFailed = false;
try
{
if (operation.State == OglIarOperationState.Completed &&
string.Equals(action, "export", StringComparison.OrdinalIgnoreCase))
{
long size = new FileInfo(stage).Length;
m_Log.InfoFormat("[OGL-IAR]: Export {0}: validiertes Archiv ({1} Bytes) wird per WebDAV auf das NAS uebertragen.",
operationId, size);
m_IarWebDav.Upload(Guid.Parse(regionId.ToString()),
Guid.Parse(operationId.ToString()), stage, m_IarWebDavMaximumBytes);
m_Log.InfoFormat("[OGL-IAR]: Export {0}: WebDAV-Upload bestaetigt; Auftrag wird als completed gemeldet.",
operationId);
}
else if (operation.State == OglIarOperationState.Failed)
{
m_Log.WarnFormat("[OGL-IAR]: Export/Import {0}: nativer Archivauftrag fehlgeschlagen: {1}",
operationId, operation.Error);
}
}
catch (Exception e)
{
remoteUploadFailed = true;
state = "failed";
m_Log.Error("[OGL-IAR]: WebDAV export failed.", e);
}
finally
{
try { if (File.Exists(stage)) File.Delete(stage); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{ m_Log.Warn("[OGL-IAR]: Could not delete temporary IAR.", e); }
}
PublishIarState(nexEvent, operationId, regionId, action, state,
remoteUploadFailed ? "iar_webdav_transfer_failed" : operation.Error,
operation.ItemCount, operation.FilteredCount, operation.ProgressPercent, operation.ProgressPhase);
operations.OperationChanged -= Changed;
return;
}
PublishIarState(nexEvent, operationId, regionId, action,
state, operation.Error, operation.ItemCount, operation.FilteredCount,
operation.ProgressPercent, operation.ProgressPhase);
if (operation.State == OglIarOperationState.Completed ||
operation.State == OglIarOperationState.Failed)
operations.OperationChanged -= Changed;
}
operations.OperationChanged += Changed;
try
{
bool dryRun = nexEvent.Data.TryGetValue("dry_run", out string dryRaw) && bool.TryParse(dryRaw, out bool dry) && dry;
bool merge = nexEvent.Data.TryGetValue("merge", out string mergeRaw) && bool.TryParse(mergeRaw, out bool mergeParsed) && mergeParsed;
// Back up the authenticated avatar's complete inventory without a
// Copy/Transfer export filter. Inventory permission masks are
// serialized unchanged; this does not grant additional rights.
OglIarOperation operation = string.Equals(action, "export", StringComparison.OrdinalIgnoreCase)
? operations.StartExport(operationId, user, inventoryPath, fileName)
: string.Equals(action, "import", StringComparison.OrdinalIgnoreCase)
? operations.StartImport(operationId, user, inventoryPath, fileName, merge, dryRun)
: throw new InvalidOperationException("unsupported_iar_action");
// WebDAV completion is published by Changed only AFTER
// the remote upload or local temporary-file cleanup.
if (!webdav || operation.State is not
(OglIarOperationState.Completed or OglIarOperationState.Failed))
PublishIarState(nexEvent, operationId, regionId, action,
operation.State.ToString().ToLowerInvariant(), operation.Error,
operation.ItemCount, operation.FilteredCount,
operation.ProgressPercent, operation.ProgressPhase);
if (operation.State == OglIarOperationState.Completed ||
operation.State == OglIarOperationState.Failed)
operations.OperationChanged -= Changed;
}
catch (Exception e)
{
operations.OperationChanged -= Changed;
if (webdav && File.Exists(stage))
{
try { File.Delete(stage); }
catch (IOException error) { m_Log.Warn("[OGL-IAR]: Could not delete temporary IAR.", error); }
}
PublishIarState(nexEvent, operationId, regionId, action, "failed", e.Message, 0, 0);
}
}
private void PublishIarState(NexEvent source, UUID operationId, UUID regionId, string action, string state, string message, int itemCount, int filteredCount, int progress = 0, string phase = "")
{
Publish(new NexEvent(
"archive.iar.operation." + state,
"opengenesislink.simulator",
new Dictionary<string, string>
{
["operation_id"] = operationId.ToString(),
["node_id"] = m_NodeId,
["region_id"] = regionId.ToString(),
["action"] = action ?? string.Empty,
["state"] = state ?? "unknown",
["message"] = message ?? string.Empty,
["item_count"] = itemCount.ToString(),
["filtered_count"] = filteredCount.ToString(),
["progress"] = progress.ToString(),
["phase"] = phase ?? string.Empty
},
source.CorrelationId));
}
private void HandleOarCommand(NexEvent nexEvent)
{
if (!IsCommandForThisNode(nexEvent)
|| !TryCommandData(nexEvent, "operation_id", out string operationRaw)
|| !Guid.TryParse(operationRaw, out Guid operationId)
|| !TryCommandData(nexEvent, "region_id", out string regionRaw)
|| !UUID.TryParse(regionRaw, out UUID regionId)
|| !TryCommandData(nexEvent, "action", out string action)
|| !TryCommandData(nexEvent, "file_name", out string fileName))
return;
if (!m_Scenes.TryGetValue(regionId, out Scene scene))
{
PublishOarState(nexEvent, operationId, regionId, action, "failed", "region_not_loaded");
return;
}
IOglOarOperations operations = scene.RequestModuleInterface<IOglOarOperations>();
if (operations == null)
{
PublishOarState(nexEvent, operationId, regionId, action, "failed", "oar_management_unavailable");
return;
}
void Changed(OglOarOperation operation)
{
if (operation.RequestId != operationId)
return;
string state = operation.State.ToString().ToLowerInvariant();
PublishOarState(nexEvent, operationId, regionId, action, state, operation.Error, operation.ProgressPercent, operation.ProgressPhase, operation.Inspection);
if (operation.State == OglOarOperationState.Completed || operation.State == OglOarOperationState.Failed)
operations.OperationChanged -= Changed;
}
operations.OperationChanged += Changed;
try
{
bool dryRun = nexEvent.Data.TryGetValue("dry_run", out string dryRaw)
&& bool.TryParse(dryRaw, out bool parsedDry)
&& parsedDry;
OglOarOperation operation = string.Equals(action, "export", StringComparison.OrdinalIgnoreCase)
? operations.StartExport(operationId, fileName)
: string.Equals(action, "import", StringComparison.OrdinalIgnoreCase)
? operations.StartImport(operationId, fileName, dryRun)
: throw new InvalidOperationException("unsupported_oar_action");
PublishOarState(
nexEvent,
operationId,
regionId,
action,
operation.State.ToString().ToLowerInvariant(),
operation.Error, operation.ProgressPercent, operation.ProgressPhase, operation.Inspection);
if (operation.State == OglOarOperationState.Completed || operation.State == OglOarOperationState.Failed)
operations.OperationChanged -= Changed;
}
catch (Exception e)
{
operations.OperationChanged -= Changed;
PublishOarState(nexEvent, operationId, regionId, action, "failed", e.Message);
}
}
private void PublishOarState(
NexEvent source,
Guid operationId,
UUID regionId,
string action,
string state,
string message,
int progress = 0,
string phase = "",
OglOarInspection inspection = null)
{
Dictionary<string, string> data =
new Dictionary<string, string>
{
["operation_id"] = operationId.ToString(),
["node_id"] = m_NodeId,
["region_id"] = regionId.ToString(),
["action"] = action ?? string.Empty,
["state"] = state ?? "unknown",
["message"] = message ?? string.Empty,
["progress"] = progress.ToString(),
["phase"] = phase ?? string.Empty
};
if (inspection != null)
{
data["archive_sha256"] = inspection.Sha256 ?? string.Empty;
data["archive_bytes"] = inspection.SizeBytes.ToString();
data["archive_valid"] = inspection.Valid.ToString();
}
Publish(new NexEvent(
"archive.oar.operation." + state,
"nexverse.simulator",
data,
source.CorrelationId));
}
// Signed NexBus + ROBUST simulators:manage is required on the
// originating endpoint. Never accept a repository URL, path or shell
// command from the event. A node must explicitly opt into staging.
private void HandleStageUpdateCommand(NexEvent request)
{
if (!IsCommandForThisNode(request) ||
!string.Equals(request.Source, "nexverse.robust", StringComparison.Ordinal) ||
!TryCommandData(request, "operation_id", out string operationId) ||
!Guid.TryParse(operationId, out Guid parsedOperationId))
return;
// The NexBus transport secret is shared across peers. Do not trust
// the claimed event Source alone for privileged update commands.
// Require an independent, expiring, ROBUST control-plane HMAC.
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (!TryCommandData(request, "issued_at", out string issuedRaw) ||
!long.TryParse(issuedRaw, System.Globalization.NumberStyles.Integer,
System.Globalization.CultureInfo.InvariantCulture, out long issuedAt) ||
!TryCommandData(request, "approval_hmac", out string approvalHmac) ||
!NexBusProtocol.VerifyNodeStageRequest(m_NodeId, operationId,
issuedAt, m_UpdateControlKey, approvalHmac, now))
{
m_Log.WarnFormat("[OGL UPDATE]: Node {0} ignored an unauthorized or expired stage request.", m_NodeId);
return;
}
foreach (KeyValuePair<string, long> previous in m_NodeUpdateReplay)
{
if (previous.Value < now - 600)
m_NodeUpdateReplay.TryRemove(previous.Key, out _);
}
if (m_NodeUpdateReplay.Count >= 1024 ||
!m_NodeUpdateReplay.TryAdd(parsedOperationId.ToString("D"), now))
{
m_Log.WarnFormat("[OGL UPDATE]: Node {0} rejected a replay or excessive stage requests.", m_NodeId);
return;
}
if (!m_UpdateStagingEnabled || string.IsNullOrWhiteSpace(m_UpdateStagingRoot) ||
!Path.IsPathFullyQualified(m_UpdateStagingRoot))
{
PublishOperationState("node.update.stage.failed", request, operationId,
"stage_update", "node_update_staging_disabled_or_invalid_root");
return;
}
if (Interlocked.CompareExchange(ref m_NodeUpdateRunning, 1, 0) != 0)
{
PublishOperationState("node.update.stage.failed", request, operationId,
"stage_update", "update_already_running");
return;
}
PublishOperationState("node.update.stage.accepted", request, operationId,
"stage_update", "stage_queued");
_ = Task.Run(() =>
{
try
{
// Script comes from the locally deployed, trusted checkout.
// The event cannot modify the script, Git URL, branch or args.
string script = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
"..", "tools", "ops", "ogl-node-stage-update.sh"));
if (!File.Exists(script))
throw new FileNotFoundException("Updater script missing from installed checkout.");
ProcessStartInfo start = new ProcessStartInfo("bash")
{
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = AppContext.BaseDirectory
};
start.ArgumentList.Add(script);
start.ArgumentList.Add(m_UpdateStagingRoot);
start.ArgumentList.Add(AppContext.BaseDirectory);
start.ArgumentList.Add(m_UpdateStagingBuild ? "1" : "0");
using Process process = Process.Start(start);
if (process == null)
throw new InvalidOperationException("Could not launch staging process.");
if (!process.WaitForExit(20 * 60 * 1000))
{
process.Kill(entireProcessTree: true);
process.WaitForExit();
throw new TimeoutException("Staging update exceeded 20-minute limit.");
}
if (process.ExitCode != 0)
throw new InvalidOperationException("Staging command failed with exit code " + process.ExitCode);
PublishOperationState("node.update.stage.completed", request,
operationId, "stage_update", "ready_for_manual_review_no_live_files_changed");
}
catch (Exception e)
{
m_Log.ErrorFormat("[OGL UPDATE]: Node {0} failed staging: {1}",
m_NodeId, e.GetType().Name);
PublishOperationState("node.update.stage.failed", request, operationId,
"stage_update", "stage_failed_check_node_logs");
}
finally
{
Interlocked.Exchange(ref m_NodeUpdateRunning, 0);
PublishHeartbeatSafe();
}
});
}
// This only authorizes a fixed command on the separately supervised
// loopback service. No Git checkout mutations or child processes run in
// the simulator. The independent systemd worker survives the simulator
// being stopped or restarted by the operator.
private void HandleLiveUpdateCommand(NexEvent request)
{
if (!IsCommandForThisNode(request) ||
!string.Equals(request.Source, "nexverse.robust", StringComparison.Ordinal) ||
!TryCommandData(request, "operation_id", out string operationId) ||
!Guid.TryParse(operationId, out Guid parsedOperationId))
return;
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (!TryCommandData(request, "issued_at", out string issuedRaw) ||
!long.TryParse(issuedRaw, System.Globalization.NumberStyles.Integer,
System.Globalization.CultureInfo.InvariantCulture, out long issuedAt) ||
!TryCommandData(request, "approval_hmac", out string approvalHmac) ||
!NexBusProtocol.VerifyNodeLiveRequest(m_NodeId, operationId,
issuedAt, m_UpdateControlKey, approvalHmac, now))
{
m_Log.WarnFormat("[OGL UPDATE]: Node {0} refused unsigned live update.", m_NodeId);
return;
}
foreach (KeyValuePair<string, long> previous in m_NodeUpdateReplay)
{
if (previous.Value < now - 600)
m_NodeUpdateReplay.TryRemove(previous.Key, out _);
}
if (m_NodeUpdateReplay.Count >= 1024 ||
!m_NodeUpdateReplay.TryAdd(parsedOperationId.ToString("D"), now))
return;
// Explicit opt-in, a separate long random localhost secret and a
// literal IPv4 loopback URL are required. No remote update host.
if (!m_LiveUpdaterEnabled ||
System.Text.Encoding.UTF8.GetByteCount(m_LiveUpdaterToken) < 32 ||
!Uri.TryCreate(m_LiveUpdaterUrl, UriKind.Absolute, out Uri updater) ||
updater.Scheme != Uri.UriSchemeHttp ||
updater.Host != "127.0.0.1" ||
updater.UserInfo.Length > 0 ||
updater.AbsolutePath != "/" ||
!string.IsNullOrEmpty(updater.Query) ||
!string.IsNullOrEmpty(updater.Fragment))
{
PublishOperationState("node.update.live.failed", request,
operationId, "update", "standalone_updater_not_configured");
return;
}
if (Interlocked.CompareExchange(ref m_NodeUpdateRunning, 1, 0) != 0)
{
PublishOperationState("node.update.live.failed", request,
operationId, "update", "node_update_already_in_progress");
return;
}
PublishOperationState("node.update.live.accepted", request,
operationId, "update", "standalone_updater_requested");
_ = Task.Run(async () =>
{
try
{
using HttpClient client = new HttpClient
{
Timeout = TimeSpan.FromSeconds(15)
};
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer", m_LiveUpdaterToken);
string baseUrl = updater.GetLeftPart(UriPartial.Authority);
string body = JsonSerializer.Serialize(new
{
node_id = m_NodeId,
operation_id = parsedOperationId.ToString("D")
});
using HttpResponseMessage started = await client.PostAsync(
baseUrl + "/v1/updates",
new StringContent(body, Encoding.UTF8, "application/json"))
.ConfigureAwait(false);
if (started.StatusCode != HttpStatusCode.Accepted &&
started.StatusCode != HttpStatusCode.OK)
throw new InvalidOperationException("Update service refused request: " +
(int)started.StatusCode);
// Poll the independent process; restarting the simulator
// does not stop the updater, only progress forwarding.
int lastPhase = -1;
for (int attempt = 0; attempt < 240; attempt++)
{
await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
using HttpResponseMessage status = await client.GetAsync(
baseUrl + "/v1/status").ConfigureAwait(false);
if (!status.IsSuccessStatusCode)
throw new IOException("Update supervisor status unavailable.");
string json = await status.Content.ReadAsStringAsync().ConfigureAwait(false);
using JsonDocument result = JsonDocument.Parse(json);
JsonElement root = result.RootElement;
if (!root.TryGetProperty("operation_id", out JsonElement op) ||
op.GetString() != parsedOperationId.ToString("D") ||
!root.TryGetProperty("node_id", out JsonElement node) ||
node.GetString() != m_NodeId ||
!root.TryGetProperty("state", out JsonElement state))
throw new InvalidOperationException("Update status belongs to another node/operation.");
string stateValue = state.GetString() ?? "unknown";
int phase = root.TryGetProperty("phase", out JsonElement progress) &&
progress.TryGetInt32(out int numeric) ? numeric : 0;
if ((stateValue == "running" || stateValue == "queued") &&
phase != lastPhase)
{
lastPhase = phase;
PublishOperationState("node.update.live.running", request,
operationId, "update", "build_step_" + phase);
}
if (stateValue == "completed")
{
PublishOperationState("node.update.live.completed", request,
operationId, "update", "manual_opensim_restart_required");
return;
}
if (stateValue == "failed" || stateValue == "interrupted")
{
PublishOperationState("node.update.live.failed", request,
operationId, "update", "update_failed_review_local_supervisor_log");
return;
}
}
throw new TimeoutException("Live update status polling exceeded 40 minutes.");
}
catch (Exception e)
{
m_Log.ErrorFormat("[OGL UPDATE]: Node {0} live update tracking failed: {1}",
m_NodeId, e.GetType().Name);
PublishOperationState("node.update.live.failed", request,
operationId, "update", "update_status_unknown_check_standalone_service");
}
finally
{
Interlocked.Exchange(ref m_NodeUpdateRunning, 0);
PublishHeartbeatSafe();
}
});
}
private void HandleNodeControlCommand(NexEvent nexEvent)
{
if (!IsCommandForThisNode(nexEvent) ||
!TryCommandData(nexEvent, "action", out string action))
return;
action = action.Trim().ToLowerInvariant();
bool accepted = true;
switch (action)
{
case "maintenance_on":
m_MaintenanceMode = true;
break;
case "maintenance_off":
m_MaintenanceMode = false;
break;
case "drain":
m_Draining = true;
m_MaintenanceMode = true;
break;
case "resume":
m_Draining = false;
m_MaintenanceMode = false;
break;
default:
accepted = false;
break;
}
Publish(new NexEvent(
accepted ? "node.control.completed" : "node.control.failed",
"nexverse.simulator",
new Dictionary<string, string>
{
["node_id"] = m_NodeId,
["action"] = action,
["maintenance_mode"] = m_MaintenanceMode.ToString(),
["draining"] = m_Draining.ToString(),
["message"] = accepted ? "node_control_applied" : "invalid_node_control_action"
}));
PublishHeartbeatSafe();
}
private bool IsCommandForThisNode(
NexEvent nexEvent)
{
return
TryCommandData(
nexEvent,
"target_node_id",
out string targetNodeId) &&
string.Equals(
targetNodeId,
m_NodeId,
StringComparison.OrdinalIgnoreCase);
}
private static bool TryCommandData(
NexEvent nexEvent,
string key,
out string value)
{
value = string.Empty;
if (nexEvent?.Data == null ||
!nexEvent.Data.TryGetValue(
key,
out string raw) ||
string.IsNullOrWhiteSpace(raw))
{
return false;
}
value = raw.Trim();
return true;
}
private static bool TryCommandInt(
NexEvent nexEvent,
string key,
out int value)
{
value = 0;
return
TryCommandData(
nexEvent,
key,
out string raw) &&
int.TryParse(
raw,
System.Globalization.NumberStyles.Integer,
System.Globalization.CultureInfo.InvariantCulture,
out value);
}
private void PublishOperationState(
string eventName,
NexEvent request,
string operationId,
string operation,
string message,
IReadOnlyDictionary<string, string> additional = null)
{
Dictionary<string, string> data =
new Dictionary<string, string>
{
["operation_id"] =
operationId ?? string.Empty,
["operation"] =
operation ?? string.Empty,
["node_id"] =
m_NodeId,
["message"] =
message ?? string.Empty
};
if (request?.Data != null &&
request.Data.TryGetValue(
"region_id",
out string requestedRegionId) &&
requestedRegionId != null)
{
data["region_id"] =
requestedRegionId;
}
if (additional != null)
{
foreach (KeyValuePair<string, string> item in additional)
data[item.Key] = item.Value ?? string.Empty;
}
Publish(new NexEvent(
eventName,
"nexverse.simulator",
data,
request?.CorrelationId));
}
private void HandleInbound(
IOSHttpRequest request,
IOSHttpResponse response)
{
response.KeepAlive = false;
response.ContentType = "application/json; charset=utf-8";
if (Volatile.Read(ref m_Stopping) != 0 || !m_Enabled)
{
WriteInbound(response, HttpStatusCode.ServiceUnavailable,
new { error = "node_shutting_down" });
return;
}
if (request == null ||
!string.Equals(
request.HttpMethod,
"POST",
StringComparison.OrdinalIgnoreCase))
{
WriteInbound(
response,
HttpStatusCode.MethodNotAllowed,
new { error = "method_not_allowed" });
return;
}
byte[] payload;
using (MemoryStream buffer = new MemoryStream())
{
request.InputStream.CopyTo(buffer);
payload = buffer.ToArray();
}
if (payload.Length == 0 || payload.Length > 1024 * 1024)
{
WriteInbound(
response,
HttpStatusCode.BadRequest,
new { error = "invalid_event_payload" });
return;
}
if (!NexBusProtocol.Verify(
payload,
m_SharedKey,
request.Headers?["X-NexBus-Signature"]))
{
WriteInbound(
response,
HttpStatusCode.Unauthorized,
new { error = "invalid_signature" });
return;
}
NexEvent nexEvent;
try
{
nexEvent = NexBusProtocol.Deserialize(payload);
}
catch (Exception e)
{
m_Log.Warn(
"[NEX-NODE]: Eingehendes NexBus-Ereignis konnte nicht dekodiert werden.",
e);
WriteInbound(
response,
HttpStatusCode.BadRequest,
new { error = "invalid_event" });
return;
}
try
{
// Close() may race with a validated, in-flight HTTP request.
// Snapshot and guard the bus; still handle disposal after the check.
DistributedNexEventBus bus = m_Bus;
if (Volatile.Read(ref m_Stopping) != 0 || bus == null)
{
WriteInbound(response, HttpStatusCode.ServiceUnavailable,
new { error = "node_shutting_down" });
return;
}
bool accepted = bus.Receive(nexEvent);
WriteInbound(
response,
HttpStatusCode.Accepted,
new
{
accepted,
event_id = nexEvent.EventId
});
}
catch (ObjectDisposedException)
{
// Expected for requests already authenticated when teardown begins.
WriteInbound(response, HttpStatusCode.ServiceUnavailable,
new { error = "node_shutting_down" });
}
catch (Exception e)
{
m_Log.Error(
$"[NEX-NODE]: NexBus-Ereignis {nexEvent.EventId} ({nexEvent.Name}) konnte nicht verarbeitet werden.",
e);
WriteInbound(
response,
HttpStatusCode.InternalServerError,
new { error = "event_processing_failed" });
}
}
private static void WriteInbound(
IOSHttpResponse response,
HttpStatusCode status,
object payload)
{
response.StatusCode = (int)status;
response.RawBuffer = JsonSerializer.SerializeToUtf8Bytes(payload);
}
private sealed class ObjectMessageRateState
{
public object SyncRoot { get; } =
new object();
public long WindowSecond;
public long LastSeenSecond;
public int Count;
}
private sealed class SimulatorNexEventTransport : INexEventTransport
{
private readonly string m_NodeId;
private readonly Uri m_Peer;
private readonly string m_SharedKey;
private readonly BlockingCollection<NexEvent> m_Queue;
private readonly CancellationTokenSource m_Cancellation =
new CancellationTokenSource();
private readonly HttpClient m_Client;
private readonly Task m_Worker;
private int m_Disposed;
public SimulatorNexEventTransport(
string nodeId,
Uri peer,
string sharedKey,
int queueCapacity,
int requestTimeoutMilliseconds)
{
m_NodeId = nodeId;
m_Peer = peer;
m_SharedKey = sharedKey;
m_Queue = new BlockingCollection<NexEvent>(
new ConcurrentQueue<NexEvent>(),
queueCapacity);
m_Client = new HttpClient
{
Timeout = TimeSpan.FromMilliseconds(requestTimeoutMilliseconds)
};
m_Worker = Task.Run(WorkerLoop);
}
public void Send(NexEvent nexEvent)
{
if (nexEvent == null ||
Volatile.Read(ref m_Disposed) != 0)
return;
if (!m_Queue.TryAdd(nexEvent))
{
m_Log.WarnFormat(
"[NEX-NODE]: Outbound NexBus queue full; dropping {0} {1}",
nexEvent.EventId,
nexEvent.Name);
}
}
private void WorkerLoop()
{
try
{
foreach (NexEvent nexEvent in
m_Queue.GetConsumingEnumerable(m_Cancellation.Token))
{
SendOne(nexEvent);
}
}
catch (OperationCanceledException)
{
}
}
private void SendOne(NexEvent nexEvent)
{
byte[] payload = NexBusProtocol.Serialize(nexEvent);
string signature = NexBusProtocol.Sign(payload, m_SharedKey);
try
{
using HttpRequestMessage request =
new HttpRequestMessage(HttpMethod.Post, m_Peer);
request.Headers.TryAddWithoutValidation(
"X-NexBus-Node",
m_NodeId);
request.Headers.TryAddWithoutValidation(
"X-NexBus-Schema",
NexVerse.Core.NexVersePlatform.NexBusSchemaVersion);
request.Headers.TryAddWithoutValidation(
"X-NexBus-Signature",
"sha256=" + signature);
request.Content = new ByteArrayContent(payload);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
using HttpResponseMessage response = m_Client.Send(
request,
HttpCompletionOption.ResponseHeadersRead,
m_Cancellation.Token);
if (!response.IsSuccessStatusCode)
{
m_Log.WarnFormat(
"[NEX-NODE]: NexBus peer rejected {0} with HTTP {1}",
nexEvent.EventId,
(int)response.StatusCode);
}
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
m_Log.WarnFormat(
"[NEX-NODE]: NexBus delivery failed for {0}: {1}",
nexEvent.EventId,
e.Message);
}
}
public void Dispose()
{
if (Interlocked.Exchange(ref m_Disposed, 1) != 0)
return;
m_Queue.CompleteAdding();
m_Cancellation.Cancel();
try
{
m_Worker.Wait(TimeSpan.FromSeconds(2));
}
catch
{
}
m_Client.Dispose();
m_Cancellation.Dispose();
m_Queue.Dispose();
}
}
}
}