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

#include "exec_cmd.h"

#include <zencompute/functionservice.h>
#include <zencompute/recordingreader.h>
#include <zencore/compactbinary.h>
#include <zencore/compactbinarybuilder.h>
#include <zencore/compactbinaryfile.h>
#include <zencore/compactbinarypackage.h>
#include <zencore/compactbinaryvalue.h>
#include <zencore/compress.h>
#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/scopeguard.h>
#include <zencore/stream.h>
#include <zencore/string.h>
#include <zencore/timer.h>

#include <EASTL/hash_map.h>
#include <EASTL/hash_set.h>
#include <EASTL/map.h>

using namespace std::literals;

namespace eastl {

template<>
struct hash<zen::IoHash> : public zen::IoHash::Hasher
{
};

}  // namespace eastl

#if ZEN_WITH_COMPUTE_SERVICES

namespace zen {

ExecCommand::ExecCommand()
{
	m_Options.add_options()("h,help", "Print help");
	m_Options.add_option("", "u", "hosturl", "Host URL", cxxopts::value(m_HostName), "<hosturl>");
	m_Options.add_option("", "", "log", "Action log directory", cxxopts::value(m_RecordingLogPath), "<path>");
	m_Options.add_option("", "p", "path", "Recording path (directory or .actionlog file)", cxxopts::value(m_RecordingPath), "<path>");
	m_Options.add_option("", "", "offset", "Recording replay start offset", cxxopts::value(m_Offset), "<offset>");
	m_Options.add_option("", "", "stride", "Recording replay stride", cxxopts::value(m_Stride), "<stride>");
	m_Options.add_option("", "", "limit", "Recording replay limit", cxxopts::value(m_Limit), "<limit>");
	m_Options.add_option("", "", "beacon", "Beacon path", cxxopts::value(m_BeaconPath), "<path>");
	m_Options.add_option("",
						 "",
						 "mode",
						 "Select execution mode (http,inproc,dump,direct,beacon,buildlog)",
						 cxxopts::value(m_Mode)->default_value("http"),
						 "<string>");
	m_Options.add_option("", "", "quiet", "Quiet mode (less logging)", cxxopts::value(m_Quiet), "<bool>");
	m_Options.parse_positional("mode");
}

ExecCommand::~ExecCommand()
{
}

void
ExecCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
	// Configure

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

	m_HostName = ResolveTargetHostSpec(m_HostName);

	if (m_RecordingPath.empty())
	{
		throw OptionParseException("replay path is required!", m_Options.help());
	}

	m_VerboseLogging = GlobalOptions.IsVerbose;
	m_QuietLogging	 = m_Quiet && !m_VerboseLogging;

	enum ExecMode
	{
		kHttp,
		kDirect,
		kInproc,
		kDump,
		kBeacon,
		kBuildLog
	} Mode;

	if (m_Mode == "http"sv)
	{
		Mode = kHttp;
	}
	else if (m_Mode == "direct"sv)
	{
		Mode = kDirect;
	}
	else if (m_Mode == "inproc"sv)
	{
		Mode = kInproc;
	}
	else if (m_Mode == "dump"sv)
	{
		Mode = kDump;
	}
	else if (m_Mode == "beacon"sv)
	{
		Mode = kBeacon;
	}
	else if (m_Mode == "buildlog"sv)
	{
		Mode = kBuildLog;
	}
	else
	{
		throw OptionParseException("invalid mode specified!", m_Options.help());
	}

	// Gather information from recording path

	std::unique_ptr<zen::compute::RecordingReader>	 Reader;
	std::unique_ptr<zen::compute::UeRecordingReader> UeReader;

	std::filesystem::path RecordingPath{m_RecordingPath};

	if (!std::filesystem::is_directory(RecordingPath))
	{
		throw OptionParseException("replay path should be a directory path!", m_Options.help());
	}
	else
	{
		if (std::filesystem::is_directory(RecordingPath / "cid"))
		{
			Reader			  = std::make_unique<zen::compute::RecordingReader>(RecordingPath);
			m_WorkerMap		  = Reader->ReadWorkers();
			m_ChunkResolver	  = Reader.get();
			m_RecordingReader = Reader.get();
		}
		else
		{
			UeReader		  = std::make_unique<zen::compute::UeRecordingReader>(RecordingPath);
			m_WorkerMap		  = UeReader->ReadWorkers();
			m_ChunkResolver	  = UeReader.get();
			m_RecordingReader = UeReader.get();
		}
	}

	ZEN_CONSOLE("found {} workers, {} action items", m_WorkerMap.size(), m_RecordingReader->GetActionCount());

	for (auto& Kv : m_WorkerMap)
	{
		CbObject	  WorkerDesc = Kv.second.GetObject();
		const IoHash& WorkerId	 = Kv.first;

		RegisterWorkerFunctionsFromDescription(WorkerDesc, WorkerId);

		if (m_VerboseLogging)
		{
			zen::ExtendableStringBuilder<1024> ObjStr;
#	if 0
			zen::CompactBinaryToJson(WorkerDesc, ObjStr);
			ZEN_CONSOLE("worker {}: {}", WorkerId, ObjStr);
#	else
			zen::CompactBinaryToYaml(WorkerDesc, ObjStr);
			ZEN_CONSOLE("worker {}:\n{}", WorkerId, ObjStr);
#	endif
		}
	}

	if (m_VerboseLogging)
	{
		EmitFunctionList(m_FunctionList);
	}

	// Iterate over work items and dispatch or log them

	int ReturnValue = 0;

	Stopwatch ExecTimer;

	switch (Mode)
	{
		case kHttp:
			// Forward requests to HTTP function service
			ReturnValue = HttpExecute();
			break;

		case kDirect:
			// Not currently supported
			ReturnValue = LocalMessagingExecute();
			break;

		case kInproc:
			// Handle execution in-core (by spawning child processes)
			ReturnValue = InProcessExecute();
			break;

		case kDump:
			// Dump high level information about actions to console
			ReturnValue = DumpWorkItems();
			break;

		case kBeacon:
			ReturnValue = BeaconExecute();
			break;

		case kBuildLog:
			ReturnValue = BuildActionsLog();
			break;

		default:
			ZEN_ERROR("Unknown operating mode! No work submitted");

			ReturnValue = 1;
	}

	ZEN_CONSOLE("complete - took {}", NiceTimeSpanMs(ExecTimer.GetElapsedTimeMs()));

	if (!ReturnValue)
	{
		ZEN_CONSOLE("all work items completed successfully");
	}
	else
	{
		ZEN_CONSOLE("some work items failed (code {})", ReturnValue);
	}
}

int
ExecCommand::InProcessExecute()
{
	ZEN_ASSERT(m_ChunkResolver);
	ChunkResolver& Resolver = *m_ChunkResolver;

	zen::compute::FunctionServiceSession FunctionSession(Resolver);

	std::filesystem::path TempPath = std::filesystem::absolute(".zen_temp");
	FunctionSession.AddLocalRunner(Resolver, TempPath);

	return ExecUsingSession(FunctionSession);
}

int
ExecCommand::ExecUsingSession(zen::compute::FunctionServiceSession& FunctionSession)
{
	struct JobTracker
	{
	public:
		inline void Insert(int LsnField)
		{
			RwLock::ExclusiveLockScope _(Lock);
			PendingJobs.insert(LsnField);
		}

		inline bool IsEmpty() const
		{
			RwLock::SharedLockScope _(Lock);
			return PendingJobs.empty();
		}

		inline void Remove(int CompleteLsn)
		{
			RwLock::ExclusiveLockScope _(Lock);
			PendingJobs.erase(CompleteLsn);
		}

		inline size_t GetSize() const
		{
			RwLock::SharedLockScope _(Lock);
			return PendingJobs.size();
		}

	private:
		mutable RwLock			Lock;
		std::unordered_set<int> PendingJobs;
	};

	JobTracker PendingJobs;

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

	auto DrainCompletedJobs = [&] {
		if (IsDraining.exchange(1))
		{
			return;
		}

		auto _ = MakeGuard([&] { IsDraining.store(0, std::memory_order_release); });

		CbObjectWriter Cbo;
		FunctionSession.GetCompleted(Cbo);

		if (CbObject Completed = Cbo.Save())
		{
			for (auto& It : Completed["completed"sv])
			{
				int32_t CompleteLsn = It.AsInt32();

				CbPackage		 ResultPackage;
				HttpResponseCode Response = FunctionSession.GetActionResult(CompleteLsn, /* out */ ResultPackage);

				if (Response == HttpResponseCode::OK)
				{
					PendingJobs.Remove(CompleteLsn);

					ZEN_CONSOLE("completed: LSN {} ({} still pending)", CompleteLsn, PendingJobs.GetSize());
				}
			}
		}
	};

	// Describe workers

	ZEN_CONSOLE("describing {} workers", m_WorkerMap.size());

	for (auto Kv : m_WorkerMap)
	{
		CbPackage WorkerDesc = Kv.second;

		FunctionSession.RegisterWorker(WorkerDesc);
	}

	// Then submit work items

	int	   FailedWorkCounter  = 0;
	size_t RemainingWorkItems = m_RecordingReader->GetActionCount();
	int	   SubmittedWorkItems = 0;

	ZEN_CONSOLE("submitting {} work items", RemainingWorkItems);

	int OffsetCounter = m_Offset;
	int StrideCounter = m_Stride;

	auto ShouldSchedule = [&]() -> bool {
		if (m_Limit && SubmittedWorkItems >= m_Limit)
		{
			// Limit reached, ignore

			return false;
		}

		if (OffsetCounter && OffsetCounter--)
		{
			// Still in offset, ignore

			return false;
		}

		if (--StrideCounter == 0)
		{
			StrideCounter = m_Stride;

			return true;
		}

		return false;
	};

	m_RecordingReader->IterateActions(
		[&](CbObject ActionObject, const IoHash& ActionId) {
			// Enqueue job

			Stopwatch SubmitTimer;

			const int Priority = 0;

			if (ShouldSchedule())
			{
				if (m_VerboseLogging)
				{
					int						AttachmentCount = 0;
					uint64_t				AttachmentBytes = 0;
					eastl::hash_set<IoHash> ReferencedChunks;

					ActionObject.IterateAttachments([&](CbFieldView Field) {
						IoHash AttachData = Field.AsAttachment();

						ReferencedChunks.insert(AttachData);
						++AttachmentCount;

						if (IoBuffer ChunkData = m_ChunkResolver->FindChunkByCid(AttachData))
						{
							AttachmentBytes += ChunkData.GetSize();
						}
					});

					zen::ExtendableStringBuilder<1024> ObjStr;
					zen::CompactBinaryToJson(ActionObject, ObjStr);
					ZEN_CONSOLE("work item {} ({} attachments, {} bytes): {}",
								ActionId,
								AttachmentCount,
								NiceBytes(AttachmentBytes),
								ObjStr);
				}

				if (zen::compute::FunctionServiceSession::EnqueueResult EnqueueResult =
						FunctionSession.EnqueueAction(ActionObject, Priority))
				{
					const int32_t LsnField = EnqueueResult.Lsn;

					--RemainingWorkItems;
					++SubmittedWorkItems;

					if (!m_QuietLogging)
					{
						ZEN_CONSOLE("submitted work item #{} - LSN {} - {}. {} remaining",
									SubmittedWorkItems,
									LsnField,
									NiceTimeSpanMs(SubmitTimer.GetElapsedTimeMs()),
									RemainingWorkItems);
					}

					PendingJobs.Insert(LsnField);
				}
				else
				{
					if (!m_QuietLogging)
					{
						std::string_view FunctionName		= ActionObject["Function"sv].AsString();
						const Guid		 FunctionVersion	= ActionObject["FunctionVersion"sv].AsUuid();
						const Guid		 BuildSystemVersion = ActionObject["BuildSystemVersion"sv].AsUuid();

						ZEN_ERROR(
							"failed to resolve function for work with (Function:{},FunctionVersion:{},BuildSystemVersion:{}). Work "
							"descriptor "
							"at: 'file://{}'",
							std::string(FunctionName),
							FunctionVersion,
							BuildSystemVersion,
							"<null>");

						EmitFunctionListOnce(m_FunctionList);
					}

					++FailedWorkCounter;
				}
			}

			// Check for completed work

			DrainCompletedJobs();
		},
		8);

	// Wait until all pending work is complete

	while (!PendingJobs.IsEmpty())
	{
		// TODO: improve this logic
		zen::Sleep(500);

		DrainCompletedJobs();
	}

	if (FailedWorkCounter)
	{
		return 1;
	}

	return 0;
}

int
ExecCommand::LocalMessagingExecute()
{
	// Non-HTTP work submission path

	// To be reimplemented using final transport

	return 0;
}

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

int
ExecCommand::HttpExecute()
{
	ZEN_ASSERT(m_ChunkResolver);
	ChunkResolver& Resolver = *m_ChunkResolver;

	std::filesystem::path TempPath = std::filesystem::absolute(".zen_temp");

	zen::compute::FunctionServiceSession FunctionSession(Resolver);
	FunctionSession.AddRemoteRunner(Resolver, TempPath, m_HostName);

	return ExecUsingSession(FunctionSession);
}

int
ExecCommand::BeaconExecute()
{
	ZEN_ASSERT(m_ChunkResolver);
	ChunkResolver&		  Resolver = *m_ChunkResolver;
	std::filesystem::path TempPath = std::filesystem::absolute(".zen_temp");

	zen::compute::FunctionServiceSession FunctionSession(Resolver);
	FunctionSession.AddRemoteRunner(Resolver, TempPath, "http://localhost:8558");
	// FunctionSession.AddRemoteRunner(Resolver, TempPath, "http://10.99.9.246:8558");

	return ExecUsingSession(FunctionSession);
}

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

void
ExecCommand::RegisterWorkerFunctionsFromDescription(const CbObject& WorkerDesc, const IoHash& WorkerId)
{
	const Guid WorkerBuildSystemVersion = WorkerDesc["buildsystem_version"sv].AsUuid();

	for (auto& Item : WorkerDesc["functions"sv])
	{
		CbObjectView Function = Item.AsObjectView();

		std::string_view FunctionName	 = Function["name"sv].AsString();
		const Guid		 FunctionVersion = Function["version"sv].AsUuid();

		m_FunctionList.emplace_back(FunctionDefinition{.FunctionName	   = std::string{FunctionName},
													   .FunctionVersion	   = FunctionVersion,
													   .BuildSystemVersion = WorkerBuildSystemVersion,
													   .WorkerId		   = WorkerId});
	}
}

void
ExecCommand::EmitFunctionListOnce(const std::vector<FunctionDefinition>& FunctionList)
{
	if (m_FunctionListEmittedOnce == false)
	{
		EmitFunctionList(FunctionList);

		m_FunctionListEmittedOnce = true;
	}
}

int
ExecCommand::DumpWorkItems()
{
	std::atomic<int> EmittedCount{0};

	eastl::hash_map<IoHash, uint64_t> SeenAttachments;	// Attachment CID -> count of references

	m_RecordingReader->IterateActions(
		[&](CbObject ActionObject, const IoHash& ActionId) {
			eastl::hash_map<IoHash, CompressedBuffer> Attachments;

			uint64_t AttachmentBytes			 = 0;
			uint64_t UncompressedAttachmentBytes = 0;

			ActionObject.IterateAttachments([&](const zen::CbFieldView AttachmentField) {
				const IoHash	 AttachmentCid	= AttachmentField.GetValue().AsHash();
				IoBuffer		 AttachmentData = m_ChunkResolver->FindChunkByCid(AttachmentCid);
				IoHash			 RawHash;
				uint64_t		 RawSize		= 0;
				CompressedBuffer CompressedData = CompressedBuffer::FromCompressed(SharedBuffer(AttachmentData), RawHash, RawSize);
				Attachments[AttachmentCid]		= CompressedData;

				AttachmentBytes += CompressedData.GetCompressedSize();
				UncompressedAttachmentBytes += CompressedData.DecodeRawSize();

				if (auto [Iter, Inserted] = SeenAttachments.insert({AttachmentCid, 1}); !Inserted)
				{
					++Iter->second;
				}
			});

			zen::ExtendableStringBuilder<1024> ObjStr;

#	if 0
			zen::CompactBinaryToJson(ActionObject, ObjStr);
			ZEN_CONSOLE("work item {} ({} attachments): {}", ActionId, Attachments.size(), ObjStr);
#	else
			zen::CompactBinaryToYaml(ActionObject, ObjStr);
			ZEN_CONSOLE("work item {} ({} attachments, {}->{} bytes):\n{}",
						ActionId,
						Attachments.size(),
						AttachmentBytes,
						UncompressedAttachmentBytes,
						ObjStr);
#	endif

			++EmittedCount;
		},
		1);

	ZEN_CONSOLE("emitted: {} actions", EmittedCount.load());

	eastl::map<uint64_t, std::vector<IoHash>> ReferenceHistogram;

	for (const auto& [K, V] : SeenAttachments)
	{
		if (V > 1)
		{
			ReferenceHistogram[V].push_back(K);
		}
	}

	for (const auto& [RefCount, Cids] : ReferenceHistogram)
	{
		ZEN_CONSOLE("{} attachments with {} references", Cids.size(), RefCount);
	}

	return 0;
}

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

int
ExecCommand::BuildActionsLog()
{
	ZEN_ASSERT(m_ChunkResolver);
	ChunkResolver& Resolver = *m_ChunkResolver;

	if (m_RecordingPath.empty())
	{
		throw OptionParseException("need to specify recording path", m_Options.help());
	}

	if (std::filesystem::exists(m_RecordingLogPath))
	{
		throw OptionParseException(fmt::format("recording log directory '{}' already exists!", m_RecordingLogPath), m_Options.help());
	}

	ZEN_NOT_IMPLEMENTED("build log generation not implemented yet!");

	std::filesystem::path TempPath = std::filesystem::absolute(".zen_temp");

	zen::compute::FunctionServiceSession FunctionSession(Resolver);
	FunctionSession.StartRecording(Resolver, m_RecordingLogPath);

	return ExecUsingSession(FunctionSession);
}

void
ExecCommand::EmitFunctionList(const std::vector<FunctionDefinition>& FunctionList)
{
	ZEN_CONSOLE("=== Known functions:\n===========================");

	ZEN_CONSOLE("{:30} {:36} {:36} {}", "function", "version", "build system", "worker id");

	for (const FunctionDefinition& Func : FunctionList)
	{
		ZEN_CONSOLE("{:30} {:36} {:36} {}", Func.FunctionName, Func.FunctionVersion, Func.BuildSystemVersion, Func.WorkerId);
	}

	ZEN_CONSOLE("===========================");
}

}  // namespace zen

#endif	// ZEN_WITH_COMPUTE_SERVICES