aboutsummaryrefslogtreecommitdiff
path: root/src/zenstore/vfsimpl.cpp
blob: 0a918d452a00a289b7548196d09637874b74646f (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
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zenstore/vfsimpl.h>

#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zenstore/cache/structuredcachestore.h>
#include <zenstore/projectstore.h>
#include <zenvfs/projfs.h>
#include <zenvfs/vfs.h>

#include <memory>
#include <unordered_map>

#if ZEN_WITH_VFS

namespace zen {

using namespace std::literals;

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

VfsOplogDataSource::VfsOplogDataSource(std::string_view ProjectId, std::string_view OplogId, Ref<ProjectStore> InProjectStore)
: m_ProjectId(ProjectId)
, m_OplogId(OplogId)
, m_ProjectStore(std::move(InProjectStore))
{
}

void
VfsOplogDataSource::ReadNamedData(std::string_view Path, void* Buffer, uint64_t ByteOffset, uint64_t ByteCount)
{
	ZEN_UNUSED(Path, Buffer, ByteOffset, ByteCount);
}

void
VfsOplogDataSource::ReadChunkData(const Oid& ChunkId, void* Buffer, uint64_t ByteOffset, uint64_t ByteCount)
{
	IoBuffer ChunkBuffer = m_ProjectStore->GetChunk(m_ProjectId, m_OplogId, ChunkId);
	if (ChunkBuffer)
	{
		ZEN_ASSERT(ChunkBuffer.GetSize() >= ByteOffset);
		ZEN_ASSERT(ChunkBuffer.GetSize() - ByteOffset >= ByteCount);
		MutableMemoryView Target(Buffer, ByteCount);
		Target.CopyFrom(ChunkBuffer.GetView().Mid(ByteOffset, ByteCount));
	}
}

void
VfsOplogDataSource::PopulateDirectory(std::string NodePath, VfsTreeNode& DirNode)
{
	// This should never be called
	ZEN_UNUSED(NodePath, DirNode);
}

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

VfsCacheDataSource::VfsCacheDataSource(std::string_view NamespaceId, std::string_view BucketId, Ref<ZenCacheStore> InCacheStore)
: m_NamespaceId(NamespaceId)
, m_BucketId(BucketId)
, m_CacheStore(std::move(InCacheStore))
{
}

VfsCacheDataSource::~VfsCacheDataSource()
{
}

void
VfsCacheDataSource::ReadNamedData(std::string_view Name, void* Buffer, uint64_t ByteOffset, uint64_t ByteCount)
{
	if (auto DotIndex = Name.find_first_of('.'); DotIndex != std::string_view::npos)
	{
		Name = Name.substr(0, DotIndex);
	}

	IoHash HashKey = IoHash::FromHexString(Name);

	CacheRequestContext CacheContext{};

	ZenCacheValue Value;
	if (m_CacheStore->Get(CacheContext, m_NamespaceId, m_BucketId, HashKey, /* out */ Value))
	{
		// TODO bounds check!
		auto DataPtr = reinterpret_cast<const uint8_t*>(Value.Value.GetData()) + ByteOffset;

		memcpy(Buffer, DataPtr, ByteCount);

		return;
	}
}

void
VfsCacheDataSource::ReadChunkData(const Oid& ChunkId, void* Buffer, uint64_t ByteOffset, uint64_t ByteCount)
{
	ZEN_UNUSED(ChunkId, Buffer, ByteOffset, ByteCount);
}

void
VfsCacheDataSource::PopulateDirectory(std::string NodePath, VfsTreeNode& DirNode)
{
	ZEN_UNUSED(NodePath, DirNode);
}

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

VfsServiceImpl::VfsServiceImpl()
{
}

VfsServiceImpl::~VfsServiceImpl()
{
	Unmount();
}

void
VfsServiceImpl::Mount(std::string_view MountPoint)
{
	ZEN_INFO("VFS mount requested at '{}'", MountPoint);

#	if ZEN_PLATFORM_WINDOWS
	if (!IsProjFsAvailable())
	{
		throw std::runtime_error("Projected File System component not available");
	}
#	endif

	if (!m_MountpointPath.empty())
	{
		throw std::runtime_error("VFS already mounted");
	}

	m_MountpointPath = MountPoint;

	RefreshVfs();
}

void
VfsServiceImpl::Unmount()
{
	if (m_MountpointPath.empty())
	{
		return;
	}

	ZEN_INFO("unmounting VFS from '{}'", m_MountpointPath);

	m_MountpointPath.clear();

	RefreshVfs();
}

void
VfsServiceImpl::AddService(Ref<ProjectStore>&& Ps)
{
	m_ProjectStore = std::move(Ps);

	RefreshVfs();
}

void
VfsServiceImpl::AddService(Ref<ZenCacheStore>&& Z$)
{
	m_ZenCacheStore = std::move(Z$);

	RefreshVfs();
}

void
VfsServiceImpl::RefreshVfs()
{
	if (m_VfsHost && m_MountpointPath.empty())
	{
		m_VfsHost->RequestStop();
		m_VfsThread.join();
		m_VfsHost.reset();
		m_VfsThreadRunning.Reset();
		m_VfsDataSource = nullptr;

		return;
	}

	if (!m_VfsHost && !m_MountpointPath.empty())
	{
		m_VfsThread = std::thread(&VfsServiceImpl::VfsThread, this);
		m_VfsThreadRunning.Wait();

		// At this stage, m_VfsHost should be initialized

		ZEN_ASSERT(m_VfsHost);
	}

	if (m_ProjectStore && m_VfsHost)
	{
		if (!m_VfsDataSource)
		{
			m_VfsDataSource = new VfsServiceDataSource(this);
		}

		m_VfsHost->AddMount("projects"sv, m_VfsDataSource);
	}

	if (m_ZenCacheStore && m_VfsHost)
	{
		if (!m_VfsDataSource)
		{
			m_VfsDataSource = new VfsServiceDataSource(this);
		}

		m_VfsHost->AddMount("ddc_cache"sv, m_VfsDataSource);
	}
}

void
VfsServiceImpl::VfsThread()
{
	SetCurrentThreadName("VFS");

	ZEN_INFO("VFS service thread now RUNNING");

	try
	{
		m_VfsHost = std::make_unique<VfsHost>(m_MountpointPath);
		m_VfsHost->Initialize();

		m_VfsThreadRunning.Set();
		m_VfsHost->Run();
	}
	catch (const std::exception& Ex)
	{
		ZEN_WARN("exception caught in VFS thread: {}", Ex.what());

		m_VfsThreadException = std::current_exception();
	}

	if (m_VfsHost)
	{
		m_VfsHost->Cleanup();
	}

	ZEN_INFO("VFS service thread now EXITING");
}

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

Ref<VfsOplogDataSource>
VfsServiceDataSource::GetOplogDataSource(std::string_view ProjectId, std::string_view OplogId)
{
	ExtendableStringBuilder<256> Key;
	Key << ProjectId << "." << OplogId;
	std::string StdKey{Key};

	RwLock::ExclusiveLockScope _(m_Lock);

	if (auto It = m_OplogSourceMap.find(StdKey); It == m_OplogSourceMap.end())
	{
		Ref<VfsOplogDataSource> NewSource{new VfsOplogDataSource(ProjectId, OplogId, m_VfsImpl->m_ProjectStore)};
		m_OplogSourceMap[StdKey] = NewSource;
		return NewSource;
	}
	else
	{
		return It->second;
	}
}

Ref<VfsCacheDataSource>
VfsServiceDataSource::GetCacheDataSource(std::string_view NamespaceId, std::string_view BucketId)
{
	ExtendableStringBuilder<256> Key;
	Key << NamespaceId << "." << BucketId;
	std::string StdKey{Key};

	RwLock::ExclusiveLockScope _(m_Lock);

	if (auto It = m_CacheSourceMap.find(StdKey); It == m_CacheSourceMap.end())
	{
		Ref<VfsCacheDataSource> NewSource{new VfsCacheDataSource(NamespaceId, BucketId, m_VfsImpl->m_ZenCacheStore)};
		m_CacheSourceMap[StdKey] = NewSource;
		return NewSource;
	}
	else
	{
		return It->second;
	}
}

void
VfsServiceDataSource::ReadNamedData(std::string_view Path, void* Buffer, uint64_t ByteOffset, uint64_t ByteCount)
{
	ZEN_UNUSED(Path, Buffer, ByteOffset, ByteCount);
}

void
VfsServiceDataSource::ReadChunkData(const Oid& ChunkId, void* Buffer, uint64_t ByteOffset, uint64_t ByteCount)
{
	ZEN_UNUSED(ChunkId, Buffer, ByteOffset, ByteCount);
}

void
VfsServiceDataSource::PopulateDirectory(std::string NodePath, VfsTreeNode& DirNode)
{
	if (NodePath == "projects"sv)
	{
		// Project enumeration

		m_VfsImpl->m_ProjectStore->DiscoverProjects();

		m_VfsImpl->m_ProjectStore->IterateProjects(
			[&](ProjectStore::Project& Project) { DirNode.AddVirtualNode(Project.Identifier, m_VfsImpl->m_VfsDataSource); });
	}
	else if (NodePath.starts_with("projects\\"sv))
	{
		std::string_view ProjectId{NodePath};
		ProjectId = ProjectId.substr(9);  // Skip "projects\"

		if (std::string_view::size_type SlashOffset = ProjectId.find_first_of('\\'); SlashOffset == std::string_view::npos)
		{
			Ref<ProjectStore::Project> Project = m_VfsImpl->m_ProjectStore->OpenProject(ProjectId);

			if (!Project)
			{
				// No such project found?

				return;
			}

			// Oplog enumeration

			std::vector<std::string> Oplogs = Project->ScanForOplogs();

			for (auto& Oplog : Oplogs)
			{
				DirNode.AddVirtualNode(Oplog, m_VfsImpl->m_VfsDataSource);
			}
		}
		else
		{
			std::string_view OplogId = ProjectId.substr(SlashOffset + 1);
			ProjectId				 = ProjectId.substr(0, SlashOffset);

			Ref<ProjectStore::Project> Project = m_VfsImpl->m_ProjectStore->OpenProject(ProjectId);

			if (!Project)
			{
				// No such project found?

				return;
			}

			// Oplog contents enumeration

			if (Ref<ProjectStore::Oplog> Oplog = Project->OpenOplog(OplogId, /*AllowCompact*/ false, /*VerifyPathOnDisk*/ true))
			{
				Ref<VfsOplogDataSource> DataSource = GetOplogDataSource(ProjectId, OplogId);

				// Get metadata for all chunks
				std::vector<ProjectStore::Oplog::ChunkInfo> ChunkInfos = Oplog->GetAllChunksInfo(Project->RootDir);

				std::unordered_map<zen::Oid, uint64_t> ChunkSizes;

				for (const auto& Ci : ChunkInfos)
				{
					ChunkSizes[Ci.ChunkId] = Ci.ChunkSize;
				}

				auto EmitFilesForDataArray = [&](zen::CbArrayView DataArray) {
					for (auto DataIter : DataArray)
					{
						if (zen::CbObjectView Data = DataIter.AsObjectView())
						{
							std::filesystem::path FileName(Data["filename"sv].AsU8String());
							zen::Oid			  ChunkId = Data["id"sv].AsObjectId();

							if (auto FindIt = ChunkSizes.find(ChunkId); FindIt != ChunkSizes.end())
							{
								DirNode.AddFileNode(FileName.string(), FindIt->second /* file size */, ChunkId, DataSource);
							}
							else
							{
								ZEN_WARN("no chunk metadata found for chunk {} (file: '{}')", ChunkId, FileName);
							}
						}
					}
				};

				Oplog->IterateOplog(
					[&](CbObjectView Op) {
						EmitFilesForDataArray(Op["packagedata"sv].AsArrayView());
						EmitFilesForDataArray(Op["bulkdata"sv].AsArrayView());
					},
					ProjectStore::Oplog::Paging{});

				DirNode.AddFileNode("stats.json", 42, Oid::Zero);
			}
		}
	}
	else if (NodePath == "ddc_cache"sv)
	{
		// Namespace enumeration

		std::vector<std::string> Namespaces = m_VfsImpl->m_ZenCacheStore->GetNamespaces();

		for (auto& Namespace : Namespaces)
		{
			DirNode.AddVirtualNode(Namespace, m_VfsImpl->m_VfsDataSource);
		}
	}
	else if (NodePath.starts_with("ddc_cache\\"sv))
	{
		std::string_view NamespaceId{NodePath};
		NamespaceId = NamespaceId.substr(10);  // Skip "ddc_cache\"

		auto& Cache = m_VfsImpl->m_ZenCacheStore;

		if (std::string_view::size_type SlashOffset = NamespaceId.find_first_of('\\'); SlashOffset == std::string_view::npos)
		{
			// Bucket enumeration

			if (auto NsInfo = Cache->GetNamespaceInfo(NamespaceId))
			{
				for (auto& BucketName : NsInfo->BucketNames)
				{
					DirNode.AddVirtualNode(BucketName, m_VfsImpl->m_VfsDataSource);
				}
			}
		}
		else
		{
			// Bucket contents enumeration

			std::string_view BucketId = NamespaceId.substr(SlashOffset + 1);
			NamespaceId				  = NamespaceId.substr(0, SlashOffset);

			Ref<VfsCacheDataSource> DataSource = GetCacheDataSource(NamespaceId, BucketId);

			auto Enumerator = [&](const IoHash& Key, const CacheValueDetails::ValueDetails& Details) {
				ExtendableStringBuilder<64> KeyString;
				Key.ToHexString(KeyString);
				KeyString.Append(".udd");
				DirNode.AddFileNode(KeyString, Details.Size, Oid::Zero, DataSource);
			};

			Cache->EnumerateBucketContents(NamespaceId, BucketId, Enumerator);
		}
	}
}

}  // namespace zen
#endif