-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathInitializer.cs
More file actions
379 lines (328 loc) · 13.5 KB
/
Initializer.cs
File metadata and controls
379 lines (328 loc) · 13.5 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using System.Xml.Linq;
using NLog;
using NLog.Targets;
using Sandbox;
using Sandbox.Engine.Utils;
using Torch.Utils;
using VRage;
using VRage.FileSystem;
using VRage.Scripting;
using VRage.Utils;
namespace Torch.Server
{
public class Initializer
{
[Obsolete("It's hack. Do not use it!")]
internal static Initializer Instance { get; private set; }
private static readonly Logger Log = LogManager.GetLogger(nameof(Initializer));
private bool _init;
private const string STEAMCMD_DIR = "steam/steamcmd";
private const string STEAMCMD_LEGACY_DIR = "steamcmd";
private const string STEAMCMD_ZIP = "temp.zip";
private static readonly string STEAMCMD_PATH = $"{STEAMCMD_DIR}\\steamcmd.exe";
private static readonly string RUNSCRIPT_PATH = $"{STEAMCMD_DIR}\\runscript.txt";
private const string RUNSCRIPT = @"force_install_dir ../../
login anonymous
app_update 298740
quit";
private TorchServer _server;
private string _basePath;
internal Persistent<TorchConfig> ConfigPersistent { get; private set; }
public TorchConfig Config => ConfigPersistent?.Data;
public TorchServer Server => _server;
public Initializer(string basePath)
{
_basePath = basePath;
Instance = this;
}
public bool Initialize(string[] args)
{
if (_init)
return false;
// Adding .net 10 preview stuff might have made optimizations/inlining too fast??
// the !Debug is called before nlog has loaded so we force it.
var config = new NLog.Config.XmlLoggingConfiguration("NLog.config", true);
LogManager.Configuration = config;
#if !DEBUG
AppDomain.CurrentDomain.UnhandledException += HandleException;
LogManager.Configuration.AddRule(LogLevel.Info, LogLevel.Fatal, "console");
LogManager.ReconfigExistingLoggers();
#endif
#if DEBUG
AppDomain.CurrentDomain.UnhandledException += HandleException;
//enables logging debug messages when built in debug mode. Amazing.
LogManager.Configuration.AddRule(LogLevel.Debug, LogLevel.Debug, "main");
LogManager.Configuration.AddRule(LogLevel.Debug, LogLevel.Debug, "console");
LogManager.Configuration.AddRule(LogLevel.Debug, LogLevel.Debug, "wpf");
LogManager.ReconfigExistingLoggers();
Log.Debug("Debug logging enabled.");
#endif
// This is what happens when Keen is bad and puts extensions into the System namespace.
if (!Enumerable.Contains(args, "-noupdate"))
RunSteamCmd(PeekForceOverwriteRunscript());
var basePath = new FileInfo(typeof(Program).Assembly.Location).Directory.ToString();
var apiSource = Path.Combine(basePath, "DedicatedServer64", "steam_api64.dll");
var apiTarget = Path.Combine(basePath, "steam_api64.dll");
if (!File.Exists(apiTarget))
{
File.Copy(apiSource, apiTarget);
}
else if (File.GetLastWriteTime(apiTarget) < File.GetLastWriteTime(apiSource))
{
File.Delete(apiTarget);
File.Copy(apiSource, apiTarget);
}
InitConfig();
if (!Config.Parse(args))
return false;
if (!string.IsNullOrEmpty(Config.WaitForPID))
{
try
{
var pid = int.Parse(Config.WaitForPID);
var waitProc = Process.GetProcessById(pid);
Log.Info("Continuing in 5 seconds.");
Log.Warn($"Waiting for process {pid} to close");
while (!waitProc.HasExited)
{
Console.Write(".");
Thread.Sleep(1000);
}
}
catch
{
// ignored
}
}
_init = true;
return true;
}
private void CopyDirectory(string sourceDir, string targetDir)
{
Directory.CreateDirectory(targetDir);
foreach (var file in Directory.GetFiles(sourceDir))
{
var targetFile = Path.Combine(targetDir, Path.GetFileName(file));
if (!File.Exists(targetFile) || File.GetLastWriteTime(targetFile) < File.GetLastWriteTime(file))
{
File.Copy(file, targetFile, true);
}
}
foreach (var directory in Directory.GetDirectories(sourceDir))
{
var targetSubDir = Path.Combine(targetDir, Path.GetFileName(directory));
CopyDirectory(directory, targetSubDir);
}
}
public void Run()
{
_server = new TorchServer(Config);
if (Config.NoGui)
{
_server.Init();
_server.Start();
}
else
{
#if !DEBUG
if (!Config.IndependentConsole)
{
Console.SetOut(TextWriter.Null);
NativeMethods.FreeConsole();
}
#endif
var gameThread = new Thread(() =>
{
_server.Init();
if (Config.Autostart || Config.TempAutostart)
{
Config.TempAutostart = false;
_server.Start();
}
});
gameThread.Start();
var ui = new TorchUI(_server);
ui.ShowDialog();
}
}
private void InitConfig()
{
var configName = "Torch.cfg";
var configPath = Path.Combine(Directory.GetCurrentDirectory(), configName);
if (File.Exists(configName))
{
Log.Info($"Loading config {configName}");
}
else
{
Log.Info($"Generating default config at {configPath}");
}
ConfigPersistent = Persistent<TorchConfig>.Load(configPath);
}
public static void RunSteamCmd(bool forceOverwriteRunscript = true)
{
var log = LogManager.GetLogger("SteamCMD");
// Migrate from old layout (steamcmd/) to new layout (steam/steamcmd/)
if (Directory.Exists(STEAMCMD_LEGACY_DIR) && !Directory.Exists(STEAMCMD_DIR))
{
log.Info("Migrating SteamCMD from legacy directory...");
Directory.CreateDirectory("steam");
Directory.Move(STEAMCMD_LEGACY_DIR, STEAMCMD_DIR);
log.Info("SteamCMD migrated to steam/steamcmd.");
}
if (!Directory.Exists(STEAMCMD_DIR))
{
Directory.CreateDirectory(STEAMCMD_DIR);
}
if (forceOverwriteRunscript || !File.Exists(RUNSCRIPT_PATH))
File.WriteAllText(RUNSCRIPT_PATH, RUNSCRIPT);
if (!File.Exists(STEAMCMD_PATH))
{
try
{
log.Info("Downloading SteamCMD.");
using (var client = new WebClient())
client.DownloadFile("https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip", STEAMCMD_ZIP);
ZipFile.ExtractToDirectory(STEAMCMD_ZIP, STEAMCMD_DIR);
File.Delete(STEAMCMD_ZIP);
log.Info("SteamCMD downloaded successfully!");
// First-run: SteamCMD needs to self-update, initialize its config store,
// and cache app depot info before it can process app_update commands.
log.Info("Initializing SteamCMD (first run)...");
var initProc = new ProcessStartInfo(STEAMCMD_PATH, "+login anonymous +quit")
{
WorkingDirectory = Path.Combine(Directory.GetCurrentDirectory(), STEAMCMD_DIR),
UseShellExecute = false,
RedirectStandardOutput = true,
StandardOutputEncoding = Encoding.ASCII
};
var initCmd = Process.Start(initProc);
while (!initCmd.HasExited)
{
log.Info(initCmd.StandardOutput.ReadLine());
Thread.Sleep(100);
}
log.Info("SteamCMD initialization complete.");
}
catch (Exception e)
{
log.Error("Failed to download SteamCMD, unable to update the DS.");
log.Error(e);
return;
}
}
log.Info("Checking for DS updates.");
var steamCmdProc = new ProcessStartInfo(STEAMCMD_PATH, "+runscript runscript.txt")
{
WorkingDirectory = Path.Combine(Directory.GetCurrentDirectory(), STEAMCMD_DIR),
UseShellExecute = false,
RedirectStandardOutput = true,
StandardOutputEncoding = Encoding.ASCII
};
var cmd = Process.Start(steamCmdProc);
// ReSharper disable once PossibleNullReferenceException
while (!cmd.HasExited)
{
log.Info(cmd.StandardOutput.ReadLine());
Thread.Sleep(100);
}
log.Info("SteamCMD update check complete.");
}
/// <summary>
/// Peek at Torch.cfg XML to read ForceOverwriteRunscript before TorchConfig can be loaded.
/// Returns true (default) if the config doesn't exist or the element is missing.
/// </summary>
private static bool PeekForceOverwriteRunscript()
{
var configPath = Path.Combine(Directory.GetCurrentDirectory(), "Torch.cfg");
if (!File.Exists(configPath))
return true;
try
{
var doc = System.Xml.Linq.XDocument.Load(configPath);
var element = doc.Root?.Element("ForceOverwriteRunscript");
if (element == null)
return true;
return bool.TryParse(element.Value, out var value) ? value : true;
}
catch
{
return true;
}
}
private void LogException(Exception ex)
{
if (ex is AggregateException ag)
{
foreach (var e in ag.InnerExceptions)
LogException(e);
return;
}
Log.Fatal(ex);
if (ex is ReflectionTypeLoadException extl)
{
foreach (var exl in extl.LoaderExceptions)
LogException(exl);
return;
}
if (ex.InnerException != null)
{
LogException(ex.InnerException);
}
}
private void SendAndDump()
{
var shortdate = DateTime.Now.ToString("yyyy-MM-dd");
var shortdateWithTime = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
var dumpPath = $"Logs\\MiniDumpT{Thread.CurrentThread.ManagedThreadId}-{shortdateWithTime}.dmp";
Log.Info($"Generating minidump at {dumpPath}");
var dumpFlags = MyMiniDump.Options.Normal | MyMiniDump.Options.WithProcessThreadData | MyMiniDump.Options.WithThreadInfo;
MyVRage.Platform.CrashReporting.WriteMiniDump(dumpPath, dumpFlags, IntPtr.Zero);
if (Config.SendLogsToKeen)
{
List<string> additionalFiles = new List<string>();
if (File.Exists(dumpPath))
additionalFiles.Add(dumpPath);
CrashInfo info = MyErrorReporter.BuildCrashInfo();
MyErrorReporter.ReportNotInteractive($"Logs\\Keen-{shortdate}.log", info.AnalyticId, false,
additionalFiles.ToList(), true, string.Empty, string.Empty, info);
}
if(Config.DeleteMiniDumps)
File.Delete(dumpPath);
}
private void HandleException(object sender, UnhandledExceptionEventArgs e)
{
_server.FatalException = true;
var ex = (Exception)e.ExceptionObject;
LogException(ex);
SendAndDump();
LogManager.Flush();
if (Config.RestartOnCrash)
{
Console.WriteLine("Restarting in 5 seconds.");
Thread.Sleep(5000);
var exe = typeof(Program).Assembly.Location;
Config.WaitForPID = Process.GetCurrentProcess().Id.ToString();
Process.Start(exe, Config.ToString());
}
else
{
MessageBox.Show("Torch encountered a fatal error and needs to close. Please check the logs or the Log event viewer for details.", "Torch Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
Process.GetCurrentProcess().Kill();
}
}
}