-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainCommon.cpp
More file actions
568 lines (539 loc) · 17.4 KB
/
MainCommon.cpp
File metadata and controls
568 lines (539 loc) · 17.4 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
#include "Config.h"
#include "Downloader.h"
#include "Logger.h"
#include "MainCommon.h"
#include "Server.h"
#include "Updater.h"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <fstream>
#include <iostream>
#include <memory>
#include <mutex>
#include <thread>
namespace
{
// timer thread state, controlled by main()
enum class TimerState
{
RUN, // timer thread should start/continue running normally
PAUSE, // timer thread should sleep until ordered to run or stop
STOP // timer thread should exit
};
// mutex, mutex-controlled, and atomic thread data
namespace threadData
{
// mutex that controls access to sibling variables
std::mutex mutex_;
// CV on which main() waits for notifications
std::condition_variable cvMain_;
// CV on which timer thread waits for notifications
std::condition_variable cvTimer_;
// timer thread state commanded by main()
TimerState timerState_{TimerState::RUN};
// whether Stop() handler is notifying main() to shut down
std::atomic_flag notifyMainStop_ = ATOMIC_FLAG_INIT;
// whether timer thread is notifying main() to check server health
bool notifyMainServer_{false};
// whether timer thread is notifying main() to check for updates
bool notifyMainUpdater_{false};
// whether main() is notifying timer thread to change state
bool notifyTimerThread_{false};
};
// (re)set start time and wake/notification times based on duration inputs
inline void ResetTimers(
const std::size_t duration1Minutes,
const std::size_t duration2Minutes,
std::chrono::steady_clock::time_point& timeStart,
std::chrono::steady_clock::time_point& time1,
std::chrono::steady_clock::time_point& time2
)
{
timeStart = std::chrono::steady_clock::now();
time1 = timeStart + std::chrono::minutes(duration1Minutes);
time2 = timeStart + std::chrono::minutes(duration2Minutes);
}
void TimerFunction(
const std::size_t sleepDurationMinutes,
const std::size_t updateIntervalMinutes
)
{
const std::chrono::minutes sleepDuration(sleepDurationMinutes);
const std::chrono::minutes updateInterval(updateIntervalMinutes);
std::chrono::steady_clock::time_point startTime;
std::chrono::steady_clock::time_point wakeTime;
std::chrono::steady_clock::time_point updateTime;
ResetTimers(
sleepDurationMinutes, updateIntervalMinutes,
startTime, wakeTime, updateTime
);
while (true)
{
// grab mutex for safe state variable access in loop when awake
std::unique_lock lock(threadData::mutex_);
// release mutex and sleep, unless or until one of the following:
// - wake time reached
// - notification received from main()
// if notified, handle new timer state
if
(
const auto notified(threadData::cvTimer_.wait_until(
lock, wakeTime,
[](){return threadData::notifyTimerThread_;}
));
notified
)
{
// mark notification as processed
threadData::notifyTimerThread_ = false;
if (threadData::timerState_ == TimerState::RUN)
{
// assume PAUSE->RUN
// reset notification target times and loop back around
ResetTimers(
sleepDurationMinutes, updateIntervalMinutes,
startTime, wakeTime, updateTime
);
continue;
}
// don't care about PAUSE here
if (threadData::timerState_ == TimerState::STOP)
{
// assume RUN->STOP or PAUSE->STOP
// break out of loop
break;
}
}
// wait time elapsed, or got PAUSE notification
const bool notifyMain(threadData::timerState_ != TimerState::PAUSE);
const bool updateTimeElapsed(
updateIntervalMinutes && std::chrono::steady_clock::now() >= updateTime
);
// update target times
wakeTime += sleepDuration;
if (updateTimeElapsed) { updateTime += updateInterval; }
// skip notifying main() if "paused"
if (!notifyMain) { continue; }
// set notification flags
threadData::notifyMainServer_ = true;
threadData::notifyMainUpdater_ = updateTimeElapsed;
// notify main()
// it will wake up and grab mutex when we loop around and go back to sleep
threadData::cvMain_.notify_all();
// end of loop body
}
}
// change timer state and notify timer thread of change
// meant to be called by main() under mutex lock
void SetTimerState(const TimerState ts)
{
threadData::timerState_ = ts;
threadData::notifyTimerThread_ = true;
threadData::cvTimer_.notify_all();
}
// check for updates according to provided options
// return pair indicating whether server and/or mod framework needs updating,
// respectively
std::pair<bool, bool> UpdateCheck(
rustLaunchSite::Logger& logger
, const rustLaunchSite::Updater& updater
, const bool checkServer
, const bool checkModFramework
, const bool updateModFrameworkOnServer)
{
std::pair<bool, bool> retVal{false, false};
if (checkServer)
{
LOGINF(logger, "Performing server update check");
retVal.first = updater.CheckServer();
}
if (const bool forceCheck{updateModFrameworkOnServer && retVal.first};
checkModFramework || forceCheck)
{
LOGINF(logger, "Performing mod framework update check");
retVal.second = updater.CheckFramework();
}
return retVal;
}
// wrapper around Updater::UpdateFramework() to loop until update succeeds
void UpdateFramework(
rustLaunchSite::Logger& logger,
const rustLaunchSite::Updater& updater,
const int retryDelaySeconds = 0, const bool suppressWarning = false)
{
LOGINF(logger, "Entering plugin framework update loop");
bool firstTry{true};
for(bool update{true}; update; update = updater.CheckFramework())
{
if (!firstTry)
{
LOGWRN(logger, "Detected plugin framework version mismatch after update attempt...");
if (retryDelaySeconds > 0)
{
LOGWRN(logger, "\t...waiting for " << retryDelaySeconds << " second(s) before trying again");
std::this_thread::sleep_for(std::chrono::seconds(retryDelaySeconds));
}
else
{
LOGWRN(logger, "\t...trying again immediately");
}
}
updater.UpdateFramework(suppressWarning);
firstTry = false;
}
LOGINF(logger, "Completed plugin framework update loop");
}
// wrapper around Updater::UpdateServer() to loop until update succeeds
void UpdateServer(
rustLaunchSite::Logger& logger,
const rustLaunchSite::Updater& updater,
const int retryDelaySeconds = 0)
{
LOGINF(logger, "Entering server update loop");
bool firstTry{true};
for(bool update{true}; update; update = updater.CheckServer())
{
if (!firstTry)
{
LOGWRN(logger, "Detected server version mismatch after update attempt...");
if (retryDelaySeconds > 0)
{
LOGWRN(logger, "\t...waiting for " << retryDelaySeconds << " second(s) before trying again");
std::this_thread::sleep_for(std::chrono::seconds(retryDelaySeconds));
}
else
{
LOGWRN(logger, "\t...trying again immediately");
}
}
updater.UpdateServer();
firstTry = false;
}
LOGINF(logger, "Completed server update loop");
}
// get shutdown reason from text file if one exists
std::string GetShutdownReason(
rustLaunchSite::Logger& logger
, const std::filesystem::path& reasonPath
, std::string_view fallbackReason = {})
{
if (!std::filesystem::exists(reasonPath))
{
LOGINF(logger, "No reason file at reasonPath=" << reasonPath);
return std::string{fallbackReason};
}
std::string retVal{};
std::ifstream reasonStream{reasonPath};
if (reasonStream)
{
// read the file
// this is done line-by-line to normalize EOL characters
std::string line{};
std::size_t lineCount{0};
std::size_t nonEmptyLineCount{0};
while (std::getline(reasonStream, line))
{
++lineCount;
if (!line.empty()) ++nonEmptyLineCount;
if (!retVal.empty()) retVal.append("\n");
retVal.append(line);
}
LOGINF(logger, "Read " << lineCount << " line(s) from reasonPath=" << reasonPath);
// if more than one nonempty line read, ensure reason starts with a newline
if (nonEmptyLineCount > 1 && !retVal.empty() && retVal.at(0) != '\n')
{
retVal.insert(0, "\n");
}
}
else
{
LOGWRN(logger, "Failed to open reason file at reasonPath=" << reasonPath);
// don't return, because we still want to try to remove the file
retVal = fallbackReason;
}
reasonStream.close();
if (std::filesystem::remove(reasonPath))
{
LOGINF(logger, "Deleted reason file at reasonPath=" << reasonPath);
}
else
{
LOGWRN(logger, "Failed to delete reason file at reasonPath=" << reasonPath);
}
return retVal;
}
}
namespace rustLaunchSite
{
int Start(Logger& logger, int argc, char* argv[])
{
LOGINF(logger, "Starting");
if (argc <= 1)
{
LOGERR(logger, "Configuration file/path must be specified as an argument");
return RLS_EXIT_ARG;
}
// create null pointers for all facilities we'll be instantiating, so that we
// can clean them up if an exception is caught
std::shared_ptr<rustLaunchSite::Config> configSptr;
std::unique_ptr<rustLaunchSite::Server> serverUptr;
std::unique_ptr<rustLaunchSite::Updater> updaterUptr;
std::unique_ptr<std::thread> timerThreadUptr;
int retVal(RLS_EXIT_SUCCESS);
try
{
// load config file
configSptr = std::make_shared<rustLaunchSite::Config>(logger, argv[1]);
// instantiate server manager
serverUptr = std::make_unique<rustLaunchSite::Server>(logger, configSptr);
// instantiate update manager
updaterUptr = std::make_unique<rustLaunchSite::Updater>(
logger
, configSptr
, std::make_shared<rustLaunchSite::Downloader>(logger)
);
{
const auto [updateServerOnStartup, updateModFrameworkOnStartup] =
UpdateCheck(
logger
, *updaterUptr
, configSptr->GetUpdateServerOnStartup()
, configSptr->GetUpdateModFrameworkOnStartup()
, configSptr->GetUpdateModFrameworkOnServerUpdate())
;
if (updateServerOnStartup)
{
UpdateServer(
logger
, *updaterUptr
, configSptr->GetUpdateServerRetryDelaySeconds());
}
if (updateModFrameworkOnStartup)
{
UpdateFramework(
logger
, *updaterUptr
, configSptr->GetUpdateModFrameworkRetryDelaySeconds()
, updateServerOnStartup);
}
}
// launch server
LOGINF(logger, "Starting server");
if (!serverUptr->Start())
{
LOGERR(logger, "Server failed to start");
// okay to just abort at this point
return RLS_EXIT_START;
}
// start timer thread
LOGINF(logger, "Starting timer thread");
timerThreadUptr = std::make_unique<std::thread>(
&TimerFunction, 1, configSptr->GetUpdateIntervalMinutes()
);
if (!timerThreadUptr)
{
LOGERR(logger, "Failed to instantiate timer thread");
return RLS_EXIT_THREAD;
}
// main loop
LOGINF(logger, "Starting main event loop");
while (true)
{
// grab mutex for safe state variable access in loop when awake
std::unique_lock lock(threadData::mutex_);
// sleep until we get a notification from the timer thread
// LOGINF(logger, "Waiting for events");
threadData::cvMain_.wait
(
lock,
[](){
return (
threadData::notifyMainStop_.test() ||
threadData::notifyMainServer_ ||
threadData::notifyMainUpdater_
);
}
);
// handle Stop() notification
if (threadData::notifyMainStop_.test())
{
// attempt an orderly shutdown
LOGINF(logger, "Server manager stop requested; stopping server");
::SetTimerState(TimerState::STOP);
serverUptr->Stop(GetShutdownReason(
logger
, configSptr->GetProcessReasonPath()
, "Server manager stopped"));
// as Stop() is the only orderly shutdown stimulus, we want to report a
// successful exit
retVal = RLS_EXIT_SUCCESS;
break;
}
// handle update check timer notification
if (threadData::notifyMainUpdater_)
{
threadData::notifyMainUpdater_ = false;
// check for updates
const auto [updateServerOnInterval, updateModFrameworkOnInterval] =
UpdateCheck(
logger
, *updaterUptr
, configSptr->GetUpdateServerOnInterval()
, configSptr->GetUpdateModFrameworkOnInterval()
, configSptr->GetUpdateModFrameworkOnServerUpdate())
;
// if any are needed: take server down, install updates, relaunch server
if (updateServerOnInterval || updateModFrameworkOnInterval)
{
// pause timer thread
// ...although this probably doesn't matter, since we hold the mutex
::SetTimerState(TimerState::PAUSE);
// derive a reason string
std::string updateReason{};
if (updateServerOnInterval)
{
updateReason.append("Facepunch");
}
if (updateModFrameworkOnInterval)
{
if (!updateReason.empty())
{
updateReason.append(" + ");
}
updateReason.append(rustLaunchSite::Config::ToString(
configSptr->GetUpdateModFrameworkType()));
}
// stop server
LOGINF(logger, "Update(s) required: " << updateReason << "; stopping server");
// install updates
serverUptr->Stop("Installing update(s): " + updateReason);
if (updateServerOnInterval)
{
UpdateServer(
logger
, *updaterUptr, configSptr->GetUpdateServerRetryDelaySeconds());
}
if (updateModFrameworkOnInterval)
{
UpdateFramework(
logger
, *updaterUptr
, configSptr->GetUpdateModFrameworkRetryDelaySeconds()
, updateServerOnInterval);
}
LOGINF(logger, "Update(s) complete; starting server");
if (!serverUptr->Start())
{
LOGERR(logger, "Server failed to start");
retVal = RLS_EXIT_UPDATE;
break;
}
// resume timer thread
::SetTimerState(TimerState::RUN);
}
}
// handle server health check timer notification
if (threadData::notifyMainServer_)
{
threadData::notifyMainServer_ = false;
// check if server is running
if (serverUptr->IsRunning())
{
// server is running; check for protocol via RCON
// just poll every time, as RCON connection seems to die if we don't
// use it?
if (const auto& serverInfo(serverUptr->GetInfo());
serverInfo.valid_)
{
LOGINF(logger, "rustLaunchSite: Got server info via RCON: players=" << serverInfo.players_ << ", protocol=" << serverInfo.protocol_);
}
}
// server is not running
else if (configSptr->GetProcessAutoRestart())
{
// configured to automatically restart
// pause timers during server restart
::SetTimerState(TimerState::PAUSE);
LOGINF(logger, "Server stopped unexpectedly");
// check for updates while the server is down
const auto [updateServerOnRelaunch, updateModFrameworkOnRelaunch] =
UpdateCheck(
logger
, *updaterUptr
, configSptr->GetUpdateServerOnRelaunch()
, configSptr->GetUpdateModFrameworkOnRelaunch()
, configSptr->GetUpdateModFrameworkOnServerUpdate())
;
if (updateServerOnRelaunch)
{
UpdateServer(
logger
, *updaterUptr
, configSptr->GetUpdateServerRetryDelaySeconds());
}
if (updateModFrameworkOnRelaunch)
{
UpdateFramework(
logger
, *updaterUptr
, configSptr->GetUpdateModFrameworkRetryDelaySeconds()
, updateServerOnRelaunch);
}
// relaunch server
LOGINF(logger, "Relaunching server");
if (!serverUptr->Start())
{
LOGERR(logger, "Server failed to relaunch");
retVal = RLS_EXIT_RESTART;
break;
}
::SetTimerState(TimerState::RUN);
}
else
{
// configured to shutdown on unexpected server stop
::SetTimerState(TimerState::STOP);
LOGERR(logger, "Server stopped unexpectedly");
retVal = RLS_EXIT_RESTART;
break;
}
}
// end of main loop
}
LOGINF(logger, "Exited main loop; beginning shutdown process");
LOGINF(logger, "Stopping timer thread");
::SetTimerState(TimerState::STOP);
timerThreadUptr->join();
LOGINF(logger, "Stopping server (if running)");
serverUptr->Stop(GetShutdownReason(
logger
, configSptr->GetProcessReasonPath(), "Server manager shutting down"));
}
catch (const std::exception& e)
{
LOGERR(logger, "ERROR: Unhandled exception: " << e.what());
retVal = RLS_EXIT_EXCEPTION;
}
catch(...)
{
LOGERR(logger, "ERROR: Unknown exception");
retVal = RLS_EXIT_EXCEPTION;
}
// std::thread blows up the application if not joined before exit, so check
// again in case we're here due to catching an exception
if (timerThreadUptr && timerThreadUptr->joinable())
{
::SetTimerState(TimerState::STOP);
timerThreadUptr->join();
}
LOGINF(logger, "Exiting");
return retVal;
}
void Stop()
{
// attempt to signal main()
threadData::notifyMainStop_.test_and_set();
threadData::cvMain_.notify_all();
}
}