Skip to content

Commit d31372e

Browse files
authored
Merge pull request #277 from spacevx/feat/server-hibernation
Introduce sv_hibernate_think & sv_shutdown
2 parents 478e159 + cf0d593 commit d31372e

7 files changed

Lines changed: 149 additions & 13 deletions

File tree

‎Game.Server/GameInterface.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -649,10 +649,14 @@ public void ServerActivate(Edict[] pEdictList, int edictCount, int clientMax) {
649649
// todo nextbots
650650
}
651651

652+
bool IsHibernating;
653+
652654
public void SetServerHibernation(bool bHibernating) {
653-
throw new NotImplementedException();
655+
IsHibernating = bHibernating;
654656
}
655657

658+
public IServerGCLobby? GetServerGCLobby() => null;
659+
656660
public bool ShouldHideServer() => false;
657661

658662
public void Think(bool finalTick) {

‎Source.Common/Platform.cs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,22 @@ public const bool IsPosix
4444
public static double Time => __timer.Value.Elapsed.TotalSeconds;
4545
public static double MSTime => __timer.Value.Elapsed.TotalMilliseconds;
4646

47+
public static ulong ApproximateProcessMemoryUsage() {
48+
#if POSIX
49+
try {
50+
ReadOnlySpan<char> statm = File.ReadAllText("/proc/self/statm").AsSpan().TrimStart();
51+
int end = statm.IndexOfAny(' ', '\t');
52+
if (ulong.TryParse(end < 0 ? statm : statm[..end], out ulong size))
53+
return 4096 * size;
54+
}
55+
catch (IOException) {
56+
}
57+
catch (UnauthorizedAccessException) {
58+
}
59+
#endif
60+
return 0;
61+
}
62+
4763
#if WIN32
4864
[DllImport("kernel32.dll")]
4965
unsafe static extern void OutputDebugStringW(char* lpOutputString);

‎Source.Common/Server/IServerGameDLL.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ bool LevelInit(ReadOnlySpan<char> pMapName,
102102

103103
void SetServerHibernation(bool bHibernating);
104104

105+
IServerGCLobby? GetServerGCLobby();
106+
105107
// Return override string to show in the server browser
106108
// "map" column, or NULL to just use the default value
107109
// (the map name)
@@ -162,3 +164,11 @@ public interface IServerGameClients
162164
void GMOD_ClientConnected(int userID);
163165
void GMOD_SentClientStringTables(int userID);
164166
}
167+
168+
public interface IServerGCLobby
169+
{
170+
bool HasLobby();
171+
bool SteamIDAllowedToConnect(in CSteamID steamId);
172+
void UpdateServerDetails();
173+
bool ShouldHibernate();
174+
}

‎Source.Engine/SV.cs‎

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,18 @@ private void CreateBaseline() {
428428
// gameEventManager.WriteEventList(&gameevents);
429429
gameevents.WriteToBuffer(sv.Signon);
430430
}
431-
public bool HasPlayers() => sv.GetClientCount() > 0;
431+
public bool HasPlayers() {
432+
#if GMOD_DLL
433+
for (int i = 0; i < sv.GetClientCount(); i++) {
434+
if (sv.Client(i).IsConnected())
435+
return true;
436+
}
437+
438+
return false;
439+
#else
440+
return sv.GetClientCount() > 0;
441+
#endif
442+
}
432443

433444
public bool IsSimulating() {
434445
if (sv.IsPaused())
@@ -459,7 +470,11 @@ internal void Frame(bool finalTick) {
459470
sv.RunFrame();
460471

461472
bool simulated = false;
473+
#if GMOD_DLL
474+
if (HasPlayers() || sv.sv_hibernate_think.GetBool()) {
475+
#else
462476
if (HasPlayers()) {
477+
#endif
463478
bool serverCanSimulate = true; // TODO: Restoring
464479

465480
if (serverCanSimulate && (isSimulating || sendDuringPause)) {
@@ -503,8 +518,34 @@ private void PreClientUpdate(bool isSimulating) {
503518
ServerGameDLL?.PreClientUpdate(isSimulating);
504519
}
505520

521+
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.");
522+
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.");
523+
524+
public bool ExitWhenEmpty;
506525
public double TimeForceShutdown;
507526

527+
[ConCommand(helpText: "Sets the server to shutdown next time it's empty")]
528+
void sv_shutdown() {
529+
ExitWhenEmpty = true;
530+
Warning("sv_shutdown command received.\n");
531+
532+
double timeCurrent = Platform.Time;
533+
if (sv.IsHibernating()) {
534+
Warning("Server is hibernating. Shutting down right now\n");
535+
TimeForceShutdown = timeCurrent + 5.0;
536+
HostState.Shutdown();
537+
}
538+
else {
539+
if (TimeForceShutdown == 0.0 && sv_shutdown_timeout_minutes.GetInt() > 0)
540+
TimeForceShutdown = timeCurrent + sv_shutdown_timeout_minutes.GetInt() * 60.0;
541+
542+
if (TimeForceShutdown > 0.0)
543+
Warning($"Server will shut down in {(int)(TimeForceShutdown - timeCurrent)} seconds, or when it becomes empty.\n");
544+
else
545+
Warning("Server will shut down when it becomes empty.\n");
546+
}
547+
}
548+
508549
public static ServerClass? FindServerClass(ReadOnlySpan<char> name) {
509550
ServerClass? cur = serverGameDLL.GetAllServerClasses();
510551
while (cur != null) {
@@ -532,13 +573,6 @@ private void PreClientUpdate(bool isSimulating) {
532573
private void Think(bool isSimulating) {
533574
sv.UpdateHibernationState();
534575

535-
if (TimeForceShutdown > 0.0) {
536-
if (TimeForceShutdown < Platform.Time) {
537-
Warning("Server shutting down because sv_shutdown was requested and timeout has expired.\n");
538-
HostState.Shutdown();
539-
}
540-
}
541-
542576
serverGlobalVariables.TickCount = sv.TickCount;
543577
serverGlobalVariables.CurTime = sv.GetTime();
544578
serverGlobalVariables.FrameTime = isSimulating ? host_state.IntervalPerTick : 0;

‎Source.Engine/Server/BaseClient.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -831,6 +831,7 @@ public virtual void Disconnect(ReadOnlySpan<char> str) {
831831
public bool IsSpawned() => SignOnState >= SignOnState.New;
832832
public bool IsFakeClient() => FakePlayer;
833833
public bool IsHLTV() => HLTV;
834+
public virtual bool IsSplitScreenUser() => false;
834835

835836
public bool SendNetMsg(INetMessage msg, bool forceReliable = false) {
836837
if (NetChannel == null)

‎Source.Engine/Server/BaseServer.cs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1332,7 +1332,16 @@ protected virtual bool CheckChallengeType(BaseClient client, int nNewUserID, Net
13321332
return false;
13331333
}
13341334

1335-
// Matchmaking
1335+
IServerGCLobby? lobby = serverGameDLL.GetServerGCLobby();
1336+
if (lobby != null) {
1337+
if (!lobby.SteamIDAllowedToConnect(client.SteamID)) {
1338+
ISteamGameServer? steamGameServer = Steam3Server().SteamGameServer();
1339+
steamGameServer?.SendUserDisconnect_DEPRECATED(client.SteamID);
1340+
1341+
RejectConnection(adr, clientChallenge, "#GameUI_ServerRejectMustUseMatchmaking");
1342+
return false;
1343+
}
1344+
}
13361345
}
13371346
else {
13381347
if (!Steam3Server().NotifyLocalClientConnect(client)) {

‎Source.Engine/Server/GameServer.cs‎

Lines changed: 65 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using Source.Common.Filesystem;
66
using Source.Common.Formats.BSP;
77
using Source.Common.Networking;
8+
using Source.Common.Server;
89
using Source.Common.Utilities;
910

1011
using System.Runtime.InteropServices;
@@ -21,7 +22,7 @@ public class GameServer : BaseServer
2122
{
2223
#if GMOD_DLL
2324
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.");
24-
readonly ConVar sv_hibernate_think = new("sv_hibernate_think", "0", 0, "Forces the server to think even when hibernating");
25+
internal readonly ConVar sv_hibernate_think = new("sv_hibernate_think", "0", 0, "Forces the server to think even when hibernating");
2526
readonly ConVar sv_hibernate_drop_bots = new("sv_hibernate_drop_bots", "1", 0, "Kicks bots when the server enters hibernation");
2627
#endif
2728
protected readonly ED ED = Singleton<ED>();
@@ -385,7 +386,23 @@ public void DumpPrecacheStats(INetworkStringTable? table) {
385386

386387
public bool IsHibernating() => Hibernating;
387388
public void UpdateHibernationState() {
388-
// todo
389+
if (!IsDedicated() || State == ServerState.Dead)
390+
return;
391+
392+
bool haveAnyClients = false;
393+
394+
for (int i = 0; i < Clients.Count; i++) {
395+
BaseClient client = Clients[i];
396+
if (client.IsConnected() && (client.IsSplitScreenUser() || !client.IsFakeClient())) {
397+
haveAnyClients = true;
398+
break;
399+
}
400+
}
401+
402+
IServerGCLobby? lobby = serverGameDLL.GetServerGCLobby();
403+
bool hibernateFromGCServer = lobby == null || lobby.ShouldHibernate();
404+
405+
SetHibernating(hibernateFromGCServer && !haveAnyClients);
389406
}
390407

391408

@@ -397,7 +414,52 @@ public void UpdateHibernationState() {
397414
public GameClient Client(int i) => (GameClient)Clients[i];
398415

399416
private void SetHibernating(bool hibernating) {
400-
// todo
417+
if (Hibernating == hibernating)
418+
return;
419+
420+
Hibernating = hibernating;
421+
422+
if (Hibernating) {
423+
#if GMOD_DLL
424+
if (sv_hibernate_drop_bots.GetBool())
425+
#endif
426+
{
427+
for (int i = 0; i < Clients.Count; i++) {
428+
BaseClient client = Clients[i];
429+
if (client.IsFakeClient() && client.IsConnected() && !client.IsSplitScreenUser() && !client.IsHLTV())
430+
client.Disconnect("Punting bot, server is hibernating");
431+
}
432+
}
433+
434+
SetPaused(false);
435+
436+
bool exit = false;
437+
if (SV.ExitWhenEmpty) {
438+
exit = true;
439+
Warning("Server shutting down because sv_shutdown was requested and a server is empty.\n");
440+
}
441+
else if (SV.TimeForceShutdown > 0.0 && Platform.Time > SV.TimeForceShutdown) {
442+
exit = true;
443+
Warning("Server shutting down because sv_shutdown was requested and timeout has expired.\n");
444+
}
445+
else {
446+
int memlimit = SV.sv_memlimit.GetInt();
447+
if (memlimit != 0) {
448+
ulong usage = Platform.ApproximateProcessMemoryUsage();
449+
if (usage > (ulong)memlimit << 20) {
450+
Warning($"Server shutting down because of using {usage >> 20}MB with an sv_memory_limit of {memlimit}MB\n");
451+
exit = true;
452+
}
453+
}
454+
}
455+
456+
if (exit)
457+
Singleton<IHostState>().Shutdown();
458+
}
459+
460+
serverGameDLL.SetServerHibernation(Hibernating);
461+
462+
Steam3Server().SendUpdatedServerDetails();
401463
}
402464

403465
internal void InitMaxClients() {

0 commit comments

Comments
 (0)