Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Game.Server/GameInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -649,10 +649,14 @@ public void ServerActivate(Edict[] pEdictList, int edictCount, int clientMax) {
// todo nextbots
}

bool IsHibernating;

public void SetServerHibernation(bool bHibernating) {
throw new NotImplementedException();
IsHibernating = bHibernating;
}

public IServerGCLobby? GetServerGCLobby() => null;

public bool ShouldHideServer() => false;

public void Think(bool finalTick) {
Expand Down
16 changes: 16 additions & 0 deletions Source.Common/Platform.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<char> 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;
Comment thread
marchc1 marked this conversation as resolved.
Resolved
}

#if WIN32
[DllImport("kernel32.dll")]
unsafe static extern void OutputDebugStringW(char* lpOutputString);
Expand Down
10 changes: 10 additions & 0 deletions Source.Common/Server/IServerGameDLL.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ bool LevelInit(ReadOnlySpan<char> 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)
Expand Down Expand Up @@ -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();
}
50 changes: 42 additions & 8 deletions Source.Engine/SV.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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<char> name) {
ServerClass? cur = serverGameDLL.GetAllServerClasses();
while (cur != null) {
Expand Down Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions Source.Engine/Server/BaseClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,7 @@ public virtual void Disconnect(ReadOnlySpan<char> 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)
Expand Down
11 changes: 10 additions & 1 deletion Source.Engine/Server/BaseServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
68 changes: 65 additions & 3 deletions Source.Engine/Server/GameServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -21,7 +22,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<ED>();
Expand Down Expand Up @@ -361,7 +362,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;
}
}

IServerGCLobby? lobby = serverGameDLL.GetServerGCLobby();
bool hibernateFromGCServer = lobby == null || lobby.ShouldHibernate();

SetHibernating(hibernateFromGCServer && !haveAnyClients);
}


Expand All @@ -373,7 +390,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<IHostState>().Shutdown();
}

serverGameDLL.SetServerHibernation(Hibernating);

Steam3Server().SendUpdatedServerDetails();
}

internal void InitMaxClients() {
Expand Down
Loading