aboutsummaryrefslogtreecommitdiff
path: root/src/zen/cmds/up_cmd.cpp
blob: aacc115a0f1ee96d79134ef186a4a2fe9485bcf7 (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
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
// Copyright Epic Games, Inc. All Rights Reserved.

#include "up_cmd.h"

#include <zencore/compactbinary.h>
#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/process.h>
#include <zencore/timer.h>
#include <zenutil/zenserverprocess.h>

#include <memory>

namespace zen {

UpCommand::UpCommand()
{
	m_Options.add_option("", "p", "port", "Host port", cxxopts::value(m_Port)->default_value("0"), "<hostport>");
	m_Options.add_option("", "b", "base-dir", "Parent folder of server executable", cxxopts::value(m_ProgramBaseDir), "<directory>");
	m_Options
		.add_option("", "c", "show-console", "Open a console window for the zenserver process", cxxopts::value(m_ShowConsole), "<console>");
	m_Options.add_option("",
						 "l",
						 "show-log",
						 "Show the output log of the zenserver process after successful start",
						 cxxopts::value(m_ShowLog),
						 "<showlog>");
}

UpCommand::~UpCommand() = default;

int
UpCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
	using namespace std::literals;

	ZEN_UNUSED(GlobalOptions);

	if (!ParseOptions(argc, argv))
	{
		return 0;
	}

	if (m_ShowConsole && m_ShowLog)
	{
		throw OptionParseException("--show-console can not be used in combination with --show-log");
	}

	{
		ZenServerState State;
		if (State.InitializeReadOnly())
		{
			struct EntryInfo
			{
				uint32_t Pid		   = 0;
				uint16_t DesiredPort   = 0;
				uint16_t EffectivePort = 0;
			};
			std::vector<EntryInfo> RunningEntries;
			State.Snapshot([&RunningEntries, DesiredPort = this->m_Port](const zen::ZenServerState::ZenServerEntry& Entry) {
				if (DesiredPort == 0 || Entry.DesiredListenPort.load() == DesiredPort)
				{
					RunningEntries.push_back(EntryInfo{.Pid			  = Entry.Pid.load(),
													   .DesiredPort	  = Entry.DesiredListenPort.load(),
													   .EffectivePort = Entry.EffectiveListenPort.load()});
				}
			});
			if (RunningEntries.size() > 0)
			{
				ZEN_CONSOLE("Zen server already running with base port {}. First instance at port {}, pid {}",
							RunningEntries[0].DesiredPort,
							RunningEntries[0].EffectivePort,
							RunningEntries[0].Pid);
				return 0;
			}
		}
	}

	std::filesystem::path ProgramBaseDir = StringToPath(m_ProgramBaseDir);

	if (ProgramBaseDir.empty())
	{
		std::filesystem::path ExePath = zen::GetRunningExecutablePath();
		ProgramBaseDir				  = ExePath.parent_path();
	}
	ZenServerEnvironment ServerEnvironment;
	ServerEnvironment.Initialize(ProgramBaseDir);
	ZenServerInstance Server(ServerEnvironment);
	std::string		  ServerArguments = GlobalOptions.PassthroughCommandLine;
	if ((m_Port != 0) && (ServerArguments.find("--port"sv) == std::string::npos))
	{
		ServerArguments.append(fmt::format(" --port {}", m_Port));
	}
	Server.SpawnServer(ServerArguments, m_ShowConsole, /*WaitTimeoutMs*/ 0);

	int Timeout = 10000;

	if (!Server.WaitUntilReady(Timeout))
	{
		if (Server.IsRunning())
		{
			ZEN_ERROR("zen server launch failed (timed out), terminating");
			Server.Terminate();
			if (!m_ShowConsole)
			{
				ZEN_CONSOLE("{}", Server.GetLogOutput());
			}
			return 111;
		}
		int ReturnCode = Server.Shutdown();
		if (!m_ShowConsole)
		{
			ZEN_CONSOLE("{}", Server.GetLogOutput());
		}
		return ReturnCode;
	}
	else
	{
		if (m_ShowLog)
		{
			ZEN_CONSOLE("{}", Server.GetLogOutput());
		}
		else
		{
			ZEN_CONSOLE("zen server up");
		}
	}
	return 0;
}

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

AttachCommand::AttachCommand()
{
	m_Options.add_option("", "p", "port", "Host port", cxxopts::value(m_Port)->default_value("8558"), "<hostport>");
	m_Options.add_option("lifetime", "", "owner-pid", "Specify owning process id", cxxopts::value(m_OwnerPid), "<identifier>");
	m_Options.add_option("", "", "data-dir", "Path to data directory to inspect for running server", cxxopts::value(m_DataDir), "<file>");
}

AttachCommand::~AttachCommand() = default;

int
AttachCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
	ZEN_UNUSED(GlobalOptions);

	if (!ParseOptions(argc, argv))
	{
		return 0;
	}

	ZenServerState Instance;
	Instance.Initialize();
	Instance.Sweep();
	ZenServerState::ZenServerEntry* Entry = Instance.Lookup(m_Port);

	std::filesystem::path DataDir = StringToPath(m_DataDir);

	if (!DataDir.empty())
	{
		if (!IsFile(DataDir / ".lock"))
		{
			ZEN_CONSOLE("lock file does not exist in directory '{}'", DataDir);
			return 1;
		}
		LockFileInfo Info = ReadLockFilePayload(LoadCompactBinaryObject(IoBufferBuilder::MakeFromFile(DataDir / ".lock")));
		std::string	 Reason;
		if (!ValidateLockFileInfo(Info, Reason))
		{
			ZEN_CONSOLE("lock file in directory '{}' is not valid. Reason: '{}'", DataDir, Reason);
			return 1;
		}
		Entry = Instance.LookupByEffectivePort(Info.EffectiveListenPort);
	}

	if (!Entry)
	{
		ZEN_WARN("no zen server instance to add sponsor process to");
		return 1;
	}

	// Sponsor processes are checked every second, so 2 second wait time should be enough
	if (!Entry->AddSponsorProcess(m_OwnerPid, 2000))
	{
		ZEN_WARN("unable to add sponsor process to running zen server instance");
		return 1;
	}

	ZEN_CONSOLE("added sponsor process {} to running instance {} on port {}", m_OwnerPid, Entry->Pid.load(), m_Port);
	return 0;
}

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

DownCommand::DownCommand()
{
	m_Options.add_option("", "p", "port", "Host port", cxxopts::value(m_Port)->default_value("0"), "<hostport>");
	m_Options.add_option("", "f", "force", "Force terminate if graceful shutdown fails", cxxopts::value(m_ForceTerminate), "<force>");
	m_Options.add_option("", "b", "base-dir", "Parent folder of server executable", cxxopts::value(m_ProgramBaseDir), "<directory>");
	m_Options.add_option("", "", "data-dir", "Path to data directory to inspect for running server", cxxopts::value(m_DataDir), "<file>");
}

DownCommand::~DownCommand() = default;

int
DownCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
	ZEN_UNUSED(GlobalOptions);

	if (!ParseOptions(argc, argv))
	{
		return 0;
	}

	// Discover executing instances
	ZenServerState Instance;
	Instance.Initialize();
	ZenServerState::ZenServerEntry* Entry = Instance.Lookup(m_Port);

	std::filesystem::path ProgramBaseDir = StringToPath(m_ProgramBaseDir);
	if (ProgramBaseDir.empty())
	{
		std::filesystem::path ExePath = GetRunningExecutablePath();
		ProgramBaseDir				  = ExePath.parent_path();
	}

	std::filesystem::path DataDir = StringToPath(m_DataDir);

	if (!DataDir.empty())
	{
		if (!IsFile(DataDir / ".lock"))
		{
			ZEN_CONSOLE("lock file does not exist in directory '{}'", DataDir);
			return 1;
		}
		LockFileInfo Info = ReadLockFilePayload(LoadCompactBinaryObject(IoBufferBuilder::MakeFromFile(DataDir / ".lock")));
		std::string	 Reason;
		if (!ValidateLockFileInfo(Info, Reason))
		{
			ZEN_CONSOLE("lock file in directory '{}' is not valid. Reason: '{}'", DataDir, Reason);
			return 1;
		}
		Entry = Instance.LookupByEffectivePort(Info.EffectiveListenPort);
	}

	if (Entry)
	{
		int			   EntryPort		= (int)Entry->DesiredListenPort.load();
		const uint32_t ServerProcessPid = Entry->Pid.load();
		try
		{
			ZenServerEnvironment ServerEnvironment;
			ServerEnvironment.Initialize(ProgramBaseDir);
			ZenServerInstance Server(ServerEnvironment);
			Server.AttachToRunningServer(EntryPort);

			ZEN_CONSOLE("attached to server on port {} (pid {}), requesting shutdown", EntryPort, ServerProcessPid);

			std::error_code Ec;
			if (Server.SignalShutdown(Ec) && !Ec)
			{
				Stopwatch Timer;
				while (Timer.GetElapsedTimeMs() < 10000)
				{
					if (Server.WaitUntilExited(100, Ec) && !Ec)
					{
						ZEN_CONSOLE("shutdown complete");
						return 0;
					}
					else if (Ec)
					{
						ZEN_CONSOLE("Waiting for server on port {} (pid {}) failed. Reason: '{}'",
									EntryPort,
									ServerProcessPid,
									Ec.message());
					}
				}
			}
			else if (Ec)
			{
				ZEN_CONSOLE("requesting shutdown of server on port {} failed. Reason: '{}'", EntryPort, Ec.message());
			}
		}
		catch (const std::exception& Ex)
		{
			ZEN_DEBUG("Exception caught when requesting shutdown: {}", Ex.what());
		}

		// Since we cannot obtain a handle to the process we are unable to block on the process
		// handle to determine when the server has shut down. Thus we signal that we would like
		// a shutdown via the shutdown flag and the check if the entry is still running.

		ZEN_CONSOLE("requesting detached shutdown of server on port {}", EntryPort);
		Entry->SignalShutdownRequest();

		Stopwatch Timer;
		while (Timer.GetElapsedTimeMs() < 10000)
		{
			Instance.Sweep();
			Entry = Instance.Lookup(EntryPort);
			if (Entry == nullptr)
			{
				ZEN_CONSOLE("shutdown complete");
				return 0;
			}
			if (Entry->Pid.load() != ServerProcessPid)
			{
				ZEN_CONSOLE("shutdown complete");
				return 0;
			}
			Sleep(100);
		}
	}

	if (m_ForceTerminate)
	{
		// Try to find the running executable by path name
		std::filesystem::path ServerExePath = ProgramBaseDir / "zenserver" ZEN_EXE_SUFFIX_LITERAL;
		ProcessHandle		  RunningProcess;
		if (std::error_code Ec = FindProcess(ServerExePath, RunningProcess); !Ec)
		{
			ZEN_WARN("attempting hard terminate of zen process with pid ({})", RunningProcess.Pid());
			try
			{
				if (RunningProcess.Terminate(0))
				{
					ZEN_CONSOLE("terminate complete");
					return 0;
				}
				ZEN_CONSOLE("failed to terminate server, still running");
				return 1;
			}
			catch (const std::exception& Ex)
			{
				ZEN_CONSOLE("failed to terminate server: '{}'", Ex.what());
				return 1;
			}
		}
		else
		{
			ZEN_CONSOLE("Failed to find process '{}', reason: {}", ServerExePath.string(), Ec.message());
		}
	}
	else if (Entry)
	{
		ZEN_CONSOLE("failed to shutdown of server on port {}, use --force to hard terminate process", Entry->DesiredListenPort.load());
		return 1;
	}

	ZEN_CONSOLE("no zen server to bring down");
	return 0;
}

}  // namespace zen