Esempio n. 1
0
        private async Task BackupFile(BackupItem file)
        {
            var totalBlocks = 0;

            try
            {
                var stream = await agentProxy.GetStream(file.StreamGuid);

                hasher.Initialize();

                var dbFile = new DBFile {
                    Name = file.Name, Backup = backup.Id, LastWriteTime = file.LastWriteTime, Length = file.Length, Valid = false
                };
                currentFileId = await metaDB.AddFile(dbFile);

                dbFile.Id = currentFileId;

                var currentFilePos = 0L;
                var buffer         = new byte[1024 * 64];
                BlocksManager.dbBlocks = 0;

                Console.WriteLine($"{DateTime.Now} - Backup file: {file.Name}");

                IList <byte[]> newbLocks;
                var            readCount = await stream.ReadAsync(buffer, 0, buffer.Length, ctoken);

                while (readCount > 0)
                {
                    CheckCancelStatus();

                    newbLocks = hasher.NextBlock(buffer, 0, readCount);
                    foreach (var newbLock in newbLocks)
                    {
                        CheckCancelStatus();
                        var blockGuid = await BlocksManager.AddBlockToDB(newbLock);

                        await metaDB.AddFileBlock(new DBFileBlock { Block = blockGuid, File = currentFileId, Offset = currentFilePos });

                        currentFilePos += newbLock.Length;
                        totalBlocks++;
                    }
                    readCount = await stream.ReadAsync(buffer, 0, buffer.Length, ctoken);
                }

                if (hasher.HasRemainingBytes)
                {
                    var lastLock  = hasher.RemainingBytes();
                    var blockGuid = await BlocksManager.AddBlockToDB(lastLock);

                    await metaDB.AddFileBlock(new DBFileBlock { Block = blockGuid, File = currentFileId, Offset = currentFilePos });

                    currentFilePos += lastLock.Length;
                    totalBlocks++;
                }

                dbFile.Valid = true;
                await metaDB.AddFile(dbFile);
            }
            catch (OperationCanceledException e)
            {
                // re-throws OperationCanceled exceptions
                throw e;
            }
            catch (Exception e)
            {
                backup.AppendLog($"Error file: {file.Name} --- {e.Message} ");
                backupStatus = Status.Warning;
                await metaDB.AddBackup(backup); // Update backup with error
            }


            Console.WriteLine($"{DateTime.Now} - Total blocks: {totalBlocks}");
            Console.WriteLine($"{DateTime.Now} - DB blocks: {BlocksManager.dbBlocks}");
        }