aboutsummaryrefslogtreecommitdiff
path: root/zenserver/zenserver.cpp
blob: 529972cc0faeb251b5401f782a52e5083b387103 (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
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
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/iobuffer.h>
#include <zencore/logging.h>
#include <zencore/refcount.h>
#include <zencore/scopeguard.h>
#include <zencore/string.h>
#include <zencore/thread.h>
#include <zencore/timer.h>
#include <zencore/windows.h>
#include <zenhttp/httpserver.h>
#include <zenstore/cas.h>
#include <zenstore/cidstore.h>
#include <zenutil/zenserverprocess.h>

#include <fmt/format.h>
#include <mimalloc-new-delete.h>
#include <mimalloc.h>
#include <asio.hpp>
#include <exception>
#include <list>
#include <lua.hpp>
#include <optional>
#include <regex>
#include <set>
#include <unordered_map>

//////////////////////////////////////////////////////////////////////////
// We don't have any doctest code in this file but this is needed to bring
// in some shared code into the executable

#if ZEN_WITH_TESTS
#	define DOCTEST_CONFIG_IMPLEMENT
#	include <zencore/testing.h>
#	undef DOCTEST_CONFIG_IMPLEMENT
#endif

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

#include "casstore.h"
#include "config.h"
#include "diag/logging.h"

#if ZEN_PLATFORM_WINDOWS
#	include "windows/service.h"
#endif

//////////////////////////////////////////////////////////////////////////
// Sentry
//

#define USE_SENTRY 1

#if USE_SENTRY
#	define SENTRY_BUILD_STATIC 1
#	include <sentry.h>

// Sentry currently does not automatically add all required Windows
// libraries to the linker when consumed via vcpkg

#	if ZEN_PLATFORM_WINDOWS
#		pragma comment(lib, "sentry.lib")
#		pragma comment(lib, "dbghelp.lib")
#		pragma comment(lib, "winhttp.lib")
#		pragma comment(lib, "version.lib")
#	endif
#endif

//////////////////////////////////////////////////////////////////////////
// Services
//

#include "admin/admin.h"
#include "cache/structuredcache.h"
#include "cache/structuredcachestore.h"
#include "compute/apply.h"
#include "diag/diagsvcs.h"
#include "experimental/usnjournal.h"
#include "projectstore.h"
#include "testing/httptest.h"
#include "testing/launch.h"
#include "upstream/jupiter.h"
#include "upstream/upstreamcache.h"
#include "upstream/zen.h"
#include "zenstore/gc.h"
#include "zenstore/scrub.h"

#define ZEN_APP_NAME "Zen store"

namespace zen {

class ZenServer
{
	ZenServerState::ZenServerEntry* m_ServerEntry = nullptr;

public:
	void Initialize(ZenServiceConfig& ServiceConfig, int BasePort, int ParentPid, ZenServerState::ZenServerEntry* ServerEntry)
	{
		m_ServerEntry = ServerEntry;
		using namespace fmt::literals;
		ZEN_INFO(ZEN_APP_NAME " initializing");

		m_DebugOptionForcedCrash = ServiceConfig.ShouldCrash;

		if (ParentPid)
		{
			zen::ProcessHandle OwnerProcess;
			OwnerProcess.Initialize(ParentPid);

			if (!OwnerProcess.IsValid())
			{
				ZEN_WARN("Unable to initialize process handle for specified parent pid #{}", ParentPid);

				// If the pid is not reachable should we just shut down immediately? the intended owner process
				// could have been killed or somehow crashed already
			}
			else
			{
				ZEN_INFO("Using parent pid #{} to control process lifetime", ParentPid);
			}

			m_ProcessMonitor.AddPid(ParentPid);
		}

		// Initialize/check mutex based on base port

		std::string MutexName = "zen_{}"_format(BasePort);

		if (zen::NamedMutex::Exists(MutexName) || ((m_ServerMutex.Create(MutexName) == false)))
		{
			throw std::runtime_error("Failed to create mutex '{}' - is another instance already running?"_format(MutexName).c_str());
		}

		// Ok so now we're configured, let's kick things off

		ZEN_INFO("initializing storage");

		zen::CasStoreConfiguration Config;
		Config.RootDirectory = m_DataRoot / "cas";

		m_CasStore->Initialize(Config);

		m_CidStore = std::make_unique<zen::CidStore>(*m_CasStore, m_DataRoot / "cid");

		ZEN_INFO("instantiating project service");

		m_ProjectStore = new zen::ProjectStore(*m_CasStore, m_DataRoot / "projects");
		m_HttpProjectService.reset(new zen::HttpProjectService{*m_CasStore, m_ProjectStore});
		m_LocalProjectService = zen::LocalProjectService::New(*m_CasStore, m_ProjectStore);

		ZEN_INFO("instantiating compute services");

		std::filesystem::path SandboxDir = m_DataRoot / "exec" / "sandbox";
		zen::CreateDirectories(SandboxDir);
		m_HttpLaunchService = std::make_unique<zen::HttpLaunchService>(*m_CasStore, SandboxDir);

		std::filesystem::path ApplySandboxDir = m_DataRoot / "exec" / "apply";
		zen::CreateDirectories(ApplySandboxDir);
		m_HttpFunctionService = std::make_unique<zen::HttpFunctionService>(*m_CasStore, *m_CidStore, ApplySandboxDir);

		if (ServiceConfig.StructuredCacheEnabled)
		{
			using namespace std::literals;
			auto ValueOrDefault = [](std::string_view Value, std::string_view Default) { return Value.empty() ? Default : Value; };

			ZEN_INFO("instantiating structured cache service");
			m_CacheStore = std::make_unique<ZenCacheStore>(*m_CasStore, m_DataRoot / "cache");

			std::unique_ptr<zen::UpstreamCache> UpstreamCache;
			if (ServiceConfig.UpstreamCacheConfig.CachePolicy != UpstreamCachePolicy::Disabled)
			{
				const ZenUpstreamCacheConfig& UpstreamConfig = ServiceConfig.UpstreamCacheConfig;

				zen::UpstreamCacheOptions UpstreamOptions;
				UpstreamOptions.ReadUpstream =
					(uint8_t(ServiceConfig.UpstreamCacheConfig.CachePolicy) & uint8_t(UpstreamCachePolicy::Read)) != 0;
				UpstreamOptions.WriteUpstream =
					(uint8_t(ServiceConfig.UpstreamCacheConfig.CachePolicy) & uint8_t(UpstreamCachePolicy::Write)) != 0;

				if (UpstreamConfig.UpstreamThreadCount < 32)
				{
					UpstreamOptions.ThreadCount = static_cast<uint32_t>(UpstreamConfig.UpstreamThreadCount);
				}

				UpstreamCache = zen::MakeUpstreamCache(UpstreamOptions, *m_CacheStore, *m_CidStore);

				if (!UpstreamConfig.ZenConfig.Url.empty())
				{
					std::unique_ptr<zen::UpstreamEndpoint> ZenEndpoint = zen::MakeZenUpstreamEndpoint(UpstreamConfig.ZenConfig.Url);
					UpstreamCache->AddEndpoint(std::move(ZenEndpoint));
				}

				{
					zen::CloudCacheClientOptions Options;
					if (UpstreamConfig.JupiterConfig.UseDevelopmentSettings)
					{
						Options = zen::CloudCacheClientOptions{
							.ServiceUrl			= "https://jupiter.devtools-dev.epicgames.com"sv,
							.DdcNamespace		= "ue4.ddc"sv,
							.BlobStoreNamespace = "test.ddc"sv,
							.OAuthProvider		= "https://epicgames.okta.com/oauth2/auso645ojjWVdRI3d0x7/v1/token"sv,
							.OAuthClientId		= "0oao91lrhqPiAlaGD0x7"sv,
							.OAuthSecret		= "-GBWjjenhCgOwhxL5yBKNJECVIoDPH0MK4RDuN7d"sv,
							.UseLegacyDdc		= false};
					}

					Options.ServiceUrl		   = ValueOrDefault(UpstreamConfig.JupiterConfig.Url, Options.ServiceUrl);
					Options.DdcNamespace	   = ValueOrDefault(UpstreamConfig.JupiterConfig.DdcNamespace, Options.DdcNamespace);
					Options.BlobStoreNamespace = ValueOrDefault(UpstreamConfig.JupiterConfig.Namespace, Options.BlobStoreNamespace);
					Options.OAuthProvider	   = ValueOrDefault(UpstreamConfig.JupiterConfig.OAuthProvider, Options.OAuthProvider);
					Options.OAuthClientId	   = ValueOrDefault(UpstreamConfig.JupiterConfig.OAuthClientId, Options.OAuthClientId);
					Options.OAuthSecret		   = ValueOrDefault(UpstreamConfig.JupiterConfig.OAuthClientSecret, Options.OAuthSecret);
					Options.UseLegacyDdc |= UpstreamConfig.JupiterConfig.UseLegacyDdc;

					if (!Options.ServiceUrl.empty())
					{
						std::unique_ptr<zen::UpstreamEndpoint> JupiterEndpoint = zen::MakeJupiterUpstreamEndpoint(Options);
						UpstreamCache->AddEndpoint(std::move(JupiterEndpoint));
					}
				}

				if (UpstreamCache->Initialize())
				{
					ZEN_INFO("upstream cache active ({})",
							 UpstreamOptions.ReadUpstream && UpstreamOptions.WriteUpstream ? "READ|WRITE"
							 : UpstreamOptions.ReadUpstream								   ? "READONLY"
							 : UpstreamOptions.WriteUpstream							   ? "WRITEONLY"
																						   : "DISABLED");
				}
				else
				{
					UpstreamCache.reset();
					ZEN_INFO("NOT using upstream cache");
				}
			}

			m_StructuredCacheService.reset(
				new zen::HttpStructuredCacheService(*m_CacheStore, *m_CasStore, *m_CidStore, std::move(UpstreamCache)));
		}
		else
		{
			ZEN_INFO("NOT instantiating structured cache service");
		}

		if (ServiceConfig.MeshEnabled)
		{
			StartMesh(BasePort);
		}
		else
		{
			ZEN_INFO("NOT starting mesh");
		}

		m_Http = zen::CreateHttpServer();
		m_Http->Initialize(BasePort);
		m_Http->RegisterService(m_HealthService);

		m_Http->RegisterService(m_TestService);	 // NOTE: this is intentionally not limited to test mode as it's useful for diagnostics
		m_Http->RegisterService(m_TestingService);

		m_Http->RegisterService(m_AdminService);

		if (m_HttpProjectService)
		{
			m_Http->RegisterService(*m_HttpProjectService);
		}

		m_Http->RegisterService(m_CasService);

		if (m_StructuredCacheService)
		{
			m_Http->RegisterService(*m_StructuredCacheService);
		}

		if (m_HttpLaunchService)
		{
			m_Http->RegisterService(*m_HttpLaunchService);
		}

		if (m_HttpFunctionService)
		{
			m_Http->RegisterService(*m_HttpFunctionService);
		}
	}

	void StartMesh(int BasePort)
	{
		ZEN_INFO("initializing mesh discovery");
		m_ZenMesh.Start(uint16_t(BasePort));
	}

	void Run()
	{
		if (m_ProcessMonitor.IsActive())
		{
			EnqueueTimer();
		}

		if (!m_TestMode)
		{
			ZEN_INFO("__________                _________ __                        ");
			ZEN_INFO("\\____    /____   ____    /   _____//  |_  ___________   ____  ");
			ZEN_INFO("  /     // __ \\ /    \\   \\_____  \\\\   __\\/  _ \\_  __ \\_/ __ \\ ");
			ZEN_INFO(" /     /\\  ___/|   |  \\  /        \\|  | (  <_> )  | \\/\\  ___/ ");
			ZEN_INFO("/_______ \\___  >___|  / /_______  /|__|  \\____/|__|    \\___  >");
			ZEN_INFO("        \\/   \\/     \\/          \\/                         \\/ ");
		}

		ZEN_INFO(ZEN_APP_NAME " now running (pid: {})", zen::GetCurrentProcessId());

#if USE_SENTRY
		sentry_clear_modulecache();
#endif

		if (m_DebugOptionForcedCrash)
		{
			__debugbreak();
		}

		const bool IsInteractiveMode = zen::IsInteractiveSession() && !m_TestMode;

		m_Http->Run(IsInteractiveMode);

		ZEN_INFO(ZEN_APP_NAME " exiting");

		m_IoContext.stop();

		Flush();
	}

	void RequestExit(int ExitCode)
	{
		RequestApplicationExit(ExitCode);
		m_Http->RequestExit();
	}

	void Cleanup() { ZEN_INFO(ZEN_APP_NAME " cleaning up"); }

	void SetDedicatedMode(bool State) { m_IsDedicatedMode = State; }
	void SetTestMode(bool State) { m_TestMode = State; }
	void SetDataRoot(std::filesystem::path Root) { m_DataRoot = Root; }

	void EnsureIoRunner()
	{
		if (!m_IoRunner.joinable())
		{
			m_IoRunner = std::move(std::jthread{[this] { m_IoContext.run(); }});
		}
	}

	void EnqueueTimer()
	{
		m_PidCheckTimer.expires_after(std::chrono::seconds(1));
		m_PidCheckTimer.async_wait([this](const asio::error_code&) { CheckOwnerPid(); });

		EnsureIoRunner();
	}

	void CheckOwnerPid()
	{
		// Pick up any new "owner" processes

		std::set<uint32_t> AddedPids;

		for (auto& PidEntry : m_ServerEntry->SponsorPids)
		{
			if (uint32_t ThisPid = PidEntry.load(std::memory_order::memory_order_relaxed))
			{
				if (PidEntry.compare_exchange_strong(ThisPid, 0))
				{
					if (AddedPids.insert(ThisPid).second)
					{
						m_ProcessMonitor.AddPid(ThisPid);

						ZEN_INFO("added process with pid #{} as a sponsor process", ThisPid);
					}
				}
			}
		}

		if (m_ProcessMonitor.IsRunning())
		{
			EnqueueTimer();
		}
		else
		{
			ZEN_INFO(ZEN_APP_NAME " exiting since sponsor processes are all gone");

			RequestExit(0);
		}
	}

	void Flush()
	{
		if (m_CasStore)
			m_CasStore->Flush();

		if (m_CidStore)
			m_CidStore->Flush();

		if (m_StructuredCacheService)
			m_StructuredCacheService->Flush();

		if (m_ProjectStore)
			m_ProjectStore->Flush();
	}

private:
	bool				  m_IsDedicatedMode = false;
	bool				  m_TestMode		= false;
	std::filesystem::path m_DataRoot;
	std::jthread		  m_IoRunner;
	asio::io_context	  m_IoContext;
	asio::steady_timer	  m_PidCheckTimer{m_IoContext};
	zen::ProcessMonitor	  m_ProcessMonitor;
	zen::NamedMutex		  m_ServerMutex;

	zen::Ref<zen::HttpServer>						 m_Http;
	std::unique_ptr<zen::CasStore>					 m_CasStore{zen::CreateCasStore()};
	std::unique_ptr<zen::CidStore>					 m_CidStore;
	std::unique_ptr<ZenCacheStore>					 m_CacheStore;
	zen::CasGc										 m_Gc{*m_CasStore};
	zen::CasScrubber								 m_Scrubber{*m_CasStore};
	HttpTestService									 m_TestService;
	zen::HttpTestingService							 m_TestingService;
	zen::HttpCasService								 m_CasService{*m_CasStore};
	zen::RefPtr<zen::ProjectStore>					 m_ProjectStore;
	zen::Ref<zen::LocalProjectService>				 m_LocalProjectService;
	std::unique_ptr<zen::HttpLaunchService>			 m_HttpLaunchService;
	std::unique_ptr<zen::HttpProjectService>		 m_HttpProjectService;
	std::unique_ptr<zen::HttpStructuredCacheService> m_StructuredCacheService;
	HttpAdminService								 m_AdminService;
	HttpHealthService								 m_HealthService;
	zen::Mesh										 m_ZenMesh{m_IoContext};
	std::unique_ptr<zen::HttpFunctionService>		 m_HttpFunctionService;

	bool m_DebugOptionForcedCrash = false;
};

}  // namespace zen

class ZenWindowsService : public WindowsService
{
public:
	ZenWindowsService(ZenServerOptions& GlobalOptions, ZenServiceConfig& ServiceConfig)
	: m_GlobalOptions(GlobalOptions)
	, m_ServiceConfig(ServiceConfig)
	{
	}

	ZenWindowsService(const ZenWindowsService&) = delete;
	ZenWindowsService& operator=(const ZenWindowsService&) = delete;

	virtual int Run() override;

private:
	ZenServerOptions& m_GlobalOptions;
	ZenServiceConfig& m_ServiceConfig;
};

int
ZenWindowsService::Run()
{
	using namespace zen;

#if USE_SENTRY
	// Initialize sentry.io client

	sentry_options_t* SentryOptions = sentry_options_new();
	sentry_options_set_dsn(SentryOptions, "https://[email protected]/5919284");
	sentry_init(SentryOptions);

	auto _ = zen::MakeGuard([] { sentry_close(); });
#endif

	auto& GlobalOptions = m_GlobalOptions;
	auto& ServiceConfig = m_ServiceConfig;

	try
	{
		// Prototype config system, we'll see how this pans out
		//
		// TODO: we need to report any parse errors here

		ParseServiceConfig(GlobalOptions.DataDir, /* out */ ServiceConfig);

		ZEN_INFO("zen cache server starting on port {}", GlobalOptions.BasePort);

		ZenServerState ServerState;
		ServerState.Initialize();
		ServerState.Sweep();

		ZenServerState::ZenServerEntry* Entry = ServerState.Lookup(GlobalOptions.BasePort);

		if (Entry)
		{
			// Instance already running for this port? Should double check pid

			ZEN_WARN("Looks like there is already a process listening to this port (pid: {})", Entry->Pid);

			if (GlobalOptions.OwnerPid)
			{
				Entry->AddSponsorProcess(GlobalOptions.OwnerPid);

				std::exit(0);
			}
		}

		Entry = ServerState.Register(GlobalOptions.BasePort);

		if (GlobalOptions.OwnerPid)
		{
			Entry->AddSponsorProcess(GlobalOptions.OwnerPid);
		}

		std::unique_ptr<std::thread>	 ShutdownThread;
		std::unique_ptr<zen::NamedEvent> ShutdownEvent;

		zen::ExtendableStringBuilder<64> ShutdownEventName;
		ShutdownEventName << "Zen_" << GlobalOptions.BasePort << "_Shutdown";
		ShutdownEvent.reset(new zen::NamedEvent{ShutdownEventName});

		ZenServer Server;
		Server.SetDataRoot(GlobalOptions.DataDir);
		Server.SetTestMode(GlobalOptions.IsTest);
		Server.SetDedicatedMode(GlobalOptions.IsDedicated);
		Server.Initialize(ServiceConfig, GlobalOptions.BasePort, GlobalOptions.OwnerPid, Entry);

		// Monitor shutdown signals

		ShutdownThread.reset(new std::thread{[&] {
			ZEN_INFO("shutdown monitor thread waiting for shutdown signal '{}'", ShutdownEventName);
			if (ShutdownEvent->Wait())
			{
				ZEN_INFO("shutdown signal received");
				Server.RequestExit(0);
			}
		}});

		// If we have a parent process, establish the mechanisms we need
		// to be able to communicate with the parent

		if (!GlobalOptions.ChildId.empty())
		{
			zen::NamedEvent ParentEvent{GlobalOptions.ChildId};
			ParentEvent.Set();
		}

		Server.Run();
		Server.Cleanup();

		ShutdownEvent->Set();
		ShutdownThread->join();
	}
	catch (std::exception& e)
	{
		SPDLOG_CRITICAL("Caught exception in main: {}", e.what());
	}

	ShutdownLogging();

	return 0;
}

int
main(int argc, char* argv[])
{
	using namespace zen;

	mi_version();

	ZenServerOptions GlobalOptions;
	ZenServiceConfig ServiceConfig;
	ParseGlobalCliOptions(argc, argv, GlobalOptions, ServiceConfig);
	InitializeLogging(GlobalOptions);

#if ZEN_PLATFORM_WINDOWS
	if (GlobalOptions.InstallService)
	{
		WindowsService::Install();

		std::exit(0);
	}

	if (GlobalOptions.UninstallService)
	{
		WindowsService::Delete();

		std::exit(0);
	}
#endif

	ZenWindowsService App(GlobalOptions, ServiceConfig);
	return App.ServiceMain();
}