2 /* -----------------------------------------------------------------------
3 * <copyright file="NetworkAgent.cs" company="GRNet">
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
11 * 1. Redistributions of source code must retain the above
12 * copyright notice, this list of conditions and the following
15 * 2. Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials
18 * provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
34 * The views and conclusions contained in the software and
35 * documentation are those of the authors and should not be
36 * interpreted as representing official policies, either expressed
37 * or implied, of GRNET S.A.
39 * -----------------------------------------------------------------------
44 using System.Collections.Generic;
45 using System.ComponentModel.Composition;
46 using System.Diagnostics;
47 using System.Diagnostics.Contracts;
50 using System.Reflection;
51 using System.Threading;
52 using System.Threading.Tasks;
53 using Castle.ActiveRecord;
54 using Pithos.Interfaces;
58 namespace Pithos.Core.Agents
61 public class NetworkAgent
63 private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
65 private Agent<CloudAction> _agent;
67 [System.ComponentModel.Composition.Import]
68 private DeleteAgent _deleteAgent=new DeleteAgent();
70 [System.ComponentModel.Composition.Import]
71 public IStatusKeeper StatusKeeper { get; set; }
73 public IStatusNotification StatusNotification { get; set; }
76 [System.ComponentModel.Composition.Import]
77 public IPithosSettings Settings { get; set; }
79 //The Proceed signals the poll agent that it can proceed with polling.
80 //Essentially it stops the poll agent to give priority to the network agent
81 //Initially the event is signalled because we don't need to pause
82 private readonly AsyncManualResetEvent _proceedEvent = new AsyncManualResetEvent(true);
84 public AsyncManualResetEvent ProceedEvent
86 get { return _proceedEvent; }
92 _agent = Agent<CloudAction>.Start(inbox =>
97 _deleteAgent.ProceedEvent.Wait();
98 var message = inbox.Receive();
99 var process=message.Then(Process,inbox.CancellationToken);
100 inbox.LoopAsync(process, loop);
107 private async Task Process(CloudAction action)
110 throw new ArgumentNullException("action");
111 if (action.AccountInfo==null)
112 throw new ArgumentException("The action.AccountInfo is empty","action");
113 Contract.EndContractBlock();
118 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
120 Log.InfoFormat("[ACTION] Start Processing {0}", action);
122 var cloudFile = action.CloudFile;
123 var downloadPath = action.GetDownloadPath();
127 _proceedEvent.Reset();
128 UpdateStatus(PithosStatus.Syncing);
129 var accountInfo = action.AccountInfo;
131 if (action.Action == CloudActionType.DeleteCloud)
133 //Redirect deletes to the delete agent
134 _deleteAgent.Post((CloudDeleteAction)action);
136 if (_deleteAgent.IsDeletedFile(action))
138 //Clear the status of already deleted files to avoid reprocessing
139 if (action.LocalFile != null)
140 StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
144 switch (action.Action)
146 case CloudActionType.UploadUnconditional:
147 //Abort if the file was deleted before we reached this point
148 await UploadCloudFile(action);
150 case CloudActionType.DownloadUnconditional:
151 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
153 case CloudActionType.RenameCloud:
154 var moveAction = (CloudMoveAction)action;
155 RenameCloudFile(accountInfo, moveAction);
157 case CloudActionType.RenameLocal:
158 RenameLocalFile(accountInfo, action);
160 case CloudActionType.MustSynch:
161 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
163 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
167 await SyncFiles(accountInfo, action);
172 Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
173 action.CloudFile.Name);
175 catch (WebException exc)
177 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
179 catch (OperationCanceledException)
183 catch (DirectoryNotFoundException)
185 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
186 action.Action, action.LocalFile, action.CloudFile);
187 //Post a delete action for the missing file
188 Post(new CloudDeleteAction(action));
190 catch (FileNotFoundException)
192 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
193 action.Action, action.LocalFile, action.CloudFile);
194 //Post a delete action for the missing file
195 Post(new CloudDeleteAction(action));
197 catch (Exception exc)
199 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
200 action.Action, action.LocalFile, action.CloudFile, exc);
208 UpdateStatus(PithosStatus.InSynch);
214 private void UpdateStatus(PithosStatus status)
216 StatusKeeper.SetPithosStatus(status);
217 StatusNotification.Notify(new Notification());
220 private void RenameLocalFile(AccountInfo accountInfo, CloudAction action)
222 if (accountInfo == null)
223 throw new ArgumentNullException("accountInfo");
225 throw new ArgumentNullException("action");
226 if (action.LocalFile == null)
227 throw new ArgumentException("The action's local file is not specified", "action");
228 if (!Path.IsPathRooted(action.LocalFile.FullName))
229 throw new ArgumentException("The action's local file path must be absolute", "action");
230 if (action.CloudFile == null)
231 throw new ArgumentException("The action's cloud file is not specified", "action");
232 Contract.EndContractBlock();
234 //We assume that the local file already exists, otherwise the poll agent
235 //would have issued a download request
237 var currentInfo = action.CloudFile;
238 var previousInfo = action.CloudFile.Previous;
239 var fileAgent = FileAgent.GetFileAgent(accountInfo);
241 var previousRelativepath = previousInfo.RelativeUrlToFilePath(accountInfo.UserName);
242 var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
244 //In every case we need to move the local file first
245 MoveLocalFile(accountInfo, previousFile, fileAgent, currentInfo);
249 private void MoveLocalFile(AccountInfo accountInfo, FileSystemInfo previousFile, FileAgent fileAgent,
250 ObjectInfo currentInfo)
252 var currentRelativepath = currentInfo.RelativeUrlToFilePath(accountInfo.UserName);
253 var newPath = Path.Combine(fileAgent.RootPath, currentRelativepath);
255 var isFile= (previousFile is FileInfo);
256 var previousFullPath = isFile?
257 FileInfoExtensions.GetProperFilePathCapitalization(previousFile.FullName):
258 FileInfoExtensions.GetProperDirectoryCapitalization(previousFile.FullName);
260 using (var gateOld = NetworkGate.Acquire(previousFullPath, NetworkOperation.Renaming))
261 using (var gateNew = NetworkGate.Acquire(newPath,NetworkOperation.Renaming))
262 using (new SessionScope(FlushAction.Auto))
265 (previousFile as FileInfo).MoveTo(newPath);
268 (previousFile as DirectoryInfo).MoveTo(newPath);
270 var state = StatusKeeper.GetStateByFilePath(previousFullPath);
271 state.FilePath = newPath;
273 StatusKeeper.SetFileState(previousFullPath,FileStatus.Deleted,FileOverlayStatus.Deleted);
277 private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
279 if (accountInfo == null)
280 throw new ArgumentNullException("accountInfo");
282 throw new ArgumentNullException("action");
283 if (action.LocalFile==null)
284 throw new ArgumentException("The action's local file is not specified","action");
285 if (!Path.IsPathRooted(action.LocalFile.FullName))
286 throw new ArgumentException("The action's local file path must be absolute","action");
287 if (action.CloudFile== null)
288 throw new ArgumentException("The action's cloud file is not specified", "action");
289 Contract.EndContractBlock();
291 var localFile = action.LocalFile;
292 var cloudFile = action.CloudFile;
293 var downloadPath=action.LocalFile.GetProperCapitalization();
295 var cloudHash = cloudFile.Hash.ToLower();
296 var previousCloudHash = cloudFile.PreviousHash.ToLower();
297 var localHash = action.LocalHash.Value.ToLower();
298 var topHash = action.TopHash.Value.ToLower();
300 //At this point we know that an object has changed on the server and that a local
301 //file already exists. We need to decide whether the file has only changed on
302 //the server or there is a conflicting change on the client.
305 //Not enough to compare only the local hashes (MD5), also have to compare the tophashes
306 //If any of the hashes match, we are done
307 if ((cloudHash == localHash || cloudHash == topHash))
309 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
313 //The hashes DON'T match. We need to sync
315 // If the previous tophash matches the local tophash, the file was only changed on the server.
316 if (localHash == previousCloudHash)
318 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
322 //If the previous and local hash don't match, there was a local conflict
323 //that was not uploaded to the server. We have a conflict
324 ReportConflict(downloadPath);
328 private void ReportConflict(string downloadPath)
330 if (String.IsNullOrWhiteSpace(downloadPath))
331 throw new ArgumentNullException("downloadPath");
332 Contract.EndContractBlock();
334 StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
335 UpdateStatus(PithosStatus.HasConflicts);
336 var message = String.Format("Conflict detected for file {0}", downloadPath);
338 StatusNotification.NotifyChange(message, TraceLevel.Warning);
341 public void Post(CloudAction cloudAction)
343 if (cloudAction == null)
344 throw new ArgumentNullException("cloudAction");
345 if (cloudAction.AccountInfo==null)
346 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
347 Contract.EndContractBlock();
349 _deleteAgent.ProceedEvent.Wait();
351 //If the action targets a local file, add a treehash calculation
352 if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
354 var accountInfo = cloudAction.AccountInfo;
355 var localFile = (FileInfo) cloudAction.LocalFile;
356 if (localFile.Length > accountInfo.BlockSize)
357 cloudAction.TopHash =
358 new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
359 accountInfo.BlockSize,
360 accountInfo.BlockHash, Settings.HashingParallelism).Result
361 .TopHash.ToHashString());
364 cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
369 //The hash for a directory is the empty string
370 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
373 if (cloudAction is CloudDeleteAction)
374 _deleteAgent.Post((CloudDeleteAction)cloudAction);
376 _agent.Post(cloudAction);
380 public IEnumerable<CloudAction> GetEnumerable()
382 return _agent.GetEnumerable();
385 public Task GetDeleteAwaiter()
387 return _deleteAgent.ProceedEvent.WaitAsync();
389 public CancellationToken CancellationToken
391 get { return _agent.CancellationToken; }
394 private static FileAgent GetFileAgent(AccountInfo accountInfo)
396 return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
401 private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
403 if (accountInfo==null)
404 throw new ArgumentNullException("accountInfo");
406 throw new ArgumentNullException("action");
407 if (action.CloudFile==null)
408 throw new ArgumentException("CloudFile","action");
409 if (action.LocalFile==null)
410 throw new ArgumentException("LocalFile","action");
411 if (action.OldLocalFile==null)
412 throw new ArgumentException("OldLocalFile","action");
413 if (action.OldCloudFile==null)
414 throw new ArgumentException("OldCloudFile","action");
415 Contract.EndContractBlock();
418 var newFilePath = action.LocalFile.FullName;
420 //How do we handle concurrent renames and deletes/uploads/downloads?
421 //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
422 // This should never happen as the network agent executes only one action at a time
423 //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
424 // the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the
425 // same name will fail.
426 // This should never happen as the network agent executes only one action at a time.
427 //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
428 // to remove the rename from the queue.
429 // We can probably ignore this case. It will result in an error which should be ignored
432 //The local file is already renamed
433 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
436 var account = action.CloudFile.Account ?? accountInfo.UserName;
437 var container = action.CloudFile.Container;
439 var client = new CloudFilesClient(accountInfo);
440 //TODO: What code is returned when the source file doesn't exist?
441 client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
443 StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
444 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
445 NativeMethods.RaiseChangeNotification(newFilePath);
449 private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
451 if (accountInfo == null)
452 throw new ArgumentNullException("accountInfo");
453 if (cloudFile == null)
454 throw new ArgumentNullException("cloudFile");
455 if (String.IsNullOrWhiteSpace(cloudFile.Account))
456 throw new ArgumentNullException("cloudFile");
457 if (String.IsNullOrWhiteSpace(cloudFile.Container))
458 throw new ArgumentNullException("cloudFile");
459 if (String.IsNullOrWhiteSpace(filePath))
460 throw new ArgumentNullException("filePath");
461 if (!Path.IsPathRooted(filePath))
462 throw new ArgumentException("The filePath must be rooted", "filePath");
463 Contract.EndContractBlock();
466 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
467 var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
469 var url = relativeUrl.ToString();
470 if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
474 //Are we already downloading or uploading the file?
475 using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
480 var client = new CloudFilesClient(accountInfo);
481 var account = cloudFile.Account;
482 var container = cloudFile.Container;
484 if (cloudFile.Content_Type == @"application/directory")
486 if (!Directory.Exists(localPath))
487 Directory.CreateDirectory(localPath);
491 //Retrieve the hashmap from the server
492 var serverHash = await client.GetHashMap(account, container, url);
493 //If it's a small file
494 if (serverHash.Hashes.Count == 1)
495 //Download it in one go
497 DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
498 //Otherwise download it block by block
500 await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
502 if (cloudFile.AllowedTo == "read")
504 var attributes = File.GetAttributes(localPath);
505 File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
509 //Now we can store the object's metadata without worrying about ghost status entries
510 StatusKeeper.StoreInfo(localPath, cloudFile);
515 //Download a small file with a single GET operation
516 private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
519 throw new ArgumentNullException("client");
521 throw new ArgumentNullException("cloudFile");
522 if (relativeUrl == null)
523 throw new ArgumentNullException("relativeUrl");
524 if (String.IsNullOrWhiteSpace(filePath))
525 throw new ArgumentNullException("filePath");
526 if (!Path.IsPathRooted(filePath))
527 throw new ArgumentException("The localPath must be rooted", "filePath");
528 Contract.EndContractBlock();
530 var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
531 //If the file already exists
532 if (File.Exists(localPath))
534 //First check with MD5 as this is a small file
535 var localMD5 = Signature.CalculateMD5(localPath);
536 var cloudHash=serverHash.TopHash.ToHashString();
537 if (localMD5==cloudHash)
539 //Then check with a treehash
540 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
541 var localHash = localTreeHash.TopHash.ToHashString();
542 if (localHash==cloudHash)
545 StatusNotification.Notify(new CloudNotification { Data = cloudFile });
547 var fileAgent = GetFileAgent(accountInfo);
548 //Calculate the relative file path for the new file
549 var relativePath = relativeUrl.RelativeUriToFilePath();
550 //The file will be stored in a temporary location while downloading with an extension .download
551 var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
552 //Make sure the target folder exists. DownloadFileTask will not create the folder
553 var tempFolder = Path.GetDirectoryName(tempPath);
554 if (!Directory.Exists(tempFolder))
555 Directory.CreateDirectory(tempFolder);
557 //Download the object to the temporary location
558 await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
560 //Create the local folder if it doesn't exist (necessary for shared objects)
561 var localFolder = Path.GetDirectoryName(localPath);
562 if (!Directory.Exists(localFolder))
563 Directory.CreateDirectory(localFolder);
564 //And move it to its actual location once downloading is finished
565 if (File.Exists(localPath))
566 File.Replace(tempPath,localPath,null,true);
568 File.Move(tempPath,localPath);
569 //Notify listeners that a local file has changed
570 StatusNotification.NotifyChangedFile(localPath);
575 //Download a file asynchronously using blocks
576 public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
579 throw new ArgumentNullException("client");
580 if (cloudFile == null)
581 throw new ArgumentNullException("cloudFile");
582 if (relativeUrl == null)
583 throw new ArgumentNullException("relativeUrl");
584 if (String.IsNullOrWhiteSpace(filePath))
585 throw new ArgumentNullException("filePath");
586 if (!Path.IsPathRooted(filePath))
587 throw new ArgumentException("The filePath must be rooted", "filePath");
588 if (serverHash == null)
589 throw new ArgumentNullException("serverHash");
590 Contract.EndContractBlock();
592 var fileAgent = GetFileAgent(accountInfo);
593 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
595 //Calculate the relative file path for the new file
596 var relativePath = relativeUrl.RelativeUriToFilePath();
597 var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
601 //Calculate the file's treehash
602 var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
604 //And compare it with the server's hash
605 var upHashes = serverHash.GetHashesAsStrings();
606 var localHashes = treeHash.HashDictionary;
607 for (int i = 0; i < upHashes.Length; i++)
609 //For every non-matching hash
610 var upHash = upHashes[i];
611 if (!localHashes.ContainsKey(upHash))
613 StatusNotification.Notify(new CloudNotification { Data = cloudFile });
615 if (blockUpdater.UseOrphan(i, upHash))
617 Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
620 Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
621 var start = i*serverHash.BlockSize;
622 //To download the last block just pass a null for the end of the range
624 if (i < upHashes.Length - 1 )
625 end= ((i + 1)*serverHash.BlockSize) ;
627 //Download the missing block
628 var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
631 blockUpdater.StoreBlock(i, block);
634 Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
638 //Want to avoid notifications if no changes were made
639 var hasChanges = blockUpdater.HasBlocks;
640 blockUpdater.Commit();
643 //Notify listeners that a local file has changed
644 StatusNotification.NotifyChangedFile(localPath);
646 Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
650 private async Task UploadCloudFile(CloudAction action)
653 throw new ArgumentNullException("action");
654 Contract.EndContractBlock();
658 var accountInfo = action.AccountInfo;
660 var fileInfo = action.LocalFile;
662 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
665 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
666 if (relativePath.StartsWith(FolderConstants.OthersFolder))
668 var parts = relativePath.Split('\\');
669 var accountName = parts[1];
670 var oldName = accountInfo.UserName;
671 var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
672 var nameIndex = absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
673 var root = absoluteUri.Substring(0, nameIndex);
675 accountInfo = new AccountInfo
677 UserName = accountName,
678 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
679 StorageUri = new Uri(root + accountName),
680 BlockHash = accountInfo.BlockHash,
681 BlockSize = accountInfo.BlockSize,
682 Token = accountInfo.Token
687 var fullFileName = fileInfo.GetProperCapitalization();
688 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
690 //Abort if the file is already being uploaded or downloaded
694 var cloudFile = action.CloudFile;
695 var account = cloudFile.Account ?? accountInfo.UserName;
697 var client = new CloudFilesClient(accountInfo);
698 //Even if GetObjectInfo times out, we can proceed with the upload
699 var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
701 //If this is a read-only file, do not upload changes
702 if (info.AllowedTo == "read")
705 //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
706 if (fileInfo is DirectoryInfo)
708 //If the directory doesn't exist the Hash property will be empty
709 if (String.IsNullOrWhiteSpace(info.Hash))
710 //Go on and create the directory
711 await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
716 var cloudHash = info.Hash.ToLower();
718 var hash = action.LocalHash.Value;
719 var topHash = action.TopHash.Value;
721 //If the file hashes match, abort the upload
722 if (hash == cloudHash || topHash == cloudHash)
724 //but store any metadata changes
725 StatusKeeper.StoreInfo(fullFileName, info);
726 Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
731 //Mark the file as modified while we upload it
732 StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
735 //Upload even small files using the Hashmap. The server may already contain
738 //First, calculate the tree hash
739 var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
740 accountInfo.BlockHash, 2);
742 await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
744 //If everything succeeds, change the file and overlay status to normal
745 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
747 //Notify the Shell to update the overlays
748 NativeMethods.RaiseChangeNotification(fullFileName);
749 StatusNotification.NotifyChangedFile(fullFileName);
751 catch (AggregateException ex)
753 var exc = ex.InnerException as WebException;
755 throw ex.InnerException;
756 if (HandleUploadWebException(action, exc))
760 catch (WebException ex)
762 if (HandleUploadWebException(action, ex))
768 Log.Error("Unexpected error while uploading file", ex);
776 private bool HandleUploadWebException(CloudAction action, WebException exc)
778 var response = exc.Response as HttpWebResponse;
779 if (response == null)
781 if (response.StatusCode == HttpStatusCode.Unauthorized)
783 Log.Error("Not allowed to upload file", exc);
784 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
785 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
786 StatusNotification.NotifyChange(message, TraceLevel.Warning);
792 public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
794 if (accountInfo == null)
795 throw new ArgumentNullException("accountInfo");
797 throw new ArgumentNullException("cloudFile");
798 if (fileInfo == null)
799 throw new ArgumentNullException("fileInfo");
800 if (String.IsNullOrWhiteSpace(url))
801 throw new ArgumentNullException(url);
803 throw new ArgumentNullException("treeHash");
804 if (String.IsNullOrWhiteSpace(cloudFile.Container) )
805 throw new ArgumentException("Invalid container","cloudFile");
806 Contract.EndContractBlock();
808 var fullFileName = fileInfo.GetProperCapitalization();
810 var account = cloudFile.Account ?? accountInfo.UserName;
811 var container = cloudFile.Container ;
813 var client = new CloudFilesClient(accountInfo);
814 //Send the hashmap to the server
815 var missingHashes = await client.PutHashMap(account, container, url, treeHash);
816 //If the server returns no missing hashes, we are done
817 while (missingHashes.Count > 0)
820 var buffer = new byte[accountInfo.BlockSize];
821 foreach (var missingHash in missingHashes)
823 //Find the proper block
824 var blockIndex = treeHash.HashDictionary[missingHash];
825 var offset = blockIndex*accountInfo.BlockSize;
827 var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
831 //And upload the block
832 await client.PostBlock(account, container, buffer, 0, read);
833 Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
835 catch (Exception exc)
837 Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
842 //Repeat until there are no more missing hashes
843 missingHashes = await client.PutHashMap(account, container, url, treeHash);