/
BackupDaemon.cpp
3648 lines (3185 loc) · 95.8 KB
/
BackupDaemon.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: BackupDaemon.cpp
// Purpose: Backup daemon
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
#include "Box.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef HAVE_SYS_MOUNT_H
#include <sys/mount.h>
#endif
#ifdef HAVE_MNTENT_H
#include <mntent.h>
#endif
#ifdef HAVE_SYS_MNTTAB_H
#include <cstdio>
#include <sys/mnttab.h>
#endif
#ifdef HAVE_PROCESS_H
#include <process.h>
#endif
#include <iostream>
#include <set>
#include <sstream>
#include "Configuration.h"
#include "IOStream.h"
#include "MemBlockStream.h"
#include "CommonException.h"
#include "BoxPortsAndFiles.h"
#include "SSLLib.h"
#include "autogen_BackupProtocol.h"
#include "autogen_ClientException.h"
#include "autogen_CommonException.h"
#include "autogen_ConversionException.h"
#include "Archive.h"
#include "BackupClientContext.h"
#include "BackupClientCryptoKeys.h"
#include "BackupClientDirectoryRecord.h"
#include "BackupClientFileAttributes.h"
#include "BackupClientInodeToIDMap.h"
#include "BackupClientMakeExcludeList.h"
#include "BackupConstants.h"
#include "BackupDaemon.h"
#include "BackupDaemonConfigVerify.h"
#include "BackupStoreConstants.h"
#include "BackupStoreDirectory.h"
#include "BackupStoreException.h"
#include "BackupStoreFile.h"
#include "BackupStoreFilenameClear.h"
#include "BannerText.h"
#include "Conversion.h"
#include "ExcludeList.h"
#include "FileStream.h"
#include "IOStreamGetLine.h"
#include "LocalProcessStream.h"
#include "Logging.h"
#include "Random.h"
#include "Timer.h"
#include "Utils.h"
#ifdef WIN32
#include "Win32ServiceFunctions.h"
#include "Win32BackupService.h"
extern Win32BackupService* gpDaemonService;
# ifdef ENABLE_VSS
# include <comdef.h>
# include <Vss.h>
# include <VsWriter.h>
# include <VsBackup.h>
// http://www.flounder.com/cstring.htm
std::string GetMsgForHresult(HRESULT hr)
{
std::ostringstream buf;
if(hr == VSS_S_ASYNC_CANCELLED)
{
buf << "VSS async operation cancelled";
}
else if(hr == VSS_S_ASYNC_FINISHED)
{
buf << "VSS async operation finished";
}
else if(hr == VSS_S_ASYNC_PENDING)
{
buf << "VSS async operation pending";
}
else
{
buf << _com_error(hr).ErrorMessage();
}
buf << " (" << BOX_FORMAT_HEX32(hr) << ")";
return buf.str();
}
std::string WideStringToString(WCHAR *buf)
{
if (buf == NULL)
{
return "(null)";
}
char* pStr = ConvertFromWideString(buf, CP_UTF8);
if(pStr == NULL)
{
return "(conversion failed)";
}
std::string result(pStr);
free(pStr);
return result;
}
std::string GuidToString(GUID guid)
{
wchar_t buf[64];
StringFromGUID2(guid, buf, sizeof(buf));
return WideStringToString(buf);
}
std::string BstrToString(const BSTR arg)
{
if(arg == NULL)
{
return std::string("(null)");
}
else
{
// Extract the *long* before where the arg points to
long len = ((long *)arg)[-1] / 2;
std::wstring wstr((WCHAR *)arg, len);
std::string str;
if(!ConvertFromWideString(wstr, &str, CP_UTF8))
{
throw std::exception("string conversion failed");
}
return str;
}
}
# endif
// Mutex support by Achim: see https://www.boxbackup.org/ticket/67
// Creates the two mutexes checked for by the installer/uninstaller to
// see if the program is still running. One of the mutexes is created
// in the global name space (which makes it possible to access the
// mutex across user sessions in Windows XP); the other is created in
// the session name space (because versions of Windows NT prior to
// 4.0 TSE don't have a global name space and don't support the
// 'Global\' prefix).
void CreateMutexes(const std::string& rName)
{
SECURITY_DESCRIPTOR SecurityDesc;
SECURITY_ATTRIBUTES SecurityAttr;
/* By default on Windows NT, created mutexes are accessible only by the user
running the process. We need our mutexes to be accessible to all users, so
that the mutex detection can work across user sessions in Windows XP. To
do this we use a security descriptor with a null DACL.
*/
InitializeSecurityDescriptor(&SecurityDesc, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&SecurityDesc, TRUE, NULL, FALSE);
SecurityAttr.nLength = sizeof(SecurityAttr);
SecurityAttr.lpSecurityDescriptor = &SecurityDesc;
SecurityAttr.bInheritHandle = FALSE;
// We don't care if this succeeds or fails. It's only used to
// ensure that an installer can detect if Box Backup is running.
CreateMutexA(&SecurityAttr, FALSE, rName.c_str());
std::string global_name = "Global\\" + rName;
CreateMutexA(&SecurityAttr, FALSE, global_name.c_str());
}
#endif
#include "MemLeakFindOn.h"
static const time_t MAX_SLEEP_TIME = 1024;
// Make the actual sync period have a little bit of extra time, up to a 64th of the main sync period.
// This prevents repetative cycles of load on the server
#define SYNC_PERIOD_RANDOM_EXTRA_TIME_SHIFT_BY 6
// --------------------------------------------------------------------------
//
// Function
// Name: BackupDaemon::BackupDaemon()
// Purpose: constructor
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
BackupDaemon::BackupDaemon()
: mState(BackupDaemon::State_Initialising),
mDeleteRedundantLocationsAfter(0),
mLastNotifiedEvent(SysadminNotifier::MAX),
mDeleteUnusedRootDirEntriesAfter(0),
mClientStoreMarker(BackupClientContext::ClientStoreMarker_NotKnown),
mStorageLimitExceeded(false),
mReadErrorsOnFilesystemObjects(false),
mLastSyncTime(0),
mNextSyncTime(0),
mCurrentSyncStartTime(0),
mUpdateStoreInterval(0),
mDeleteStoreObjectInfoFile(false),
mDoSyncForcedByPreviousSyncError(false),
mNumFilesUploaded(-1),
mNumDirsCreated(-1),
mMaxBandwidthFromSyncAllowScript(0),
mLogAllFileAccess(false),
mpProgressNotifier(this),
mpLocationResolver(this),
mpRunStatusProvider(this),
mpSysadminNotifier(this),
mapCommandSocketPollTimer(NULL)
#ifdef WIN32
, mInstallService(false),
mRemoveService(false),
mRunAsService(false),
mServiceName("bbackupd")
#endif
#ifdef ENABLE_VSS
, mpVssBackupComponents(NULL)
#endif
{
// Only ever one instance of a daemon
SSLLib::Initialise();
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupDaemon::~BackupDaemon()
// Purpose: Destructor
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
BackupDaemon::~BackupDaemon()
{
DeleteAllLocations();
DeleteAllIDMaps();
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupDaemon::DaemonName()
// Purpose: Get name of daemon
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
const char *BackupDaemon::DaemonName() const
{
return "bbackupd";
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupDaemon::DaemonBanner()
// Purpose: Daemon banner
// Created: 1/1/04
//
// --------------------------------------------------------------------------
std::string BackupDaemon::DaemonBanner() const
{
return BANNER_TEXT("Backup Client");
}
void BackupDaemon::Usage()
{
this->Daemon::Usage();
#ifdef WIN32
std::cout <<
" -s Run as a Windows Service, for internal use only\n"
" -i Install Windows Service (you may want to specify a config file)\n"
" -r Remove Windows Service\n"
" -S <name> Service name for -i and -r options\n";
#endif
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupDaemon::GetConfigVerify()
// Purpose: Get configuration specification
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
const ConfigurationVerify *BackupDaemon::GetConfigVerify() const
{
// Defined elsewhere
return &BackupDaemonConfigVerify;
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupDaemon::SetupInInitialProcess()
// Purpose: Platforms with non-checkable credentials on
// local sockets only.
// Prints a warning if the command socket is used.
// Created: 25/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::SetupInInitialProcess()
{
const Configuration& config(GetConfiguration());
// These keys may or may not be required, depending on the configured
// store type (e.g. not when using Amazon S3 stores), so they can't be
// verified by BackupDaemonConfigVerify.
std::vector<std::string> requiredKeys;
requiredKeys.push_back("StoreHostname");
requiredKeys.push_back("AccountNumber");
requiredKeys.push_back("CertificateFile");
requiredKeys.push_back("PrivateKeyFile");
requiredKeys.push_back("TrustedCAsFile");
bool missingRequiredKeys = false;
for(std::vector<std::string>::const_iterator i = requiredKeys.begin();
i != requiredKeys.end(); i++)
{
if(!config.KeyExists(*i))
{
BOX_ERROR("Missing required configuration key: " << *i);
missingRequiredKeys = true;
}
}
if(missingRequiredKeys)
{
THROW_EXCEPTION_MESSAGE(CommonException, InvalidConfiguration,
"Some required configuration keys are missing in " <<
GetConfigFileName());
}
#ifdef PLATFORM_CANNOT_FIND_PEER_UID_OF_UNIX_SOCKET
// Print a warning on this platform if the CommandSocket is used.
if(GetConfiguration().KeyExists("CommandSocket"))
{
BOX_WARNING(
"==============================================================================\n"
"SECURITY WARNING: This platform cannot check the credentials of connections to\n"
"the command socket. This is a potential DoS security problem.\n"
"Remove the CommandSocket directive from the bbackupd.conf file if bbackupctl\n"
"is not used.\n"
"==============================================================================\n"
);
}
#endif
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupDaemon::DeleteAllLocations()
// Purpose: Deletes all records stored
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
void BackupDaemon::DeleteAllLocations()
{
// Run through, and delete everything
for(Locations::iterator i = mLocations.begin();
i != mLocations.end(); ++i)
{
delete *i;
}
// Clear the contents of the map, so it is empty
mLocations.clear();
// And delete everything from the associated mount vector
mIDMapMounts.clear();
}
#ifdef WIN32
std::string BackupDaemon::GetOptionString()
{
std::string oldOpts = this->Daemon::GetOptionString();
ASSERT(oldOpts.find("s") == std::string::npos);
ASSERT(oldOpts.find("S") == std::string::npos);
ASSERT(oldOpts.find("i") == std::string::npos);
ASSERT(oldOpts.find("r") == std::string::npos);
return oldOpts + "sS:ir";
}
int BackupDaemon::ProcessOption(signed int option)
{
switch(option)
{
case 's':
{
mRunAsService = true;
return 0;
}
case 'S':
{
mServiceName = optarg;
Logging::SetProgramName(mServiceName);
return 0;
}
case 'i':
{
mInstallService = true;
return 0;
}
case 'r':
{
mRemoveService = true;
return 0;
}
default:
{
return this->Daemon::ProcessOption(option);
}
}
}
int BackupDaemon::Main(const std::string &rConfigFileName)
{
if (mInstallService)
{
return InstallService(rConfigFileName.c_str(), mServiceName);
}
if (mRemoveService)
{
return RemoveService(mServiceName);
}
#ifdef ENABLE_VSS
HRESULT result = CoInitialize(NULL);
if(result != S_OK)
{
BOX_ERROR("VSS: Failed to initialize COM: " <<
GetMsgForHresult(result));
return 1;
}
#endif
CreateMutexes("__boxbackup_mutex__");
int returnCode;
if (mRunAsService)
{
// We will be called reentrantly by the Service Control
// Manager, and we had better not call OurService again!
mRunAsService = false;
BOX_INFO("Box Backup service starting");
returnCode = OurService(rConfigFileName.c_str());
BOX_INFO("Box Backup service shut down");
}
else
{
returnCode = this->Daemon::Main(rConfigFileName);
}
return returnCode;
}
#endif // WIN32
// --------------------------------------------------------------------------
//
// Function
// Name: BackupDaemon::Run()
// Purpose: Run function for daemon
// Created: 18/2/04
//
// --------------------------------------------------------------------------
void BackupDaemon::Run()
{
// initialise global timer mechanism
Timers::Init();
mapCommandSocketPollTimer.reset(new Timer(COMMAND_SOCKET_POLL_INTERVAL,
"CommandSocketPollTimer"));
#ifndef WIN32
// Ignore SIGPIPE so that if a command connection is broken,
// the daemon doesn't terminate.
::signal(SIGPIPE, SIG_IGN);
#endif
// Create a command socket?
const Configuration &conf(GetConfiguration());
if(conf.KeyExists("CommandSocket"))
{
// Yes, create a local UNIX socket
mapCommandSocketInfo.reset(new CommandSocketInfo);
const char *socketName =
conf.GetKeyValue("CommandSocket").c_str();
#ifdef WIN32
mapCommandSocketInfo->mListeningSocket.Listen(
socketName);
#else
EMU_UNLINK(socketName);
mapCommandSocketInfo->mListeningSocket.Listen(
Socket::TypeUNIX, socketName);
#endif
}
// Handle things nicely on exceptions
try
{
Run2();
}
catch(...)
{
try
{
mapCommandSocketInfo.reset();
}
catch(std::exception &e)
{
BOX_WARNING("Internal error while closing command "
"socket after another exception, ignored: " <<
e.what());
}
catch(...)
{
BOX_WARNING("Error closing command socket after "
"exception, ignored.");
}
mapCommandSocketPollTimer.reset();
Timers::Cleanup();
throw;
}
// Clean up
mapCommandSocketInfo.reset();
mapCommandSocketPollTimer.reset();
Timers::Cleanup();
}
void BackupDaemon::InitCrypto()
{
// Read in the certificates creating a TLS context
const Configuration &conf(GetConfiguration());
std::string certFile(conf.GetKeyValue("CertificateFile"));
std::string keyFile(conf.GetKeyValue("PrivateKeyFile"));
std::string caFile(conf.GetKeyValue("TrustedCAsFile"));
mTlsContext.Initialise(false /* as client */, certFile.c_str(),
keyFile.c_str(), caFile.c_str());
// Set up the keys for various things
BackupClientCryptoKeys_Setup(conf.GetKeyValue("KeysFile"));
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupDaemon::Run2()
// Purpose: Run function for daemon (second stage)
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
void BackupDaemon::Run2()
{
InitCrypto();
const Configuration &conf(GetConfiguration());
// How often to connect to the store (approximate)
mUpdateStoreInterval = SecondsToBoxTime(
conf.GetKeyValueInt("UpdateStoreInterval"));
mBackupErrorDelay = conf.GetKeyValueInt("BackupErrorDelay");
// But are we connecting automatically?
bool automaticBackup = conf.GetKeyValueBool("AutomaticBackup");
// When the next sync should take place -- which is ASAP
mNextSyncTime = 0;
// When the last sync started (only updated if the store was not full when the sync ended)
mLastSyncTime = 0;
// --------------------------------------------------------------------------------------------
mDeleteStoreObjectInfoFile = DeserializeStoreObjectInfo(mLastSyncTime,
mNextSyncTime);
// --------------------------------------------------------------------------------------------
// Set state
SetState(State_Idle);
mDoSyncForcedByPreviousSyncError = false;
// Loop around doing backups
do
{
// Flags used below
bool storageLimitExceeded = false;
bool doSync = false;
bool mDoSyncForcedByCommand = false;
// Check whether we should be stopping, and if so,
// don't hang around waiting on the command socket.
if(StopRun())
{
BOX_INFO("Skipping command socket polling "
"due to shutdown request");
break;
}
// Is a delay necessary?
box_time_t currentTime = GetCurrentBoxTime();
box_time_t requiredDelay = (mNextSyncTime < currentTime)
? (0) : (mNextSyncTime - currentTime);
mNextSyncTime = currentTime + requiredDelay;
if (mDoSyncForcedByPreviousSyncError)
{
BOX_INFO("Last backup was not successful, "
"next one starting at " <<
FormatTime(mNextSyncTime, false, true));
}
else if (automaticBackup)
{
BOX_INFO("Automatic backups are enabled, "
"next one starting at " <<
FormatTime(mNextSyncTime, false, true));
}
else
{
BOX_INFO("No automatic backups, waiting for "
"bbackupctl snapshot command");
requiredDelay = SecondsToBoxTime(MAX_SLEEP_TIME);
}
if(requiredDelay > SecondsToBoxTime(MAX_SLEEP_TIME))
{
requiredDelay = SecondsToBoxTime(MAX_SLEEP_TIME);
}
// Only delay if necessary
if(requiredDelay == 0)
{
// No sleep necessary, so don't listen on the command
// socket at all right now.
}
else if(mapCommandSocketInfo.get() != 0)
{
// A command socket exists, so sleep by waiting for a
// connection or command on it.
WaitOnCommandSocket(requiredDelay, doSync,
mDoSyncForcedByCommand);
}
else
{
// No command socket or connection, just do a normal
// sleep.
time_t sleepSeconds =
BoxTimeToSeconds(requiredDelay);
::sleep((sleepSeconds <= 0)
? 1 : sleepSeconds);
}
// We have now slept, so if automaticBackup is enabled then
// it's time for a backup now.
if(StopRun())
{
BOX_INFO("Stopping idle loop due to shutdown request");
break;
}
else if(doSync)
{
BOX_INFO("Starting a backup immediately due to "
"bbackupctl sync command");
}
else if(GetCurrentBoxTime() < mNextSyncTime)
{
BOX_TRACE("Deadline not reached, sleeping again");
continue;
}
else if(mDoSyncForcedByPreviousSyncError)
{
BOX_INFO("Last backup was not successful, next one "
"starting now");
}
else if(!automaticBackup)
{
BOX_TRACE("Sleeping again because automatic backups "
"are not enabled");
continue;
}
else
{
BOX_INFO("Automatic backups are enabled, next one "
"starting now");
}
// If we pass this point, or exit the loop, we should have
// logged something at INFO level or higher to explain why.
// Use a script to see if sync is allowed now?
if(mDoSyncForcedByCommand)
{
BOX_INFO("Skipping SyncAllowScript due to bbackupctl "
"force-sync command");
}
else
{
int d = UseScriptToSeeIfSyncAllowed();
if(d > 0)
{
// Script has asked for a delay
mNextSyncTime = GetCurrentBoxTime() +
SecondsToBoxTime(d);
BOX_INFO("Impending backup stopped by "
"SyncAllowScript, next attempt "
"scheduled for " <<
FormatTime(mNextSyncTime, false));
continue;
}
}
mCurrentSyncStartTime = GetCurrentBoxTime();
RunSyncNowWithExceptionHandling();
// Set state
SetState(storageLimitExceeded?State_StorageLimitExceeded:State_Idle);
}
while(!StopRun());
// Make sure we have a clean start next time round (if restart)
DeleteAllLocations();
DeleteAllIDMaps();
}
std::auto_ptr<BackupClientContext> BackupDaemon::RunSyncNowWithExceptionHandling()
{
bool errorOccurred = false;
int errorCode = 0, errorSubCode = 0;
std::string errorString = "unknown";
try
{
OnBackupStart();
// Do sync
RunSyncNow();
}
catch(BoxException &e)
{
errorOccurred = true;
errorString = e.what();
errorCode = e.GetType();
errorSubCode = e.GetSubType();
}
catch(std::exception &e)
{
BOX_ERROR("Internal error during backup run: " << e.what());
errorOccurred = true;
errorString = e.what();
}
catch(...)
{
// TODO: better handling of exceptions here...
// need to be very careful
errorOccurred = true;
}
// do not retry immediately without a good reason
mDoSyncForcedByPreviousSyncError = false;
// Is it a berkely db failure?
bool isBerkelyDbFailure = false;
// Notify system administrator about the final state of the backup
if(errorOccurred)
{
if (errorCode == BackupStoreException::ExceptionType
&& errorSubCode == BackupStoreException::BerkelyDBFailure)
{
isBerkelyDbFailure = true;
}
if(isBerkelyDbFailure)
{
// Delete corrupt files
DeleteCorruptBerkelyDbFiles();
}
ResetCachedState();
// Handle restart?
if(StopRun())
{
BOX_NOTICE("Exception (" << errorCode << "/" <<
errorSubCode << ") due to signal");
OnBackupFinish();
return mapClientContext; // releases mapClientContext
}
NotifySysadmin(SysadminNotifier::BackupError);
// If the Berkely db files get corrupted,
// delete them and try again immediately.
if(isBerkelyDbFailure)
{
BOX_ERROR("Berkely db inode map files corrupted, "
"deleting and restarting scan. Renamed files "
"and directories will not be tracked until "
"after this scan.");
::sleep(1);
}
else
{
// Not restart/terminate, pause and retry
// Notify administrator
SetState(State_Error);
BOX_ERROR("Exception caught (" << errorString <<
" " << errorCode << "/" << errorSubCode <<
"), reset state and waiting to retry...");
::sleep(10);
mNextSyncTime = GetCurrentBoxTime() +
SecondsToBoxTime(mBackupErrorDelay) +
Random::RandomInt(mUpdateStoreInterval >>
SYNC_PERIOD_RANDOM_EXTRA_TIME_SHIFT_BY);
}
}
if(mReadErrorsOnFilesystemObjects)
{
NotifySysadmin(SysadminNotifier::ReadError);
}
if(mStorageLimitExceeded)
{
NotifySysadmin(SysadminNotifier::StoreFull);
}
if (!errorOccurred && !mReadErrorsOnFilesystemObjects &&
!mStorageLimitExceeded)
{
NotifySysadmin(SysadminNotifier::BackupOK);
}
// If we were retrying after an error, and this backup succeeded,
// then now would be a good time to stop :-)
mDoSyncForcedByPreviousSyncError = errorOccurred && !isBerkelyDbFailure;
OnBackupFinish();
return mapClientContext; // releases mapClientContext
}
void BackupDaemon::ResetCachedState()
{
// Clear state data
// Go back to beginning of time
mLastSyncTime = 0;
mClientStoreMarker = BackupClientContext::ClientStoreMarker_NotKnown; // no store marker, so download everything
DeleteAllLocations();
DeleteAllIDMaps();
}
std::auto_ptr<BackupClientContext> BackupDaemon::GetNewContext
(
LocationResolver &rResolver,
TLSContext &rTLSContext,
const std::string &rHostname,
int32_t Port,
uint32_t AccountNumber,
bool ExtendedLogging,
bool ExtendedLogToFile,
std::string ExtendedLogFile,
ProgressNotifier &rProgressNotifier,
bool TcpNiceMode
)
{
std::auto_ptr<BackupClientContext> context(new BackupClientContext(
rResolver, rTLSContext, rHostname, Port, AccountNumber,
ExtendedLogging, ExtendedLogToFile, ExtendedLogFile,
rProgressNotifier, TcpNiceMode));
return context;
}
// Returns the BackupClientContext so that tests can use it to hold the
// connection open and prevent housekeeping from running. Otherwise don't use
// it, let it be destroyed and close the connection.
std::auto_ptr<BackupClientContext> BackupDaemon::RunSyncNow()
{
Timers::AssertInitialised();
// Delete the serialised store object file,
// so that we don't try to reload it after a
// partially completed backup
if(mDeleteStoreObjectInfoFile && !DeleteStoreObjectInfo())
{
BOX_ERROR("Failed to delete the StoreObjectInfoFile, "
"backup cannot continue safely.");
THROW_EXCEPTION(ClientException,
FailedToDeleteStoreObjectInfoFile);
}
// In case the backup throws an exception,
// we should not try to delete the store info
// object file again.
mDeleteStoreObjectInfoFile = false;
const Configuration &conf(GetConfiguration());
std::auto_ptr<FileLogger> fileLogger;
if (conf.KeyExists("LogFile"))
{
bool overwrite = false;
if (conf.KeyExists("LogFileOverwrite"))
{
overwrite = conf.GetKeyValueBool("LogFileOverwrite");
}
Log::Level level = Log::INFO;
if (conf.KeyExists("LogFileLevel"))
{
level = Logging::GetNamedLevel(
conf.GetKeyValue("LogFileLevel"));
}
fileLogger.reset(new FileLogger(conf.GetKeyValue("LogFile"),
level, !overwrite));
}
std::string extendedLogFile;
if (conf.KeyExists("ExtendedLogFile"))
{
extendedLogFile = conf.GetKeyValue("ExtendedLogFile");
}
if (conf.KeyExists("LogAllFileAccess"))
{
mLogAllFileAccess = conf.GetKeyValueBool("LogAllFileAccess");
}
// Then create a client context object (don't
// just connect, as this may be unnecessary)
mapClientContext = GetNewContext(
*mpLocationResolver,
mTlsContext,
conf.GetKeyValue("StoreHostname"),
conf.GetKeyValueInt("StorePort"),
conf.GetKeyValueUint32("AccountNumber"),
conf.GetKeyValueBool("ExtendedLogging"),
conf.KeyExists("ExtendedLogFile"),
extendedLogFile,
*mpProgressNotifier,
conf.GetKeyValueBool("TcpNice")
);
// The minimum age a file needs to be before it will be
// considered for uploading
box_time_t minimumFileAge = SecondsToBoxTime(
conf.GetKeyValueInt("MinimumFileAge"));
// The maximum time we'll wait to upload a file, regardless
// of how often it's modified
box_time_t maxUploadWait = SecondsToBoxTime(
conf.GetKeyValueInt("MaxUploadWait"));