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

#include "FileCas.h"

#include <zencore/except.h>
#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/memory.h>
#include <zencore/scopeguard.h>
#include <zencore/string.h>
#include <zencore/testing.h>
#include <zencore/testutils.h>
#include <zencore/thread.h>
#include <zencore/uid.h>
#include <zenstore/basicfile.h>

#include <gsl/gsl-lite.hpp>

#include <barrier>
#include <filesystem>
#include <functional>
#include <unordered_map>

// clang-format off
#include <zencore/prewindows.h>

struct IUnknown;  // Workaround for "combaseapi.h(229): error C2187: syntax error: 'identifier' was unexpected here" when using /permissive-
#include <atlfile.h>

#include <zencore/postwindows.h>
// clang-format on

namespace zen {

using namespace fmt::literals;

FileCasStrategy::ShardingHelper::ShardingHelper(const std::filesystem::path& RootPath, const IoHash& ChunkHash)
{
	ShardedPath.Append(RootPath.c_str());
	ShardedPath.Append(std::filesystem::path::preferred_separator);

	ExtendableStringBuilder<64> HashString;
	ChunkHash.ToHexString(HashString);

	const char* str = HashString.c_str();

	// Shard into a path with two directory levels containing 12 bits and 8 bits
	// respectively.
	//
	// This results in a maximum of 4096 * 256 directories
	//
	// The numbers have been chosen somewhat arbitrarily but are large to scale
	// to very large chunk repositories without creating too many directories
	// on a single level since NTFS does not deal very well with this.
	//
	// It may or may not make sense to make this a configurable policy, and it
	// would probably be a good idea to measure performance for different
	// policies and chunk counts

	ShardedPath.AppendAsciiRange(str, str + 3);

	ShardedPath.Append(std::filesystem::path::preferred_separator);
	ShardedPath.AppendAsciiRange(str + 3, str + 5);
	Shard2len = ShardedPath.Size();

	ShardedPath.Append(std::filesystem::path::preferred_separator);
	ShardedPath.AppendAsciiRange(str + 5, str + 40);
}

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

FileCasStrategy::FileCasStrategy(const CasStoreConfiguration& Config) : m_Config(Config), m_Log(logging::Get("filecas"))
{
}

FileCasStrategy::~FileCasStrategy()
{
}

CasStore::InsertResult
FileCasStrategy::InsertChunk(IoBuffer Chunk, const IoHash& ChunkHash)
{
	// File-based chunks have special case handling whereby we move the file into
	// place in the file store directory, thus avoiding unnecessary copying

	IoBufferFileReference FileRef;
	if (Chunk.IsWholeFile() && Chunk.GetFileReference(/* out */ FileRef))
	{
		ShardingHelper Name(m_Config.RootDirectory.c_str(), ChunkHash);

		const HANDLE ChunkFileHandle = FileRef.FileHandle;

		auto DeletePayloadFileOnClose = [&] {
			// This will cause the file to be deleted when the last handle to it is closed
			FILE_DISPOSITION_INFO Fdi{};
			Fdi.DeleteFile = TRUE;
			BOOL Success   = SetFileInformationByHandle(ChunkFileHandle, FileDispositionInfo, &Fdi, sizeof Fdi);

			if (!Success)
			{
				ZEN_WARN("Failed to flag temporary payload file '{}' for deletion: '{}'",
						 PathFromHandle(ChunkFileHandle),
						 GetLastErrorAsString());
			}
		};

		// See if file already exists
		//
		// Future improvement: maintain Bloom filter to avoid expensive file system probes?

		RwLock::ExclusiveLockScope _(LockForHash(ChunkHash));

		{
			CAtlFile PayloadFile;

			if (HRESULT hRes = PayloadFile.Create(Name.ShardedPath.c_str(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING); SUCCEEDED(hRes))
			{
				// If we succeeded in opening the target file then we don't need to do anything else because it already exists
				// and should contain the content we were about to insert

				// We do need to ensure the source file goes away on close, however

				DeletePayloadFileOnClose();

				return CasStore::InsertResult{.New = false};
			}
			else
			{
				if (hRes == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND))
				{
					// Shard directory does not exist
				}
				else if (hRes == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
				{
					// Shard directory exists, but not the file
				}
				else if (hRes == HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION))
				{
					// Sharing violation, likely because we are trying to open a file
					// which has been renamed on another thread, and the file handle
					// used to rename it is still open. We handle this case below
					// instead of here
				}
				else
				{
					ZEN_INFO("Unexpected error opening file '{}': {}", WideToUtf8(Name.ShardedPath), hRes);
				}
			}
		}

		std::filesystem::path FullPath(Name.ShardedPath.c_str());

		std::filesystem::path FilePath = FullPath.parent_path();
		std::wstring		  FileName = FullPath.native();

		const DWORD		  BufferSize = sizeof(FILE_RENAME_INFO) + gsl::narrow<DWORD>(FileName.size() * sizeof(WCHAR));
		FILE_RENAME_INFO* RenameInfo = reinterpret_cast<FILE_RENAME_INFO*>(Memory::Alloc(BufferSize));
		memset(RenameInfo, 0, BufferSize);

		RenameInfo->ReplaceIfExists = FALSE;
		RenameInfo->FileNameLength	= gsl::narrow<DWORD>(FileName.size());
		memcpy(RenameInfo->FileName, FileName.c_str(), FileName.size() * sizeof(WCHAR));
		RenameInfo->FileName[FileName.size()] = 0;

		auto $ = MakeGuard([&] { Memory::Free(RenameInfo); });

		// Try to move file into place

		BOOL Success = SetFileInformationByHandle(ChunkFileHandle, FileRenameInfo, RenameInfo, BufferSize);

		if (!Success)
		{
			// The rename/move could fail because the target directory does not yet exist. This code attempts
			// to create it

			CAtlFile DirHandle;

			auto InternalCreateDirectoryHandle = [&] {
				return DirHandle.Create(FilePath.c_str(),
										GENERIC_READ | GENERIC_WRITE,
										FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
										OPEN_EXISTING,
										FILE_FLAG_BACKUP_SEMANTICS);
			};

			// It's possible for several threads to enter this logic trying to create the same
			// directory. Only one will create the directory of course, but all threads will
			// make it through okay

			HRESULT hRes = InternalCreateDirectoryHandle();

			if (FAILED(hRes))
			{
				// TODO: we can handle directory creation more intelligently and efficiently than
				// this currently does

				CreateDirectories(FilePath.c_str());

				hRes = InternalCreateDirectoryHandle();
			}

			if (FAILED(hRes))
			{
				ThrowSystemException(hRes, "Failed to open shard directory '{}'"_format(FilePath));
			}

			// Retry rename/move

			Success = SetFileInformationByHandle(ChunkFileHandle, FileRenameInfo, RenameInfo, BufferSize);
		}

		if (Success)
		{
			return CasStore::InsertResult{.New = true};
		}

		const DWORD LastError = GetLastError();

		if ((LastError == ERROR_FILE_EXISTS) || (LastError == ERROR_ALREADY_EXISTS))
		{
			DeletePayloadFileOnClose();

			return CasStore::InsertResult{.New = false};
		}

		ZEN_WARN("rename of CAS payload file failed ('{}'), falling back to regular write for insert of {}",
				 GetSystemErrorAsString(LastError),
				 ChunkHash);

		DeletePayloadFileOnClose();
	}

	return InsertChunk(Chunk.Data(), Chunk.Size(), ChunkHash);
}

CasStore::InsertResult
FileCasStrategy::InsertChunk(const void* const ChunkData, const size_t ChunkSize, const IoHash& ChunkHash)
{
	ShardingHelper Name(m_Config.RootDirectory.c_str(), ChunkHash);

	// See if file already exists
	//
	// Future improvement: maintain Bloom filter to avoid expensive file system probes?

	CAtlFile PayloadFile;

	HRESULT hRes = PayloadFile.Create(Name.ShardedPath.c_str(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING);

	if (SUCCEEDED(hRes))
	{
		// If we succeeded in opening the file then we don't need to do anything else because it already exists and should contain the
		// content we were about to insert
		return CasStore::InsertResult{.New = false};
	}

	PayloadFile.Close();

	RwLock::ExclusiveLockScope _(LockForHash(ChunkHash));

	// For now, use double-checked locking to see if someone else was first

	hRes = PayloadFile.Create(Name.ShardedPath.c_str(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING);

	if (SUCCEEDED(hRes))
	{
		// If we succeeded in opening the file then we don't need to do anything
		// else because someone else managed to create the file before we did. Just return.
		return {.New = false};
	}

	if ((hRes != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) && (hRes != HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)))
	{
		ZEN_WARN("Unexpected error code when opening shard file for read: {:#x}", uint32_t(hRes));
	}

	auto InternalCreateFile = [&] { return PayloadFile.Create(Name.ShardedPath.c_str(), GENERIC_WRITE, FILE_SHARE_DELETE, CREATE_ALWAYS); };

	hRes = InternalCreateFile();

	if (hRes == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND))
	{
		// Ensure parent directories exist and retry file creation

		std::filesystem::create_directories(std::wstring_view(Name.ShardedPath.c_str(), Name.Shard2len));

		hRes = InternalCreateFile();
	}

	if (FAILED(hRes))
	{
		ThrowSystemException(hRes, "Failed to open shard file '{}'"_format(WideToUtf8(Name.ShardedPath)));
	}

	size_t ChunkRemain = ChunkSize;
	auto   ChunkCursor = reinterpret_cast<const uint8_t*>(ChunkData);

	while (ChunkRemain != 0)
	{
		uint32_t ByteCount = uint32_t(std::min<size_t>(4 * 1024 * 1024ull, ChunkRemain));

		PayloadFile.Write(ChunkCursor, ByteCount);

		ChunkCursor += ByteCount;
		ChunkRemain -= ByteCount;
	}

	// We cannot rely on RAII to close the file handle since it would be closed
	// *after* the lock is released due to the initialization order
	PayloadFile.Close();

	return {.New = true};
}

IoBuffer
FileCasStrategy::FindChunk(const IoHash& ChunkHash)
{
	ShardingHelper Name(m_Config.RootDirectory.c_str(), ChunkHash);

	RwLock::SharedLockScope _(LockForHash(ChunkHash));

	return IoBufferBuilder::MakeFromFile(Name.ShardedPath.c_str());
}

bool
FileCasStrategy::HaveChunk(const IoHash& ChunkHash)
{
	ShardingHelper Name(m_Config.RootDirectory.c_str(), ChunkHash);

	RwLock::SharedLockScope _(LockForHash(ChunkHash));

	std::error_code Ec;
	if (std::filesystem::exists(Name.ShardedPath.c_str(), Ec))
	{
		return true;
	}

	return false;
}
void
FileCasStrategy::DeleteChunk(const IoHash& ChunkHash, std::error_code& Ec)
{
	ShardingHelper Name(m_Config.RootDirectory.c_str(), ChunkHash);

	ZEN_DEBUG("deleting CAS payload file '{}'", WideToUtf8(Name.ShardedPath));

	std::filesystem::remove(Name.ShardedPath.c_str(), Ec);
}

void
FileCasStrategy::FilterChunks(CasChunkSet& InOutChunks)
{
	// NOTE: it's not a problem now, but in the future if a GC should happen while this
	// is in flight, the result could be wrong since chunks could go away in the meantime.
	//
	// It would be good to have a pinning mechanism to make this less likely but
	// given that chunks could go away at any point after the results are returned to
	// a caller, this is something which needs to be taken into account by anyone consuming
	// this functionality in any case

	InOutChunks.RemoveChunksIf([&](const IoHash& Hash) { return HaveChunk(Hash); });
}

void
FileCasStrategy::IterateChunks(std::function<void(const IoHash& Hash, BasicFile& PayloadFile)>&& Callback)
{
	struct Visitor : public FileSystemTraversal::TreeVisitor
	{
		Visitor(const std::filesystem::path& RootDir) : RootDirectory(RootDir) {}
		virtual void VisitFile(const std::filesystem::path& Parent, const std::wstring_view& File, uint64_t FileSize) override
		{
			ZEN_UNUSED(FileSize);

			std::filesystem::path RelPath = std::filesystem::relative(Parent, RootDirectory);

			std::wstring PathString = RelPath.native();

			if ((PathString.size() == (3 + 2 + 1)) && (File.size() == (40 - 3 - 2)))
			{
				if (PathString.at(3) == std::filesystem::path::preferred_separator)
				{
					PathString.erase(3, 1);
				}
				PathString.append(File);

				StringBuilder<64> Utf8;
				WideToUtf8(PathString, Utf8);

				// TODO: should validate that we're actually dealing with a valid hex string here

				IoHash NameHash = IoHash::FromHexString({Utf8.Data(), Utf8.Size()});

				BasicFile		PayloadFile;
				std::error_code Ec;
				PayloadFile.Open(Parent / File, false, Ec);

				if (!Ec)
				{
					Callback(NameHash, PayloadFile);
				}
			}
		}

		virtual bool VisitDirectory([[maybe_unused]] const std::filesystem::path& Parent,
									[[maybe_unused]] const std::wstring_view&	  DirectoryName)
		{
			return true;
		}

		const std::filesystem::path&									RootDirectory;
		std::function<void(const IoHash& Hash, BasicFile& PayloadFile)> Callback;
	} CasVisitor{m_Config.RootDirectory};

	CasVisitor.Callback = std::move(Callback);

	FileSystemTraversal Traversal;
	Traversal.TraverseFileSystem(m_Config.RootDirectory, CasVisitor);
}

void
FileCasStrategy::Flush()
{
	// Since we don't keep files open after writing there's nothing specific
	// to flush here.
	//
	// Depending on what semantics we want Flush() to provide, it could be
	// argued that this should just flush the volume which we are using to
	// store the CAS files on here, to ensure metadata is flushed along
	// with file data
	//
	// Related: to facilitate more targeted validation during recovery we could
	// maintain a log of when chunks were created
}

void
FileCasStrategy::Scrub(ScrubContext& Ctx)
{
	std::vector<IoHash>	  BadHashes;
	std::atomic<uint64_t> ChunkCount{0}, ChunkBytes{0};

	IterateChunks([&](const IoHash& Hash, BasicFile& Payload) {
		IoHashStream Hasher;
		Payload.StreamFile([&](const void* Data, size_t Size) { Hasher.Append(Data, Size); });
		IoHash ComputedHash = Hasher.GetHash();

		if (ComputedHash != Hash)
		{
			BadHashes.push_back(Hash);
		}

		++ChunkCount;
		ChunkBytes.fetch_add(Payload.FileSize());
	});

	Ctx.ReportScrubbed(ChunkCount, ChunkBytes);

	if (!BadHashes.empty())
	{
		ZEN_ERROR("file CAS scrubbing: {} bad chunks found", BadHashes.size());

		if (Ctx.RunRecovery())
		{
			ZEN_WARN("recovery: deleting backing files for {} bad chunks which were identified as bad", BadHashes.size());

			for (const IoHash& Hash : BadHashes)
			{
				std::error_code Ec;
				DeleteChunk(Hash, Ec);

				if (Ec)
				{
					ZEN_WARN("failed to delete file for chunk {}", Hash);
				}
			}
		}
	}

	Ctx.ReportBadCasChunks(BadHashes);

	ZEN_INFO("file CAS scrubbed: {} chunks ({})", ChunkCount.load(), NiceBytes(ChunkBytes));
}

void
FileCasStrategy::GarbageCollect(GcContext& GcCtx)
{
	ZEN_UNUSED(GcCtx);
}

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

#if ZEN_WITH_TESTS

TEST_CASE("cas.file.move")
{
	using namespace fmt::literals;

	ScopedTemporaryDirectory TempDir{"d:\\filecas_testdir"};

	CasStoreConfiguration CasConfig;
	CasConfig.RootDirectory = TempDir.Path() / "cas";

	FileCasStrategy FileCas(CasConfig);

	{
		std::filesystem::path Payload1Path{TempDir.Path() / "payload_1"};

		IoBuffer ZeroBytes{1024 * 1024};
		IoHash	 ZeroHash = IoHash::HashBuffer(ZeroBytes);

		BasicFile PayloadFile;
		PayloadFile.Open(Payload1Path, true);
		PayloadFile.Write(ZeroBytes, 0);
		PayloadFile.Close();

		IoBuffer Payload1 = IoBufferBuilder::MakeFromTemporaryFile(Payload1Path);

		CasStore::InsertResult Result = FileCas.InsertChunk(Payload1, ZeroHash);
		CHECK_EQ(Result.New, true);
	}

#	if 0
	SUBCASE("stresstest")
	{
		std::vector<IoHash> PayloadHashes;

		const int kWorkers = 64;
		const int kItemCount = 128;

		for (int w = 0; w < kWorkers; ++w)
		{
			for (int i = 0; i < kItemCount; ++i)
			{
				IoBuffer Payload{1024};
				*reinterpret_cast<int*>(Payload.MutableData()) = i;
				PayloadHashes.push_back(IoHash::HashBuffer(Payload));

				std::filesystem::path PayloadPath{TempDir.Path() / "payload_{}_{}"_format(w, i)};
				WriteFile(PayloadPath, Payload);
			}
		}

		std::barrier Sync{kWorkers};

		auto PopulateAll = [&](int w) {
			std::vector<IoBuffer> Buffers;

			for (int i = 0; i < kItemCount; ++i)
			{
				std::filesystem::path PayloadPath{TempDir.Path() / "payload_{}_{}"_format(w, i)};
				IoBuffer			  Payload = IoBufferBuilder::MakeFromTemporaryFile(PayloadPath);
				Buffers.push_back(Payload);
				Sync.arrive_and_wait();
				CasStore::InsertResult Result = FileCas.InsertChunk(Payload, PayloadHashes[i]);
			}
		};

		std::vector<std::jthread> Threads;

		for (int i = 0; i < kWorkers; ++i)
		{
			Threads.push_back(std::jthread(PopulateAll, i));
		}

		for (std::jthread& Thread : Threads)
		{
			Thread.join();
		}
	}
#	endif
}

#endif

void
filecas_forcelink()
{
}

}  // namespace zen