1 // -----------------------------------------------------------------------
2 // <copyright file="NetworkAgent.cs" company="GRNET">
3 // Copyright 2011-2012 GRNET S.A. All rights reserved.
5 // Redistribution and use in source and binary forms, with or
6 // without modification, are permitted provided that the following
9 // 1. Redistributions of source code must retain the above
10 // copyright notice, this list of conditions and the following
13 // 2. Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following
15 // disclaimer in the documentation and/or other materials
16 // provided with the distribution.
18 // THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 // USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 // POSSIBILITY OF SUCH DAMAGE.
31 // The views and conclusions contained in the software and
32 // documentation are those of the authors and should not be
33 // interpreted as representing official policies, either expressed
34 // or implied, of GRNET S.A.
36 // -----------------------------------------------------------------------
38 //TODO: Now there is a UUID tag. This can be used for renames/moves
42 using System.Collections.Concurrent;
43 using System.Collections.Generic;
44 using System.ComponentModel.Composition;
45 using System.Diagnostics;
46 using System.Diagnostics.Contracts;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Threading.Tasks.Dataflow;
53 using Castle.ActiveRecord;
54 using Pithos.Interfaces;
58 namespace Pithos.Core.Agents
60 //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
62 public class NetworkAgent
64 private Agent<CloudAction> _agent;
66 [System.ComponentModel.Composition.Import]
67 private DeleteAgent _deleteAgent=new DeleteAgent();
69 [System.ComponentModel.Composition.Import]
70 public IStatusKeeper StatusKeeper { get; set; }
72 public IStatusNotification StatusNotification { get; set; }
74 private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
76 private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
78 [System.ComponentModel.Composition.Import]
79 public IPithosSettings Settings { get; set; }
81 private bool _firstPoll = true;
83 //The Sync Event signals a manual synchronisation
84 private readonly AsyncManualResetEvent _syncEvent=new AsyncManualResetEvent();
86 private ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();
91 _agent = Agent<CloudAction>.Start(inbox =>
96 _deleteAgent.PauseEvent.Wait();
97 var message = inbox.Receive();
98 var process=message.Then(Process,inbox.CancellationToken);
99 inbox.LoopAsync(process, loop);
106 private async Task Process(CloudAction action)
109 throw new ArgumentNullException("action");
110 if (action.AccountInfo==null)
111 throw new ArgumentException("The action.AccountInfo is empty","action");
112 Contract.EndContractBlock();
114 UpdateStatus(PithosStatus.Syncing);
115 var accountInfo = action.AccountInfo;
117 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
119 Log.InfoFormat("[ACTION] Start Processing {0}", action);
121 var cloudFile = action.CloudFile;
122 var downloadPath = action.GetDownloadPath();
126 if (action.Action == CloudActionType.DeleteCloud)
128 //Redirect deletes to the delete agent
129 _deleteAgent.Post((CloudDeleteAction)action);
131 if (_deleteAgent.IsDeletedFile(action))
133 //Clear the status of already deleted files to avoid reprocessing
134 if (action.LocalFile != null)
135 this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
139 switch (action.Action)
141 case CloudActionType.UploadUnconditional:
142 //Abort if the file was deleted before we reached this point
143 await UploadCloudFile(action);
145 case CloudActionType.DownloadUnconditional:
146 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
148 case CloudActionType.RenameCloud:
149 var moveAction = (CloudMoveAction)action;
150 RenameCloudFile(accountInfo, moveAction);
152 case CloudActionType.MustSynch:
153 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
155 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
159 await SyncFiles(accountInfo, action);
164 Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
165 action.CloudFile.Name);
167 catch (WebException exc)
169 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
171 catch (OperationCanceledException)
175 catch (DirectoryNotFoundException)
177 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
178 action.Action, action.LocalFile, action.CloudFile);
179 //Post a delete action for the missing file
180 Post(new CloudDeleteAction(action));
182 catch (FileNotFoundException)
184 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
185 action.Action, action.LocalFile, action.CloudFile);
186 //Post a delete action for the missing file
187 Post(new CloudDeleteAction(action));
189 catch (Exception exc)
191 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
192 action.Action, action.LocalFile, action.CloudFile, exc);
198 UpdateStatus(PithosStatus.InSynch);
203 private void UpdateStatus(PithosStatus status)
205 StatusKeeper.SetPithosStatus(status);
206 StatusNotification.Notify(new Notification());
210 private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
212 if (accountInfo == null)
213 throw new ArgumentNullException("accountInfo");
215 throw new ArgumentNullException("action");
216 if (action.LocalFile==null)
217 throw new ArgumentException("The action's local file is not specified","action");
218 if (!Path.IsPathRooted(action.LocalFile.FullName))
219 throw new ArgumentException("The action's local file path must be absolute","action");
220 if (action.CloudFile== null)
221 throw new ArgumentException("The action's cloud file is not specified", "action");
222 Contract.EndContractBlock();
224 var localFile = action.LocalFile;
225 var cloudFile = action.CloudFile;
226 var downloadPath=action.LocalFile.GetProperCapitalization();
228 var cloudHash = cloudFile.Hash.ToLower();
229 var localHash = action.LocalHash.Value.ToLower();
230 var topHash = action.TopHash.Value.ToLower();
232 //Not enough to compare only the local hashes, also have to compare the tophashes
234 //If any of the hashes match, we are done
235 if ((cloudHash == localHash || cloudHash == topHash))
237 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
241 //The hashes DON'T match. We need to sync
242 var lastLocalTime = localFile.LastWriteTime;
243 var lastUpTime = cloudFile.Last_Modified;
245 //If the local file is newer upload it
246 if (lastUpTime <= lastLocalTime)
248 //It probably means it was changed while the app was down
249 UploadCloudFile(action);
253 //It the cloud file has a later date, it was modified by another user or computer.
254 //We need to check the local file's status
255 var status = StatusKeeper.GetFileStatus(downloadPath);
258 case FileStatus.Unchanged:
259 //If the local file's status is Unchanged, we can go on and download the newer cloud file
260 await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
262 case FileStatus.Modified:
263 //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
264 //We can't ensure that a file modified online since the last time will appear as Modified, unless we
265 //index all files before we start listening.
266 case FileStatus.Created:
267 //If the local file is Created, it means that the local and cloud files aren't related,
268 // yet they have the same name.
270 //In both cases we must mark the file as in conflict
271 ReportConflict(downloadPath);
274 //Other cases should never occur. Mark them as Conflict as well but log a warning
275 ReportConflict(downloadPath);
276 Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
277 downloadPath, action.CloudFile.Name);
283 private void ReportConflict(string downloadPath)
285 if (String.IsNullOrWhiteSpace(downloadPath))
286 throw new ArgumentNullException("downloadPath");
287 Contract.EndContractBlock();
289 StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
290 UpdateStatus(PithosStatus.HasConflicts);
291 var message = String.Format("Conflict detected for file {0}", downloadPath);
293 StatusNotification.NotifyChange(message, TraceLevel.Warning);
296 public void Post(CloudAction cloudAction)
298 if (cloudAction == null)
299 throw new ArgumentNullException("cloudAction");
300 if (cloudAction.AccountInfo==null)
301 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
302 Contract.EndContractBlock();
304 _deleteAgent.PauseEvent.Wait();
306 //If the action targets a local file, add a treehash calculation
307 if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
309 var accountInfo = cloudAction.AccountInfo;
310 var localFile = (FileInfo) cloudAction.LocalFile;
311 if (localFile.Length > accountInfo.BlockSize)
312 cloudAction.TopHash =
313 new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
314 accountInfo.BlockSize,
315 accountInfo.BlockHash, Settings.HashingParallelism).Result
316 .TopHash.ToHashString());
319 cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
324 //The hash for a directory is the empty string
325 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
328 if (cloudAction is CloudDeleteAction)
329 _deleteAgent.Post((CloudDeleteAction)cloudAction);
331 _agent.Post(cloudAction);
336 /// Start a manual synchronization
338 public void SynchNow()
343 //Remote files are polled periodically. Any changes are processed
344 public async Task PollRemoteFiles(DateTime? since = null)
346 UpdateStatus(PithosStatus.Syncing);
347 StatusNotification.Notify(new PollNotification());
349 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
351 //If this poll fails, we will retry with the same since value
352 var nextSince = since;
355 //Next time we will check for all changes since the current check minus 1 second
356 //This is done to ensure there are no discrepancies due to clock differences
357 var current = DateTime.Now.AddSeconds(-1);
359 var tasks = from accountInfo in _accounts
360 select ProcessAccountFiles(accountInfo, since);
362 await TaskEx.WhenAll(tasks.ToList());
365 //Reschedule the poll with the current timestamp as a "since" value
370 Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
371 //In case of failure retry with the same "since" value
374 UpdateStatus(PithosStatus.InSynch);
375 //Wait for the polling interval to pass or the Sync event to be signalled
376 nextSince = await WaitForScheduledOrManualPoll(nextSince);
378 PollRemoteFiles(nextSince);
384 /// Wait for the polling period to expire or a manual sync request
386 /// <param name="since"></param>
387 /// <returns></returns>
388 private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
390 var sync=_syncEvent.WaitAsync();
391 var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
392 var signaledTask = await TaskEx.WhenAny(sync, wait);
394 //If polling is signalled by SynchNow, ignore the since tag
395 if (signaledTask is Task<bool>)
400 public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
402 if (accountInfo==null)
403 throw new ArgumentNullException("accountInfo");
404 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
405 throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
406 Contract.EndContractBlock();
409 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
411 await _deleteAgent.PauseEvent.WaitAsync();
413 Log.Info("Scheduled");
414 var client = new CloudFilesClient(accountInfo);
416 var containers = client.ListContainers(accountInfo.UserName);
419 CreateContainerFolders(accountInfo, containers);
423 await _deleteAgent.PauseEvent.WaitAsync();
424 //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
425 //than delete a file that was created while we were executing the poll
426 var pollTime = DateTime.Now;
428 //Get the list of server objects changed since the last check
429 //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
430 var listObjects = (from container in containers
431 select Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
432 client.ListObjects(accountInfo.UserName,container.Name, since),container.Name)).ToList();
434 var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => client.ListSharedObjects(since), "shared");
435 listObjects.Add(listShared);
436 var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
438 using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
440 var dict = listTasks.ToDictionary(t => t.AsyncState);
442 //Get all non-trash objects. Remember, the container name is stored in AsyncState
443 var remoteObjects = from objectList in listTasks
444 where (string) objectList.AsyncState != "trash"
445 from obj in objectList.Result
448 var trashObjects = dict["trash"].Result;
449 var sharedObjects = dict["shared"].Result;
451 //Items with the same name, hash may be both in the container and the trash
452 //Don't delete items that exist in the container
453 var realTrash = from trash in trashObjects
456 info => info.Name == trash.Name && info.Hash == trash.Hash)
458 ProcessTrashedFiles(accountInfo, realTrash);
460 var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
462 where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
463 !name.StartsWith(FolderConstants.CacheFolder + "/",
464 StringComparison.InvariantCultureIgnoreCase)
465 select info).ToList();
467 var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
469 ProcessDeletedFiles(accountInfo, differencer.Deleted, pollTime);
471 //Create a list of actions from the remote files
472 var allActions = ChangesToActions(accountInfo, differencer.Changed)
474 CreatesToActions(accountInfo,differencer.Created));
476 //And remove those that are already being processed by the agent
477 var distinctActions = allActions
478 .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
481 //Queue all the actions
482 foreach (var message in distinctActions)
487 Log.Info("[LISTENER] End Processing");
492 Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
496 Log.Info("[LISTENER] Finished");
501 AccountsDifferencer _differencer= new AccountsDifferencer();
504 /// Deletes local files that are not found in the list of cloud files
506 /// <param name="accountInfo"></param>
507 /// <param name="cloudFiles"></param>
508 /// <param name="pollTime"></param>
509 private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
511 if (accountInfo == null)
512 throw new ArgumentNullException("accountInfo");
513 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
514 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
515 if (cloudFiles == null)
516 throw new ArgumentNullException("cloudFiles");
517 Contract.EndContractBlock();
522 //Only consider files that are not being modified, ie they are in the Unchanged state
523 var deleteCandidates = FileState.Queryable.Where(state =>
524 state.FilePath.StartsWith(accountInfo.AccountPath)
525 && state.FileStatus == FileStatus.Unchanged).ToList();
528 //TODO: filesToDelete must take into account the Others container
529 var filesToDelete = (from deleteCandidate in deleteCandidates
530 let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
531 let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
533 !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
534 select localFile).ToList();
538 //Set the status of missing files to Conflict
539 foreach (var item in filesToDelete)
541 //Try to acquire a gate on the file, to take into account files that have been dequeued
542 //and are being processed
543 using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
547 StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
550 UpdateStatus(PithosStatus.HasConflicts);
551 StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
552 StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info);
556 var deletedFiles = new List<FileSystemInfo>();
557 foreach (var objectInfo in cloudFiles)
559 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
560 var item = GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
563 if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
565 item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
570 _lastSeen.TryRemove(item.FullName, out lastDate);
571 deletedFiles.Add(item);
573 StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted);
575 StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info);
580 private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
582 var containerPaths = from container in containers
583 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
584 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
585 select containerPath;
587 foreach (var path in containerPaths)
589 Directory.CreateDirectory(path);
593 //Creates an appropriate action for each server file
594 private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> changes)
597 throw new ArgumentNullException();
598 Contract.EndContractBlock();
599 var fileAgent = GetFileAgent(accountInfo);
601 //In order to avoid multiple iterations over the files, we iterate only once
602 //over the remote files
603 foreach (var objectInfo in changes)
605 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
606 //and remove any matching objects from the list, adding them to the commonObjects list
607 if (fileAgent.Exists(relativePath))
609 //If a directory object already exists, we don't need to perform any other action
610 var localFile = fileAgent.GetFileSystemInfo(relativePath);
611 if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
613 using (new SessionScope(FlushAction.Never))
615 var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
616 _lastSeen[localFile.FullName] = DateTime.Now;
617 //Common files should be checked on a per-case basis to detect differences, which is newer
619 yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
620 localFile, objectInfo, state, accountInfo.BlockSize,
621 accountInfo.BlockHash);
626 //Remote files should be downloaded
627 yield return new CloudDownloadAction(accountInfo,objectInfo);
632 private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> creates)
635 throw new ArgumentNullException();
636 Contract.EndContractBlock();
637 var fileAgent = GetFileAgent(accountInfo);
639 //In order to avoid multiple iterations over the files, we iterate only once
640 //over the remote files
641 foreach (var objectInfo in creates)
643 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
644 //and remove any matching objects from the list, adding them to the commonObjects list
645 if (fileAgent.Exists(relativePath))
647 //If the object already exists, we probably have a conflict
648 //If a directory object already exists, we don't need to perform any other action
649 var localFile = fileAgent.GetFileSystemInfo(relativePath);
650 StatusKeeper.SetFileState(localFile.FullName,FileStatus.Conflict,FileOverlayStatus.Conflict);
654 //Remote files should be downloaded
655 yield return new CloudDownloadAction(accountInfo,objectInfo);
661 private static FileAgent GetFileAgent(AccountInfo accountInfo)
663 return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
666 private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
668 var fileAgent = GetFileAgent(accountInfo);
669 foreach (var trashObject in trashObjects)
671 var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
672 //HACK: Assume only the "pithos" container is used. Must find out what happens when
673 //deleting a file from a different container
674 var relativePath = Path.Combine("pithos", barePath);
675 fileAgent.Delete(relativePath);
680 private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
682 if (accountInfo==null)
683 throw new ArgumentNullException("accountInfo");
685 throw new ArgumentNullException("action");
686 if (action.CloudFile==null)
687 throw new ArgumentException("CloudFile","action");
688 if (action.LocalFile==null)
689 throw new ArgumentException("LocalFile","action");
690 if (action.OldLocalFile==null)
691 throw new ArgumentException("OldLocalFile","action");
692 if (action.OldCloudFile==null)
693 throw new ArgumentException("OldCloudFile","action");
694 Contract.EndContractBlock();
697 var newFilePath = action.LocalFile.FullName;
699 //How do we handle concurrent renames and deletes/uploads/downloads?
700 //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
701 // This should never happen as the network agent executes only one action at a time
702 //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
703 // the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the
704 // same name will fail.
705 // This should never happen as the network agent executes only one action at a time.
706 //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
707 // to remove the rename from the queue.
708 // We can probably ignore this case. It will result in an error which should be ignored
711 //The local file is already renamed
712 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
715 var account = action.CloudFile.Account ?? accountInfo.UserName;
716 var container = action.CloudFile.Container;
718 var client = new CloudFilesClient(accountInfo);
719 //TODO: What code is returned when the source file doesn't exist?
720 client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
722 StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
723 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
724 NativeMethods.RaiseChangeNotification(newFilePath);
728 private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
730 if (accountInfo == null)
731 throw new ArgumentNullException("accountInfo");
732 if (cloudFile == null)
733 throw new ArgumentNullException("cloudFile");
734 if (String.IsNullOrWhiteSpace(cloudFile.Account))
735 throw new ArgumentNullException("cloudFile");
736 if (String.IsNullOrWhiteSpace(cloudFile.Container))
737 throw new ArgumentNullException("cloudFile");
738 if (String.IsNullOrWhiteSpace(filePath))
739 throw new ArgumentNullException("filePath");
740 if (!Path.IsPathRooted(filePath))
741 throw new ArgumentException("The filePath must be rooted", "filePath");
742 Contract.EndContractBlock();
745 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
746 var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
748 var url = relativeUrl.ToString();
749 if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
753 //Are we already downloading or uploading the file?
754 using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
759 var client = new CloudFilesClient(accountInfo);
760 var account = cloudFile.Account;
761 var container = cloudFile.Container;
763 if (cloudFile.Content_Type == @"application/directory")
765 if (!Directory.Exists(localPath))
766 Directory.CreateDirectory(localPath);
770 //Retrieve the hashmap from the server
771 var serverHash = await client.GetHashMap(account, container, url);
772 //If it's a small file
773 if (serverHash.Hashes.Count == 1)
774 //Download it in one go
776 DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
777 //Otherwise download it block by block
779 await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
781 if (cloudFile.AllowedTo == "read")
783 var attributes = File.GetAttributes(localPath);
784 File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
788 //Now we can store the object's metadata without worrying about ghost status entries
789 StatusKeeper.StoreInfo(localPath, cloudFile);
794 //Download a small file with a single GET operation
795 private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
798 throw new ArgumentNullException("client");
800 throw new ArgumentNullException("cloudFile");
801 if (relativeUrl == null)
802 throw new ArgumentNullException("relativeUrl");
803 if (String.IsNullOrWhiteSpace(filePath))
804 throw new ArgumentNullException("filePath");
805 if (!Path.IsPathRooted(filePath))
806 throw new ArgumentException("The localPath must be rooted", "filePath");
807 Contract.EndContractBlock();
809 var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
810 //If the file already exists
811 if (File.Exists(localPath))
813 //First check with MD5 as this is a small file
814 var localMD5 = Signature.CalculateMD5(localPath);
815 var cloudHash=serverHash.TopHash.ToHashString();
816 if (localMD5==cloudHash)
818 //Then check with a treehash
819 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
820 var localHash = localTreeHash.TopHash.ToHashString();
821 if (localHash==cloudHash)
824 StatusNotification.Notify(new CloudNotification { Data = cloudFile });
826 var fileAgent = GetFileAgent(accountInfo);
827 //Calculate the relative file path for the new file
828 var relativePath = relativeUrl.RelativeUriToFilePath();
829 //The file will be stored in a temporary location while downloading with an extension .download
830 var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
831 //Make sure the target folder exists. DownloadFileTask will not create the folder
832 var tempFolder = Path.GetDirectoryName(tempPath);
833 if (!Directory.Exists(tempFolder))
834 Directory.CreateDirectory(tempFolder);
836 //Download the object to the temporary location
837 await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
839 //Create the local folder if it doesn't exist (necessary for shared objects)
840 var localFolder = Path.GetDirectoryName(localPath);
841 if (!Directory.Exists(localFolder))
842 Directory.CreateDirectory(localFolder);
843 //And move it to its actual location once downloading is finished
844 if (File.Exists(localPath))
845 File.Replace(tempPath,localPath,null,true);
847 File.Move(tempPath,localPath);
848 //Notify listeners that a local file has changed
849 StatusNotification.NotifyChangedFile(localPath);
854 //Download a file asynchronously using blocks
855 public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
858 throw new ArgumentNullException("client");
859 if (cloudFile == null)
860 throw new ArgumentNullException("cloudFile");
861 if (relativeUrl == null)
862 throw new ArgumentNullException("relativeUrl");
863 if (String.IsNullOrWhiteSpace(filePath))
864 throw new ArgumentNullException("filePath");
865 if (!Path.IsPathRooted(filePath))
866 throw new ArgumentException("The filePath must be rooted", "filePath");
867 if (serverHash == null)
868 throw new ArgumentNullException("serverHash");
869 Contract.EndContractBlock();
871 var fileAgent = GetFileAgent(accountInfo);
872 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
874 //Calculate the relative file path for the new file
875 var relativePath = relativeUrl.RelativeUriToFilePath();
876 var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
880 //Calculate the file's treehash
881 var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
883 //And compare it with the server's hash
884 var upHashes = serverHash.GetHashesAsStrings();
885 var localHashes = treeHash.HashDictionary;
886 for (int i = 0; i < upHashes.Length; i++)
888 //For every non-matching hash
889 var upHash = upHashes[i];
890 if (!localHashes.ContainsKey(upHash))
892 StatusNotification.Notify(new CloudNotification { Data = cloudFile });
894 if (blockUpdater.UseOrphan(i, upHash))
896 Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
899 Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
900 var start = i*serverHash.BlockSize;
901 //To download the last block just pass a null for the end of the range
903 if (i < upHashes.Length - 1 )
904 end= ((i + 1)*serverHash.BlockSize) ;
906 //Download the missing block
907 var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
910 blockUpdater.StoreBlock(i, block);
913 Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
917 //Want to avoid notifications if no changes were made
918 var hasChanges = blockUpdater.HasBlocks;
919 blockUpdater.Commit();
922 //Notify listeners that a local file has changed
923 StatusNotification.NotifyChangedFile(localPath);
925 Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
929 private async Task UploadCloudFile(CloudAction action)
932 throw new ArgumentNullException("action");
933 Contract.EndContractBlock();
937 var accountInfo = action.AccountInfo;
939 var fileInfo = action.LocalFile;
941 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
944 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
945 if (relativePath.StartsWith(FolderConstants.OthersFolder))
947 var parts = relativePath.Split('\\');
948 var accountName = parts[1];
949 var oldName = accountInfo.UserName;
950 var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
951 var nameIndex = absoluteUri.IndexOf(oldName);
952 var root = absoluteUri.Substring(0, nameIndex);
954 accountInfo = new AccountInfo
956 UserName = accountName,
957 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
958 StorageUri = new Uri(root + accountName),
959 BlockHash = accountInfo.BlockHash,
960 BlockSize = accountInfo.BlockSize,
961 Token = accountInfo.Token
966 var fullFileName = fileInfo.GetProperCapitalization();
967 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
969 //Abort if the file is already being uploaded or downloaded
973 var cloudFile = action.CloudFile;
974 var account = cloudFile.Account ?? accountInfo.UserName;
976 var client = new CloudFilesClient(accountInfo);
977 //Even if GetObjectInfo times out, we can proceed with the upload
978 var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
980 //If this is a read-only file, do not upload changes
981 if (info.AllowedTo == "read")
984 //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
985 if (fileInfo is DirectoryInfo)
987 //If the directory doesn't exist the Hash property will be empty
988 if (String.IsNullOrWhiteSpace(info.Hash))
989 //Go on and create the directory
990 await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
995 var cloudHash = info.Hash.ToLower();
997 var hash = action.LocalHash.Value;
998 var topHash = action.TopHash.Value;
1000 //If the file hashes match, abort the upload
1001 if (hash == cloudHash || topHash == cloudHash)
1003 //but store any metadata changes
1004 StatusKeeper.StoreInfo(fullFileName, info);
1005 Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1010 //Mark the file as modified while we upload it
1011 StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1012 //And then upload it
1014 //Upload even small files using the Hashmap. The server may already contain
1015 //the relevant block
1017 //First, calculate the tree hash
1018 var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1019 accountInfo.BlockHash, 2);
1021 await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1023 //If everything succeeds, change the file and overlay status to normal
1024 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1026 //Notify the Shell to update the overlays
1027 NativeMethods.RaiseChangeNotification(fullFileName);
1028 StatusNotification.NotifyChangedFile(fullFileName);
1030 catch (AggregateException ex)
1032 var exc = ex.InnerException as WebException;
1034 throw ex.InnerException;
1035 if (HandleUploadWebException(action, exc))
1039 catch (WebException ex)
1041 if (HandleUploadWebException(action, ex))
1045 catch (Exception ex)
1047 Log.Error("Unexpected error while uploading file", ex);
1055 private bool HandleUploadWebException(CloudAction action, WebException exc)
1057 var response = exc.Response as HttpWebResponse;
1058 if (response == null)
1060 if (response.StatusCode == HttpStatusCode.Unauthorized)
1062 Log.Error("Not allowed to upload file", exc);
1063 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1064 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1065 StatusNotification.NotifyChange(message, TraceLevel.Warning);
1071 public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1073 if (accountInfo == null)
1074 throw new ArgumentNullException("accountInfo");
1075 if (cloudFile==null)
1076 throw new ArgumentNullException("cloudFile");
1077 if (fileInfo == null)
1078 throw new ArgumentNullException("fileInfo");
1079 if (String.IsNullOrWhiteSpace(url))
1080 throw new ArgumentNullException(url);
1082 throw new ArgumentNullException("treeHash");
1083 if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1084 throw new ArgumentException("Invalid container","cloudFile");
1085 Contract.EndContractBlock();
1087 var fullFileName = fileInfo.GetProperCapitalization();
1089 var account = cloudFile.Account ?? accountInfo.UserName;
1090 var container = cloudFile.Container ;
1092 var client = new CloudFilesClient(accountInfo);
1093 //Send the hashmap to the server
1094 var missingHashes = await client.PutHashMap(account, container, url, treeHash);
1095 //If the server returns no missing hashes, we are done
1096 while (missingHashes.Count > 0)
1099 var buffer = new byte[accountInfo.BlockSize];
1100 foreach (var missingHash in missingHashes)
1102 //Find the proper block
1103 var blockIndex = treeHash.HashDictionary[missingHash];
1104 var offset = blockIndex*accountInfo.BlockSize;
1106 var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1110 //And upload the block
1111 await client.PostBlock(account, container, buffer, 0, read);
1112 Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1114 catch (Exception exc)
1116 Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1121 //Repeat until there are no more missing hashes
1122 missingHashes = await client.PutHashMap(account, container, url, treeHash);
1127 public void AddAccount(AccountInfo accountInfo)
1129 if (!_accounts.Contains(accountInfo))
1130 _accounts.Add(accountInfo);