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 * -----------------------------------------------------------------------
43 //TODO: Now there is a UUID tag. This can be used for renames/moves
47 using System.Collections.Concurrent;
48 using System.Collections.Generic;
49 using System.ComponentModel.Composition;
50 using System.Diagnostics;
51 using System.Diagnostics.Contracts;
55 using System.Threading;
56 using System.Threading.Tasks;
57 using System.Threading.Tasks.Dataflow;
58 using Castle.ActiveRecord;
59 using Pithos.Interfaces;
63 namespace Pithos.Core.Agents
65 //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
67 public class NetworkAgent
69 private Agent<CloudAction> _agent;
71 [System.ComponentModel.Composition.Import]
72 private DeleteAgent _deleteAgent=new DeleteAgent();
74 [System.ComponentModel.Composition.Import]
75 public IStatusKeeper StatusKeeper { get; set; }
77 public IStatusNotification StatusNotification { get; set; }
79 private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
81 private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
83 [System.ComponentModel.Composition.Import]
84 public IPithosSettings Settings { get; set; }
86 //The Proceed signals the poll agent that it can proceed with polling.
87 //Essentially it stops the poll agent to give priority to the network agent
88 //Initially the event is signalled because we don't need to pause
89 private readonly AsyncManualResetEvent _proceedEvent = new AsyncManualResetEvent(true);
91 public AsyncManualResetEvent ProceedEvent
93 get { return _proceedEvent; }
99 _agent = Agent<CloudAction>.Start(inbox =>
104 _deleteAgent.ProceedEvent.Wait();
105 var message = inbox.Receive();
106 var process=message.Then(Process,inbox.CancellationToken);
107 inbox.LoopAsync(process, loop);
114 private async Task Process(CloudAction action)
117 throw new ArgumentNullException("action");
118 if (action.AccountInfo==null)
119 throw new ArgumentException("The action.AccountInfo is empty","action");
120 Contract.EndContractBlock();
125 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
127 Log.InfoFormat("[ACTION] Start Processing {0}", action);
129 var cloudFile = action.CloudFile;
130 var downloadPath = action.GetDownloadPath();
134 _proceedEvent.Reset();
135 UpdateStatus(PithosStatus.Syncing);
136 var accountInfo = action.AccountInfo;
138 if (action.Action == CloudActionType.DeleteCloud)
140 //Redirect deletes to the delete agent
141 _deleteAgent.Post((CloudDeleteAction)action);
143 if (_deleteAgent.IsDeletedFile(action))
145 //Clear the status of already deleted files to avoid reprocessing
146 if (action.LocalFile != null)
147 this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
151 switch (action.Action)
153 case CloudActionType.UploadUnconditional:
154 //Abort if the file was deleted before we reached this point
155 await UploadCloudFile(action);
157 case CloudActionType.DownloadUnconditional:
158 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
160 case CloudActionType.RenameCloud:
161 var moveAction = (CloudMoveAction)action;
162 RenameCloudFile(accountInfo, moveAction);
164 case CloudActionType.RenameLocal:
165 RenameLocalFile(accountInfo, action);
167 case CloudActionType.MustSynch:
168 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
170 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
174 await SyncFiles(accountInfo, action);
179 Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
180 action.CloudFile.Name);
182 catch (WebException exc)
184 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
186 catch (OperationCanceledException)
190 catch (DirectoryNotFoundException)
192 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory 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 (FileNotFoundException)
199 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
200 action.Action, action.LocalFile, action.CloudFile);
201 //Post a delete action for the missing file
202 Post(new CloudDeleteAction(action));
204 catch (Exception exc)
206 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
207 action.Action, action.LocalFile, action.CloudFile, exc);
215 UpdateStatus(PithosStatus.InSynch);
221 private void UpdateStatus(PithosStatus status)
223 StatusKeeper.SetPithosStatus(status);
224 StatusNotification.Notify(new Notification());
227 private void RenameLocalFile(AccountInfo accountInfo, CloudAction action)
229 if (accountInfo == null)
230 throw new ArgumentNullException("accountInfo");
232 throw new ArgumentNullException("action");
233 if (action.LocalFile == null)
234 throw new ArgumentException("The action's local file is not specified", "action");
235 if (!Path.IsPathRooted(action.LocalFile.FullName))
236 throw new ArgumentException("The action's local file path must be absolute", "action");
237 if (action.CloudFile == null)
238 throw new ArgumentException("The action's cloud file is not specified", "action");
239 Contract.EndContractBlock();
241 //We assume that the local file already exists, otherwise the poll agent
242 //would have issued a download request
244 var currentInfo = action.CloudFile;
245 var previousInfo = action.CloudFile.Previous;
246 var fileAgent = FileAgent.GetFileAgent(accountInfo);
248 var previousRelativepath = previousInfo.RelativeUrlToFilePath(accountInfo.UserName);
249 var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
251 //In every case we need to move the local file first
252 MoveLocalFile(accountInfo, previousFile, fileAgent, currentInfo);
256 private void MoveLocalFile(AccountInfo accountInfo, FileSystemInfo previousFile, FileAgent fileAgent,
257 ObjectInfo currentInfo)
259 var currentRelativepath = currentInfo.RelativeUrlToFilePath(accountInfo.UserName);
260 var newPath = Path.Combine(fileAgent.RootPath, currentRelativepath);
262 var isFile= (previousFile is FileInfo);
263 var previousFullPath = isFile?
264 FileInfoExtensions.GetProperFilePathCapitalization(previousFile.FullName):
265 FileInfoExtensions.GetProperDirectoryCapitalization(previousFile.FullName);
267 using (var gateOld = NetworkGate.Acquire(previousFullPath, NetworkOperation.Renaming))
268 using (var gateNew = NetworkGate.Acquire(newPath,NetworkOperation.Renaming))
269 using (new SessionScope(FlushAction.Auto))
272 (previousFile as FileInfo).MoveTo(newPath);
275 (previousFile as DirectoryInfo).MoveTo(newPath);
277 var state = StatusKeeper.GetStateByFilePath(previousFullPath);
278 state.FilePath = newPath;
280 StatusKeeper.SetFileState(previousFullPath,FileStatus.Deleted,FileOverlayStatus.Deleted);
284 private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
286 if (accountInfo == null)
287 throw new ArgumentNullException("accountInfo");
289 throw new ArgumentNullException("action");
290 if (action.LocalFile==null)
291 throw new ArgumentException("The action's local file is not specified","action");
292 if (!Path.IsPathRooted(action.LocalFile.FullName))
293 throw new ArgumentException("The action's local file path must be absolute","action");
294 if (action.CloudFile== null)
295 throw new ArgumentException("The action's cloud file is not specified", "action");
296 Contract.EndContractBlock();
298 var localFile = action.LocalFile;
299 var cloudFile = action.CloudFile;
300 var downloadPath=action.LocalFile.GetProperCapitalization();
302 var cloudHash = cloudFile.Hash.ToLower();
303 var previousCloudHash = cloudFile.PreviousHash.ToLower();
304 var localHash = action.LocalHash.Value.ToLower();
305 var topHash = action.TopHash.Value.ToLower();
307 //At this point we know that an object has changed on the server and that a local
308 //file already exists. We need to decide whether the file has only changed on
309 //the server or there is a conflicting change on the client.
312 //Not enough to compare only the local hashes (MD5), also have to compare the tophashes
313 //If any of the hashes match, we are done
314 if ((cloudHash == localHash || cloudHash == topHash))
316 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
320 //The hashes DON'T match. We need to sync
322 // If the previous tophash matches the local tophash, the file was only changed on the server.
323 if (localHash == previousCloudHash)
325 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
329 //If the previous and local hash don't match, there was a local conflict
330 //that was not uploaded to the server. We have a conflict
331 ReportConflict(downloadPath);
335 private void ReportConflict(string downloadPath)
337 if (String.IsNullOrWhiteSpace(downloadPath))
338 throw new ArgumentNullException("downloadPath");
339 Contract.EndContractBlock();
341 StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
342 UpdateStatus(PithosStatus.HasConflicts);
343 var message = String.Format("Conflict detected for file {0}", downloadPath);
345 StatusNotification.NotifyChange(message, TraceLevel.Warning);
348 public void Post(CloudAction cloudAction)
350 if (cloudAction == null)
351 throw new ArgumentNullException("cloudAction");
352 if (cloudAction.AccountInfo==null)
353 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
354 Contract.EndContractBlock();
356 _deleteAgent.ProceedEvent.Wait();
358 //If the action targets a local file, add a treehash calculation
359 if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
361 var accountInfo = cloudAction.AccountInfo;
362 var localFile = (FileInfo) cloudAction.LocalFile;
363 if (localFile.Length > accountInfo.BlockSize)
364 cloudAction.TopHash =
365 new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
366 accountInfo.BlockSize,
367 accountInfo.BlockHash, Settings.HashingParallelism).Result
368 .TopHash.ToHashString());
371 cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
376 //The hash for a directory is the empty string
377 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
380 if (cloudAction is CloudDeleteAction)
381 _deleteAgent.Post((CloudDeleteAction)cloudAction);
383 _agent.Post(cloudAction);
387 public IEnumerable<CloudAction> GetEnumerable()
389 return _agent.GetEnumerable();
392 public Task GetDeleteAwaiter()
394 return _deleteAgent.ProceedEvent.WaitAsync();
396 public CancellationToken CancellationToken
398 get { return _agent.CancellationToken; }
401 private static FileAgent GetFileAgent(AccountInfo accountInfo)
403 return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
408 private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
410 if (accountInfo==null)
411 throw new ArgumentNullException("accountInfo");
413 throw new ArgumentNullException("action");
414 if (action.CloudFile==null)
415 throw new ArgumentException("CloudFile","action");
416 if (action.LocalFile==null)
417 throw new ArgumentException("LocalFile","action");
418 if (action.OldLocalFile==null)
419 throw new ArgumentException("OldLocalFile","action");
420 if (action.OldCloudFile==null)
421 throw new ArgumentException("OldCloudFile","action");
422 Contract.EndContractBlock();
425 var newFilePath = action.LocalFile.FullName;
427 //How do we handle concurrent renames and deletes/uploads/downloads?
428 //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
429 // This should never happen as the network agent executes only one action at a time
430 //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
431 // the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the
432 // same name will fail.
433 // This should never happen as the network agent executes only one action at a time.
434 //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
435 // to remove the rename from the queue.
436 // We can probably ignore this case. It will result in an error which should be ignored
439 //The local file is already renamed
440 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
443 var account = action.CloudFile.Account ?? accountInfo.UserName;
444 var container = action.CloudFile.Container;
446 var client = new CloudFilesClient(accountInfo);
447 //TODO: What code is returned when the source file doesn't exist?
448 client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
450 StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
451 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
452 NativeMethods.RaiseChangeNotification(newFilePath);
456 private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
458 if (accountInfo == null)
459 throw new ArgumentNullException("accountInfo");
460 if (cloudFile == null)
461 throw new ArgumentNullException("cloudFile");
462 if (String.IsNullOrWhiteSpace(cloudFile.Account))
463 throw new ArgumentNullException("cloudFile");
464 if (String.IsNullOrWhiteSpace(cloudFile.Container))
465 throw new ArgumentNullException("cloudFile");
466 if (String.IsNullOrWhiteSpace(filePath))
467 throw new ArgumentNullException("filePath");
468 if (!Path.IsPathRooted(filePath))
469 throw new ArgumentException("The filePath must be rooted", "filePath");
470 Contract.EndContractBlock();
473 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
474 var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
476 var url = relativeUrl.ToString();
477 if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
481 //Are we already downloading or uploading the file?
482 using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
487 var client = new CloudFilesClient(accountInfo);
488 var account = cloudFile.Account;
489 var container = cloudFile.Container;
491 if (cloudFile.Content_Type == @"application/directory")
493 if (!Directory.Exists(localPath))
494 Directory.CreateDirectory(localPath);
498 //Retrieve the hashmap from the server
499 var serverHash = await client.GetHashMap(account, container, url);
500 //If it's a small file
501 if (serverHash.Hashes.Count == 1)
502 //Download it in one go
504 DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
505 //Otherwise download it block by block
507 await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
509 if (cloudFile.AllowedTo == "read")
511 var attributes = File.GetAttributes(localPath);
512 File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
516 //Now we can store the object's metadata without worrying about ghost status entries
517 StatusKeeper.StoreInfo(localPath, cloudFile);
522 //Download a small file with a single GET operation
523 private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
526 throw new ArgumentNullException("client");
528 throw new ArgumentNullException("cloudFile");
529 if (relativeUrl == null)
530 throw new ArgumentNullException("relativeUrl");
531 if (String.IsNullOrWhiteSpace(filePath))
532 throw new ArgumentNullException("filePath");
533 if (!Path.IsPathRooted(filePath))
534 throw new ArgumentException("The localPath must be rooted", "filePath");
535 Contract.EndContractBlock();
537 var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
538 //If the file already exists
539 if (File.Exists(localPath))
541 //First check with MD5 as this is a small file
542 var localMD5 = Signature.CalculateMD5(localPath);
543 var cloudHash=serverHash.TopHash.ToHashString();
544 if (localMD5==cloudHash)
546 //Then check with a treehash
547 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
548 var localHash = localTreeHash.TopHash.ToHashString();
549 if (localHash==cloudHash)
552 StatusNotification.Notify(new CloudNotification { Data = cloudFile });
554 var fileAgent = GetFileAgent(accountInfo);
555 //Calculate the relative file path for the new file
556 var relativePath = relativeUrl.RelativeUriToFilePath();
557 //The file will be stored in a temporary location while downloading with an extension .download
558 var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
559 //Make sure the target folder exists. DownloadFileTask will not create the folder
560 var tempFolder = Path.GetDirectoryName(tempPath);
561 if (!Directory.Exists(tempFolder))
562 Directory.CreateDirectory(tempFolder);
564 //Download the object to the temporary location
565 await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
567 //Create the local folder if it doesn't exist (necessary for shared objects)
568 var localFolder = Path.GetDirectoryName(localPath);
569 if (!Directory.Exists(localFolder))
570 Directory.CreateDirectory(localFolder);
571 //And move it to its actual location once downloading is finished
572 if (File.Exists(localPath))
573 File.Replace(tempPath,localPath,null,true);
575 File.Move(tempPath,localPath);
576 //Notify listeners that a local file has changed
577 StatusNotification.NotifyChangedFile(localPath);
582 //Download a file asynchronously using blocks
583 public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
586 throw new ArgumentNullException("client");
587 if (cloudFile == null)
588 throw new ArgumentNullException("cloudFile");
589 if (relativeUrl == null)
590 throw new ArgumentNullException("relativeUrl");
591 if (String.IsNullOrWhiteSpace(filePath))
592 throw new ArgumentNullException("filePath");
593 if (!Path.IsPathRooted(filePath))
594 throw new ArgumentException("The filePath must be rooted", "filePath");
595 if (serverHash == null)
596 throw new ArgumentNullException("serverHash");
597 Contract.EndContractBlock();
599 var fileAgent = GetFileAgent(accountInfo);
600 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
602 //Calculate the relative file path for the new file
603 var relativePath = relativeUrl.RelativeUriToFilePath();
604 var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
608 //Calculate the file's treehash
609 var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
611 //And compare it with the server's hash
612 var upHashes = serverHash.GetHashesAsStrings();
613 var localHashes = treeHash.HashDictionary;
614 for (int i = 0; i < upHashes.Length; i++)
616 //For every non-matching hash
617 var upHash = upHashes[i];
618 if (!localHashes.ContainsKey(upHash))
620 StatusNotification.Notify(new CloudNotification { Data = cloudFile });
622 if (blockUpdater.UseOrphan(i, upHash))
624 Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
627 Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
628 var start = i*serverHash.BlockSize;
629 //To download the last block just pass a null for the end of the range
631 if (i < upHashes.Length - 1 )
632 end= ((i + 1)*serverHash.BlockSize) ;
634 //Download the missing block
635 var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
638 blockUpdater.StoreBlock(i, block);
641 Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
645 //Want to avoid notifications if no changes were made
646 var hasChanges = blockUpdater.HasBlocks;
647 blockUpdater.Commit();
650 //Notify listeners that a local file has changed
651 StatusNotification.NotifyChangedFile(localPath);
653 Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
657 private async Task UploadCloudFile(CloudAction action)
660 throw new ArgumentNullException("action");
661 Contract.EndContractBlock();
665 var accountInfo = action.AccountInfo;
667 var fileInfo = action.LocalFile;
669 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
672 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
673 if (relativePath.StartsWith(FolderConstants.OthersFolder))
675 var parts = relativePath.Split('\\');
676 var accountName = parts[1];
677 var oldName = accountInfo.UserName;
678 var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
679 var nameIndex = absoluteUri.IndexOf(oldName);
680 var root = absoluteUri.Substring(0, nameIndex);
682 accountInfo = new AccountInfo
684 UserName = accountName,
685 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
686 StorageUri = new Uri(root + accountName),
687 BlockHash = accountInfo.BlockHash,
688 BlockSize = accountInfo.BlockSize,
689 Token = accountInfo.Token
694 var fullFileName = fileInfo.GetProperCapitalization();
695 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
697 //Abort if the file is already being uploaded or downloaded
701 var cloudFile = action.CloudFile;
702 var account = cloudFile.Account ?? accountInfo.UserName;
704 var client = new CloudFilesClient(accountInfo);
705 //Even if GetObjectInfo times out, we can proceed with the upload
706 var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
708 //If this is a read-only file, do not upload changes
709 if (info.AllowedTo == "read")
712 //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
713 if (fileInfo is DirectoryInfo)
715 //If the directory doesn't exist the Hash property will be empty
716 if (String.IsNullOrWhiteSpace(info.Hash))
717 //Go on and create the directory
718 await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
723 var cloudHash = info.Hash.ToLower();
725 var hash = action.LocalHash.Value;
726 var topHash = action.TopHash.Value;
728 //If the file hashes match, abort the upload
729 if (hash == cloudHash || topHash == cloudHash)
731 //but store any metadata changes
732 StatusKeeper.StoreInfo(fullFileName, info);
733 Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
738 //Mark the file as modified while we upload it
739 StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
742 //Upload even small files using the Hashmap. The server may already contain
745 //First, calculate the tree hash
746 var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
747 accountInfo.BlockHash, 2);
749 await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
751 //If everything succeeds, change the file and overlay status to normal
752 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
754 //Notify the Shell to update the overlays
755 NativeMethods.RaiseChangeNotification(fullFileName);
756 StatusNotification.NotifyChangedFile(fullFileName);
758 catch (AggregateException ex)
760 var exc = ex.InnerException as WebException;
762 throw ex.InnerException;
763 if (HandleUploadWebException(action, exc))
767 catch (WebException ex)
769 if (HandleUploadWebException(action, ex))
775 Log.Error("Unexpected error while uploading file", ex);
783 private bool HandleUploadWebException(CloudAction action, WebException exc)
785 var response = exc.Response as HttpWebResponse;
786 if (response == null)
788 if (response.StatusCode == HttpStatusCode.Unauthorized)
790 Log.Error("Not allowed to upload file", exc);
791 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
792 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
793 StatusNotification.NotifyChange(message, TraceLevel.Warning);
799 public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
801 if (accountInfo == null)
802 throw new ArgumentNullException("accountInfo");
804 throw new ArgumentNullException("cloudFile");
805 if (fileInfo == null)
806 throw new ArgumentNullException("fileInfo");
807 if (String.IsNullOrWhiteSpace(url))
808 throw new ArgumentNullException(url);
810 throw new ArgumentNullException("treeHash");
811 if (String.IsNullOrWhiteSpace(cloudFile.Container) )
812 throw new ArgumentException("Invalid container","cloudFile");
813 Contract.EndContractBlock();
815 var fullFileName = fileInfo.GetProperCapitalization();
817 var account = cloudFile.Account ?? accountInfo.UserName;
818 var container = cloudFile.Container ;
820 var client = new CloudFilesClient(accountInfo);
821 //Send the hashmap to the server
822 var missingHashes = await client.PutHashMap(account, container, url, treeHash);
823 //If the server returns no missing hashes, we are done
824 while (missingHashes.Count > 0)
827 var buffer = new byte[accountInfo.BlockSize];
828 foreach (var missingHash in missingHashes)
830 //Find the proper block
831 var blockIndex = treeHash.HashDictionary[missingHash];
832 var offset = blockIndex*accountInfo.BlockSize;
834 var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
838 //And upload the block
839 await client.PostBlock(account, container, buffer, 0, read);
840 Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
842 catch (Exception exc)
844 Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
849 //Repeat until there are no more missing hashes
850 missingHashes = await client.PutHashMap(account, container, url, treeHash);
855 public void AddAccount(AccountInfo accountInfo)
857 if (!_accounts.Contains(accountInfo))
858 _accounts.Add(accountInfo);