Esempio n. 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); }
                        }
                    }
                }
        }
Esempio n. 2
0
        public void RunRepairRemote()
        {
            if (!System.IO.File.Exists(m_options.Dbpath))
            {
                throw new UserInformationException(string.Format("Database file does not exist: {0}", m_options.Dbpath), "RepairDatabaseFileDoesNotExist");
            }

            m_result.OperationProgressUpdater.UpdateProgress(0);

            using (var db = new LocalRepairDatabase(m_options.Dbpath))
                using (var backend = new BackendManager(m_backendurl, m_options, m_result.BackendWriter, db))
                {
                    m_result.SetDatabase(db);
                    Utility.UpdateOptionsFromDb(db, m_options);
                    Utility.VerifyParameters(db, m_options);

                    if (db.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 (db.RepairInProgress)
                    {
                        throw new UserInformationException("The database was attempted repaired, but the repair did not complete. This database may be incomplete and the repair process is not allowed to alter remote files as that could result in data loss.", "DatabaseIsInRepairState");
                    }

                    var tp          = FilelistProcessor.RemoteListAnalysis(backend, m_options, db, m_result.BackendWriter, null);
                    var buffer      = new byte[m_options.Blocksize];
                    var blockhasher = Library.Utility.HashAlgorithmHelper.Create(m_options.BlockHashAlgorithm);
                    var hashsize    = blockhasher.HashSize / 8;

                    if (blockhasher == null)
                    {
                        throw new UserInformationException(Strings.Common.InvalidHashAlgorithm(m_options.BlockHashAlgorithm), "BlockHashAlgorithmNotSupported");
                    }
                    if (!blockhasher.CanReuseTransform)
                    {
                        throw new UserInformationException(Strings.Common.InvalidCryptoSystem(m_options.BlockHashAlgorithm), "BlockHashAlgorithmNotSupported");
                    }

                    var progress      = 0;
                    var targetProgess = tp.ExtraVolumes.Count() + tp.MissingVolumes.Count() + tp.VerificationRequiredVolumes.Count();

                    if (m_options.Dryrun)
                    {
                        if (!tp.ParsedVolumes.Any() && tp.OtherVolumes.Any())
                        {
                            if (tp.BackupPrefixes.Length == 1)
                            {
                                throw new UserInformationException(string.Format("Found no backup files with prefix {0}, but files with prefix {1}, did you forget to set the backup prefix?", m_options.Prefix, tp.BackupPrefixes[0]), "RemoteFolderEmptyWithPrefix");
                            }
                            else
                            {
                                throw new UserInformationException(string.Format("Found no backup files with prefix {0}, but files with prefixes {1}, did you forget to set the backup prefix?", m_options.Prefix, string.Join(", ", tp.BackupPrefixes)), "RemoteFolderEmptyWithPrefix");
                            }
                        }
                        else if (!tp.ParsedVolumes.Any() && tp.ExtraVolumes.Any())
                        {
                            throw new UserInformationException(string.Format("No files were missing, but {0} remote files were, found, did you mean to run recreate-database?", tp.ExtraVolumes.Count()), "NoRemoteFilesMissing");
                        }
                    }

                    if (tp.ExtraVolumes.Any() || tp.MissingVolumes.Any() || tp.VerificationRequiredVolumes.Any())
                    {
                        if (tp.VerificationRequiredVolumes.Any())
                        {
                            using (var testdb = new LocalTestDatabase(db))
                            {
                                foreach (var n in tp.VerificationRequiredVolumes)
                                {
                                    try
                                    {
                                        if (m_result.TaskControlRendevouz() == TaskControlState.Stop)
                                        {
                                            backend.WaitForComplete(db, null);
                                            return;
                                        }

                                        progress++;
                                        m_result.OperationProgressUpdater.UpdateProgress((float)progress / targetProgess);

                                        long   size;
                                        string hash;
                                        KeyValuePair <string, IEnumerable <KeyValuePair <Duplicati.Library.Interface.TestEntryStatus, string> > > res;

                                        using (var tf = backend.GetWithInfo(n.Name, out size, out hash))
                                            res = TestHandler.TestVolumeInternals(testdb, n, tf, m_options, 1);

                                        if (res.Value.Any())
                                        {
                                            throw new Exception(string.Format("Remote verification failure: {0}", res.Value.First()));
                                        }

                                        if (!m_options.Dryrun)
                                        {
                                            Logging.Log.WriteInformationMessage(LOGTAG, "CapturedRemoteFileHash", "Sucessfully captured hash for {0}, updating database", n.Name);
                                            db.UpdateRemoteVolume(n.Name, RemoteVolumeState.Verified, size, hash);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Logging.Log.WriteErrorMessage(LOGTAG, "RemoteFileVerificationError", ex, "Failed to perform verification for file: {0}, please run verify; message: {1}", n.Name, ex.Message);
                                        if (ex is System.Threading.ThreadAbortException)
                                        {
                                            throw;
                                        }
                                    }
                                }
                            }
                        }

                        // TODO: It is actually possible to use the extra files if we parse them
                        foreach (var n in tp.ExtraVolumes)
                        {
                            try
                            {
                                if (m_result.TaskControlRendevouz() == TaskControlState.Stop)
                                {
                                    backend.WaitForComplete(db, null);
                                    return;
                                }

                                progress++;
                                m_result.OperationProgressUpdater.UpdateProgress((float)progress / targetProgess);

                                // If this is a new index file, we can accept it if it matches our local data
                                // This makes it possible to augment the remote store with new index data
                                if (n.FileType == RemoteVolumeType.Index && m_options.IndexfilePolicy != Options.IndexFileStrategy.None)
                                {
                                    try
                                    {
                                        string hash;
                                        long   size;
                                        using (var tf = backend.GetWithInfo(n.File.Name, out size, out hash))
                                            using (var ifr = new IndexVolumeReader(n.CompressionModule, tf, m_options, m_options.BlockhashSize))
                                            {
                                                foreach (var rv in ifr.Volumes)
                                                {
                                                    var entry = db.GetRemoteVolume(rv.Filename);
                                                    if (entry.ID < 0)
                                                    {
                                                        throw new Exception(string.Format("Unknown remote file {0} detected", rv.Filename));
                                                    }

                                                    if (!new [] { RemoteVolumeState.Uploading, RemoteVolumeState.Uploaded, RemoteVolumeState.Verified }.Contains(entry.State))
                                                    {
                                                        throw new Exception(string.Format("Volume {0} has local state {1}", rv.Filename, entry.State));
                                                    }

                                                    if (entry.Hash != rv.Hash || entry.Size != rv.Length || !new [] { RemoteVolumeState.Uploading, RemoteVolumeState.Uploaded, RemoteVolumeState.Verified }.Contains(entry.State))
                                                    {
                                                        throw new Exception(string.Format("Volume {0} hash/size mismatch ({1} - {2}) vs ({3} - {4})", rv.Filename, entry.Hash, entry.Size, rv.Hash, rv.Length));
                                                    }

                                                    db.CheckAllBlocksAreInVolume(rv.Filename, rv.Blocks);
                                                }

                                                var blocksize = m_options.Blocksize;
                                                foreach (var ixb in ifr.BlockLists)
                                                {
                                                    db.CheckBlocklistCorrect(ixb.Hash, ixb.Length, ixb.Blocklist, blocksize, hashsize);
                                                }

                                                var selfid = db.GetRemoteVolumeID(n.File.Name);
                                                foreach (var rv in ifr.Volumes)
                                                {
                                                    db.AddIndexBlockLink(selfid, db.GetRemoteVolumeID(rv.Filename), null);
                                                }
                                            }

                                        // All checks fine, we accept the new index file
                                        Logging.Log.WriteInformationMessage(LOGTAG, "AcceptNewIndexFile", "Accepting new index file {0}", n.File.Name);
                                        db.RegisterRemoteVolume(n.File.Name, RemoteVolumeType.Index, size, RemoteVolumeState.Uploading);
                                        db.UpdateRemoteVolume(n.File.Name, RemoteVolumeState.Verified, size, hash);
                                        continue;
                                    }
                                    catch (Exception rex)
                                    {
                                        Logging.Log.WriteErrorMessage(LOGTAG, "FailedNewIndexFile", rex, "Failed to accept new index file: {0}, message: {1}", n.File.Name, rex.Message);
                                    }
                                }

                                if (!m_options.Dryrun)
                                {
                                    db.RegisterRemoteVolume(n.File.Name, n.FileType, n.File.Size, RemoteVolumeState.Deleting);
                                    backend.Delete(n.File.Name, n.File.Size);
                                }
                                else
                                {
                                    Logging.Log.WriteDryrunMessage(LOGTAG, "WouldDeleteFile", "would delete file {0}", n.File.Name);
                                }
                            }
                            catch (Exception ex)
                            {
                                Logging.Log.WriteErrorMessage(LOGTAG, "FailedExtraFileCleanup", ex, "Failed to perform cleanup for extra file: {0}, message: {1}", n.File.Name, ex.Message);
                                if (ex is System.Threading.ThreadAbortException)
                                {
                                    throw;
                                }
                            }
                        }

                        if (!m_options.RebuildMissingDblockFiles)
                        {
                            var missingDblocks = tp.MissingVolumes.Where(x => x.Type == RemoteVolumeType.Blocks).ToArray();
                            if (missingDblocks.Length > 0)
                            {
                                throw new UserInformationException($"The backup storage destination is missing data files. You can either enable `--rebuild-missing-dblock-files` or run the purge command to remove these files. The following files are missing: {string.Join(", ", missingDblocks.Select(x => x.Name))}", "MissingDblockFiles");
                            }
                        }

                        foreach (var n in tp.MissingVolumes)
                        {
                            IDisposable newEntry = null;

                            try
                            {
                                if (m_result.TaskControlRendevouz() == TaskControlState.Stop)
                                {
                                    backend.WaitForComplete(db, null);
                                    return;
                                }

                                progress++;
                                m_result.OperationProgressUpdater.UpdateProgress((float)progress / targetProgess);

                                if (n.Type == RemoteVolumeType.Files)
                                {
                                    var filesetId = db.GetFilesetIdFromRemotename(n.Name);

                                    // We cannot wrap the FilesetVolumeWriter in a using statement here because a reference to it is
                                    // retained in newEntry.
                                    FilesetVolumeWriter volumeWriter = new FilesetVolumeWriter(m_options, DateTime.UtcNow);
                                    newEntry = volumeWriter;
                                    volumeWriter.SetRemoteFilename(n.Name);

                                    db.WriteFileset(volumeWriter, filesetId, null);
                                    DateTime filesetTime = db.FilesetTimes.First(x => x.Key == filesetId).Value;
                                    volumeWriter.CreateFilesetFile(db.IsFilesetFullBackup(filesetTime));

                                    volumeWriter.Close();
                                    if (m_options.Dryrun)
                                    {
                                        Logging.Log.WriteDryrunMessage(LOGTAG, "WouldReUploadFileset", "would re-upload fileset {0}, with size {1}, previous size {2}", n.Name, Library.Utility.Utility.FormatSizeString(new System.IO.FileInfo(volumeWriter.LocalFilename).Length), Library.Utility.Utility.FormatSizeString(n.Size));
                                    }
                                    else
                                    {
                                        db.UpdateRemoteVolume(volumeWriter.RemoteFilename, RemoteVolumeState.Uploading, -1, null, null);
                                        backend.Put(volumeWriter);
                                    }
                                }
                                else if (n.Type == RemoteVolumeType.Index)
                                {
                                    using (IndexVolumeWriter w = new IndexVolumeWriter(m_options))
                                    {
                                        newEntry = w;
                                        w.SetRemoteFilename(n.Name);

                                        var h = Library.Utility.HashAlgorithmHelper.Create(m_options.BlockHashAlgorithm);

                                        foreach (var blockvolume in db.GetBlockVolumesFromIndexName(n.Name))
                                        {
                                            w.StartVolume(blockvolume.Name);
                                            var volumeid = db.GetRemoteVolumeID(blockvolume.Name);

                                            foreach (var b in db.GetBlocks(volumeid))
                                            {
                                                w.AddBlock(b.Hash, b.Size);
                                            }

                                            w.FinishVolume(blockvolume.Hash, blockvolume.Size);

                                            if (m_options.IndexfilePolicy == Options.IndexFileStrategy.Full)
                                            {
                                                foreach (var b in db.GetBlocklists(volumeid, m_options.Blocksize, hashsize))
                                                {
                                                    var bh = Convert.ToBase64String(h.ComputeHash(b.Item2, 0, b.Item3));
                                                    if (bh != b.Item1)
                                                    {
                                                        throw new Exception(string.Format("Internal consistency check failed, generated index block has wrong hash, {0} vs {1}", bh, b.Item1));
                                                    }

                                                    w.WriteBlocklist(b.Item1, b.Item2, 0, b.Item3);
                                                }
                                            }
                                        }

                                        w.Close();

                                        if (m_options.Dryrun)
                                        {
                                            Logging.Log.WriteDryrunMessage(LOGTAG, "WouldReUploadIndexFile", "would re-upload index file {0}, with size {1}, previous size {2}", n.Name, Library.Utility.Utility.FormatSizeString(new System.IO.FileInfo(w.LocalFilename).Length), Library.Utility.Utility.FormatSizeString(n.Size));
                                        }
                                        else
                                        {
                                            db.UpdateRemoteVolume(w.RemoteFilename, RemoteVolumeState.Uploading, -1, null, null);
                                            backend.Put(w);
                                        }
                                    }
                                }
                                else if (n.Type == RemoteVolumeType.Blocks)
                                {
                                    using (BlockVolumeWriter w = new BlockVolumeWriter(m_options))
                                    {
                                        newEntry = w;
                                        w.SetRemoteFilename(n.Name);

                                        using (var mbl = db.CreateBlockList(n.Name))
                                        {
                                            //First we grab all known blocks from local files
                                            foreach (var block in mbl.GetSourceFilesWithBlocks(m_options.Blocksize))
                                            {
                                                var hash = block.Hash;
                                                var size = (int)block.Size;

                                                foreach (var source in block.Sources)
                                                {
                                                    var file   = source.File;
                                                    var offset = source.Offset;

                                                    try
                                                    {
                                                        if (System.IO.File.Exists(file))
                                                        {
                                                            using (var f = System.IO.File.OpenRead(file))
                                                            {
                                                                f.Position = offset;
                                                                if (size == Library.Utility.Utility.ForceStreamRead(f, buffer, size))
                                                                {
                                                                    var newhash = Convert.ToBase64String(blockhasher.ComputeHash(buffer, 0, size));
                                                                    if (newhash == hash)
                                                                    {
                                                                        if (mbl.SetBlockRestored(hash, size))
                                                                        {
                                                                            w.AddBlock(hash, buffer, 0, size, Duplicati.Library.Interface.CompressionHint.Default);
                                                                        }
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Logging.Log.WriteErrorMessage(LOGTAG, "FileAccessError", ex, "Failed to access file: {0}", file);
                                                    }
                                                }
                                            }

                                            //Then we grab all remote volumes that have the missing blocks
                                            foreach (var vol in new AsyncDownloader(mbl.GetMissingBlockSources().ToList(), backend))
                                            {
                                                try
                                                {
                                                    using (var tmpfile = vol.TempFile)
                                                        using (var f = new BlockVolumeReader(RestoreHandler.GetCompressionModule(vol.Name), tmpfile, m_options))
                                                            foreach (var b in f.Blocks)
                                                            {
                                                                if (mbl.SetBlockRestored(b.Key, b.Value))
                                                                {
                                                                    if (f.ReadBlock(b.Key, buffer) == b.Value)
                                                                    {
                                                                        w.AddBlock(b.Key, buffer, 0, (int)b.Value, Duplicati.Library.Interface.CompressionHint.Default);
                                                                    }
                                                                }
                                                            }
                                                }
                                                catch (Exception ex)
                                                {
                                                    Logging.Log.WriteErrorMessage(LOGTAG, "RemoteFileAccessError", ex, "Failed to access remote file: {0}", vol.Name);
                                                }
                                            }

                                            // If we managed to recover all blocks, NICE!
                                            var missingBlocks = mbl.GetMissingBlocks().Count();
                                            if (missingBlocks > 0)
                                            {
                                                Logging.Log.WriteInformationMessage(LOGTAG, "RepairMissingBlocks", "Repair cannot acquire {0} required blocks for volume {1}, which are required by the following filesets: ", missingBlocks, n.Name);
                                                foreach (var f in mbl.GetFilesetsUsingMissingBlocks())
                                                {
                                                    Logging.Log.WriteInformationMessage(LOGTAG, "AffectedFilesetName", f.Name);
                                                }

                                                var recoverymsg = string.Format("If you want to continue working with the database, you can use the \"{0}\" and \"{1}\" commands to purge the missing data from the database and the remote storage.", "list-broken-files", "purge-broken-files");

                                                if (!m_options.Dryrun)
                                                {
                                                    Logging.Log.WriteInformationMessage(LOGTAG, "RecoverySuggestion", "This may be fixed by deleting the filesets and running repair again");

                                                    throw new UserInformationException(string.Format("Repair not possible, missing {0} blocks.\n" + recoverymsg, missingBlocks), "RepairIsNotPossible");
                                                }
                                                else
                                                {
                                                    Logging.Log.WriteInformationMessage(LOGTAG, "RecoverySuggestion", recoverymsg);
                                                }
                                            }
                                            else
                                            {
                                                if (m_options.Dryrun)
                                                {
                                                    Logging.Log.WriteDryrunMessage(LOGTAG, "WouldReUploadBlockFile", "would re-upload block file {0}, with size {1}, previous size {2}", n.Name, Library.Utility.Utility.FormatSizeString(new System.IO.FileInfo(w.LocalFilename).Length), Library.Utility.Utility.FormatSizeString(n.Size));
                                                }
                                                else
                                                {
                                                    db.UpdateRemoteVolume(w.RemoteFilename, RemoteVolumeState.Uploading, -1, null, null);
                                                    backend.Put(w);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                if (newEntry != null)
                                {
                                    try { newEntry.Dispose(); }
                                    catch { }
                                    finally { newEntry = null; }
                                }

                                Logging.Log.WriteErrorMessage(LOGTAG, "CleanupMissingFileError", ex, "Failed to perform cleanup for missing file: {0}, message: {1}", n.Name, ex.Message);

                                if (ex is System.Threading.ThreadAbortException)
                                {
                                    throw;
                                }
                            }
                        }
                    }
                    else
                    {
                        Logging.Log.WriteInformationMessage(LOGTAG, "DatabaseIsSynchronized", "Destination and database are synchronized, not making any changes");
                    }

                    m_result.OperationProgressUpdater.UpdateProgress(1);
                    backend.WaitForComplete(db, null);
                    db.WriteResults();
                }
        }
Esempio n. 3
0
        public static Task Run(BackupDatabase database, Options options, BackupResults result, ITaskReader taskreader, string lasttempfilelist, long lasttempfileid)
        {
            return(AutomationExtensions.RunTask(new
            {
                UploadChannel = Channels.BackendRequest.ForWrite
            },

                                                async self =>
            {
                // Check if we should upload a synthetic filelist
                if (options.DisableSyntheticFilelist || string.IsNullOrWhiteSpace(lasttempfilelist) || lasttempfileid < 0)
                {
                    return;
                }

                // Check that we still need to process this after the cleanup has performed its duties
                var syntbase = await database.GetRemoteVolumeFromIDAsync(lasttempfileid);

                // If we do not have a valid entry, warn and quit
                if (syntbase.Name == null || syntbase.State != RemoteVolumeState.Uploaded)
                {
                    // TODO: If the repair succeeds, this could give a false warning?
                    Logging.Log.WriteWarningMessage(LOGTAG, "MissingTemporaryFilelist", null, "Expected there to be a temporary fileset for synthetic filelist ({0}, {1}), but none was found?", lasttempfileid, lasttempfilelist);
                    return;
                }

                // Files is missing or repaired
                if (syntbase.Name == null || (syntbase.State != RemoteVolumeState.Uploading && syntbase.State != RemoteVolumeState.Temporary))
                {
                    Logging.Log.WriteInformationMessage(LOGTAG, "SkippingSyntheticListUpload", "Skipping synthetic upload because temporary fileset appers to be complete: ({0}, {1}, {2})", lasttempfileid, lasttempfilelist, syntbase.State);
                    return;
                }

                // Ready to build and upload the synthetic list
                await database.CommitTransactionAsync("PreSyntheticFilelist");
                var incompleteFilesets = (await database.GetIncompleteFilesetsAsync()).OrderBy(x => x.Value).ToList();

                result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_PreviousBackupFinalize);
                Logging.Log.WriteInformationMessage(LOGTAG, "PreviousBackupFilelistUpload", "Uploading filelist from previous interrupted backup");

                if (!await taskreader.ProgressAsync)
                {
                    return;
                }

                var incompleteSet = incompleteFilesets.Last();
                var badIds = from n in incompleteFilesets select n.Key;

                var prevs = (from n in await database.GetFilesetTimesAsync()
                             where
                             n.Key < incompleteSet.Key
                             &&
                             !badIds.Contains(n.Key)
                             orderby n.Key
                             select n.Key).ToArray();

                var prevId = prevs.Length == 0 ? -1 : prevs.Last();

                try
                {
                    var s = 1;
                    var fileTime = incompleteSet.Value + TimeSpan.FromSeconds(s);

                    // Probe for an unused filename
                    while (s < 60)
                    {
                        var id = await database.GetRemoteVolumeIDAsync(VolumeBase.GenerateFilename(RemoteVolumeType.Files, options, null, fileTime));
                        if (id < 0)
                        {
                            break;
                        }

                        fileTime = incompleteSet.Value + TimeSpan.FromSeconds(++s);
                    }

                    using (FilesetVolumeWriter fsw = new FilesetVolumeWriter(options, fileTime))
                    {
                        fsw.VolumeID = await database.RegisterRemoteVolumeAsync(fsw.RemoteFilename, RemoteVolumeType.Files, RemoteVolumeState.Temporary);

                        if (!string.IsNullOrEmpty(options.ControlFiles))
                        {
                            foreach (var p in options.ControlFiles.Split(new char[] { System.IO.Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                fsw.AddControlFile(p, options.GetCompressionHintFromFilename(p));
                            }
                        }

                        // We declare this to be a partial backup since the synthetic filelist is only created
                        // when a backup is interrupted.
                        fsw.CreateFilesetFile(false);
                        var newFilesetID = await database.CreateFilesetAsync(fsw.VolumeID, fileTime);
                        await database.LinkFilesetToVolumeAsync(newFilesetID, fsw.VolumeID);
                        await database.AppendFilesFromPreviousSetAsync(null, newFilesetID, prevId, fileTime);

                        await database.WriteFilesetAsync(fsw, newFilesetID);

                        if (!await taskreader.ProgressAsync)
                        {
                            return;
                        }

                        await database.UpdateRemoteVolumeAsync(fsw.RemoteFilename, RemoteVolumeState.Uploading, -1, null);
                        await database.CommitTransactionAsync("CommitUpdateFilelistVolume");
                        await self.UploadChannel.WriteAsync(new FilesetUploadRequest(fsw));
                    }
                }
                catch
                {
                    await database.RollbackTransactionAsync();
                    throw;
                }
            }
                                                ));
        }