aboutsummaryrefslogtreecommitdiff
path: root/zenutil/zenserverprocess.cpp
blob: 9d38d3939e521a896d191816e4743a22ec1798ba (plain) (blame)
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
// Copyright Epic Games, Inc. All Rights Reserved.

#include "zenserverprocess.h"

#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/string.h>

#include <shellapi.h>
#include <spdlog/spdlog.h>

//////////////////////////////////////////////////////////////////////////

std::atomic<int> TestCounter{0};

ZenServerEnvironment::ZenServerEnvironment()
{
}

ZenServerEnvironment::~ZenServerEnvironment()
{
}

void
ZenServerEnvironment::Initialize(std::filesystem::path ProgramBaseDir)
{
	m_ProgramBaseDir = ProgramBaseDir;

	spdlog::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;

	spdlog::info("Program base dir is '{}'", ProgramBaseDir);
	spdlog::info("Cleaning test base dir '{}'", TestBaseDir);
	zen::DeleteDirectories(TestBaseDir.c_str());

	m_IsTestInstance = true;
	m_IsInitialized	 = true;
}

std::filesystem::path
ZenServerEnvironment::CreateNewTestDir()
{
	using namespace std::literals;

	zen::ExtendableWideStringBuilder<256> TestDir;
	TestDir << "test"sv << int64_t(++TestCounter);

	std::filesystem::path TestPath = m_TestBaseDir / TestDir.c_str();

	spdlog::info("Creating new test dir @ '{}'", TestPath);

	zen::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()
{
	if (m_Process.IsValid())
	{
		if (m_Terminate)
		{
			spdlog::info("Terminating zenserver process");
			m_Process.Terminate(111);
		}
		else
		{
			SignalShutdown();
			m_Process.Wait();
		}
	}
}

void
ZenServerInstance::SpawnServer(int BasePort)
{
	ZEN_ASSERT(!m_Process.IsValid());  // Only spawn once

	const std::filesystem::path BaseDir	   = m_Env.ProgramBaseDir();
	const std::filesystem::path Executable = BaseDir / "zenserver.exe";

	const int MyPid	  = _getpid();
	const int ChildId = ++ChildIdCounter;

	zen::ExtendableStringBuilder<32> ChildEventName;
	ChildEventName << "Zen_Child_" << ChildId;
	zen::NamedEvent ChildEvent{ChildEventName};

	zen::ExtendableStringBuilder<32> ChildShutdownEventName;
	ChildShutdownEventName << "Zen_Child_" << ChildId;
	ChildShutdownEventName << "_Shutdown";
	zen::NamedEvent ChildShutdownEvent{ChildShutdownEventName};

	zen::ExtendableStringBuilder<32> LogId;
	LogId << "Zen" << ChildId;

	zen::ExtendableWideStringBuilder<128> CommandLine;
	CommandLine << "\"";
	CommandLine.Append(Executable.c_str());
	CommandLine << "\"";

	const bool IsTest = m_Env.IsTestEnvironment();

	if (IsTest)
	{
		CommandLine << " --test --owner-pid " << MyPid << " --log-id " << LogId;
	}

	CommandLine << " --child-id " << ChildEventName;

	if (BasePort)
	{
		CommandLine << " --port " << BasePort;
	}

	if (!m_TestDir.empty())
	{
		CommandLine << " --data-dir ";
		CommandLine << m_TestDir.c_str();
	}

	if (m_MeshEnabled)
	{
		CommandLine << " --mesh";
	}

	std::filesystem::path CurrentDirectory = std::filesystem::current_path();

	spdlog::debug("Spawning server");

	PROCESS_INFORMATION ProcessInfo{};
	STARTUPINFO			StartupInfo{.cb = sizeof(STARTUPINFO)};

	DWORD CreationFlags = 0;

	if (!IsTest)
	{
		CreationFlags |= CREATE_NEW_CONSOLE;
	}

	HANDLE hProcess = NULL;

	{
		const bool			  InheritHandles	= false;
		void*				  Environment		= nullptr;
		LPSECURITY_ATTRIBUTES ProcessAttributes = nullptr;
		LPSECURITY_ATTRIBUTES ThreadAttributes	= nullptr;

		BOOL Success = CreateProcessW(Executable.c_str(),
									  (LPWSTR)CommandLine.c_str(),
									  ProcessAttributes,
									  ThreadAttributes,
									  InheritHandles,
									  CreationFlags,
									  Environment,
									  CurrentDirectory.c_str(),
									  &StartupInfo,
									  &ProcessInfo);

		if (Success)
		{
			hProcess = ProcessInfo.hProcess;
			CloseHandle(ProcessInfo.hThread);
		}
		else
		{
			DWORD WinError = ::GetLastError();

			if (WinError == ERROR_ELEVATION_REQUIRED)
			{
				// Try launching elevated process

				spdlog::debug("Regular spawn failed - spawning elevated server");

				SHELLEXECUTEINFO ShellExecuteInfo;
				ZeroMemory(&ShellExecuteInfo, sizeof(ShellExecuteInfo));
				ShellExecuteInfo.cbSize		  = sizeof(ShellExecuteInfo);
				ShellExecuteInfo.fMask		  = SEE_MASK_UNICODE | SEE_MASK_NOCLOSEPROCESS;
				ShellExecuteInfo.lpFile		  = Executable.c_str();
				ShellExecuteInfo.lpVerb		  = TEXT("runas");
				ShellExecuteInfo.nShow		  = SW_SHOW;
				ShellExecuteInfo.lpParameters = CommandLine.c_str();

				if (::ShellExecuteEx(&ShellExecuteInfo))
				{
					WinError = NO_ERROR;

					hProcess = ShellExecuteInfo.hProcess;
				}
			}

			if (WinError != NO_ERROR)
			{
				std::error_code err(WinError, std::system_category());

				spdlog::error("Server spawn failed: {}", err.message());

				throw std::system_error(err, "failed to create server process");
			}
		}
	}

	spdlog::debug("Server spawned OK");

	if (IsTest)
	{
		m_Process.Initialize(hProcess);
		m_ShutdownEvent = std::move(ChildShutdownEvent);
	}
	else
	{
		CloseHandle(hProcess);
	}

	m_ReadyEvent = std::move(ChildEvent);
}

void
ZenServerInstance::WaitUntilReady()
{
	m_ReadyEvent.Wait();
}

bool
ZenServerInstance::WaitUntilReady(int Timeout)
{
	return m_ReadyEvent.Wait(Timeout);
}