/
BackupFileSystem.cpp
1982 lines (1675 loc) · 60.2 KB
/
BackupFileSystem.cpp
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
// --------------------------------------------------------------------------
//
// File
// Name: BackupFileSystem.cpp
// Purpose: Generic interface for reading and writing files and
// directories, abstracting over RaidFile, S3, FTP etc.
// Created: 2015/08/03
//
// --------------------------------------------------------------------------
#include "Box.h"
#include <sys/types.h>
#include <sstream>
#include "autogen_BackupStoreException.h"
#include "BackupConstants.h"
#include "BackupStoreDirectory.h"
#include "BackupFileSystem.h"
#include "BackupStoreAccountDatabase.h"
#include "BackupStoreFile.h"
#include "BackupStoreInfo.h"
#include "BackupStoreRefCountDatabase.h"
#include "BufferedStream.h"
#include "BufferedWriteStream.h"
#include "ByteCountingStream.h"
#include "CollectInBufferStream.h"
#include "Configuration.h"
#include "BackupStoreObjectMagic.h"
#include "HTTPResponse.h"
#include "IOStream.h"
#include "InvisibleTempFileStream.h"
#include "RaidFileController.h"
#include "RaidFileRead.h"
#include "RaidFileUtil.h"
#include "RaidFileWrite.h"
#include "S3Client.h"
#include "StoreStructure.h"
#include "MemLeakFindOn.h"
void BackupFileSystem::GetLock()
{
for(int triesLeft = 8; triesLeft >= 0; triesLeft--)
{
try
{
TryGetLock();
}
catch(BackupStoreException &e)
{
if(EXCEPTION_IS_TYPE(e, BackupStoreException,
CouldNotLockStoreAccount) && triesLeft)
{
// Sleep a bit, and try again, as long as we have retries left.
ShortSleep(MilliSecondsToBoxTime(1000), true);
}
else
{
throw;
}
}
// Success!
break;
}
}
// Refresh forces the any current BackupStoreInfo to be discarded and reloaded from the
// store. This would be dangerous if anyone was holding onto a reference to it!
BackupStoreInfo& BackupFileSystem::GetBackupStoreInfo(bool ReadOnly, bool Refresh)
{
if(mapBackupStoreInfo.get())
{
if(!Refresh && (ReadOnly || !mapBackupStoreInfo->IsReadOnly()))
{
// Return the current BackupStoreInfo
return *mapBackupStoreInfo;
}
else
{
// Need to reopen to change from read-only to read-write.
mapBackupStoreInfo.reset();
}
}
mapBackupStoreInfo = GetBackupStoreInfoInternal(ReadOnly);
return *mapBackupStoreInfo;
}
void BackupFileSystem::RefCountDatabaseBeforeCommit(BackupStoreRefCountDatabase& refcount_db)
{
ASSERT(&refcount_db == mapPotentialRefCountDatabase.get());
// This is the temporary database, so it is about to be committed and become the permanent
// database, so we need to close the current permanent database (if any) first.
mapPermanentRefCountDatabase.reset();
}
void BackupFileSystem::RefCountDatabaseAfterCommit(BackupStoreRefCountDatabase& refcount_db)
{
// Can only commit a temporary database:
ASSERT(&refcount_db == mapPotentialRefCountDatabase.get());
// This was the temporary database, but it is now permanent, and has replaced the
// permanent file, so we need to change the databases returned by the temporary
// and permanent getter functions:
mapPermanentRefCountDatabase = mapPotentialRefCountDatabase;
// And save it to permanent storage (TODO: avoid double Save() by AfterCommit
// handler and refcount DB destructor):
SaveRefCountDatabase(refcount_db);
// Reopen the database that was closed by Commit().
mapPermanentRefCountDatabase->Reopen();
}
void BackupFileSystem::RefCountDatabaseAfterDiscard(BackupStoreRefCountDatabase& refcount_db)
{
ASSERT(&refcount_db == mapPotentialRefCountDatabase.get());
mapPotentialRefCountDatabase.reset();
}
// --------------------------------------------------------------------------
//
// Class
// Name: BackupStoreRefCountDatabaseWrapper
// Purpose: Wrapper around BackupStoreRefCountDatabase that
// automatically notifies the BackupFileSystem when
// Commit() or Discard() is called.
// Created: 2016/04/16
//
// --------------------------------------------------------------------------
typedef BackupStoreRefCountDatabase::refcount_t refcount_t;
class BackupStoreRefCountDatabaseWrapper : public BackupStoreRefCountDatabase
{
private:
// No copying allowed
BackupStoreRefCountDatabaseWrapper(const BackupStoreRefCountDatabase &);
std::auto_ptr<BackupStoreRefCountDatabase> mapUnderlying;
BackupFileSystem& mrFileSystem;
public:
BackupStoreRefCountDatabaseWrapper(
std::auto_ptr<BackupStoreRefCountDatabase> apUnderlying,
BackupFileSystem& filesystem)
: mapUnderlying(apUnderlying),
mrFileSystem(filesystem)
{ }
virtual ~BackupStoreRefCountDatabaseWrapper()
{
// If this is the permanent database, and not read-only, it to permanent
// storage on destruction. (TODO: avoid double Save() by AfterCommit
// handler and this destructor)
if(this == mrFileSystem.mapPermanentRefCountDatabase.get() &&
// ReadOnly: don't make the database read-write if it isn't already
!IsReadOnly())
{
mrFileSystem.SaveRefCountDatabase(*this);
}
}
virtual void Commit()
{
mrFileSystem.RefCountDatabaseBeforeCommit(*this);
mapUnderlying->Commit();
// Upload the changed file to the server.
mrFileSystem.RefCountDatabaseAfterCommit(*this);
}
virtual void Discard()
{
mapUnderlying->Discard();
mrFileSystem.RefCountDatabaseAfterDiscard(*this);
}
virtual void Close() { mapUnderlying->Close(); }
virtual void Reopen() { mapUnderlying->Reopen(); }
virtual bool IsReadOnly() { return mapUnderlying->IsReadOnly(); }
// Data access functions
virtual refcount_t GetRefCount(int64_t ObjectID) const
{
return mapUnderlying->GetRefCount(ObjectID);
}
virtual int64_t GetLastObjectIDUsed() const
{
return mapUnderlying->GetLastObjectIDUsed();
}
// Data modification functions
virtual void AddReference(int64_t ObjectID)
{
mapUnderlying->AddReference(ObjectID);
}
// RemoveReference returns false if refcount drops to zero
virtual bool RemoveReference(int64_t ObjectID)
{
return mapUnderlying->RemoveReference(ObjectID);
}
virtual int ReportChangesTo(BackupStoreRefCountDatabase& rOldRefs)
{
return mapUnderlying->ReportChangesTo(rOldRefs);
}
};
void RaidBackupFileSystem::TryGetLock()
{
if(mWriteLock.GotLock())
{
return;
}
// Make the filename of the write lock file
std::string writeLockFile;
StoreStructure::MakeWriteLockFilename(mAccountRootDir, mStoreDiscSet,
writeLockFile);
// Request the lock
if(!mWriteLock.TryAndGetLock(writeLockFile.c_str(),
0600 /* restrictive file permissions */))
{
THROW_EXCEPTION_MESSAGE(BackupStoreException,
CouldNotLockStoreAccount, "Failed to get exclusive "
"lock on account");
}
}
std::string RaidBackupFileSystem::GetAccountIdentifier()
{
std::string account_name;
try
{
account_name = GetBackupStoreInfo(true).GetAccountName();
}
catch(RaidFileException &e)
{
account_name = "unknown";
}
std::ostringstream oss;
oss << BOX_FORMAT_ACCOUNT(mAccountID) << " (" << account_name << ")";
return oss.str();
}
std::string RaidBackupFileSystem::GetObjectFileName(int64_t ObjectID,
bool EnsureDirectoryExists)
{
std::string filename;
StoreStructure::MakeObjectFilename(ObjectID, mAccountRootDir, mStoreDiscSet,
filename, EnsureDirectoryExists);
return filename;
}
int RaidBackupFileSystem::GetBlockSize()
{
RaidFileController &rcontroller(RaidFileController::GetController());
RaidFileDiscSet &rdiscSet(rcontroller.GetDiscSet(mStoreDiscSet));
return rdiscSet.GetBlockSize();
}
std::auto_ptr<BackupStoreInfo> RaidBackupFileSystem::GetBackupStoreInfoInternal(bool ReadOnly)
{
// Generate the filename
std::string fn(mAccountRootDir + INFO_FILENAME);
// Open the file for reading (passing on optional request for revision ID)
std::auto_ptr<RaidFileRead> rf(RaidFileRead::Open(mStoreDiscSet, fn));
std::auto_ptr<BackupStoreInfo> info = BackupStoreInfo::Load(*rf, fn, ReadOnly);
// Check it
if(info->GetAccountID() != mAccountID)
{
THROW_FILE_ERROR("Found wrong account ID in store info",
fn, BackupStoreException, BadStoreInfoOnLoad);
}
return info;
}
void RaidBackupFileSystem::PutBackupStoreInfo(BackupStoreInfo& rInfo)
{
if(rInfo.IsReadOnly())
{
THROW_EXCEPTION_MESSAGE(BackupStoreException, StoreInfoIsReadOnly,
"Tried to save BackupStoreInfo when configured as read-only");
}
std::string filename(mAccountRootDir + INFO_FILENAME);
RaidFileWrite rf(mStoreDiscSet, filename);
rf.Open(true); // AllowOverwrite
rInfo.Save(rf);
// Commit it to disc, converting it to RAID now
rf.Commit(BACKUP_STORE_CONVERT_TO_RAID_IMMEDIATELY);
}
BackupStoreRefCountDatabase& RaidBackupFileSystem::GetPermanentRefCountDatabase(
bool ReadOnly)
{
if(mapPermanentRefCountDatabase.get())
{
return *mapPermanentRefCountDatabase;
}
// It's dangerous to have two read-write databases open at the same time (it would
// be too easy to update the refcounts in the wrong one by mistake), and temporary
// databases are always read-write, so if a temporary database is already open
// then we should only allow a read-only permanent database to be opened.
ASSERT(!mapPotentialRefCountDatabase.get() || ReadOnly);
BackupStoreAccountDatabase::Entry account(mAccountID, mStoreDiscSet);
mapPermanentRefCountDatabase = BackupStoreRefCountDatabase::Load(account,
ReadOnly);
return *mapPermanentRefCountDatabase;
}
BackupStoreRefCountDatabase& RaidBackupFileSystem::GetPotentialRefCountDatabase()
{
// Creating the "official" potential refcount DB is actually a change
// to the store, even if you don't commit it, because it's in the same
// directory and would conflict with another process trying to do the
// same thing, so it requires that you hold the write lock.
ASSERT(mWriteLock.GotLock());
if(mapPotentialRefCountDatabase.get())
{
return *mapPotentialRefCountDatabase;
}
// It's dangerous to have two read-write databases open at the same
// time (it would be too easy to update the refcounts in the wrong one
// by mistake), and temporary databases are always read-write, so if a
// permanent database is already open then it must be a read-only one.
ASSERT(!mapPermanentRefCountDatabase.get() ||
mapPermanentRefCountDatabase->IsReadOnly());
// We deliberately do not give the caller control of the
// reuse_existing_file parameter to Create(), because that would make
// it easy to bypass the restriction of only one (committable)
// temporary database at a time, and to accidentally overwrite the main
// refcount DB.
BackupStoreAccountDatabase::Entry account(mAccountID, mStoreDiscSet);
std::auto_ptr<BackupStoreRefCountDatabase> ap_new_db =
BackupStoreRefCountDatabase::Create(account);
mapPotentialRefCountDatabase.reset(
new BackupStoreRefCountDatabaseWrapper(ap_new_db, *this));
return *mapPotentialRefCountDatabase;
}
void RaidBackupFileSystem::SaveRefCountDatabase(BackupStoreRefCountDatabase& refcount_db)
{
// You can only save the permanent database.
ASSERT(&refcount_db == mapPermanentRefCountDatabase.get());
// The database is already saved in the store, so we don't need to do anything.
}
//! Returns whether an object (a file or directory) exists with this object ID, and its
//! revision ID, which for a RaidFile is based on its timestamp and file size.
bool RaidBackupFileSystem::ObjectExists(int64_t ObjectID, int64_t *pRevisionID)
{
// Don't bother creating the containing directory if it doesn't exist.
std::string filename = GetObjectFileName(ObjectID, false);
return RaidFileRead::FileExists(mStoreDiscSet, filename, pRevisionID);
}
//! Reads a directory with the specified ID into the supplied BackupStoreDirectory
//! object, also initialising its revision ID and SizeInBlocks.
void RaidBackupFileSystem::GetDirectory(int64_t ObjectID, BackupStoreDirectory& rDirOut)
{
int64_t revID = 0;
// Don't bother creating the containing directory if it doesn't exist.
std::string filename = GetObjectFileName(ObjectID, false);
std::auto_ptr<RaidFileRead> objectFile(RaidFileRead::Open(mStoreDiscSet,
filename, &revID));
// Read it from the stream, then set it's revision ID
BufferedStream buf(*objectFile);
rDirOut.ReadFromStream(buf, IOStream::TimeOutInfinite);
rDirOut.SetRevisionID(revID);
// Make sure the size of the directory is available for writing the dir back
int64_t dirSize = objectFile->GetDiscUsageInBlocks();
ASSERT(dirSize > 0);
rDirOut.SetUserInfo1_SizeInBlocks(dirSize);
}
void RaidBackupFileSystem::PutDirectory(BackupStoreDirectory& rDir)
{
// Create the containing directory if it doesn't exist.
std::string filename = GetObjectFileName(rDir.GetObjectID(), true);
RaidFileWrite writeDir(mStoreDiscSet, filename);
writeDir.Open(true); // allow overwriting
BufferedWriteStream buffer(writeDir);
rDir.WriteToStream(buffer);
buffer.Flush();
// get the disc usage (must do this before commiting it)
int64_t dirSize = writeDir.GetDiscUsageInBlocks();
// Commit directory
writeDir.Commit(BACKUP_STORE_CONVERT_TO_RAID_IMMEDIATELY);
int64_t revid = 0;
if(!RaidFileRead::FileExists(mStoreDiscSet, filename, &revid))
{
THROW_EXCEPTION(BackupStoreException, Internal)
}
rDir.SetUserInfo1_SizeInBlocks(dirSize);
rDir.SetRevisionID(revid);
}
class RaidPutFileCompleteTransaction : public BackupFileSystem::Transaction
{
private:
RaidFileWrite mStoreFile;
std::string mFileName;
int mDiscSet;
bool mCommitted;
public:
RaidPutFileCompleteTransaction(int StoreDiscSet, const std::string& filename,
BackupStoreRefCountDatabase::refcount_t refcount)
: mStoreFile(StoreDiscSet, filename, refcount),
mFileName(filename),
mDiscSet(StoreDiscSet),
mCommitted(false),
mNumBlocks(-1)
{ }
~RaidPutFileCompleteTransaction();
virtual void Commit();
virtual int64_t GetNumBlocks()
{
ASSERT(mNumBlocks != -1);
return mNumBlocks;
}
RaidFileWrite& GetRaidFile() { return mStoreFile; }
// It doesn't matter what we return here, because this should never be called
// for a PutFileCompleteTransaction (the API is intended for
// PutFilePatchTransaction instead):
virtual bool IsNewFileIndependent() { return false; }
int64_t mNumBlocks;
};
void RaidPutFileCompleteTransaction::Commit()
{
ASSERT(!mCommitted);
mStoreFile.Commit(BACKUP_STORE_CONVERT_TO_RAID_IMMEDIATELY);
#ifndef NDEBUG
// Verify the file -- only necessary for non-diffed versions.
//
// We cannot use VerifyEncodedFileFormat() until the file is committed. We already
// verified it as we were saving it, so this is a double check that should not be
// necessary, and thus is only done in debug builds.
std::auto_ptr<RaidFileRead> checkFile(RaidFileRead::Open(mDiscSet, mFileName));
if(!BackupStoreFile::VerifyEncodedFileFormat(*checkFile))
{
mStoreFile.Delete();
THROW_EXCEPTION_MESSAGE(BackupStoreException, AddedFileDoesNotVerify,
"Newly saved file does not verify after write: this should not "
"happen: " << mFileName);
}
#endif // !NDEBUG
mCommitted = true;
}
RaidPutFileCompleteTransaction::~RaidPutFileCompleteTransaction()
{
if(!mCommitted)
{
mStoreFile.Discard();
}
}
std::auto_ptr<BackupFileSystem::Transaction>
RaidBackupFileSystem::PutFileComplete(int64_t ObjectID, IOStream& rFileData,
BackupStoreRefCountDatabase::refcount_t refcount)
{
// Create the containing directory if it doesn't exist.
std::string filename = GetObjectFileName(ObjectID, true);
// We can only do this when the file (ObjectID) doesn't already exist.
ASSERT(refcount == 0);
// But RaidFileWrite won't allow us to write to a file that doesn't have exactly one
// reference, so we pretend for now that there is one. If the file already exists,
// then Open(false) below will raise an exception for us.
RaidPutFileCompleteTransaction* pTrans = new RaidPutFileCompleteTransaction(
mStoreDiscSet, filename, 1);
std::auto_ptr<BackupFileSystem::Transaction> apTrans(pTrans);
RaidFileWrite& rStoreFile(pTrans->GetRaidFile());
rStoreFile.Open(false); // no overwriting
BackupStoreFile::VerifyStream validator(rFileData);
// A full file, just store to disc
if(!validator.CopyStreamTo(rStoreFile, BACKUP_STORE_TIMEOUT))
{
THROW_EXCEPTION(BackupStoreException, ReadFileFromStreamTimedOut);
}
// Close() is necessary to perform final validation on the block index.
validator.Close(false); // Don't CloseCopyStream, RaidFile doesn't like it.
// Need to do this before committing the RaidFile, can't do it after.
pTrans->mNumBlocks = rStoreFile.GetDiscUsageInBlocks();
return apTrans;
}
class RaidPutFilePatchTransaction : public BackupFileSystem::Transaction
{
private:
RaidFileWrite mNewCompleteFile;
RaidFileWrite mReversedPatchFile;
bool mReversedDiffIsCompletelyDifferent;
int64_t mBlocksUsedByNewFile;
int64_t mChangeInBlocksUsedByOldFile;
public:
RaidPutFilePatchTransaction(int StoreDiscSet,
const std::string& newCompleteFilename,
const std::string& reversedPatchFilename,
BackupStoreRefCountDatabase::refcount_t refcount)
// It's not quite true that mNewCompleteFile has 1 reference: it doesn't exist
// yet, so it has 0 right now. However when the transaction is committed it will
// have 1, and RaidFileWrite gets upset if we try to modify a file with != 1
// references, so we need to pretend now that we already have the reference.
: mNewCompleteFile(StoreDiscSet, newCompleteFilename, 1),
mReversedPatchFile(StoreDiscSet, reversedPatchFilename, refcount),
mReversedDiffIsCompletelyDifferent(false),
mBlocksUsedByNewFile(0),
mChangeInBlocksUsedByOldFile(0)
{ }
virtual void Commit();
RaidFileWrite& GetNewCompleteFile() { return mNewCompleteFile; }
RaidFileWrite& GetReversedPatchFile() { return mReversedPatchFile; }
void SetReversedDiffIsCompletelyDifferent(bool IsCompletelyDifferent)
{
mReversedDiffIsCompletelyDifferent = IsCompletelyDifferent;
}
virtual bool IsNewFileIndependent()
{
return mReversedDiffIsCompletelyDifferent;
}
void SetBlocksUsedByNewFile(int64_t BlocksUsedByNewFile)
{
mBlocksUsedByNewFile = BlocksUsedByNewFile;
}
virtual int64_t GetNumBlocks()
{
return mBlocksUsedByNewFile;
}
void SetChangeInBlocksUsedByOldFile(int64_t ChangeInBlocksUsedByOldFile)
{
mChangeInBlocksUsedByOldFile = ChangeInBlocksUsedByOldFile;
}
virtual int64_t GetChangeInBlocksUsedByOldFile()
{
return mChangeInBlocksUsedByOldFile;
}
};
void RaidPutFilePatchTransaction::Commit()
{
mNewCompleteFile.Commit(BACKUP_STORE_CONVERT_TO_RAID_IMMEDIATELY);
mReversedPatchFile.Commit(BACKUP_STORE_CONVERT_TO_RAID_IMMEDIATELY);
}
std::auto_ptr<BackupFileSystem::Transaction>
RaidBackupFileSystem::PutFilePatch(int64_t ObjectID, int64_t DiffFromFileID,
IOStream& rPatchData, BackupStoreRefCountDatabase::refcount_t refcount)
{
// Create the containing directory if it doesn't exist.
std::string newVersionFilename = GetObjectFileName(ObjectID, true);
// Filename of the old version
std::string oldVersionFilename = GetObjectFileName(DiffFromFileID,
false); // no need to make sure the directory it's in exists
RaidPutFilePatchTransaction* pTrans = new RaidPutFilePatchTransaction(
mStoreDiscSet, newVersionFilename, oldVersionFilename, refcount);
std::auto_ptr<BackupFileSystem::Transaction> apTrans(pTrans);
RaidFileWrite& rNewCompleteFile(pTrans->GetNewCompleteFile());
RaidFileWrite& rReversedPatchFile(pTrans->GetReversedPatchFile());
rNewCompleteFile.Open(false); // no overwriting
// Diff file, needs to be recreated.
// Choose a temporary filename.
std::string tempFn(RaidFileController::DiscSetPathToFileSystemPath(mStoreDiscSet,
newVersionFilename + ".difftemp",
1)); // NOT the same disc as the write file, to avoid using lots of space on the same disc unnecessarily
try
{
// Open it twice
#ifdef WIN32
InvisibleTempFileStream diff(tempFn.c_str(), O_RDWR | O_CREAT | O_BINARY);
InvisibleTempFileStream diff2(tempFn.c_str(), O_RDWR | O_BINARY);
#else
FileStream diff(tempFn.c_str(), O_RDWR | O_CREAT | O_EXCL);
FileStream diff2(tempFn.c_str(), O_RDONLY);
// Unlink it immediately, so it definitely goes away
if(EMU_UNLINK(tempFn.c_str()) != 0)
{
THROW_EXCEPTION(CommonException, OSFileError);
}
#endif
// Stream the incoming diff to this temporary file
if(!rPatchData.CopyStreamTo(diff, BACKUP_STORE_TIMEOUT))
{
THROW_EXCEPTION(BackupStoreException, ReadFileFromStreamTimedOut);
}
// Verify the diff
diff.Seek(0, IOStream::SeekType_Absolute);
if(!BackupStoreFile::VerifyEncodedFileFormat(diff))
{
THROW_EXCEPTION(BackupStoreException, AddedFileDoesNotVerify);
}
// Seek to beginning of diff file
diff.Seek(0, IOStream::SeekType_Absolute);
// Reassemble that diff -- open previous file, and combine the patch and file
std::auto_ptr<RaidFileRead> from(RaidFileRead::Open(mStoreDiscSet, oldVersionFilename));
BackupStoreFile::CombineFile(diff, diff2, *from, rNewCompleteFile);
// Then... reverse the patch back (open the from file again, and create a write file to overwrite it)
std::auto_ptr<RaidFileRead> from2(RaidFileRead::Open(mStoreDiscSet, oldVersionFilename));
rReversedPatchFile.Open(true); // allow overwriting
from->Seek(0, IOStream::SeekType_Absolute);
diff.Seek(0, IOStream::SeekType_Absolute);
bool isCompletelyDifferent;
BackupStoreFile::ReverseDiffFile(diff, *from, *from2, rReversedPatchFile,
DiffFromFileID, &isCompletelyDifferent);
pTrans->SetReversedDiffIsCompletelyDifferent(isCompletelyDifferent);
// Store disc space used
int64_t oldVersionNewBlocksUsed =
rReversedPatchFile.GetDiscUsageInBlocks();
// And make a space adjustment for the size calculation
int64_t spaceSavedByConversionToPatch = from->GetDiscUsageInBlocks() -
oldVersionNewBlocksUsed;
pTrans->SetChangeInBlocksUsedByOldFile(-spaceSavedByConversionToPatch);
pTrans->SetBlocksUsedByNewFile(rNewCompleteFile.GetDiscUsageInBlocks());
return apTrans;
// Everything cleans up here...
}
catch(...)
{
// Be very paranoid about deleting this temp file -- we could only leave a zero byte file anyway
EMU_UNLINK(tempFn.c_str());
throw;
}
}
std::auto_ptr<IOStream> RaidBackupFileSystem::GetObject(int64_t ObjectID, bool required)
{
std::string filename = GetObjectFileName(ObjectID,
false); // no need to make sure the directory it's in exists.
if(!required && !RaidFileRead::FileExists(mStoreDiscSet, filename))
{
return std::auto_ptr<IOStream>();
}
std::auto_ptr<RaidFileRead> objectFile(RaidFileRead::Open(mStoreDiscSet,
filename));
return static_cast<std::auto_ptr<IOStream> >(objectFile);
}
std::auto_ptr<IOStream> RaidBackupFileSystem::GetFilePatch(int64_t ObjectID,
std::vector<int64_t>& rPatchChain)
{
// File exists, but is a patch from a new version. Generate the older version.
// The last entry in the chain is the full file, the others are patches back from it.
// Open the last one, which is the current full file.
std::auto_ptr<IOStream> from(GetFile(rPatchChain[rPatchChain.size() - 1]));
// Then, for each patch in the chain, do a combine
for(int p = ((int)rPatchChain.size()) - 2; p >= 0; --p)
{
// ID of patch
int64_t patchID = rPatchChain[p];
// Open it a couple of times. TODO FIXME: this could be very inefficient.
std::auto_ptr<IOStream> diff(GetFile(patchID));
std::auto_ptr<IOStream> diff2(GetFile(patchID));
// Choose a temporary filename for the result of the combination
std::ostringstream fs;
fs << mAccountRootDir << ".recombinetemp." << p;
std::string tempFn =
RaidFileController::DiscSetPathToFileSystemPath(mStoreDiscSet,
fs.str(), p + 16);
// Open the temporary file
std::auto_ptr<IOStream> combined(
new InvisibleTempFileStream(
tempFn, O_RDWR | O_CREAT | O_EXCL |
O_BINARY | O_TRUNC));
// Do the combining
BackupStoreFile::CombineFile(*diff, *diff2, *from, *combined);
// Move to the beginning of the combined file
combined->Seek(0, IOStream::SeekType_Absolute);
// Then shuffle round for the next go
if(from.get())
{
from->Close();
}
from = combined;
}
std::auto_ptr<IOStream> stream(
BackupStoreFile::ReorderFileToStreamOrder(from.get(),
true)); // take ownership
// Release from file to avoid double deletion
from.release();
return stream;
}
// Delete an object whose type is unknown. For RaidFile, we don't need to know what type
// it is to use RaidFileWrite::Delete() on it.
void RaidBackupFileSystem::DeleteObjectUnknown(int64_t ObjectID)
{
std::string filename = GetObjectFileName(ObjectID, false);
RaidFileWrite deleteFile(mStoreDiscSet, filename);
deleteFile.Delete();
}
std::auto_ptr<BackupFileSystem::Transaction>
RaidBackupFileSystem::CombineFileOrDiff(int64_t OlderPatchID, int64_t NewerObjectID, bool NewerIsPatch)
{
// This normally only happens during housekeeping, which is using a temporary
// refcount database, so insist on that for now.
BackupStoreRefCountDatabase* pRefCount = mapPotentialRefCountDatabase.get();
ASSERT(pRefCount != NULL);
ASSERT(mapPermanentRefCountDatabase.get() == NULL ||
mapPermanentRefCountDatabase->IsReadOnly());
// Open the older object twice (the patch)
std::auto_ptr<IOStream> pdiff = GetFile(OlderPatchID);
std::auto_ptr<IOStream> pdiff2 = GetFile(OlderPatchID);
// Open the newer object (the file to be deleted)
std::auto_ptr<IOStream> pobjectBeingDeleted = GetFile(NewerObjectID);
// And open a write file to overwrite the older object (the patch)
std::string older_filename = GetObjectFileName(OlderPatchID,
false); // no need to make sure the directory it's in exists.
std::auto_ptr<RaidPutFileCompleteTransaction>
ap_overwrite_older(new RaidPutFileCompleteTransaction(
mStoreDiscSet, older_filename,
pRefCount->GetRefCount(OlderPatchID)));
RaidFileWrite& overwrite_older(ap_overwrite_older->GetRaidFile());
overwrite_older.Open(true /* allow overwriting */);
if(NewerIsPatch)
{
// Combine two adjacent patches (reverse diffs) into a single one object.
BackupStoreFile::CombineDiffs(*pobjectBeingDeleted, *pdiff, *pdiff2, overwrite_older);
}
else
{
// Combine an older patch (reverse diff) with the subsequent complete file.
BackupStoreFile::CombineFile(*pdiff, *pdiff2, *pobjectBeingDeleted, overwrite_older);
}
// Need to do this before committing the RaidFile, can't do it after.
ap_overwrite_older->mNumBlocks = overwrite_older.GetDiscUsageInBlocks();
// The file will be committed later when the directory is safely commited.
return static_cast<std::auto_ptr<BackupFileSystem::Transaction> >(ap_overwrite_older);
}
std::auto_ptr<BackupFileSystem::Transaction>
RaidBackupFileSystem::CombineFile(int64_t OlderPatchID, int64_t NewerFileID)
{
return CombineFileOrDiff(OlderPatchID, NewerFileID, false); // !NewerIsPatch
}
std::auto_ptr<BackupFileSystem::Transaction>
RaidBackupFileSystem::CombineDiffs(int64_t OlderPatchID, int64_t NewerPatchID)
{
return CombineFileOrDiff(OlderPatchID, NewerPatchID, true); // NewerIsPatch
}
int64_t RaidBackupFileSystem::GetFileSizeInBlocks(int64_t ObjectID)
{
std::string filename = GetObjectFileName(ObjectID, false);
std::auto_ptr<RaidFileRead> apRead = RaidFileRead::Open(mStoreDiscSet, filename);
return apRead->GetDiscUsageInBlocks();
}
BackupFileSystem::CheckObjectsResult
RaidBackupFileSystem::CheckObjects(bool fix_errors)
{
// Find the maximum start ID of directories -- worked out by looking at disc
// contents, not trusting anything.
CheckObjectsResult result;
CheckObjectsScanDir(0, 1, mAccountRootDir, result, fix_errors);
// Then go through and scan all the objects within those directories
for(int64_t start_id = 0; start_id <= result.maxObjectIDFound;
start_id += (1<<STORE_ID_SEGMENT_LENGTH))
{
CheckObjectsDir(start_id, result, fix_errors);
}
return result;
}
// --------------------------------------------------------------------------
//
// Function
// Name: static TwoDigitHexToInt(const char *, int &)
// Purpose: Convert a two digit hex string to an int, returning whether it's valid or not
// Created: 21/4/04
//
// --------------------------------------------------------------------------
static inline bool TwoDigitHexToInt(const char *String, int &rNumberOut)
{
int n = 0;
// Char 0
if(String[0] >= '0' && String[0] <= '9')
{
n = (String[0] - '0') << 4;
}
else if(String[0] >= 'a' && String[0] <= 'f')
{
n = ((String[0] - 'a') + 0xa) << 4;
}
else
{
return false;
}
// Char 1
if(String[1] >= '0' && String[1] <= '9')
{
n |= String[1] - '0';
}
else if(String[1] >= 'a' && String[1] <= 'f')
{
n |= (String[1] - 'a') + 0xa;
}
else
{
return false;
}
// Return a valid number
rNumberOut = n;
return true;
}
// --------------------------------------------------------------------------
//
// Function
// Name: RaidBackupFileSystem::CheckObjectsScanDir(
// int64_t StartID, int Level,
// const std::string &rDirName,
// BackupFileSystem::CheckObjectsResult& Result,
// bool fix_errors)
// Purpose: Read in the contents of the directory, recurse to
// lower levels, return the maximum starting ID of any
// directory found. Internal method.
// Created: 21/4/04
//
// --------------------------------------------------------------------------
void RaidBackupFileSystem::CheckObjectsScanDir(int64_t StartID, int Level,
const std::string &rDirName, BackupFileSystem::CheckObjectsResult& Result,
bool fix_errors)
{
//TRACE2("Scan directory for max dir starting ID %s, StartID %lld\n", rDirName.c_str(), StartID);
if(Result.maxObjectIDFound < StartID)
{
Result.maxObjectIDFound = StartID;
}
// Read in all the directories, and recurse downwards.
// If any of the directories is missing, create it.
RaidFileController &rcontroller(RaidFileController::GetController());
RaidFileDiscSet rdiscSet(rcontroller.GetDiscSet(mStoreDiscSet));
if(!rdiscSet.IsNonRaidSet())
{
unsigned int numDiscs = rdiscSet.size();
for(unsigned int l = 0; l < numDiscs; ++l)
{
// build name
std::string dn(rdiscSet[l] + DIRECTORY_SEPARATOR + rDirName);
EMU_STRUCT_STAT st;
if(EMU_STAT(dn.c_str(), &st) != 0 &&
errno == ENOENT)
{
if(mkdir(dn.c_str(), 0755) != 0)
{
THROW_SYS_FILE_ERROR("Failed to create missing "
"RaidFile directory", dn,
RaidFileException, OSError);
}
}
}
}
std::vector<std::string> dirs;
RaidFileRead::ReadDirectoryContents(mStoreDiscSet, rDirName,
RaidFileRead::DirReadType_DirsOnly, dirs);
for(std::vector<std::string>::const_iterator i(dirs.begin());
i != dirs.end(); ++i)
{
// Check to see if it's the right name
int n = 0;
if((*i).size() == 2 && TwoDigitHexToInt((*i).c_str(), n)
&& n < (1<<STORE_ID_SEGMENT_LENGTH))
{
// Next level down
BackupFileSystem::CheckObjectsResult sub_result;
CheckObjectsScanDir(
StartID | (n << (Level * STORE_ID_SEGMENT_LENGTH)),
Level + 1, rDirName + DIRECTORY_SEPARATOR + *i,
sub_result, fix_errors);
Result.numErrorsFound += sub_result.numErrorsFound;
// Found a greater starting ID?
if(Result.maxObjectIDFound < sub_result.maxObjectIDFound)
{
Result.maxObjectIDFound = sub_result.maxObjectIDFound;
}
}
else
{
BOX_ERROR("Spurious or invalid directory '" << rDirName <<
DIRECTORY_SEPARATOR << (*i) << "' found, " <<
(fix_errors?"deleting":"delete manually"));
++Result.numErrorsFound;
}