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
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "zenutil/zenserverprocess.h"
#include <zencore/except.h>
#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/session.h>
#include <zencore/string.h>
#include <zencore/thread.h>
#include <atomic>
#if ZEN_PLATFORM_WINDOWS
# include <atlbase.h>
# include <zencore/windows.h>
#else
# include <sys/mman.h>
#endif
//////////////////////////////////////////////////////////////////////////
namespace zen {
namespace zenutil {
#if ZEN_PLATFORM_WINDOWS
class SecurityAttributes
{
public:
inline SECURITY_ATTRIBUTES* Attributes() { return &m_Attributes; }
protected:
SECURITY_ATTRIBUTES m_Attributes{};
SECURITY_DESCRIPTOR m_Sd{};
};
// Security attributes which allows any user access
class AnyUserSecurityAttributes : public SecurityAttributes
{
public:
AnyUserSecurityAttributes()
{
m_Attributes.nLength = sizeof m_Attributes;
m_Attributes.bInheritHandle = false; // Disable inheritance
const BOOL Success = InitializeSecurityDescriptor(&m_Sd, SECURITY_DESCRIPTOR_REVISION);
if (Success)
{
if (!SetSecurityDescriptorDacl(&m_Sd, TRUE, (PACL)NULL, FALSE))
{
ThrowLastError("SetSecurityDescriptorDacl failed");
}
m_Attributes.lpSecurityDescriptor = &m_Sd;
}
}
};
#endif // ZEN_PLATFORM_WINDOWS
} // namespace zenutil
//////////////////////////////////////////////////////////////////////////
ZenServerState::ZenServerState()
{
}
ZenServerState::~ZenServerState()
{
if (m_OurEntry)
{
// Clean up our entry now that we're leaving
m_OurEntry->Reset();
m_OurEntry = nullptr;
}
#if ZEN_PLATFORM_WINDOWS
if (m_Data)
{
UnmapViewOfFile(m_Data);
}
if (m_hMapFile)
{
CloseHandle(m_hMapFile);
}
#else
if (m_Data != nullptr)
{
munmap(m_Data, m_MaxEntryCount * sizeof(ZenServerEntry));
}
int Fd = int(intptr_t(m_hMapFile));
close(Fd);
#endif
m_Data = nullptr;
}
void
ZenServerState::Initialize()
{
size_t MapSize = m_MaxEntryCount * sizeof(ZenServerEntry);
#if ZEN_PLATFORM_WINDOWS
// TODO: there's a small chance of a race here, this logic could be tightened up with a mutex to
// ensure only a single process at a time creates the mapping
// TODO: the fallback to Local instead of Global has a flaw where if you start a non-elevated instance
// first then start an elevated instance second you'll have the first instance with a local
// mapping and the second instance with a global mapping. This kind of elevated/non-elevated
// shouldn't be common, but handling for it should be improved in the future.
HANDLE hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, L"Global\\ZenMap");
if (hMap == NULL)
{
hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, L"Local\\ZenMap");
}
if (hMap == NULL)
{
// Security attributes to enable any user to access state
zenutil::AnyUserSecurityAttributes Attrs;
hMap = CreateFileMapping(INVALID_HANDLE_VALUE, // use paging file
Attrs.Attributes(), // allow anyone to access
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
DWORD(MapSize), // maximum object size (low-order DWORD)
L"Global\\ZenMap"); // name of mapping object
if (hMap == NULL)
{
hMap = CreateFileMapping(INVALID_HANDLE_VALUE, // use paging file
Attrs.Attributes(), // allow anyone to access
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
m_MaxEntryCount * sizeof(ZenServerEntry), // maximum object size (low-order DWORD)
L"Local\\ZenMap"); // name of mapping object
}
if (hMap == NULL)
{
ThrowLastError("Could not open or create file mapping object for Zen server state");
}
}
void* pBuf = MapViewOfFile(hMap, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0, // offset high
0, // offset low
DWORD(MapSize));
if (pBuf == NULL)
{
ThrowLastError("Could not map view of Zen server state");
}
#else
int Fd = shm_open("/UnrealEngineZen", O_RDWR | O_CREAT | O_CLOEXEC, 0666);
if (Fd < 0)
{
ThrowLastError("Could not open a shared memory object");
}
fchmod(Fd, 0666);
void* hMap = (void*)intptr_t(Fd);
int Result = ftruncate(Fd, MapSize);
ZEN_UNUSED(Result);
void* pBuf = mmap(nullptr, MapSize, PROT_READ | PROT_WRITE, MAP_SHARED, Fd, 0);
if (pBuf == MAP_FAILED)
{
ThrowLastError("Could not map view of Zen server state");
}
#endif
m_hMapFile = hMap;
m_Data = reinterpret_cast<ZenServerEntry*>(pBuf);
m_IsReadOnly = false;
}
bool
ZenServerState::InitializeReadOnly()
{
size_t MapSize = m_MaxEntryCount * sizeof(ZenServerEntry);
#if ZEN_PLATFORM_WINDOWS
HANDLE hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, L"Global\\ZenMap");
if (hMap == NULL)
{
hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, L"Local\\ZenMap");
}
if (hMap == NULL)
{
return false;
}
void* pBuf = MapViewOfFile(hMap, // handle to map object
FILE_MAP_READ, // read permission
0, // offset high
0, // offset low
MapSize);
if (pBuf == NULL)
{
ThrowLastError("Could not map view of Zen server state");
}
#else
int Fd = shm_open("/UnrealEngineZen", O_RDONLY | O_CLOEXEC, 0666);
if (Fd < 0)
{
return false;
}
void* hMap = (void*)intptr_t(Fd);
void* pBuf = mmap(nullptr, MapSize, PROT_READ, MAP_PRIVATE, Fd, 0);
if (pBuf == MAP_FAILED)
{
ThrowLastError("Could not map read-only view of Zen server state");
}
#endif
m_hMapFile = hMap;
m_Data = reinterpret_cast<ZenServerEntry*>(pBuf);
return true;
}
ZenServerState::ZenServerEntry*
ZenServerState::Lookup(int DesiredListenPort)
{
for (int i = 0; i < m_MaxEntryCount; ++i)
{
if (m_Data[i].DesiredListenPort == DesiredListenPort)
{
return &m_Data[i];
}
}
return nullptr;
}
ZenServerState::ZenServerEntry*
ZenServerState::Register(int DesiredListenPort)
{
if (m_Data == nullptr)
{
return nullptr;
}
// Allocate an entry
int Pid = GetCurrentProcessId();
for (int i = 0; i < m_MaxEntryCount; ++i)
{
ZenServerEntry& Entry = m_Data[i];
if (Entry.DesiredListenPort.load(std::memory_order_relaxed) == 0)
{
uint16_t Expected = 0;
if (Entry.DesiredListenPort.compare_exchange_strong(Expected, uint16_t(DesiredListenPort)))
{
// Successfully allocated entry
m_OurEntry = &Entry;
Entry.Pid = Pid;
Entry.EffectiveListenPort = 0;
Entry.Flags = 0;
const Oid SesId = GetSessionId();
memcpy(Entry.SessionId, &SesId, sizeof SesId);
return &Entry;
}
}
}
return nullptr;
}
void
ZenServerState::Sweep()
{
if (m_Data == nullptr)
{
return;
}
ZEN_ASSERT(m_IsReadOnly == false);
for (int i = 0; i < m_MaxEntryCount; ++i)
{
ZenServerEntry& Entry = m_Data[i];
if (Entry.DesiredListenPort)
{
if (IsProcessRunning(Entry.Pid) == false)
{
ZEN_DEBUG("Sweep - pid {} not running, reclaiming entry (port {})", Entry.Pid, Entry.DesiredListenPort);
Entry.Reset();
}
}
}
}
void
ZenServerState::Snapshot(std::function<void(const ZenServerEntry&)>&& Callback)
{
if (m_Data == nullptr)
{
return;
}
for (int i = 0; i < m_MaxEntryCount; ++i)
{
ZenServerEntry& Entry = m_Data[i];
if (Entry.DesiredListenPort)
{
Callback(Entry);
}
}
}
void
ZenServerState::ZenServerEntry::Reset()
{
Pid = 0;
DesiredListenPort = 0;
Flags = 0;
EffectiveListenPort = 0;
}
void
ZenServerState::ZenServerEntry::SignalShutdownRequest()
{
Flags |= uint16_t(FlagsEnum::kShutdownPlease);
}
void
ZenServerState::ZenServerEntry::SignalReady()
{
Flags |= uint16_t(FlagsEnum::kIsReady);
}
bool
ZenServerState::ZenServerEntry::AddSponsorProcess(uint32_t PidToAdd)
{
for (std::atomic<uint32_t>& PidEntry : SponsorPids)
{
if (PidEntry.load(std::memory_order_relaxed) == 0)
{
uint32_t Expected = 0;
if (PidEntry.compare_exchange_strong(Expected, PidToAdd))
{
// Success!
return true;
}
}
else if (PidEntry.load(std::memory_order_relaxed) == PidToAdd)
{
// Success, the because pid is already in the list
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////
std::atomic<int> TestCounter{0};
ZenServerEnvironment::ZenServerEnvironment()
{
}
ZenServerEnvironment::~ZenServerEnvironment()
{
}
void
ZenServerEnvironment::Initialize(std::filesystem::path ProgramBaseDir)
{
m_ProgramBaseDir = ProgramBaseDir;
ZEN_DEBUG("Program base dir is '{}'", ProgramBaseDir);
m_IsInitialized = true;
}
void
ZenServerEnvironment::InitializeForTest(std::filesystem::path ProgramBaseDir, std::filesystem::path TestBaseDir)
{
m_ProgramBaseDir = ProgramBaseDir;
m_TestBaseDir = TestBaseDir;
ZEN_INFO("Program base dir is '{}'", ProgramBaseDir);
ZEN_INFO("Cleaning test base dir '{}'", TestBaseDir);
DeleteDirectories(TestBaseDir.c_str());
m_IsTestInstance = true;
m_IsInitialized = true;
}
std::filesystem::path
ZenServerEnvironment::CreateNewTestDir()
{
using namespace std::literals;
ExtendableWideStringBuilder<256> TestDir;
TestDir << "test"sv << int64_t(++TestCounter);
std::filesystem::path TestPath = m_TestBaseDir / TestDir.c_str();
ZEN_INFO("Creating new test dir @ '{}'", TestPath);
CreateDirectories(TestPath.c_str());
return TestPath;
}
std::filesystem::path
ZenServerEnvironment::GetTestRootDir(std::string_view Path)
{
std::filesystem::path Root = m_ProgramBaseDir.parent_path().parent_path();
std::filesystem::path Relative{Path};
return Root / Relative;
}
//////////////////////////////////////////////////////////////////////////
std::atomic<int> ChildIdCounter{0};
ZenServerInstance::ZenServerInstance(ZenServerEnvironment& TestEnvironment) : m_Env(TestEnvironment)
{
ZEN_ASSERT(TestEnvironment.IsInitialized());
}
ZenServerInstance::~ZenServerInstance()
{
Shutdown();
}
void
ZenServerInstance::SignalShutdown()
{
m_ShutdownEvent.Set();
}
void
ZenServerInstance::Shutdown()
{
if (m_Process.IsValid())
{
if (m_Terminate)
{
ZEN_INFO("Terminating zenserver process");
m_Process.Terminate(111);
m_Process.Reset();
}
else
{
SignalShutdown();
m_Process.Wait();
m_Process.Reset();
}
}
}
void
ZenServerInstance::SpawnServer(int BasePort, std::string_view AdditionalServerArgs)
{
ZEN_ASSERT(!m_Process.IsValid()); // Only spawn once
const int MyPid = zen::GetCurrentProcessId();
const int ChildId = ++ChildIdCounter;
ExtendableStringBuilder<32> ChildEventName;
ChildEventName << "Zen_Child_" << ChildId;
NamedEvent ChildEvent{ChildEventName};
CreateShutdownEvent(BasePort);
ExtendableStringBuilder<32> LogId;
LogId << "Zen" << ChildId;
ExtendableStringBuilder<512> CommandLine;
CommandLine << "zenserver" ZEN_EXE_SUFFIX_LITERAL; // see CreateProc() call for actual binary path
const bool IsTest = m_Env.IsTestEnvironment();
if (IsTest)
{
if (!m_OwnerPid.has_value())
{
m_OwnerPid = MyPid;
}
CommandLine << " --test --log-id " << LogId;
}
if (m_OwnerPid.has_value())
{
CommandLine << " --owner-pid " << m_OwnerPid.value();
}
CommandLine << " --child-id " << ChildEventName;
if (BasePort)
{
CommandLine << " --port " << BasePort;
m_BasePort = BasePort;
}
if (!m_TestDir.empty())
{
CommandLine << " --data-dir ";
PathToUtf8(m_TestDir.c_str(), CommandLine);
}
if (m_MeshEnabled)
{
CommandLine << " --mesh";
}
if (!AdditionalServerArgs.empty())
{
CommandLine << " " << AdditionalServerArgs;
}
std::filesystem::path CurrentDirectory = std::filesystem::current_path();
ZEN_DEBUG("Spawning server '{}'", LogId);
uint32_t CreationFlags = 0;
if (!IsTest)
{
CreationFlags |= CreateProcOptions::Flag_NewConsole;
}
const std::filesystem::path BaseDir = m_Env.ProgramBaseDir();
const std::filesystem::path Executable = BaseDir / "zenserver" ZEN_EXE_SUFFIX_LITERAL;
CreateProcOptions CreateOptions = {
.WorkingDirectory = &CurrentDirectory,
.Flags = CreationFlags,
};
CreateProcResult ChildPid = CreateProc(Executable, CommandLine.ToView(), CreateOptions);
#if ZEN_PLATFORM_WINDOWS
if (!ChildPid && ::GetLastError() == ERROR_ELEVATION_REQUIRED)
{
ZEN_DEBUG("Regular spawn failed - spawning elevated server");
CreateOptions.Flags |= CreateProcOptions::Flag_Elevated;
ChildPid = CreateProc(Executable, CommandLine.ToView(), CreateOptions);
}
#endif
if (!ChildPid)
{
ThrowLastError("Server spawn failed");
}
ZEN_DEBUG("Server '{}' spawned OK", LogId);
if (IsTest)
{
m_Process.Initialize(ChildPid);
}
m_ReadyEvent = std::move(ChildEvent);
}
void
ZenServerInstance::CreateShutdownEvent(int BasePort)
{
ExtendableStringBuilder<32> ChildShutdownEventName;
ChildShutdownEventName << "Zen_" << BasePort;
ChildShutdownEventName << "_Shutdown";
NamedEvent ChildShutdownEvent{ChildShutdownEventName};
m_ShutdownEvent = std::move(ChildShutdownEvent);
}
void
ZenServerInstance::AttachToRunningServer(int BasePort)
{
ZenServerState State;
if (!State.InitializeReadOnly())
{
// TODO: return success/error code instead?
throw std::runtime_error("No zen state found");
}
const ZenServerState::ZenServerEntry* Entry = nullptr;
if (BasePort)
{
Entry = State.Lookup(BasePort);
}
else
{
State.Snapshot([&](const ZenServerState::ZenServerEntry& InEntry) { Entry = &InEntry; });
}
if (!Entry)
{
// TODO: return success/error code instead?
throw std::runtime_error("No server found");
}
m_Process.Initialize(Entry->Pid);
CreateShutdownEvent(BasePort);
}
void
ZenServerInstance::Detach()
{
if (m_Process.IsValid())
{
m_Process.Reset();
m_ShutdownEvent.Close();
}
}
void
ZenServerInstance::WaitUntilReady()
{
while (m_ReadyEvent.Wait(100) == false)
{
if (!m_Process.IsRunning() || !m_Process.IsValid())
{
ZEN_INFO("Wait abandoned by invalid process (running={})", m_Process.IsRunning());
return;
}
}
}
bool
ZenServerInstance::WaitUntilReady(int Timeout)
{
return m_ReadyEvent.Wait(Timeout);
}
std::string
ZenServerInstance::GetBaseUri() const
{
ZEN_ASSERT(m_BasePort);
return fmt::format("http://localhost:{}", m_BasePort);
}
} // namespace zen
|