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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "filecas.h"
#include <zencore/compress.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/timer.h>
#include <zencore/trace.h>
#include <zencore/uid.h>
#include <zenstore/gc.h>
#include <zenstore/scrubcontext.h>
#include <zenutil/basicfile.h>
#if ZEN_WITH_TESTS
# include <zencore/compactbinarybuilder.h>
#endif
#include <gsl/gsl-lite.hpp>
#include <barrier>
#include <filesystem>
#include <functional>
#include <unordered_map>
ZEN_THIRD_PARTY_INCLUDES_START
#include <xxhash.h>
#if ZEN_PLATFORM_WINDOWS
# include <zencore/windows.h>
#else
# include <fcntl.h>
# include <sys/stat.h>
# include <unistd.h>
#endif
ZEN_THIRD_PARTY_INCLUDES_END
namespace zen {
namespace {
template<typename T>
void Reset(T& V)
{
T Tmp;
V.swap(Tmp);
}
} // namespace
namespace filecas::impl {
const char* IndexExtension = ".uidx";
const char* LogExtension = ".ulog";
std::filesystem::path GetIndexPath(const std::filesystem::path& RootDir) { return RootDir / fmt::format("cas{}", IndexExtension); }
std::filesystem::path GetTempIndexPath(const std::filesystem::path& RootDir)
{
return RootDir / fmt::format("cas.tmp{}", IndexExtension);
}
std::filesystem::path GetLogPath(const std::filesystem::path& RootDir) { return RootDir / fmt::format("cas{}", LogExtension); }
#pragma pack(push)
#pragma pack(1)
struct FileCasIndexHeader
{
static constexpr uint32_t ExpectedMagic = 0x75696478; // 'uidx';
static constexpr uint32_t CurrentVersion = 1;
uint32_t Magic = ExpectedMagic;
uint32_t Version = CurrentVersion;
uint64_t EntryCount = 0;
uint64_t LogPosition = 0;
uint32_t Reserved = 0;
uint32_t Checksum = 0;
static uint32_t ComputeChecksum(const FileCasIndexHeader& Header)
{
return XXH32(&Header.Magic, sizeof(FileCasIndexHeader) - sizeof(uint32_t), 0xC0C0'BABA);
}
};
static_assert(sizeof(FileCasIndexHeader) == 32);
#pragma pack(pop)
} // namespace filecas::impl
FileCasStrategy::ShardingHelper::ShardingHelper(const std::filesystem::path& RootPath, const IoHash& ChunkHash)
{
ShardedPath.Append(RootPath.c_str());
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.AppendSeparator();
ShardedPath.AppendAsciiRange(str, str + 3);
ShardedPath.AppendSeparator();
ShardedPath.AppendAsciiRange(str + 3, str + 5);
Shard2len = ShardedPath.Size();
ShardedPath.AppendSeparator();
ShardedPath.AppendAsciiRange(str + 5, str + 40);
}
//////////////////////////////////////////////////////////////////////////
static const float IndexMinLoadFactor = 0.2f;
static const float IndexMaxLoadFactor = 0.7f;
FileCasStrategy::FileCasStrategy(GcManager& Gc) : m_Log(logging::Get("filecas")), m_Gc(Gc)
{
m_Index.min_load_factor(IndexMinLoadFactor);
m_Index.max_load_factor(IndexMaxLoadFactor);
m_Gc.AddGcStorage(this);
m_Gc.AddGcReferenceStore(*this);
}
FileCasStrategy::~FileCasStrategy()
{
m_Gc.RemoveGcReferenceStore(*this);
m_Gc.RemoveGcStorage(this);
}
void
FileCasStrategy::Initialize(const std::filesystem::path& RootDirectory, bool IsNewStore)
{
ZEN_TRACE_CPU("FileCas::Initialize");
using namespace filecas::impl;
m_IsInitialized = true;
m_RootDirectory = RootDirectory;
m_Index.clear();
std::filesystem::path LogPath = GetLogPath(m_RootDirectory);
std::filesystem::path IndexPath = GetIndexPath(m_RootDirectory);
if (IsNewStore)
{
std::filesystem::remove(LogPath);
std::filesystem::remove(IndexPath);
if (std::filesystem::is_directory(m_RootDirectory))
{
// We need to explicitly only delete sharded root folders as the cas manifest, tinyobject and smallobject cas folders may reside
// in this folder as well
struct Visitor : public FileSystemTraversal::TreeVisitor
{
virtual void VisitFile(const std::filesystem::path&, const path_view&, uint64_t) override
{
// We don't care about files
}
static bool IsHexChar(std::filesystem::path::value_type C)
{
return std::find(&HexChars[0], &HexChars[16], C) != &HexChars[16];
}
virtual bool VisitDirectory([[maybe_unused]] const std::filesystem::path& Parent,
[[maybe_unused]] const path_view& DirectoryName) override
{
if (DirectoryName.length() == 3)
{
if (IsHexChar(DirectoryName[0]) && IsHexChar(DirectoryName[1]) && IsHexChar(DirectoryName[2]))
{
ShardedRoots.push_back(Parent / DirectoryName);
}
}
return false;
}
std::vector<std::filesystem::path> ShardedRoots;
} CasVisitor;
FileSystemTraversal Traversal;
Traversal.TraverseFileSystem(m_RootDirectory, CasVisitor);
for (const std::filesystem::path& SharededRoot : CasVisitor.ShardedRoots)
{
std::filesystem::remove_all(SharededRoot);
}
}
}
if (std::filesystem::is_regular_file(IndexPath))
{
uint32_t IndexVersion = 0;
m_LogFlushPosition = ReadIndexFile(IndexPath, IndexVersion);
if (IndexVersion == 0)
{
ZEN_WARN("removing invalid index file at '{}'", IndexPath);
std::filesystem::remove(IndexPath);
}
}
uint64_t LogEntryCount = 0;
if (std::filesystem::is_regular_file(LogPath))
{
if (TCasLogFile<FileCasIndexEntry>::IsValid(LogPath))
{
LogEntryCount = ReadLog(LogPath, m_LogFlushPosition);
}
else
{
ZEN_WARN("removing invalid cas log at '{}'", LogPath);
std::filesystem::remove(LogPath);
}
}
for (const auto& Entry : m_Index)
{
m_TotalSize.fetch_add(Entry.second.Size, std::memory_order::relaxed);
}
CreateDirectories(m_RootDirectory);
m_CasLog.Open(LogPath, CasLogFile::Mode::kWrite);
if (IsNewStore || LogEntryCount > 0)
{
MakeIndexSnapshot();
}
}
CasStore::InsertResult
FileCasStrategy::InsertChunk(IoBuffer Chunk, const IoHash& ChunkHash, CasStore::InsertMode Mode)
{
ZEN_TRACE_CPU("FileCas::InsertChunk");
ZEN_ASSERT(m_IsInitialized);
#if !ZEN_WITH_TESTS
ZEN_ASSERT(Chunk.GetContentType() == ZenContentType::kCompressedBinary);
#endif
if (Mode == CasStore::InsertMode::kCopyOnly)
{
{
RwLock::SharedLockScope _(m_Lock);
if (m_Index.contains(ChunkHash))
{
return CasStore::InsertResult{.New = false};
}
}
return InsertChunkData(Chunk.Data(), Chunk.Size(), 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;
bool IsWholeFile = Chunk.IsWholeFile();
if (IsWholeFile && Chunk.GetFileReference(/* out */ FileRef))
{
ZEN_TRACE_CPU("FileCas::InsertChunk::Move");
{
bool Exists = true;
{
RwLock::SharedLockScope _(m_Lock);
Exists = m_Index.contains(ChunkHash);
}
if (Exists)
{
return CasStore::InsertResult{.New = false};
}
}
ShardingHelper Name(m_RootDirectory.c_str(), ChunkHash);
RwLock::ExclusiveLockScope HashLock(LockForHash(ChunkHash));
#if ZEN_PLATFORM_WINDOWS
const HANDLE ChunkFileHandle = FileRef.FileHandle;
// See if file already exists
{
ZEN_TRACE_CPU("FileCas::InsertChunk::Exists");
windows::FileHandle 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
size_t ChunkSize = Chunk.GetSize();
uint64_t FileSize = 0;
if (HRESULT hSizeRes = PayloadFile.GetSize(FileSize); SUCCEEDED(hSizeRes) && FileSize == ChunkSize)
{
HashLock.ReleaseNow();
bool IsNew = false;
{
RwLock::ExclusiveLockScope __(m_Lock);
IsNew = m_Index.insert({ChunkHash, IndexEntry{.Size = ChunkSize}}).second;
}
if (IsNew)
{
m_TotalSize.fetch_add(static_cast<uint64_t>(ChunkSize), std::memory_order::relaxed);
}
return CasStore::InsertResult{.New = IsNew};
}
else
{
ZEN_WARN("get file size FAILED or file size mismatch of file cas '{}'. Expected {}, found {}. Trying to overwrite",
Name.ShardedPath.ToUtf8(),
ChunkSize,
FileSize);
}
}
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 '{}': {}", Name.ShardedPath.ToUtf8(), 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
windows::FileHandle 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, fmt::format("Failed to open shard directory '{}'", FilePath));
}
// Retry rename/move
Success = SetFileInformationByHandle(ChunkFileHandle, FileRenameInfo, RenameInfo, BufferSize);
}
if (Success)
{
m_CasLog.Append({.Key = ChunkHash, .Size = Chunk.Size()});
Chunk.SetDeleteOnClose(false);
HashLock.ReleaseNow();
bool IsNew = false;
{
RwLock::ExclusiveLockScope __(m_Lock);
IsNew = m_Index.insert({ChunkHash, IndexEntry{.Size = Chunk.Size()}}).second;
}
if (IsNew)
{
m_TotalSize.fetch_add(Chunk.Size(), std::memory_order::relaxed);
}
return CasStore::InsertResult{.New = IsNew};
}
const DWORD LastError = GetLastError();
if ((LastError == ERROR_FILE_EXISTS) || (LastError == ERROR_ALREADY_EXISTS))
{
HashLock.ReleaseNow();
bool IsNew = false;
{
RwLock::ExclusiveLockScope __(m_Lock);
IsNew = m_Index.insert({ChunkHash, IndexEntry{.Size = Chunk.Size()}}).second;
}
if (IsNew)
{
m_TotalSize.fetch_add(Chunk.Size(), std::memory_order::relaxed);
}
return CasStore::InsertResult{.New = IsNew};
}
ZEN_WARN("rename of CAS payload file failed ('{}'), falling back to regular write for insert of {}",
GetSystemErrorAsString(LastError),
ChunkHash);
#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC
std::filesystem::path SourcePath = PathFromHandle(FileRef.FileHandle);
std::filesystem::path DestPath = Name.ShardedPath.c_str();
int Ret = link(SourcePath.c_str(), DestPath.c_str());
if (Ret < 0 && zen::GetLastError() == ENOENT)
{
// Destination directory doesn't exist. Create it any try again.
CreateDirectories(DestPath.parent_path().c_str());
Ret = link(SourcePath.c_str(), DestPath.c_str());
}
if (Ret == 0)
{
m_CasLog.Append({.Key = ChunkHash, .Size = Chunk.Size()});
Chunk.SetDeleteOnClose(false);
HashLock.ReleaseNow();
bool IsNew = false;
{
RwLock::ExclusiveLockScope __(m_Lock);
IsNew = m_Index.insert({ChunkHash, IndexEntry{.Size = Chunk.Size()}}).second;
}
if (IsNew)
{
m_TotalSize.fetch_add(Chunk.Size(), std::memory_order::relaxed);
}
return CasStore::InsertResult{.New = IsNew};
}
else
{
int LinkError = zen::GetLastError();
// It is possible that someone beat us to it in linking the file. In that
// case a "file exists" error is okay. All others are not.
if (LinkError == EEXIST)
{
HashLock.ReleaseNow();
bool IsNew = false;
{
RwLock::ExclusiveLockScope __(m_Lock);
IsNew = m_Index.insert({ChunkHash, IndexEntry{.Size = Chunk.Size()}}).second;
}
if (IsNew)
{
m_TotalSize.fetch_add(Chunk.Size(), std::memory_order::relaxed);
}
return CasStore::InsertResult{.New = IsNew};
}
ZEN_WARN("link of CAS payload file failed ('{}'), falling back to regular write for insert of {}",
GetSystemErrorAsString(LinkError),
ChunkHash);
}
#endif // ZEN_PLATFORM_*
}
return InsertChunkData(Chunk.Data(), Chunk.Size(), ChunkHash);
}
CasStore::InsertResult
FileCasStrategy::InsertChunkData(const void* const ChunkData, const size_t ChunkSize, const IoHash& ChunkHash)
{
ZEN_TRACE_CPU("FileCas::InsertChunkData");
ZEN_ASSERT(m_IsInitialized);
{
RwLock::SharedLockScope _(m_Lock);
if (m_Index.contains(ChunkHash))
{
return {.New = false};
}
}
ZEN_TRACE_CPU("FileCas::InsertChunkData::Write");
ShardingHelper Name(m_RootDirectory.c_str(), ChunkHash);
// See if file already exists
#if ZEN_PLATFORM_WINDOWS
windows::FileHandle 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
bool IsNew = false;
{
RwLock::ExclusiveLockScope _(m_Lock);
IsNew = m_Index.insert({ChunkHash, IndexEntry{.Size = ChunkSize}}).second;
}
if (IsNew)
{
m_TotalSize.fetch_add(static_cast<uint64_t>(ChunkSize), std::memory_order::relaxed);
}
return CasStore::InsertResult{.New = IsNew};
}
PayloadFile.Close();
#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC
if (access(Name.ShardedPath.c_str(), F_OK) == 0)
{
return CasStore::InsertResult{.New = false};
}
#endif
RwLock::ExclusiveLockScope HashLock(LockForHash(ChunkHash));
#if ZEN_PLATFORM_WINDOWS
// 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))
{
uint64_t FileSize = 0;
if (HRESULT hSizeRes = PayloadFile.GetSize(FileSize); SUCCEEDED(hSizeRes) && FileSize == ChunkSize)
{
// If we succeeded in opening the file then and the size is correct we don't need to do anything
// else because someone else managed to create the file before we did. Just return.
HashLock.ReleaseNow();
bool IsNew = false;
{
RwLock::ExclusiveLockScope __(m_Lock);
IsNew = m_Index.insert({ChunkHash, IndexEntry{.Size = ChunkSize}}).second;
}
if (IsNew)
{
m_TotalSize.fetch_add(static_cast<uint64_t>(ChunkSize), std::memory_order::relaxed);
}
return CasStore::InsertResult{.New = IsNew};
}
else
{
ZEN_WARN("get file size FAILED or file size mismatch of file cas '{}'. Expected {}, found {}. Trying to overwrite",
Name.ShardedPath.ToUtf8(),
ChunkSize,
FileSize);
}
}
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
CreateDirectories(std::wstring_view(Name.ShardedPath.c_str(), Name.Shard2len));
hRes = InternalCreateFile();
}
if (FAILED(hRes))
{
ThrowSystemException(hRes, fmt::format("Failed to open shard file '{}'", Name.ShardedPath.ToUtf8()));
}
#else
// Attempt to exclusively create the file.
auto InternalCreateFile = [&] {
int Fd = open(Name.ShardedPath.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0666);
if (Fd >= 0)
{
fchmod(Fd, 0666);
}
return Fd;
};
int Fd = InternalCreateFile();
if (Fd < 0)
{
switch (zen::GetLastError())
{
case EEXIST:
// Another thread has beat us to it so we're golden.
{
HashLock.ReleaseNow();
bool IsNew = false;
{
RwLock::ExclusiveLockScope __(m_Lock);
IsNew = m_Index.insert({ChunkHash, IndexEntry{.Size = ChunkSize}}).second;
}
if (IsNew)
{
m_TotalSize.fetch_add(static_cast<uint64_t>(ChunkSize), std::memory_order::relaxed);
}
return {.New = IsNew};
}
break;
case ENOENT:
if (zen::CreateDirectories(std::string_view(Name.ShardedPath.c_str(), Name.Shard2len)))
{
Fd = InternalCreateFile();
if (Fd >= 0)
{
break;
}
}
ThrowLastError(fmt::format("Failed creating shard directory '{}'", Name.ShardedPath));
default:
ThrowLastError(fmt::format("Unexpected error occurred opening shard file '{}'", Name.ShardedPath.ToUtf8()));
}
}
struct FdWrapper
{
~FdWrapper() { Close(); }
void Write(const void* Cursor, size_t Size) { (void)!write(Fd, Cursor, Size); }
void Close()
{
if (Fd >= 0)
{
close(Fd);
Fd = -1;
}
}
int Fd;
} PayloadFile = {Fd};
#endif // ZEN_PLATFORM_WINDOWS
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();
m_CasLog.Append({.Key = ChunkHash, .Size = ChunkSize});
HashLock.ReleaseNow();
bool IsNew = false;
{
RwLock::ExclusiveLockScope __(m_Lock);
IsNew = m_Index.insert({ChunkHash, IndexEntry{.Size = ChunkSize}}).second;
}
if (IsNew)
{
m_TotalSize.fetch_add(static_cast<uint64_t>(ChunkSize), std::memory_order::relaxed);
}
return {.New = IsNew};
}
IoBuffer
FileCasStrategy::FindChunk(const IoHash& ChunkHash)
{
ZEN_TRACE_CPU("FileCas::FindChunk");
ZEN_ASSERT(m_IsInitialized);
uint64_t ExpectedSize = 0;
{
RwLock::SharedLockScope _(m_Lock);
if (auto It = m_Index.find(ChunkHash); It != m_Index.end())
{
ExpectedSize = It->second.Size;
}
else
{
return {};
}
}
ShardingHelper Name(m_RootDirectory.c_str(), ChunkHash);
RwLock::SharedLockScope _(LockForHash(ChunkHash));
if (IoBuffer Chunk = IoBufferBuilder::MakeFromFile(Name.ShardedPath.c_str()); Chunk.GetSize() == ExpectedSize)
{
return Chunk;
}
return {};
}
bool
FileCasStrategy::HaveChunk(const IoHash& ChunkHash)
{
ZEN_ASSERT(m_IsInitialized);
RwLock::SharedLockScope _(m_Lock);
return m_Index.contains(ChunkHash);
}
void
FileCasStrategy::DeleteChunk(const IoHash& ChunkHash, std::error_code& Ec)
{
ZEN_TRACE_CPU("FileCas::DeleteChunk");
ShardingHelper Name(m_RootDirectory.c_str(), ChunkHash);
uint64_t FileSize = static_cast<uint64_t>(std::filesystem::file_size(Name.ShardedPath.c_str(), Ec));
if (Ec)
{
ZEN_WARN("get file size FAILED, file cas '{}'", Name.ShardedPath.ToUtf8());
FileSize = 0;
}
ZEN_DEBUG("deleting CAS payload file '{}' {}", Name.ShardedPath.ToUtf8(), NiceBytes(FileSize));
std::filesystem::remove(Name.ShardedPath.c_str(), Ec);
if (!Ec || !std::filesystem::exists(Name.ShardedPath.c_str()))
{
{
RwLock::ExclusiveLockScope _(m_Lock);
if (auto It = m_Index.find(ChunkHash); It != m_Index.end())
{
m_TotalSize.fetch_sub(It->second.Size, std::memory_order_relaxed);
m_Index.erase(It);
}
}
m_CasLog.Append({.Key = ChunkHash, .Flags = FileCasIndexEntry::kTombStone, .Size = FileSize});
}
}
void
FileCasStrategy::FilterChunks(HashKeySet& InOutChunks)
{
ZEN_ASSERT(m_IsInitialized);
// 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.RemoveHashesIf([&](const IoHash& Hash) { return HaveChunk(Hash); });
}
void
FileCasStrategy::IterateChunks(std::function<void(const IoHash& Hash, IoBuffer&& Payload)>&& Callback)
{
ZEN_TRACE_CPU("FileCas::IterateChunks");
ZEN_ASSERT(m_IsInitialized);
RwLock::SharedLockScope _(m_Lock);
for (const auto& It : m_Index)
{
const IoHash& NameHash = It.first;
ShardingHelper Name(m_RootDirectory.c_str(), NameHash);
IoBuffer Payload = IoBufferBuilder::MakeFromFile(Name.ShardedPath.c_str());
Callback(NameHash, std::move(Payload));
}
}
void
FileCasStrategy::IterateChunks(std::function<void(const IoHash& Hash, uint64_t Size)>&& Callback)
{
ZEN_TRACE_CPU("FileCas::IterateChunks");
ZEN_ASSERT(m_IsInitialized);
RwLock::SharedLockScope _(m_Lock);
for (const auto& It : m_Index)
{
const IoHash& NameHash = It.first;
Callback(NameHash, It.second.Size);
}
}
void
FileCasStrategy::Flush()
{
ZEN_TRACE_CPU("FileCas::Flush");
m_CasLog.Flush();
MakeIndexSnapshot();
}
void
FileCasStrategy::ScrubStorage(ScrubContext& Ctx)
{
ZEN_TRACE_CPU("FileCas::ScrubStorage");
if (Ctx.IsSkipCas())
{
ZEN_INFO("SKIPPED scrubbing: '{}'", m_RootDirectory);
return;
}
Stopwatch Timer;
ZEN_INFO("scrubbing file CAS @ '{}'", m_RootDirectory);
ZEN_ASSERT(m_IsInitialized);
std::vector<IoHash> BadHashes;
uint64_t ChunkCount{0}, ChunkBytes{0};
int DiscoveredFilesNotInIndex = 0;
{
std::vector<FileCasStrategy::FileCasIndexEntry> ScannedEntries = FileCasStrategy::ScanFolderForCasFiles(m_RootDirectory);
RwLock::ExclusiveLockScope _(m_Lock);
for (const FileCasStrategy::FileCasIndexEntry& Entry : ScannedEntries)
{
if (m_Index.insert({Entry.Key, {.Size = Entry.Size}}).second)
{
m_TotalSize.fetch_add(static_cast<uint64_t>(Entry.Size), std::memory_order::relaxed);
m_CasLog.Append({.Key = Entry.Key, .Size = Entry.Size});
++DiscoveredFilesNotInIndex;
}
}
}
ZEN_INFO("discovered {} files @ '{}' ({} not in index), scrubbing", m_Index.size(), m_RootDirectory, DiscoveredFilesNotInIndex);
IterateChunks([&](const IoHash& Hash, IoBuffer&& Payload) {
if (!Payload)
{
BadHashes.push_back(Hash);
return;
}
++ChunkCount;
ChunkBytes += Payload.GetSize();
IoBuffer InMemoryBuffer = IoBufferBuilder::ReadFromFileMaybe(Payload);
IoHash RawHash;
uint64_t RawSize;
if (CompressedBuffer::ValidateCompressedHeader(Payload, /* out */ RawHash, /* out */ RawSize))
{
if (RawHash == Hash)
{
// Header hash matches the file name, full validation requires that
// we check that the decompressed data hash also matches
CompressedBuffer CompBuffer = CompressedBuffer::FromCompressedNoValidate(std::move(InMemoryBuffer));
OodleCompressor Compressor;
OodleCompressionLevel CompressionLevel;
uint64_t BlockSize;
if (CompBuffer.TryGetCompressParameters(Compressor, CompressionLevel, BlockSize))
{
if (BlockSize == 0)
{
BlockSize = 256 * 1024;
}
else if (BlockSize < (1024 * 1024))
{
BlockSize = BlockSize * (1024 * 1024 / BlockSize);
}
std::unique_ptr<uint8_t[]> DecompressionBuffer(new uint8_t[BlockSize]);
IoHashStream Hasher;
uint64_t RawOffset = 0;
while (RawSize)
{
const uint64_t DecompressedBlockSize = Min(BlockSize, RawSize);
bool Ok = CompBuffer.TryDecompressTo(MutableMemoryView((void*)DecompressionBuffer.get(), DecompressedBlockSize),
RawOffset);
if (Ok)
{
Hasher.Append(DecompressionBuffer.get(), DecompressedBlockSize);
}
RawSize -= DecompressedBlockSize;
RawOffset += DecompressedBlockSize;
}
const IoHash FinalHash = Hasher.GetHash();
if (FinalHash == Hash)
{
// all good
return;
}
}
}
}
BadHashes.push_back(Hash);
});
Ctx.ReportScrubbed(ChunkCount, ChunkBytes);
if (!BadHashes.empty())
{
ZEN_WARN("file CAS scrubbing: {} bad chunks found @ '{}'", BadHashes.size(), m_RootDirectory);
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, Ec.message());
}
}
}
else
{
ZEN_WARN("recovery: NOT deleting backing files for {} bad chunks", BadHashes.size());
}
}
// Let whomever it concerns know about the bad chunks. This could
// be used to invalidate higher level data structures more efficiently
// than a full validation pass might be able to do
Ctx.ReportBadCidChunks(BadHashes);
ZEN_INFO("file CAS @ '{}' scrubbed: {} chunks ({}), took {}",
m_RootDirectory,
ChunkCount,
NiceBytes(ChunkBytes),
NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
}
void
FileCasStrategy::CollectGarbage(GcContext& GcCtx)
{
ZEN_TRACE_CPU("FileCas::CollectGarbage");
ZEN_ASSERT(m_IsInitialized);
if (GcCtx.SkipCid())
{
return;
}
ZEN_DEBUG("collecting garbage from {}", m_RootDirectory);
std::vector<IoHash> ChunksToDelete;
std::atomic<uint64_t> ChunksToDeleteBytes{0};
std::atomic<uint64_t> ChunkCount{0}, ChunkBytes{0};
std::vector<IoHash> CandidateCas;
CandidateCas.resize(1);
uint64_t DeletedCount = 0;
uint64_t OldTotalSize = m_TotalSize.load(std::memory_order::relaxed);
Stopwatch TotalTimer;
const auto _ = MakeGuard([&] {
ZEN_DEBUG("garbage collect for '{}' DONE after {}, deleted {} out of {} files, removed {} out of {}",
m_RootDirectory,
NiceTimeSpanMs(TotalTimer.GetElapsedTimeMs()),
DeletedCount,
ChunkCount.load(),
NiceBytes(OldTotalSize - m_TotalSize.load(std::memory_order::relaxed)),
NiceBytes(OldTotalSize));
});
{
ZEN_TRACE_CPU("FileCas::CollectGarbage::Filter");
IterateChunks([&](const IoHash& Hash, uint64_t Size) {
bool KeepThis = false;
CandidateCas[0] = Hash;
GcCtx.FilterCids(CandidateCas, [&](const IoHash& Hash) {
ZEN_UNUSED(Hash);
KeepThis = true;
});
if (!KeepThis)
{
ChunksToDelete.push_back(Hash);
ChunksToDeleteBytes.fetch_add(Size);
}
++ChunkCount;
ChunkBytes.fetch_add(Size);
});
}
// TODO, any entires we did not encounter during our IterateChunks should be removed from the index
if (ChunksToDelete.empty())
{
ZEN_DEBUG("gc for '{}' SKIPPED, nothing to delete", m_RootDirectory);
return;
}
ZEN_DEBUG("deleting file CAS garbage for '{}': {} out of {} chunks ({})",
m_RootDirectory,
ChunksToDelete.size(),
ChunkCount.load(),
NiceBytes(ChunksToDeleteBytes));
if (GcCtx.IsDeletionMode() == false)
{
ZEN_DEBUG("NOTE: not actually deleting anything since deletion is disabled");
return;
}
for (const IoHash& Hash : ChunksToDelete)
{
ZEN_TRACE("deleting chunk {}", Hash);
std::error_code Ec;
DeleteChunk(Hash, Ec);
if (Ec)
{
ZEN_WARN("gc for '{}' failed to delete file for chunk {}: '{}'", m_RootDirectory, Hash, Ec.message());
continue;
}
DeletedCount++;
}
GcCtx.AddDeletedCids(ChunksToDelete);
}
GcStorageSize
FileCasStrategy::StorageSize() const
{
return {.DiskSize = m_TotalSize.load(std::memory_order::relaxed)};
}
bool
FileCasStrategy::ValidateEntry(const FileCasIndexEntry& Entry, std::string& OutReason)
{
if (Entry.Key == IoHash::Zero)
{
OutReason = fmt::format("Invalid hash key {}", Entry.Key.ToHexString());
return false;
}
if (Entry.Flags & (~FileCasIndexEntry::kTombStone))
{
OutReason = fmt::format("Invalid flags {} for entry {}", Entry.Flags, Entry.Key.ToHexString());
return false;
}
if (Entry.IsFlagSet(FileCasIndexEntry::kTombStone))
{
return true;
}
uint64_t Size = Entry.Size;
if (Size == 0)
{
OutReason = fmt::format("Invalid size {} for entry {}", Size, Entry.Key.ToHexString());
return false;
}
return true;
}
void
FileCasStrategy::MakeIndexSnapshot()
{
ZEN_TRACE_CPU("FileCas::MakeIndexSnapshot");
using namespace filecas::impl;
uint64_t LogCount = m_CasLog.GetLogCount();
if (m_LogFlushPosition == LogCount)
{
return;
}
ZEN_DEBUG("write store snapshot for '{}'", m_RootDirectory);
uint64_t EntryCount = 0;
Stopwatch Timer;
const auto _ = MakeGuard([&] {
ZEN_INFO("wrote store snapshot for '{}' containing {} entries in {}",
m_RootDirectory,
EntryCount,
NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
});
namespace fs = std::filesystem;
fs::path IndexPath = GetIndexPath(m_RootDirectory);
fs::path STmpIndexPath = GetTempIndexPath(m_RootDirectory);
// Move index away, we keep it if something goes wrong
if (fs::is_regular_file(STmpIndexPath))
{
std::error_code Ec;
if (!fs::remove(STmpIndexPath, Ec) || Ec)
{
ZEN_WARN("snapshot failed to clean up temp snapshot at {}, reason: '{}'", STmpIndexPath, Ec.message());
return;
}
}
try
{
if (fs::is_regular_file(IndexPath))
{
fs::rename(IndexPath, STmpIndexPath);
}
// Write the current state of the location map to a new index state
std::vector<FileCasIndexEntry> Entries;
uint64_t IndexLogPosition = 0;
{
RwLock::SharedLockScope __(m_Lock);
IndexLogPosition = m_CasLog.GetLogCount();
Entries.resize(m_Index.size());
uint64_t EntryIndex = 0;
for (const auto& Entry : m_Index)
{
FileCasIndexEntry& IndexEntry = Entries[EntryIndex++];
IndexEntry.Key = Entry.first;
IndexEntry.Size = Entry.second.Size;
}
}
TemporaryFile ObjectIndexFile;
std::error_code Ec;
ObjectIndexFile.CreateTemporary(IndexPath.parent_path(), Ec);
if (Ec)
{
throw std::system_error(Ec, fmt::format("Failed to create temp file for index snapshot at '{}'", IndexPath));
}
filecas::impl::FileCasIndexHeader Header = {.EntryCount = Entries.size(), .LogPosition = IndexLogPosition};
Header.Checksum = filecas::impl::FileCasIndexHeader::ComputeChecksum(Header);
ObjectIndexFile.Write(&Header, sizeof(filecas::impl::FileCasIndexHeader), 0);
ObjectIndexFile.Write(Entries.data(), Entries.size() * sizeof(FileCasIndexEntry), sizeof(filecas::impl::FileCasIndexHeader));
ObjectIndexFile.Flush();
ObjectIndexFile.MoveTemporaryIntoPlace(IndexPath, Ec);
if (Ec)
{
throw std::system_error(Ec, fmt::format("Failed to move temp file '{}' to '{}'", ObjectIndexFile.GetPath(), IndexPath));
}
EntryCount = Entries.size();
m_LogFlushPosition = IndexLogPosition;
}
catch (const std::exception& Err)
{
ZEN_WARN("snapshot FAILED, reason: '{}'", Err.what());
// Restore any previous snapshot
if (fs::is_regular_file(STmpIndexPath))
{
std::error_code Ec;
fs::remove(IndexPath, Ec); // We don't care if this fails, we try to move the old temp file regardless
fs::rename(STmpIndexPath, IndexPath, Ec);
if (Ec)
{
ZEN_WARN("snapshot failed to restore old snapshot from {}, reason: '{}'", STmpIndexPath, Ec.message());
}
}
}
if (fs::is_regular_file(STmpIndexPath))
{
std::error_code Ec;
if (!fs::remove(STmpIndexPath, Ec) || Ec)
{
ZEN_WARN("snapshot failed to remove temporary file {}, reason: '{}'", STmpIndexPath, Ec.message());
}
}
}
uint64_t
FileCasStrategy::ReadIndexFile(const std::filesystem::path& IndexPath, uint32_t& OutVersion)
{
ZEN_TRACE_CPU("FileCas::ReadIndexFile");
using namespace filecas::impl;
std::vector<FileCasIndexEntry> Entries;
if (std::filesystem::is_regular_file(IndexPath))
{
Stopwatch Timer;
const auto _ = MakeGuard([&] {
ZEN_INFO("read store '{}' index containing {} entries in {}",
IndexPath,
Entries.size(),
NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
});
BasicFile ObjectIndexFile;
ObjectIndexFile.Open(IndexPath, BasicFile::Mode::kRead);
uint64_t Size = ObjectIndexFile.FileSize();
if (Size >= sizeof(FileCasIndexHeader))
{
uint64_t ExpectedEntryCount = (Size - sizeof(sizeof(FileCasIndexHeader))) / sizeof(FileCasIndexEntry);
FileCasIndexHeader Header;
ObjectIndexFile.Read(&Header, sizeof(Header), 0);
if ((Header.Magic == FileCasIndexHeader::ExpectedMagic) && (Header.Version == FileCasIndexHeader::CurrentVersion) &&
(Header.Checksum == FileCasIndexHeader::ComputeChecksum(Header)) && (Header.EntryCount <= ExpectedEntryCount))
{
Entries.resize(Header.EntryCount);
ObjectIndexFile.Read(Entries.data(), Header.EntryCount * sizeof(FileCasIndexEntry), sizeof(FileCasIndexHeader));
std::string InvalidEntryReason;
for (const FileCasIndexEntry& Entry : Entries)
{
if (!ValidateEntry(Entry, InvalidEntryReason))
{
ZEN_WARN("skipping invalid entry in '{}', reason: '{}'", IndexPath, InvalidEntryReason);
continue;
}
m_Index.insert_or_assign(Entry.Key, IndexEntry{.Size = Entry.Size});
}
OutVersion = FileCasIndexHeader::CurrentVersion;
return Header.LogPosition;
}
else
{
ZEN_WARN("skipping invalid index file '{}'", IndexPath);
}
}
return 0;
}
if (std::filesystem::is_directory(m_RootDirectory))
{
ZEN_INFO("missing index for file cas, scanning for cas files in {}", m_RootDirectory);
TCasLogFile<FileCasIndexEntry> CasLog;
uint64_t TotalSize = 0;
Stopwatch TotalTimer;
const auto _ = MakeGuard([&] {
ZEN_INFO("scanned file cas folder '{}' DONE after {}, found {} files totalling {}",
m_RootDirectory,
NiceTimeSpanMs(TotalTimer.GetElapsedTimeMs()),
CasLog.GetLogCount(),
NiceBytes(TotalSize));
});
std::filesystem::path LogPath = GetLogPath(m_RootDirectory);
std::vector<FileCasStrategy::FileCasIndexEntry> ScannedEntries = FileCasStrategy::ScanFolderForCasFiles(m_RootDirectory);
CasLog.Open(LogPath, CasLogFile::Mode::kTruncate);
std::string InvalidEntryReason;
for (const FileCasStrategy::FileCasIndexEntry& Entry : ScannedEntries)
{
m_Index.insert_or_assign(Entry.Key, IndexEntry{.Size = Entry.Size});
TotalSize += Entry.Size;
CasLog.Append(Entry);
}
CasLog.Close();
}
return 0;
}
uint64_t
FileCasStrategy::ReadLog(const std::filesystem::path& LogPath, uint64_t SkipEntryCount)
{
ZEN_TRACE_CPU("FileCas::ReadLog");
using namespace filecas::impl;
if (std::filesystem::is_regular_file(LogPath))
{
uint64_t LogEntryCount = 0;
Stopwatch Timer;
const auto _ = MakeGuard([&] {
ZEN_INFO("read store '{}' log containing {} entries in {}", LogPath, LogEntryCount, NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
});
TCasLogFile<FileCasIndexEntry> CasLog;
CasLog.Open(LogPath, CasLogFile::Mode::kRead);
if (CasLog.Initialize())
{
uint64_t EntryCount = CasLog.GetLogCount();
if (EntryCount < SkipEntryCount)
{
ZEN_WARN("reading full log at '{}', reason: Log position from index snapshot is out of range", LogPath);
SkipEntryCount = 0;
}
LogEntryCount = EntryCount - SkipEntryCount;
m_Index.reserve(LogEntryCount);
uint64_t InvalidEntryCount = 0;
CasLog.Replay(
[&](const FileCasIndexEntry& Record) {
std::string InvalidEntryReason;
if (Record.Flags & FileCasIndexEntry::kTombStone)
{
m_Index.erase(Record.Key);
return;
}
if (!ValidateEntry(Record, InvalidEntryReason))
{
ZEN_WARN("skipping invalid entry in '{}', reason: '{}'", LogPath, InvalidEntryReason);
++InvalidEntryCount;
return;
}
m_Index.insert_or_assign(Record.Key, IndexEntry{.Size = Record.Size});
},
SkipEntryCount);
if (InvalidEntryCount)
{
ZEN_WARN("found {} invalid entries in '{}'", InvalidEntryCount, LogPath);
}
return LogEntryCount;
}
}
return 0;
}
std::vector<FileCasStrategy::FileCasIndexEntry>
FileCasStrategy::ScanFolderForCasFiles(const std::filesystem::path& RootDir)
{
ZEN_TRACE_CPU("FileCas::ScanFolderForCasFiles");
using namespace filecas::impl;
std::vector<FileCasIndexEntry> Entries;
struct Visitor : public FileSystemTraversal::TreeVisitor
{
Visitor(const std::filesystem::path& RootDir, std::vector<FileCasIndexEntry>& Entries) : RootDirectory(RootDir), Entries(Entries) {}
virtual void VisitFile(const std::filesystem::path& Parent, const path_view& File, uint64_t FileSize) override
{
std::filesystem::path RelPath = std::filesystem::relative(Parent, RootDirectory);
std::filesystem::path::string_type 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);
// TODO: should validate that we're actually dealing with a valid hex string here
#if ZEN_PLATFORM_WINDOWS
StringBuilder<64> Utf8;
WideToUtf8(PathString, Utf8);
IoHash NameHash = IoHash::FromHexString({Utf8.Data(), Utf8.Size()});
#else
IoHash NameHash = IoHash::FromHexString(PathString);
#endif
Entries.emplace_back(FileCasIndexEntry{.Key = NameHash, .Size = FileSize});
}
}
virtual bool VisitDirectory([[maybe_unused]] const std::filesystem::path& Parent,
[[maybe_unused]] const path_view& DirectoryName) override
{
return true;
}
const std::filesystem::path& RootDirectory;
std::vector<FileCasIndexEntry>& Entries;
} CasVisitor{RootDir, Entries};
FileSystemTraversal Traversal;
Traversal.TraverseFileSystem(RootDir, CasVisitor);
return Entries;
};
class FileCasStoreCompactor : public GcStoreCompactor
{
public:
FileCasStoreCompactor(FileCasStrategy& Owner, std::vector<IoHash>&& ReferencesToClean)
: m_FileCasStrategy(Owner)
, m_ReferencesToClean(std::move(ReferencesToClean))
{
m_ReferencesToClean.shrink_to_fit();
}
virtual void CompactStore(GcCtx& Ctx, GcCompactStoreStats& Stats, const std::function<uint64_t()>&)
{
ZEN_TRACE_CPU("FileCas::CompactStore");
Stopwatch Timer;
const auto _ = MakeGuard([&] {
Reset(m_ReferencesToClean);
if (!Ctx.Settings.Verbose)
{
return;
}
ZEN_INFO("GCV2: filecas [COMPACT] '{}': RemovedDisk: {} in {}",
m_FileCasStrategy.m_RootDirectory,
NiceBytes(Stats.RemovedDisk),
NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
});
ZEN_INFO("GCV2: filecas [COMPACT] '{}': {} {} files",
m_FileCasStrategy.m_RootDirectory,
Ctx.Settings.IsDeleteMode ? "Removing" : "Checking",
m_ReferencesToClean.size());
size_t Skipped = 0;
for (const IoHash& ChunkHash : m_ReferencesToClean)
{
FileCasStrategy::ShardingHelper Name(m_FileCasStrategy.m_RootDirectory.c_str(), ChunkHash);
{
RwLock::SharedLockScope __(m_FileCasStrategy.m_Lock);
if (auto It = m_FileCasStrategy.m_Index.find(ChunkHash); It != m_FileCasStrategy.m_Index.end())
{
// Not regarded as pruned, leave it be
continue;
}
if (Ctx.IsCancelledFlag.load())
{
return;
}
if (Ctx.Settings.IsDeleteMode)
{
if (Ctx.Settings.Verbose)
{
ZEN_INFO("GCV2: filecas [COMPACT] '{}': Deleting CAS payload file '{}'",
m_FileCasStrategy.m_RootDirectory,
Name.ShardedPath.ToUtf8());
}
std::error_code Ec;
uint64_t SizeOnDisk = std::filesystem::file_size(Name.ShardedPath.c_str(), Ec);
if (Ec)
{
SizeOnDisk = 0;
}
bool Existed = std::filesystem::remove(Name.ShardedPath.c_str(), Ec);
if (Ec)
{
ZEN_WARN("GCV2: filecas [COMPACT] '{}': Failed deleting CAS payload file '{}'. Reason '{}'",
m_FileCasStrategy.m_RootDirectory,
Name.ShardedPath.ToUtf8(),
Ec.message());
continue;
}
if (!Existed)
{
continue;
}
Stats.RemovedDisk += SizeOnDisk;
}
else
{
std::error_code Ec;
bool Existed = std::filesystem::is_regular_file(Name.ShardedPath.c_str(), Ec);
if (Ec)
{
if (Ctx.Settings.Verbose)
{
ZEN_INFO("GCV2: filecas [COMPACT] '{}': Failed checking CAS payload file '{}'. Reason '{}'",
m_FileCasStrategy.m_RootDirectory,
Name.ShardedPath.ToUtf8(),
Ec.message());
}
continue;
}
if (!Existed)
{
continue;
}
Skipped++;
}
}
}
if (Skipped > 0)
{
if (Ctx.Settings.Verbose)
{
ZEN_INFO("GCV2: filecas [COMPACT] '{}': Skipped deleting of {} eligible files", m_FileCasStrategy.m_RootDirectory, Skipped);
}
}
Reset(m_ReferencesToClean);
}
private:
FileCasStrategy& m_FileCasStrategy;
std::vector<IoHash> m_ReferencesToClean;
};
class FileCasReferencePruner : public GcReferencePruner
{
public:
FileCasReferencePruner(FileCasStrategy& Owner, std::vector<IoHash>&& Cids) : m_FileCasStrategy(Owner), m_Cids(std::move(Cids)) {}
virtual std::string GetGcName(GcCtx& Ctx) override { return m_FileCasStrategy.GetGcName(Ctx); }
virtual GcStoreCompactor* RemoveUnreferencedData(GcCtx& Ctx,
GcStats& Stats,
const GetUnusedReferencesFunc& GetUnusedReferences) override
{
ZEN_TRACE_CPU("FileCas::RemoveUnreferencedData");
Stopwatch Timer;
const auto _ = MakeGuard([&] {
if (!Ctx.Settings.Verbose)
{
return;
}
ZEN_INFO("GCV2: filecas [PRUNE] '{}': Count: {}, Unreferenced: {}, FreedMemory: {} in {}",
m_FileCasStrategy.m_RootDirectory,
Stats.CheckedCount,
Stats.FoundCount,
NiceBytes(Stats.FreedMemory),
NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
});
std::vector<IoHash> UnusedCids = GetUnusedReferences(m_Cids);
Stats.CheckedCount = m_Cids.size();
Stats.FoundCount = UnusedCids.size();
if (UnusedCids.empty())
{
// Nothing to collect
return nullptr;
}
if (Ctx.Settings.IsDeleteMode)
{
std::vector<FileCasStrategy::FileCasIndexEntry> ExpiredEntries;
ExpiredEntries.reserve(UnusedCids.size());
{
RwLock::ExclusiveLockScope __(m_FileCasStrategy.m_Lock);
if (Ctx.IsCancelledFlag.load())
{
return nullptr;
}
uint64_t RemovedSize = 0;
for (const IoHash& ChunkHash : UnusedCids)
{
if (auto It = m_FileCasStrategy.m_Index.find(ChunkHash); It != m_FileCasStrategy.m_Index.end())
{
uint64_t FileSize = It->second.Size;
ExpiredEntries.push_back(
{.Key = ChunkHash, .Flags = FileCasStrategy::FileCasIndexEntry::kTombStone, .Size = FileSize});
RemovedSize += FileSize;
}
}
m_FileCasStrategy.m_TotalSize.fetch_sub(RemovedSize, std::memory_order_relaxed);
if (!ExpiredEntries.empty())
{
for (const FileCasStrategy::FileCasIndexEntry& Entry : ExpiredEntries)
{
m_FileCasStrategy.m_Index.erase(Entry.Key);
Stats.DeletedCount++;
}
m_FileCasStrategy.m_CasLog.Append(ExpiredEntries);
m_FileCasStrategy.m_CasLog.Flush();
}
}
}
return new FileCasStoreCompactor(m_FileCasStrategy, std::move(UnusedCids));
}
private:
FileCasStrategy& m_FileCasStrategy;
std::vector<IoHash> m_Cids;
};
std::string
FileCasStrategy::GetGcName(GcCtx&)
{
return fmt::format("filecas: '{}'", m_RootDirectory.string());
}
GcReferencePruner*
FileCasStrategy::CreateReferencePruner(GcCtx& Ctx, GcReferenceStoreStats&)
{
ZEN_TRACE_CPU("FileCas::CreateReferencePruner");
Stopwatch Timer;
const auto _ = MakeGuard([&] {
if (!Ctx.Settings.Verbose)
{
return;
}
ZEN_INFO("GCV2: filecas [CREATE PRUNER] '{}' in {}", m_RootDirectory, NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
});
std::vector<IoHash> CidsToCheck;
{
RwLock::SharedLockScope __(m_Lock);
if (m_Index.empty())
{
return {};
}
if (Ctx.IsCancelledFlag.load())
{
return nullptr;
}
CidsToCheck.reserve(m_Index.size());
for (const auto& It : m_Index)
{
CidsToCheck.push_back(It.first);
}
}
return new FileCasReferencePruner(*this, std::move(CidsToCheck));
}
//////////////////////////////////////////////////////////////////////////
#if ZEN_WITH_TESTS
TEST_CASE("cas.file.move")
{
// specifying an absolute path here can be helpful when using procmon to dig into things
ScopedTemporaryDirectory TempDir; // {"d:\\filecas_testdir"};
GcManager Gc;
FileCasStrategy FileCas(Gc);
FileCas.Initialize(TempDir.Path() / "cas", /* IsNewStore */ true);
{
std::filesystem::path Payload1Path{TempDir.Path() / "payload_1"};
IoBuffer ZeroBytes{1024 * 1024};
IoHash ZeroHash = IoHash::HashBuffer(ZeroBytes);
BasicFile PayloadFile;
PayloadFile.Open(Payload1Path, BasicFile::Mode::kTruncate);
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() / fmt::format("payload_{}_{}", 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() / fmt::format("payload_{}_{}", 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
}
TEST_CASE("cas.file.gc")
{
// specifying an absolute path here can be helpful when using procmon to dig into things
ScopedTemporaryDirectory TempDir; // {"d:\\filecas_testdir"};
GcManager Gc;
FileCasStrategy FileCas(Gc);
FileCas.Initialize(TempDir.Path() / "cas", /* IsNewStore */ true);
const int kIterationCount = 100;
std::vector<IoHash> Keys{kIterationCount};
auto InsertChunks = [&] {
for (int i = 0; i < kIterationCount; ++i)
{
CbObjectWriter Cbo;
Cbo << "id" << i;
CbObject Obj = Cbo.Save();
IoBuffer ObjBuffer = Obj.GetBuffer().AsIoBuffer();
IoHash Hash = HashBuffer(ObjBuffer);
FileCas.InsertChunk(ObjBuffer, Hash);
Keys[i] = Hash;
}
};
// Drop everything
{
InsertChunks();
GcContext Ctx(GcClock::Now() - std::chrono::hours(24), GcClock::Now() - std::chrono::hours(24));
FileCas.CollectGarbage(Ctx);
for (const IoHash& Key : Keys)
{
IoBuffer Chunk = FileCas.FindChunk(Key);
CHECK(!Chunk);
}
}
// Keep roughly half of the chunks
{
InsertChunks();
GcContext Ctx(GcClock::Now() - std::chrono::hours(24), GcClock::Now() - std::chrono::hours(24));
for (const IoHash& Key : Keys)
{
if (Key.Hash[0] & 1)
{
Ctx.AddRetainedCids(std::vector<IoHash>{Key});
}
}
FileCas.CollectGarbage(Ctx);
for (const IoHash& Key : Keys)
{
if (Key.Hash[0] & 1)
{
CHECK(FileCas.FindChunk(Key));
}
else
{
CHECK(!FileCas.FindChunk(Key));
}
}
}
}
#endif
void
filecas_forcelink()
{
}
} // namespace zen
|