-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathTorchServer.cs
More file actions
367 lines (308 loc) · 11.9 KB
/
TorchServer.cs
File metadata and controls
367 lines (308 loc) · 11.9 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
#region
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using NLog;
using Sandbox;
using Sandbox.Engine.Networking;
using Sandbox.Game;
using Sandbox.Game.Multiplayer;
using Sandbox.Game.World;
using Torch.API;
using Torch.API.Managers;
using Torch.API.Session;
using Torch.Commands;
using Torch.Managers;
using Torch.Managers.PatchManager;
using Torch.Mod;
using Torch.Mod.Messages;
using Torch.Server.Commands;
using Torch.Server.Managers;
using Torch.Utils;
using VRage;
using VRage.Dedicated;
using VRage.Dedicated.RemoteAPI;
using VRage.GameServices;
using VRage.Scripting;
using VRage.Steam;
using Timer = System.Threading.Timer;
#endregion
#pragma warning disable 618
namespace Torch.Server
{
public class TorchServer : TorchBase, ITorchServer
{
private bool _hasRun;
private bool _canRun;
private TimeSpan _elapsedPlayTime;
private bool _isRunning;
private float _simRatio;
private ServerState _state;
private bool _isRestartPending;
private Stopwatch _uptime;
private Timer _watchdog;
private int _players;
private MultiplayerManagerDedicated _multiplayerManagerDedicated;
internal bool FatalException { get; set; }
private System.Timers.Timer _simUpdateTimer = new System.Timers.Timer(200);
private bool _simDirty;
//Here to trigger rebuild
/// <inheritdoc />
public TorchServer(TorchConfig config) : base(config)
{
DedicatedInstance = new InstanceManager(this);
AddManager(DedicatedInstance);
AddManager(new EntityControlManager(this));
AddManager(new RemoteAPIManager(this));
AddManager(new UpdateManager(this));
AddManager(new GameUpdateManager(this));
AddManager(new AnalyticsManager(this));
Managers.GetManager<UpdateManager>().CheckAndUpdateTorch();
var sessionManager = Managers.GetManager<ITorchSessionManager>();
sessionManager.AddFactory(x => new MultiplayerManagerDedicated(this));
// Needs to be done at some point after MyVRageWindows.Init
// where the debug listeners are registered
if (!((TorchConfig)Config).EnableAsserts)
MyDebug.Listeners.Clear();
_simUpdateTimer.Elapsed += SimUpdateElapsed;
_simUpdateTimer.Start();
}
private void SimUpdateElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_simDirty)
{
OnPropertyChanged(nameof(SimulationRatio));
_simDirty = false;
}
}
public bool HasRun { get => _hasRun; set => SetValue(ref _hasRun, value); }
/// <inheritdoc />
public float SimulationRatio
{
get => _simRatio;
set
{
if (_simRatio.IsEqual(value, 0.01f))
return;
_simRatio = value;
_simDirty = true;
//SetValue(ref _simRatio, value);
}
}
/// <inheritdoc />
public TimeSpan ElapsedPlayTime { get => _elapsedPlayTime; set => SetValue(ref _elapsedPlayTime, value); }
/// <inheritdoc />
public Thread GameThread { get; private set; }
/// <inheritdoc />
public bool IsRunning { get => _isRunning; set => SetValue(ref _isRunning, value); }
public bool CanRun { get => _canRun; set => SetValue(ref _canRun, value); }
/// <inheritdoc />
public InstanceManager DedicatedInstance { get; }
/// <inheritdoc />
public string InstanceName => Config?.InstanceName;
/// <inheritdoc />
protected override uint SteamAppId => 244850;
/// <inheritdoc />
protected override string SteamAppName => "SpaceEngineersDedicated";
/// <inheritdoc />
public ServerState State { get => _state; private set => SetValue(ref _state, value); }
public event Action<ITorchServer> Initialized;
public bool IsRestartPending { get => _isRestartPending; set => SetValue(ref _isRestartPending, value); }
/// <inheritdoc />
public string InstancePath => Config?.InstancePath;
public int OnlinePlayers { get => _players; private set => SetValue(ref _players, value); }
/// <inheritdoc />
public override void Init()
{
var updateManager = Managers.GetManager<UpdateManager>();
Log.Info("Initializing server");
MySandboxGame.IsDedicated = true;
base.Init();
Managers.GetManager<ITorchSessionManager>().SessionStateChanged += OnSessionStateChanged;
GetManager<InstanceManager>().LoadInstance(Config.InstancePath);
CanRun = true;
Initialized?.Invoke(this);
Log.Info($"Initialized server '{Config.InstanceName}' at '{Config.InstancePath}'");
}
/// <inheritdoc />
public override void Start()
{
if (State != ServerState.Stopped)
return;
if (IsRunning || HasRun)
{
Restart();
return;
}
State = ServerState.Starting;
IsRunning = true;
HasRun = true;
CanRun = false;
PatchManager.CommitInternal();
Log.Info("Starting server.");
MySandboxGame.ConfigDedicated = DedicatedInstance.DedicatedConfig.Model;
_uptime = Stopwatch.StartNew();
base.Start();
}
/// <inheritdoc />
public override void Stop()
{
if (State == ServerState.Stopped)
Log.Error("Server is already stopped");
Log.Info("Stopping server.");
base.Stop();
Log.Info("Server stopped.");
State = ServerState.Stopped;
IsRunning = false;
CanRun = true;
}
/// <summary>
/// Restart the program.
/// </summary>
public override void Restart(bool save = true)
{
if (Config.DisconnectOnRestart)
{
ModCommunication.SendMessageToClients(new JoinServerMessage("0.0.0.0:25555"));
Log.Info("Ejected all players from server for restart.");
}
if (IsRunning && save)
Save().ContinueWith(DoRestart, this, TaskContinuationOptions.RunContinuationsAsynchronously);
else
DoRestart(null, this);
void DoRestart(Task<GameSaveResult> task, object torch0)
{
var torch = (TorchServer)torch0;
var config = (TorchConfig)torch.Config;
if (IsRunning)
{
config.TempAutostart = true;
torch.Stop();
}
LogManager.Flush();
string exe = Assembly.GetExecutingAssembly().Location;
Debug.Assert(exe != null);
config.WaitForPID = Process.GetCurrentProcess().Id.ToString();
Process.Start(exe, config.ToString());
Process.GetCurrentProcess().Kill();
}
}
private void OnSessionStateChanged(ITorchSession session, TorchSessionState newState)
{
if (newState == TorchSessionState.Unloading || newState == TorchSessionState.Unloaded)
{
_watchdog?.Dispose();
_watchdog = null;
ModCommunication.Unregister();
}
if (newState == TorchSessionState.Loaded)
{
_multiplayerManagerDedicated = CurrentSession.Managers.GetManager<MultiplayerManagerDedicated>();
CurrentSession.Managers.GetManager<CommandManager>().RegisterCommandModule(typeof(WhitelistCommands));
ModCommunication.Register();
}
}
/// <inheritdoc />
public override void Init(object gameInstance)
{
base.Init(gameInstance);
if (gameInstance is MySandboxGame && MySession.Static != null)
State = ServerState.Running;
else
State = ServerState.Stopped;
}
/// <inheritdoc />
public override void Update()
{
base.Update();
// Stops 1.00-1.02 flicker.
SimulationRatio = Math.Min(Sync.ServerSimulationRatio, 1);
var elapsed = TimeSpan.FromSeconds(Math.Floor(_uptime.Elapsed.TotalSeconds));
ElapsedPlayTime = elapsed;
OnlinePlayers = _multiplayerManagerDedicated?.Players.Count ?? 0;
if (_watchdog == null && Config.TickTimeout > 0)
{
Log.Info("Starting server watchdog.");
_watchdog = new Timer(CheckServerResponding, this, TimeSpan.Zero,
TimeSpan.FromSeconds(Config.TickTimeout));
}
}
#region Freeze Detection
private static void CheckServerResponding(object state)
{
var server = (TorchServer)state;
var mre = new ManualResetEvent(false);
server.Invoke(() => mre.Set());
if (!mre.WaitOne(TimeSpan.FromSeconds(Instance.Config.TickTimeout)))
{
if (server.FatalException)
{
server._watchdog.Dispose();
return;
}
#if DEBUG
Log.Error(
$"Server watchdog detected that the server was frozen for at least {((TorchServer) state).Config.TickTimeout} seconds.");
Log.Error(DumpFrozenThread(MySandboxGame.Static.UpdateThread));
#else
Log.Error(DumpFrozenThread(MySandboxGame.Static.UpdateThread));
throw new TimeoutException($"Server watchdog detected that the server was frozen for at least {((TorchServer)state).Config.TickTimeout} seconds.");
#endif
}
Log.Debug("Server watchdog responded");
}
private static string DumpFrozenThread(Thread thread, int traces = 3, int pause = 5000)
{
var stacks = new List<string>(traces);
var totalSize = 0;
for (var i = 0; i < traces; i++)
{
string dump = DumpStack(thread).ToString();
totalSize += dump.Length;
stacks.Add(dump);
Thread.Sleep(pause);
}
string commonPrefix = StringUtils.CommonSuffix(stacks);
// Advance prefix to include the line terminator.
commonPrefix = commonPrefix.Substring(commonPrefix.IndexOf('\n') + 1);
var result = new StringBuilder(totalSize - (stacks.Count - 1) * commonPrefix.Length);
result.AppendLine($"Frozen thread dump {thread.Name}");
result.AppendLine("Common prefix:").AppendLine(commonPrefix);
for (var i = 0; i < stacks.Count; i++)
if (stacks[i].Length > commonPrefix.Length)
{
result.AppendLine($"Suffix {i}");
result.AppendLine(stacks[i].Substring(0, stacks[i].Length - commonPrefix.Length));
}
return result.ToString();
}
private static StackTrace DumpStack(Thread thread)
{
try
{
thread.Suspend();
}
catch
{
// ignored
}
var stack = new StackTrace(thread, true);
try
{
thread.Resume();
}
catch
{
// ignored
}
return stack;
}
#endregion
}
}