NBloodServerSupervisor/Supervisor/PublicServerManager.cs

91 lines
2.9 KiB
C#
Raw Normal View History

2020-01-23 21:03:54 +01:00
using Common;
using Model;
using System;
using System.Diagnostics;
2020-01-24 14:34:10 +01:00
using System.IO;
2020-01-23 21:03:54 +01:00
using System.Linq;
2020-01-24 12:23:40 +01:00
using System.Runtime.InteropServices;
2020-01-23 21:03:54 +01:00
using System.Threading;
using System.Threading.Tasks;
namespace Supervisor
{
static class PublicServerManager
2020-01-23 21:03:54 +01:00
{
2020-01-24 12:23:40 +01:00
public static void Start()
2020-01-23 21:03:54 +01:00
{
Thread.Sleep(TimeSpan.FromSeconds(2));
KillOrphanedServers();
Task.Factory.StartNew(() =>
{
while (true)
{
2020-01-24 12:23:40 +01:00
LaunchNewServersWhenNeeded();
2020-01-23 21:03:54 +01:00
Thread.Sleep(TimeSpan.FromSeconds(1));
}
});
}
private static void KillOrphanedServers()
{
foreach (var process in Process.GetProcessesByName("nblood_server"))
{
if (!Program.State.Servers.Values.Any(s => s.ProcessId == process.Id))
{
process.Kill();
}
}
}
2020-01-24 12:23:40 +01:00
private static void LaunchNewServersWhenNeeded()
2020-01-23 21:03:54 +01:00
{
foreach (Mod mod in Constants.SupportedMods.Values)
2020-01-23 21:03:54 +01:00
{
const int maxPlayers = 8;
for (int i = 3; i <= maxPlayers; i++)
2020-01-23 21:03:54 +01:00
{
if (IsNewServerNeeded(i, mod))
2020-01-23 21:03:54 +01:00
{
2020-01-27 17:25:45 +01:00
try
{
2020-01-27 17:25:45 +01:00
var spawnedServer = ProcessSpawner.SpawnServer(i, mod.Name);
int port = spawnedServer.Port;
int processId = spawnedServer.Process.Id;
Program.State.Servers.AddOrUpdate(port, new Server()
{
Port = port,
ProcessId = processId,
MaximumPlayers = i,
CurrentPlayers = 1,
Mod = mod,
},
(prt, server) =>
{
server.ProcessId = processId;
server.MaximumPlayers = i;
server.CurrentPlayers = 1;
server.Mod = mod;
return server;
});
}
catch
{
2020-01-27 17:25:45 +01:00
// No free ports, cannot create process
// Log...
}
}
2020-01-23 21:03:54 +01:00
}
}
}
private static bool IsNewServerNeeded(int i, Mod mod)
2020-01-23 21:03:54 +01:00
{
return !Program.State.Servers.Values.Any(s =>
!s.IsPrivate
&& s.Mod.Name == mod.Name
&& s.MaximumPlayers == i
&& s.CurrentPlayers < s.MaximumPlayers);
2020-01-23 21:03:54 +01:00
}
}
}