-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathServer.cs
More file actions
752 lines (591 loc) · 19.8 KB
/
Server.cs
File metadata and controls
752 lines (591 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MultiAdmin.Config;
using MultiAdmin.ConsoleTools;
using MultiAdmin.Features;
using MultiAdmin.ServerIO;
using MultiAdmin.Utility;
namespace MultiAdmin
{
public class Server
{
public readonly Dictionary<string, ICommand> commands = new();
public readonly List<Feature> features = new();
// We want a tick only list since its the only event that happens constantly, all the rest can be in a single list
private readonly List<IEventTick> tick = new();
private readonly MultiAdminConfig serverConfig;
public MultiAdminConfig ServerConfig => serverConfig ?? MultiAdminConfig.GlobalConfig;
public readonly string? serverId;
public readonly string? configLocation;
private readonly uint? port;
public readonly string?[]? args;
public readonly string? serverDir;
public readonly string logDir;
public uint Port => port ?? ServerConfig.Port.Value;
private DateTime initStopTimeoutTime;
private DateTime initRestartTimeoutTime;
public ModFeatures supportedModFeatures = ModFeatures.None;
public Server(string? serverId = null, string? configLocation = null, uint? port = null, string?[]? args = null)
{
this.serverId = serverId;
serverDir = string.IsNullOrEmpty(serverId)
? null
: Utils.GetFullPathSafe(Path.Combine(MultiAdminConfig.GlobalConfig.ServersFolder.Value, serverId));
this.configLocation = Utils.GetFullPathSafe(configLocation) ??
Utils.GetFullPathSafe(MultiAdminConfig.GlobalConfig.ConfigLocation.Value) ??
Utils.GetFullPathSafe(serverDir);
// Load config
serverConfig = MultiAdminConfig.GlobalConfig;
// Load config hierarchy
string? serverConfigLocation = this.configLocation;
while (!string.IsNullOrEmpty(serverConfigLocation))
{
// Update the Server object's config location with the valid config location
this.configLocation = serverConfigLocation;
// Load the child MultiAdminConfig
serverConfig = new MultiAdminConfig(Path.Combine(serverConfigLocation, MultiAdminConfig.ConfigFileName),
serverConfig);
// Set the server config location to the value from the config, this should be empty or null if there is no valid value
serverConfigLocation = Utils.GetFullPathSafe(serverConfig.ConfigLocation.Value);
// If the config hierarchy already contains the MultiAdmin config from the target path, stop looping
// Without this, a user could unintentionally cause a lockup when their server starts up due to infinite looping
if (serverConfig.ConfigHierarchyContainsPath(serverConfigLocation))
break;
}
// Set port
this.port = port;
// Set args
this.args = args;
logDir = Utils.GetFullPathSafe(Path.Combine(string.IsNullOrEmpty(serverDir) ? "" : serverDir,
serverConfig.LogLocation.Value)) ?? throw new FileNotFoundException($"Log file \"{nameof(logDir)}\" was not set");
// Register all features
RegisterFeatures();
}
#region Server Status
public ServerStatus LastStatus { get; private set; } = ServerStatus.NotStarted;
private ServerStatus status = ServerStatus.NotStarted;
public ServerStatus Status
{
get => status;
private set
{
LastStatus = status;
status = value;
}
}
public bool IsStopped => Status == ServerStatus.NotStarted || Status == ServerStatus.Stopped ||
Status == ServerStatus.StoppedUnexpectedly;
public bool IsRunning => !IsStopped;
public bool IsStarted => !IsStopped && !IsStarting;
public bool IsStarting => Status == ServerStatus.Starting;
public bool IsStopping => Status == ServerStatus.Stopping || Status == ServerStatus.ForceStopping ||
Status == ServerStatus.Restarting;
public bool IsLoading { get; set; }
public bool SetServerRequestedStatus(ServerStatus status)
{
// Don't override the console's own requests
if (IsStopping)
{
return false;
}
Status = status;
return true;
}
#endregion
private string? startDateTime;
public string? StartDateTime
{
get => startDateTime;
private set
{
startDateTime = value;
// Update related variables
LogDirFile = string.IsNullOrEmpty(value) || string.IsNullOrEmpty(logDir)
? null
: $"{Path.Combine(logDir.EscapeFormat(), value)}_{{0}}_log_{Port}.txt";
lock (this)
{
MaLogFile = string.IsNullOrEmpty(LogDirFile) ? null : string.Format(LogDirFile, "MA");
ScpLogFile = string.IsNullOrEmpty(LogDirFile) ? null : string.Format(LogDirFile, "SCP");
}
}
}
public bool CheckStopTimeout =>
(DateTime.Now - initStopTimeoutTime).Seconds > ServerConfig.ServerStopTimeout.Value;
public bool CheckRestartTimeout =>
(DateTime.Now - initRestartTimeoutTime).Seconds > ServerConfig.ServerRestartTimeout.Value;
public string? LogDirFile { get; private set; }
public string? MaLogFile { get; private set; }
public string? ScpLogFile { get; private set; }
private StreamWriter? maLogStream;
public Process? GameProcess { get; private set; }
public bool IsGameProcessRunning
{
get
{
if (GameProcess == null)
return false;
GameProcess.Refresh();
return !GameProcess.HasExited;
}
}
public static readonly string? DedicatedDir = Utils.GetFullPathSafe(Path.Combine("SCPSL_Data", "Dedicated"));
public ServerSocket? SessionSocket { get; private set; }
#region Server Core
private void MainLoop()
{
// Creates and starts a timer
Stopwatch timer = new();
timer.Restart();
while (IsGameProcessRunning)
{
foreach (IEventTick tickEvent in tick) tickEvent.OnTick();
timer.Stop();
// Wait the delay per tick (calculating how long the tick took and compensating)
Thread.Sleep(Math.Max(ServerConfig.MultiAdminTickDelay.Value - timer.Elapsed.Milliseconds, 0));
timer.Restart();
if (Status == ServerStatus.Restarting && CheckRestartTimeout)
{
Write("Server restart timed out, killing the server process...", ConsoleColor.Red);
RestartServer(true);
}
if (Status == ServerStatus.Stopping && CheckStopTimeout)
{
Write("Server exit timed out, killing the server process...", ConsoleColor.Red);
StopServer(true);
}
if (Status == ServerStatus.ForceStopping)
{
Write("Force stopping the server process...", ConsoleColor.Red);
StopServer(true);
}
}
}
/// <summary>
/// Sends the string <paramref name="message" /> to the SCP: SL server process.
/// </summary>
/// <param name="message"></param>
public bool SendMessage(string message)
{
if (SessionSocket == null || !SessionSocket.Connected)
{
Write("Unable to send command to server, the console is disconnected", ConsoleColor.Red);
return false;
}
SessionSocket.SendMessage(message);
return true;
}
#endregion
#region Server Execution Controls
public void WriteConfigInformation()
{
if (!string.IsNullOrEmpty(MultiAdminConfig.GlobalConfigFilePath))
Write($"Using global config \"{MultiAdminConfig.GlobalConfigFilePath}\"...");
if (ServerConfig != null)
{
foreach (MultiAdminConfig config in ServerConfig.GetConfigHierarchy())
{
if (!string.IsNullOrEmpty(config?.Config?.ConfigPath) &&
MultiAdminConfig.GlobalConfigFilePath != config.Config.ConfigPath)
Write($"Using server config \"{config.Config.ConfigPath}\"...");
}
}
}
public static string GetExecutablePath()
{
string scpslExe;
if (OperatingSystem.IsLinux())
scpslExe = "SCPSL.x86_64";
else if (OperatingSystem.IsWindows())
scpslExe = "SCPSL.exe";
else
throw new FileNotFoundException("Invalid OS, can't run executable");
if (!File.Exists(scpslExe))
throw new FileNotFoundException(
$"Can't find game executable \"{scpslExe}\", the working directory must be the game directory");
return scpslExe;
}
public void StartServer(bool restartOnCrash = true)
{
if (!IsStopped) throw new Exceptions.ServerAlreadyRunningException();
bool shouldRestart = false;
do
{
Status = ServerStatus.Starting;
IsLoading = true;
StartDateTime = Utils.DateTime;
try
{
// Set up logging
maLogStream?.Close();
Directory.CreateDirectory(logDir);
maLogStream = File.AppendText(MaLogFile ?? throw new FileNotFoundException($"Log file \"{nameof(MaLogFile)}\" was not set"));
#region Startup Info Printing & Logging
WriteConfigInformation();
#endregion
// Reload the config immediately as server is starting
ReloadConfig();
// Init features
InitFeatures();
string scpslExe = GetExecutablePath();
Write($"Executing \"{scpslExe}\"...", ConsoleColor.DarkGreen);
// Start the console socket connection to the game server
ServerSocket consoleSocket = new();
// Start the connection before the game to find an open port for communication
consoleSocket.Connect();
SessionSocket = consoleSocket;
List<string?> scpslArgs = new()
{
$"-multiadmin:{Program.MaVersion}:{(int)ModFeatures.All}",
"-batchmode",
"-nographics",
"-silent-crashes",
"-nodedicateddelete",
$"-id{Environment.ProcessId}",
$"-console{consoleSocket.Port}",
$"-port{Port}"
};
if (string.IsNullOrEmpty(ScpLogFile) || ServerConfig.NoLog.Value)
{
scpslArgs.Add("-nolog");
if (OperatingSystem.IsLinux())
{
scpslArgs.Add("-logFile");
scpslArgs.Add("/dev/null");
}
else if (OperatingSystem.IsWindows())
{
scpslArgs.Add("-logFile");
scpslArgs.Add("NUL");
}
}
else
{
scpslArgs.Add("-logFile");
scpslArgs.Add(ScpLogFile);
}
if (ServerConfig.DisableConfigValidation.Value)
{
scpslArgs.Add("-disableconfigvalidation");
}
if (ServerConfig.ShareNonConfigs.Value)
{
scpslArgs.Add("-sharenonconfigs");
}
if (!string.IsNullOrEmpty(configLocation))
{
scpslArgs.Add("-configpath");
scpslArgs.Add(configLocation);
}
string? appDataPath = Utils.GetFullPathSafe(ServerConfig.AppDataLocation.Value);
if (!string.IsNullOrEmpty(appDataPath))
{
scpslArgs.Add("-appdatapath");
scpslArgs.Add(appDataPath);
}
// Add custom arguments
if (args != null) scpslArgs.AddRange(args);
ProcessStartInfo startInfo = new(scpslExe, scpslArgs.JoinArgs())
{
CreateNoWindow = true,
UseShellExecute = false
};
Write($"Starting server with the following parameters:\n{scpslExe} {startInfo.Arguments}");
if (ServerConfig.ActualConsoleInputSystem == InputHandler.ConsoleInputSystem.Original)
Write("You are using the original input system. It may prevent MultiAdmin from closing and/or cause ghost game processes", ConsoleColor.Red);
// Reset the supported mod features
supportedModFeatures = ModFeatures.None;
ForEachHandler<IEventServerPreStart>(eventPreStart => eventPreStart.OnServerPreStart());
// Start the input reader
CancellationTokenSource inputHandlerCancellation = new();
Task? inputHandler = null;
if (!Program.Headless)
{
inputHandler = Task.Run(() => InputHandler.Write(this, inputHandlerCancellation.Token), inputHandlerCancellation.Token);
}
// Start the output reader
OutputHandler outputHandler = new(this);
// Assign the socket events to the OutputHandler
consoleSocket.OnReceiveMessage += outputHandler.HandleMessage;
consoleSocket.OnReceiveAction += outputHandler.HandleAction;
// Finally, start the game
GameProcess = Process.Start(startInfo);
Status = ServerStatus.Running;
MainLoop();
try
{
switch (Status)
{
case ServerStatus.Stopping:
case ServerStatus.ForceStopping:
case ServerStatus.ExitActionStop:
Status = ServerStatus.Stopped;
shouldRestart = false;
break;
case ServerStatus.Restarting:
case ServerStatus.ExitActionRestart:
shouldRestart = true;
break;
default:
Status = ServerStatus.StoppedUnexpectedly;
ForEachHandler<IEventCrash>(eventCrash => eventCrash.OnCrash());
Write("Game engine exited unexpectedly", ConsoleColor.Red);
shouldRestart = restartOnCrash;
break;
}
// Cleanup after exit from MainLoop
GameProcess?.Dispose();
GameProcess = null;
// Stop the input handler if it's running
if (inputHandler != null)
{
inputHandlerCancellation.Cancel();
try
{
inputHandler.Wait();
}
catch (Exception)
{
// Task was cancelled or disposed, this is fine since we're waiting for that
}
inputHandler.Dispose();
inputHandlerCancellation.Dispose();
}
consoleSocket.Disconnect();
// Remove the socket events for OutputHandler
consoleSocket.OnReceiveMessage -= outputHandler.HandleMessage;
consoleSocket.OnReceiveAction -= outputHandler.HandleAction;
SessionSocket = null;
StartDateTime = null;
}
catch (Exception e)
{
Write(e.Message, ConsoleColor.Red);
Program.LogDebugException(nameof(StartServer), e);
Write("Shutdown failed...", ConsoleColor.Red);
}
if (shouldRestart) Write("Restarting server...");
}
catch (Exception e)
{
Write(e.Message, ConsoleColor.Red);
Program.LogDebugException(nameof(StartServer), e);
// If the server should try to start up again
if (ServerConfig.ServerStartRetry.Value)
{
shouldRestart = true;
int waitDelayMs = ServerConfig.ServerStartRetryDelay.Value;
if (waitDelayMs > 0)
{
Write($"Startup failed! Waiting for {waitDelayMs} ms before retrying...", ConsoleColor.Red);
Thread.Sleep(waitDelayMs);
}
else
{
Write("Startup failed! Retrying...", ConsoleColor.Red);
}
}
else
{
Write("Startup failed! Exiting...", ConsoleColor.Red);
}
}
} while (shouldRestart);
// Finish server instance
maLogStream?.Close();
maLogStream = null;
}
public void SetStopStatus(bool killGame = false)
{
if (!IsRunning) throw new Exceptions.ServerNotRunningException();
initStopTimeoutTime = DateTime.Now;
Status = killGame ? ServerStatus.ForceStopping : ServerStatus.Stopping;
ForEachHandler<IEventServerStop>(stopEvent => stopEvent.OnServerStop());
}
public void StopServer(bool killGame = false)
{
if (!IsRunning) throw new Exceptions.ServerNotRunningException();
SetStopStatus(killGame);
if ((killGame || !SendMessage("QUIT")) && IsGameProcessRunning)
GameProcess?.Kill();
}
public void SetRestartStatus()
{
if (!IsRunning) throw new Exceptions.ServerNotRunningException();
initRestartTimeoutTime = DateTime.Now;
Status = ServerStatus.Restarting;
}
public void RestartServer(bool killGame = false)
{
if (!IsRunning) throw new Exceptions.ServerNotRunningException();
SetRestartStatus();
if ((killGame || !SendMessage("SOFTRESTART")) && IsGameProcessRunning)
GameProcess?.Kill();
}
#endregion
#region Feature Registration, Initialization, and Execution
private void RegisterFeature(Feature feature)
{
switch (feature)
{
case IEventTick eventTick:
tick.Add(eventTick);
break;
case ICommand command:
{
string commandKey = command.GetCommand().ToLower().Trim();
// If the command was already registered
if (commands.ContainsKey(commandKey))
{
string message =
$"Warning, {nameof(MultiAdmin)} tried to register duplicate command \"{commandKey}\"";
Program.LogDebug(nameof(RegisterFeature), message);
Write(message);
}
else
{
commands.Add(commandKey, command);
}
break;
}
}
features.Add(feature);
}
private void RegisterFeatures()
{
RegisterFeature(new ConfigGenerator(this));
RegisterFeature(new ConfigReload(this));
RegisterFeature(new ExitCommand(this));
RegisterFeature(new FileCopyRoundQueue(this));
RegisterFeature(new GithubGenerator(this));
RegisterFeature(new HelpCommand(this));
RegisterFeature(new MemoryChecker(this));
RegisterFeature(new MultiAdminInfo(this));
RegisterFeature(new NewCommand(this));
RegisterFeature(new Restart(this));
RegisterFeature(new RestartRoundCounter(this));
RegisterFeature(new Titlebar(this));
}
private void InitFeatures()
{
foreach (Feature feature in features)
{
feature.Init();
feature.OnConfigReload();
}
}
public void ForEachHandler<T>(Action<T> action) where T : IMAEvent
{
foreach (Feature feature in features)
if (feature is T eventHandler)
action.Invoke(eventHandler);
}
#endregion
#region Console Output and Logging
public void Write(ColoredMessage?[] messages, ConsoleColor? timeStampColor = null)
{
lock (ColoredConsole.WriteLock)
{
if (messages == null) return;
Log(messages.GetText());
if (Program.Headless) return;
ColoredMessage?[] timeStampedMessage = Utils.TimeStampMessage(messages, timeStampColor);
timeStampedMessage.WriteLine(ServerConfig.ActualConsoleInputSystem == InputHandler.ConsoleInputSystem.New);
if (ServerConfig.ActualConsoleInputSystem == InputHandler.ConsoleInputSystem.New)
InputHandler.WriteInputAndSetCursor(true);
}
}
public void Write(ColoredMessage message, ConsoleColor? timeStampColor = null)
{
lock (ColoredConsole.WriteLock)
{
Write(new ColoredMessage[] { message }, timeStampColor ?? message.textColor);
}
}
public void Write(string message, ConsoleColor? color = ConsoleColor.Yellow,
ConsoleColor? timeStampColor = null)
{
lock (ColoredConsole.WriteLock)
{
Write(new ColoredMessage(message, color), timeStampColor);
}
}
public void Log(string message)
{
lock (ColoredConsole.WriteLock)
{
if (maLogStream == null || string.IsNullOrEmpty(MaLogFile) || ServerConfig.NoLog.Value) return;
try
{
message = Utils.TimeStampMessage(message);
maLogStream.Write(message);
if (!message.EndsWith(Environment.NewLine)) maLogStream.WriteLine();
maLogStream.Flush();
}
catch (Exception e)
{
Program.LogDebugException(nameof(Log), e);
new ColoredMessage[]
{
new ColoredMessage("Error while logging for MultiAdmin:", ConsoleColor.Red),
new ColoredMessage(e.ToString(), ConsoleColor.Red)
}.WriteLines();
}
}
}
#endregion
public void ReloadConfig(bool copyFiles = true, bool runEvent = true)
{
ServerConfig.ReloadConfig();
// Handle directory copying
string copyFromDir;
if (copyFiles && !string.IsNullOrEmpty(configLocation) &&
!string.IsNullOrEmpty(copyFromDir = ServerConfig.CopyFromFolderOnReload.Value))
{
CopyFromDir(copyFromDir, ServerConfig.FolderCopyWhitelist.Value,
ServerConfig.FolderCopyBlacklist.Value);
}
// Handle each config reload event
if (runEvent)
foreach (Feature feature in features)
feature.OnConfigReload();
}
public bool CopyFromDir(string? sourceDir, string[]? fileWhitelist = null, string[]? fileBlacklist = null)
{
if (string.IsNullOrEmpty(configLocation) || string.IsNullOrEmpty(sourceDir)) return false;
try
{
sourceDir = Utils.GetFullPathSafe(sourceDir);
if (!string.IsNullOrEmpty(sourceDir))
{
Write($"Copying files and folders from \"{sourceDir}\" into \"{configLocation}\"...");
Utils.CopyAll(sourceDir, configLocation, fileWhitelist, fileBlacklist);
Write("Done copying files and folders!");
return true;
}
}
catch (Exception e)
{
Write($"Error while copying files and folders:\n{e}", ConsoleColor.Red);
}
return false;
}
}
public enum ServerStatus
{
NotStarted,
Starting,
Running,
Stopping,
ExitActionStop,
ForceStopping,
Restarting,
ExitActionRestart,
Stopped,
StoppedUnexpectedly
}
}