Example #1
0
        private async Task RunAsync(string[] sources, Library.Utility.IFilter filter, CancellationToken token)
        {
            m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_Begin);

            // New isolated scope for each operation
            using (new IsolatedChannelScope())
                using (m_database = new LocalBackupDatabase(m_options.Dbpath, m_options))
                {
                    m_result.SetDatabase(m_database);
                    m_result.Dryrun = m_options.Dryrun;

                    // Check the database integrity
                    Utility.UpdateOptionsFromDb(m_database, m_options);
                    Utility.VerifyParameters(m_database, m_options);

                    var probe_path = m_database.GetFirstPath();
                    if (probe_path != null && Util.GuessDirSeparator(probe_path) != Util.DirectorySeparatorString)
                    {
                        throw new UserInformationException(string.Format("The backup contains files that belong to another operating system. Proceeding with a backup would cause the database to contain paths from two different operation systems, which is not supported. To proceed without losing remote data, delete all filesets and make sure the --{0} option is set, then run the backup again to re-use the existing data on the remote store.", "no-auto-compact"), "CrossOsDatabaseReuseNotSupported");
                    }

                    if (m_database.PartiallyRecreated)
                    {
                        throw new UserInformationException("The database was only partially recreated. This database may be incomplete and the repair process is not allowed to alter remote files as that could result in data loss.", "DatabaseIsPartiallyRecreated");
                    }

                    if (m_database.RepairInProgress)
                    {
                        throw new UserInformationException("The database was attempted repaired, but the repair did not complete. This database may be incomplete and the backup process cannot continue. You may delete the local database and attempt to repair it again.", "DatabaseRepairInProgress");
                    }

                    // If there is no filter, we set an empty filter to simplify the code
                    // If there is a filter, we make sure that the sources are included
                    m_filter       = filter ?? new Library.Utility.FilterExpression();
                    m_sourceFilter = new Library.Utility.FilterExpression(sources, true);

                    Task parallelScanner = null;
                    Task uploaderTask    = null;
                    try
                    {
                        // Setup runners and instances here
                        using (var db = new Backup.BackupDatabase(m_database, m_options))
                            using (var backendManager = new BackendManager(m_backendurl, m_options, m_result.BackendWriter, m_database))
                                using (var filesetvolume = new FilesetVolumeWriter(m_options, m_database.OperationTimestamp))
                                    using (var stats = new Backup.BackupStatsCollector(m_result))
                                        // Keep a reference to these channels to avoid shutdown
                                        using (var uploadtarget = ChannelManager.GetChannel(Backup.Channels.BackendRequest.ForWrite))
                                        {
                                            long filesetid;
                                            var  counterToken = new CancellationTokenSource();
                                            var  uploader     = new Backup.BackendUploader(() => DynamicLoader.BackendLoader.GetBackend(m_backendurl, m_options.RawOptions), m_options, db, m_result.TaskReader, stats);
                                            using (var snapshot = GetSnapshot(sources, m_options))
                                            {
                                                try
                                                {
                                                    // Make sure the database is sane
                                                    await db.VerifyConsistencyAsync(m_options.Blocksize, m_options.BlockhashSize, !m_options.DisableFilelistConsistencyChecks);

                                                    // Start the uploader process
                                                    uploaderTask = uploader.Run();

                                                    // If we have an interrupted backup, grab the fileset
                                                    string lastTempFilelist  = null;
                                                    long   lastTempFilesetId = -1;
                                                    if (!m_options.DisableSyntheticFilelist)
                                                    {
                                                        var candidates = (await db.GetIncompleteFilesetsAsync()).OrderBy(x => x.Value).ToArray();
                                                        if (candidates.Any())
                                                        {
                                                            lastTempFilesetId = candidates.Last().Key;
                                                            lastTempFilelist  = m_database.GetRemoteVolumeFromFilesetID(lastTempFilesetId).Name;
                                                        }
                                                    }

                                                    // TODO: Rewrite to using the uploader process, or the BackendHandler interface
                                                    // Do a remote verification, unless disabled
                                                    PreBackupVerify(backendManager, lastTempFilelist);

                                                    // If the previous backup was interrupted, send a synthetic list
                                                    await Backup.UploadSyntheticFilelist.Run(db, m_options, m_result, m_result.TaskReader, lastTempFilelist, lastTempFilesetId);

                                                    // Grab the previous backup ID, if any
                                                    var prevfileset = m_database.FilesetTimes.FirstOrDefault();
                                                    if (prevfileset.Value.ToUniversalTime() > m_database.OperationTimestamp.ToUniversalTime())
                                                    {
                                                        throw new Exception(string.Format("The previous backup has time {0}, but this backup has time {1}. Something is wrong with the clock.", prevfileset.Value.ToLocalTime(), m_database.OperationTimestamp.ToLocalTime()));
                                                    }

                                                    var lastfilesetid = prevfileset.Value.Ticks == 0 ? -1 : prevfileset.Key;

                                                    // Rebuild any index files that are missing
                                                    await Backup.RecreateMissingIndexFiles.Run(db, m_options, m_result.TaskReader);

                                                    // Prepare the operation by registering the filelist
                                                    m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_ProcessingFiles);

                                                    var repcnt = 0;
                                                    while (repcnt < 100 && await db.GetRemoteVolumeIDAsync(filesetvolume.RemoteFilename) >= 0)
                                                    {
                                                        filesetvolume.ResetRemoteFilename(m_options, m_database.OperationTimestamp.AddSeconds(repcnt++));
                                                    }

                                                    if (await db.GetRemoteVolumeIDAsync(filesetvolume.RemoteFilename) >= 0)
                                                    {
                                                        throw new Exception("Unable to generate a unique fileset name");
                                                    }

                                                    var filesetvolumeid = await db.RegisterRemoteVolumeAsync(filesetvolume.RemoteFilename, RemoteVolumeType.Files, RemoteVolumeState.Temporary);

                                                    filesetid = await db.CreateFilesetAsync(filesetvolumeid, VolumeBase.ParseFilename(filesetvolume.RemoteFilename).Time);

                                                    // create USN-based scanner if enabled
                                                    var journalService = GetJournalService(sources, snapshot, filter, lastfilesetid);

                                                    // Start parallel scan, or use the database
                                                    if (m_options.DisableFileScanner)
                                                    {
                                                        var d = m_database.GetLastBackupFileCountAndSize();
                                                        m_result.OperationProgressUpdater.UpdatefileCount(d.Item1, d.Item2, true);
                                                    }
                                                    else
                                                    {
                                                        parallelScanner = Backup.CountFilesHandler.Run(sources, snapshot, journalService, m_result, m_options, m_sourceFilter, m_filter, m_result.TaskReader, counterToken.Token);
                                                    }

                                                    // Run the backup operation
                                                    if (await m_result.TaskReader.ProgressAsync)
                                                    {
                                                        await RunMainOperation(sources, snapshot, journalService, db, stats, m_options, m_sourceFilter, m_filter, m_result, m_result.TaskReader, filesetid, lastfilesetid, token).ConfigureAwait(false);
                                                    }
                                                }
                                                finally
                                                {
                                                    //If the scanner is still running for some reason, make sure we kill it now
                                                    counterToken.Cancel();
                                                }
                                            }

                                            // Add the fileset file to the dlist file
                                            filesetvolume.CreateFilesetFile(!token.IsCancellationRequested);

                                            // Ensure the database is in a sane state after adding data
                                            using (new Logging.Timer(LOGTAG, "VerifyConsistency", "VerifyConsistency"))
                                                await db.VerifyConsistencyAsync(m_options.Blocksize, m_options.BlockhashSize, false);

                                            // Send the actual filelist
                                            if (await m_result.TaskReader.ProgressAsync)
                                            {
                                                await Backup.UploadRealFilelist.Run(m_result, db, m_options, filesetvolume, filesetid, m_result.TaskReader);
                                            }

                                            // Wait for upload completion
                                            m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_WaitForUpload);
                                            var lastVolumeSize = await FlushBackend(m_result, uploadtarget, uploaderTask).ConfigureAwait(false);

                                            // Make sure we have the database up-to-date
                                            await db.CommitTransactionAsync("CommitAfterUpload", false);

                                            // TODO: Remove this later
                                            m_transaction = m_database.BeginTransaction();

                                            if (await m_result.TaskReader.ProgressAsync)
                                            {
                                                CompactIfRequired(backendManager, lastVolumeSize);
                                            }

                                            if (m_options.UploadVerificationFile && await m_result.TaskReader.ProgressAsync)
                                            {
                                                m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_VerificationUpload);
                                                FilelistProcessor.UploadVerificationFile(backendManager.BackendUrl, m_options, m_result.BackendWriter, m_database, m_transaction);
                                            }

                                            if (m_options.Dryrun)
                                            {
                                                m_transaction.Rollback();
                                                m_transaction = null;
                                            }
                                            else
                                            {
                                                using (new Logging.Timer(LOGTAG, "CommitFinalizingBackup", "CommitFinalizingBackup"))
                                                    m_transaction.Commit();

                                                m_transaction = null;

                                                if (m_result.TaskControlRendevouz() != TaskControlState.Abort)
                                                {
                                                    if (m_options.NoBackendverification)
                                                    {
                                                        UpdateStorageStatsFromDatabase();
                                                    }
                                                    else
                                                    {
                                                        PostBackupVerification(filesetvolume.RemoteFilename);
                                                    }
                                                }
                                            }

                                            m_database.WriteResults();
                                            m_database.PurgeLogData(m_options.LogRetention);
                                            m_database.PurgeDeletedVolumes(DateTime.UtcNow);

                                            if (m_options.AutoVacuum)
                                            {
                                                m_result.VacuumResults = new VacuumResults(m_result);
                                                new VacuumHandler(m_options, (VacuumResults)m_result.VacuumResults).Run();
                                            }
                                            m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_Complete);
                                            return;
                                        }
                    }
                    catch (Exception ex)
                    {
                        var aex = BuildException(ex, uploaderTask, parallelScanner);
                        Logging.Log.WriteErrorMessage(LOGTAG, "FatalError", ex, "Fatal error");
                        if (aex == ex)
                        {
                            throw;
                        }

                        throw aex;
                    }
                    finally
                    {
                        if (parallelScanner != null && !parallelScanner.IsCompleted)
                        {
                            parallelScanner.Wait(500);
                        }

                        // TODO: We want to commit? always?
                        if (m_transaction != null)
                        {
                            try { m_transaction.Rollback(); }
                            catch (Exception ex) { Logging.Log.WriteErrorMessage(LOGTAG, "RollbackError", ex, "Rollback error: {0}", ex.Message); }
                        }
                    }
                }
        }
Example #2
0
 public Task <RemoteVolumeEntry> GetRemoteVolumeFromFilesetIDAsync(long filesetID)
 {
     return(RunOnMain(() => m_database.GetRemoteVolumeFromFilesetID(filesetID, m_transaction)));
 }