From 18a1bdbaef772f8c0fb954603ecb20570daf16f3 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:36:15 +0100 Subject: [PATCH 1/3] Add ApproximateProcessMemoryUsage --- Source.Common/Platform.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Source.Common/Platform.cs b/Source.Common/Platform.cs index ee06a8f7..3d732fc6 100644 --- a/Source.Common/Platform.cs +++ b/Source.Common/Platform.cs @@ -44,6 +44,22 @@ public const bool IsPosix public static double Time => __timer.Value.Elapsed.TotalSeconds; public static double MSTime => __timer.Value.Elapsed.TotalMilliseconds; + public static ulong ApproximateProcessMemoryUsage() { +#if POSIX + try { + ReadOnlySpan statm = File.ReadAllText("/proc/self/statm").AsSpan().TrimStart(); + int end = statm.IndexOfAny(' ', '\t'); + if (ulong.TryParse(end < 0 ? statm : statm[..end], out ulong size)) + return 4096 * size; + } + catch (IOException) { + } + catch (UnauthorizedAccessException) { + } +#endif + return 0; + } + #if WIN32 [DllImport("kernel32.dll")] unsafe static extern void OutputDebugStringW(char* lpOutputString); From 38d5f0e68b8efca9ef408726b844b3ae46439478 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:36:16 +0100 Subject: [PATCH 2/3] Port server hibernation and sv_shutdown --- Game.Server/GameInterface.cs | 4 +- Source.Engine/SV.cs | 50 ++++++++++++++++++---- Source.Engine/Server/BaseClient.cs | 1 + Source.Engine/Server/GameServer.cs | 67 ++++++++++++++++++++++++++++-- 4 files changed, 110 insertions(+), 12 deletions(-) diff --git a/Game.Server/GameInterface.cs b/Game.Server/GameInterface.cs index 8edc76cc..97243ba5 100644 --- a/Game.Server/GameInterface.cs +++ b/Game.Server/GameInterface.cs @@ -649,8 +649,10 @@ public void ServerActivate(Edict[] pEdictList, int edictCount, int clientMax) { // todo nextbots } + bool IsHibernating; + public void SetServerHibernation(bool bHibernating) { - throw new NotImplementedException(); + IsHibernating = bHibernating; } public bool ShouldHideServer() => false; diff --git a/Source.Engine/SV.cs b/Source.Engine/SV.cs index 85bcdb1c..fac83e38 100644 --- a/Source.Engine/SV.cs +++ b/Source.Engine/SV.cs @@ -428,7 +428,18 @@ private void CreateBaseline() { // gameEventManager.WriteEventList(&gameevents); gameevents.WriteToBuffer(sv.Signon); } - public bool HasPlayers() => sv.GetClientCount() > 0; + public bool HasPlayers() { +#if GMOD_DLL + for (int i = 0; i < sv.GetClientCount(); i++) { + if (sv.Client(i).IsConnected()) + return true; + } + + return false; +#else + return sv.GetClientCount() > 0; +#endif + } public bool IsSimulating() { if (sv.IsPaused()) @@ -459,7 +470,11 @@ internal void Frame(bool finalTick) { sv.RunFrame(); bool simulated = false; +#if GMOD_DLL + if (HasPlayers() || sv.sv_hibernate_think.GetBool()) { +#else if (HasPlayers()) { +#endif bool serverCanSimulate = true; // TODO: Restoring if (serverCanSimulate && (isSimulating || sendDuringPause)) { @@ -503,8 +518,34 @@ private void PreClientUpdate(bool isSimulating) { ServerGameDLL?.PreClientUpdate(isSimulating); } + public static readonly ConVar sv_shutdown_timeout_minutes = new("sv_shutdown_timeout_minutes", "360", FCvar.Replicated, "If sv_shutdown is pending, wait at most N minutes for server to drain before forcing shutdown."); + public static readonly ConVar sv_memlimit = new("sv_memlimit", "0", FCvar.Cheat, "If set, whenever the server is empty, if the total memory used by the server is greater than this # of megabytes, the server will exit."); + + public bool ExitWhenEmpty; public double TimeForceShutdown; + [ConCommand(helpText: "Sets the server to shutdown next time it's empty")] + void sv_shutdown() { + ExitWhenEmpty = true; + Warning("sv_shutdown command received.\n"); + + double timeCurrent = Platform.Time; + if (sv.IsHibernating()) { + Warning("Server is hibernating. Shutting down right now\n"); + TimeForceShutdown = timeCurrent + 5.0; + HostState.Shutdown(); + } + else { + if (TimeForceShutdown == 0.0 && sv_shutdown_timeout_minutes.GetInt() > 0) + TimeForceShutdown = timeCurrent + sv_shutdown_timeout_minutes.GetInt() * 60.0; + + if (TimeForceShutdown > 0.0) + Warning($"Server will shut down in {(int)(TimeForceShutdown - timeCurrent)} seconds, or when it becomes empty.\n"); + else + Warning("Server will shut down when it becomes empty.\n"); + } + } + public static ServerClass? FindServerClass(ReadOnlySpan name) { ServerClass? cur = serverGameDLL.GetAllServerClasses(); while (cur != null) { @@ -532,13 +573,6 @@ private void PreClientUpdate(bool isSimulating) { private void Think(bool isSimulating) { sv.UpdateHibernationState(); - if (TimeForceShutdown > 0.0) { - if (TimeForceShutdown < Platform.Time) { - Warning("Server shutting down because sv_shutdown was requested and timeout has expired.\n"); - HostState.Shutdown(); - } - } - serverGlobalVariables.TickCount = sv.TickCount; serverGlobalVariables.CurTime = sv.GetTime(); serverGlobalVariables.FrameTime = isSimulating ? host_state.IntervalPerTick : 0; diff --git a/Source.Engine/Server/BaseClient.cs b/Source.Engine/Server/BaseClient.cs index 80cf829e..5699466a 100644 --- a/Source.Engine/Server/BaseClient.cs +++ b/Source.Engine/Server/BaseClient.cs @@ -831,6 +831,7 @@ public virtual void Disconnect(ReadOnlySpan str) { public bool IsSpawned() => SignOnState >= SignOnState.New; public bool IsFakeClient() => FakePlayer; public bool IsHLTV() => HLTV; + public virtual bool IsSplitScreenUser() => false; public bool SendNetMsg(INetMessage msg, bool forceReliable = false) { if (NetChannel == null) diff --git a/Source.Engine/Server/GameServer.cs b/Source.Engine/Server/GameServer.cs index 05442e42..9116bba2 100644 --- a/Source.Engine/Server/GameServer.cs +++ b/Source.Engine/Server/GameServer.cs @@ -21,7 +21,7 @@ public class GameServer : BaseServer { #if GMOD_DLL readonly ConVar sv_startup_time = new("sv_startup_time", "0", 0, "Sets the starting CurTime of the server (in seconds). This is used for finding issues on a server that has been running for a long time. You don't need to change this."); - readonly ConVar sv_hibernate_think = new("sv_hibernate_think", "0", 0, "Forces the server to think even when hibernating"); + internal readonly ConVar sv_hibernate_think = new("sv_hibernate_think", "0", 0, "Forces the server to think even when hibernating"); readonly ConVar sv_hibernate_drop_bots = new("sv_hibernate_drop_bots", "1", 0, "Kicks bots when the server enters hibernation"); #endif protected readonly ED ED = Singleton(); @@ -361,7 +361,23 @@ public void DumpPrecacheStats(INetworkStringTable? table) { public bool IsHibernating() => Hibernating; public void UpdateHibernationState() { - // todo + if (!IsDedicated() || State == ServerState.Dead) + return; + + bool haveAnyClients = false; + + for (int i = 0; i < Clients.Count; i++) { + BaseClient client = Clients[i]; + if (client.IsConnected() && (client.IsSplitScreenUser() || !client.IsFakeClient())) { + haveAnyClients = true; + break; + } + } + + // todo: serverGameDLL.GetServerGCLobby()?.ShouldHibernate(), it needs IServerGCLobby ported first + bool hibernateFromGCServer = true; + + SetHibernating(hibernateFromGCServer && !haveAnyClients); } @@ -373,7 +389,52 @@ public void UpdateHibernationState() { public GameClient Client(int i) => (GameClient)Clients[i]; private void SetHibernating(bool hibernating) { - // todo + if (Hibernating == hibernating) + return; + + Hibernating = hibernating; + + if (Hibernating) { +#if GMOD_DLL + if (sv_hibernate_drop_bots.GetBool()) +#endif + { + for (int i = 0; i < Clients.Count; i++) { + BaseClient client = Clients[i]; + if (client.IsFakeClient() && client.IsConnected() && !client.IsSplitScreenUser() && !client.IsHLTV()) + client.Disconnect("Punting bot, server is hibernating"); + } + } + + SetPaused(false); + + bool exit = false; + if (SV.ExitWhenEmpty) { + exit = true; + Warning("Server shutting down because sv_shutdown was requested and a server is empty.\n"); + } + else if (SV.TimeForceShutdown > 0.0 && Platform.Time > SV.TimeForceShutdown) { + exit = true; + Warning("Server shutting down because sv_shutdown was requested and timeout has expired.\n"); + } + else { + int memlimit = SV.sv_memlimit.GetInt(); + if (memlimit != 0) { + ulong usage = Platform.ApproximateProcessMemoryUsage(); + if (usage > (ulong)memlimit << 20) { + Warning($"Server shutting down because of using {usage >> 20}MB with an sv_memory_limit of {memlimit}MB\n"); + exit = true; + } + } + } + + if (exit) + Singleton().Shutdown(); + } + + serverGameDLL.SetServerHibernation(Hibernating); + + Steam3Server().SendUpdatedServerDetails(); } internal void InitMaxClients() { From cf0d5938c6cac7016faf213add6e598e76213587 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:44:20 +0100 Subject: [PATCH 3/3] Port IServerGCLobby --- Game.Server/GameInterface.cs | 2 ++ Source.Common/Server/IServerGameDLL.cs | 10 ++++++++++ Source.Engine/Server/BaseServer.cs | 11 ++++++++++- Source.Engine/Server/GameServer.cs | 5 +++-- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/Game.Server/GameInterface.cs b/Game.Server/GameInterface.cs index 97243ba5..e3c8af26 100644 --- a/Game.Server/GameInterface.cs +++ b/Game.Server/GameInterface.cs @@ -655,6 +655,8 @@ public void SetServerHibernation(bool bHibernating) { IsHibernating = bHibernating; } + public IServerGCLobby? GetServerGCLobby() => null; + public bool ShouldHideServer() => false; public void Think(bool finalTick) { diff --git a/Source.Common/Server/IServerGameDLL.cs b/Source.Common/Server/IServerGameDLL.cs index 5d317fd2..d44cddba 100644 --- a/Source.Common/Server/IServerGameDLL.cs +++ b/Source.Common/Server/IServerGameDLL.cs @@ -102,6 +102,8 @@ bool LevelInit(ReadOnlySpan pMapName, void SetServerHibernation(bool bHibernating); + IServerGCLobby? GetServerGCLobby(); + // Return override string to show in the server browser // "map" column, or NULL to just use the default value // (the map name) @@ -162,3 +164,11 @@ public interface IServerGameClients void GMOD_ClientConnected(int userID); void GMOD_SentClientStringTables(int userID); } + +public interface IServerGCLobby +{ + bool HasLobby(); + bool SteamIDAllowedToConnect(in CSteamID steamId); + void UpdateServerDetails(); + bool ShouldHibernate(); +} diff --git a/Source.Engine/Server/BaseServer.cs b/Source.Engine/Server/BaseServer.cs index 0305e564..4593c275 100644 --- a/Source.Engine/Server/BaseServer.cs +++ b/Source.Engine/Server/BaseServer.cs @@ -1332,7 +1332,16 @@ protected virtual bool CheckChallengeType(BaseClient client, int nNewUserID, Net return false; } - // Matchmaking + IServerGCLobby? lobby = serverGameDLL.GetServerGCLobby(); + if (lobby != null) { + if (!lobby.SteamIDAllowedToConnect(client.SteamID)) { + ISteamGameServer? steamGameServer = Steam3Server().SteamGameServer(); + steamGameServer?.SendUserDisconnect_DEPRECATED(client.SteamID); + + RejectConnection(adr, clientChallenge, "#GameUI_ServerRejectMustUseMatchmaking"); + return false; + } + } } else { if (!Steam3Server().NotifyLocalClientConnect(client)) { diff --git a/Source.Engine/Server/GameServer.cs b/Source.Engine/Server/GameServer.cs index 9116bba2..61bd4aa3 100644 --- a/Source.Engine/Server/GameServer.cs +++ b/Source.Engine/Server/GameServer.cs @@ -5,6 +5,7 @@ using Source.Common.Filesystem; using Source.Common.Formats.BSP; using Source.Common.Networking; +using Source.Common.Server; using Source.Common.Utilities; using System.Runtime.InteropServices; @@ -374,8 +375,8 @@ public void UpdateHibernationState() { } } - // todo: serverGameDLL.GetServerGCLobby()?.ShouldHibernate(), it needs IServerGCLobby ported first - bool hibernateFromGCServer = true; + IServerGCLobby? lobby = serverGameDLL.GetServerGCLobby(); + bool hibernateFromGCServer = lobby == null || lobby.ShouldHibernate(); SetHibernating(hibernateFromGCServer && !haveAnyClients); }