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 // -----------------------------------------------------------------------
39 using System.Collections.Concurrent;
40 using System.Collections.Generic;
41 using System.ComponentModel.Composition;
42 using System.Diagnostics;
43 using System.Diagnostics.Contracts;
47 using System.Threading;
48 using System.Threading.Tasks;
49 using System.Threading.Tasks.Dataflow;
50 using Castle.ActiveRecord;
51 using Pithos.Interfaces;
55 namespace Pithos.Core.Agents
57 //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
59 public class NetworkAgent
61 private Agent<CloudAction> _agent;
63 //A separate agent is used to execute delete actions immediatelly;
64 private ActionBlock<CloudDeleteAction> _deleteAgent;
65 readonly ConcurrentDictionary<string,DateTime> _deletedFiles=new ConcurrentDictionary<string, DateTime>();
68 private readonly ManualResetEventSlim _pauseAgent = new ManualResetEventSlim(true);
70 [System.ComponentModel.Composition.Import]
71 public IStatusKeeper StatusKeeper { get; set; }
73 public IStatusNotification StatusNotification { get; set; }
75 private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
77 private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
79 [System.ComponentModel.Composition.Import]
80 public IPithosSettings Settings { get; set; }
82 private bool _firstPoll = true;
83 private TaskCompletionSource<bool> _tcs;
84 private ConcurrentDictionary<string,DateTime> _lastSeen=new ConcurrentDictionary<string, DateTime>();
89 _agent = Agent<CloudAction>.Start(inbox =>
95 var message = inbox.Receive();
96 var process=message.Then(Process,inbox.CancellationToken);
97 inbox.LoopAsync(process, loop);
102 _deleteAgent = new ActionBlock<CloudDeleteAction>(message =>ProcessDelete(message),new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism=4});
107 var message = inbox.Receive();
108 var process = message.Then(ProcessDelete,inbox.CancellationToken);
109 inbox.LoopAsync(process, loop);
116 private async Task Process(CloudAction action)
119 throw new ArgumentNullException("action");
120 if (action.AccountInfo==null)
121 throw new ArgumentException("The action.AccountInfo is empty","action");
122 Contract.EndContractBlock();
124 UpdateStatus(PithosStatus.Syncing);
125 var accountInfo = action.AccountInfo;
127 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
129 Log.InfoFormat("[ACTION] Start Processing {0}", action);
131 var cloudFile = action.CloudFile;
132 var downloadPath = action.GetDownloadPath();
136 if (action.Action == CloudActionType.DeleteCloud)
138 //Redirect deletes to the delete agent
139 _deleteAgent.Post((CloudDeleteAction)action);
141 if (IsDeletedFile(action))
143 //Clear the status of already deleted files to avoid reprocessing
144 if (action.LocalFile != null)
145 this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
149 switch (action.Action)
151 case CloudActionType.UploadUnconditional:
152 //Abort if the file was deleted before we reached this point
153 await UploadCloudFile(action);
155 case CloudActionType.DownloadUnconditional:
156 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
158 case CloudActionType.RenameCloud:
159 var moveAction = (CloudMoveAction)action;
160 RenameCloudFile(accountInfo, moveAction);
162 case CloudActionType.MustSynch:
163 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
165 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
169 await SyncFiles(accountInfo, action);
174 Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
175 action.CloudFile.Name);
177 catch (WebException exc)
179 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
181 catch (OperationCanceledException)
185 catch (DirectoryNotFoundException)
187 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
188 action.Action, action.LocalFile, action.CloudFile);
189 //Post a delete action for the missing file
190 Post(new CloudDeleteAction(action));
192 catch (FileNotFoundException)
194 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
195 action.Action, action.LocalFile, action.CloudFile);
196 //Post a delete action for the missing file
197 Post(new CloudDeleteAction(action));
199 catch (Exception exc)
201 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
202 action.Action, action.LocalFile, action.CloudFile, exc);
208 UpdateStatus(PithosStatus.InSynch);
213 private void UpdateStatus(PithosStatus status)
215 StatusKeeper.SetPithosStatus(status);
216 StatusNotification.Notify(new Notification());
220 /// Processes cloud delete actions
222 /// <param name="action">The delete action to execute</param>
223 /// <returns></returns>
225 /// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download
226 /// operations that may be in progress.
228 /// A separate agent is used to process deletes because the main agent may be busy with a long operation.
231 private async Task ProcessDelete(CloudDeleteAction action)
234 throw new ArgumentNullException("action");
235 if (action.AccountInfo==null)
236 throw new ArgumentException("The action.AccountInfo is empty","action");
237 Contract.EndContractBlock();
239 var accountInfo = action.AccountInfo;
241 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
243 Log.InfoFormat("[ACTION] Start Processing {0}", action);
245 var cloudFile = action.CloudFile;
249 //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
251 using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
254 //Add the file URL to the deleted files list
255 var key = GetFileKey(action.CloudFile);
256 _deletedFiles[key] = DateTime.Now;
259 // and then delete the file from the server
260 DeleteCloudFile(accountInfo, cloudFile);
262 Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
263 action.CloudFile.Name);
266 catch (WebException exc)
268 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
270 catch (OperationCanceledException)
274 catch (DirectoryNotFoundException)
276 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
277 action.Action, action.LocalFile, action.CloudFile);
278 //Repost a delete action for the missing file
279 _deleteAgent.Post(action);
281 catch (FileNotFoundException)
283 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
284 action.Action, action.LocalFile, action.CloudFile);
285 //Post a delete action for the missing file
286 _deleteAgent.Post(action);
288 catch (Exception exc)
290 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
291 action.Action, action.LocalFile, action.CloudFile, exc);
293 _deleteAgent.Post(action);
297 //Set the event when all delete actions are processed
298 if (_deleteAgent.InputCount == 0)
305 private static string GetFileKey(ObjectInfo info)
307 var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
311 private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
313 if (accountInfo == null)
314 throw new ArgumentNullException("accountInfo");
316 throw new ArgumentNullException("action");
317 if (action.LocalFile==null)
318 throw new ArgumentException("The action's local file is not specified","action");
319 if (!Path.IsPathRooted(action.LocalFile.FullName))
320 throw new ArgumentException("The action's local file path must be absolute","action");
321 if (action.CloudFile== null)
322 throw new ArgumentException("The action's cloud file is not specified", "action");
323 Contract.EndContractBlock();
325 var localFile = action.LocalFile;
326 var cloudFile = action.CloudFile;
327 var downloadPath=action.LocalFile.GetProperCapitalization();
329 var cloudHash = cloudFile.Hash.ToLower();
330 var localHash = action.LocalHash.Value.ToLower();
331 var topHash = action.TopHash.Value.ToLower();
333 //Not enough to compare only the local hashes, also have to compare the tophashes
335 //If any of the hashes match, we are done
336 if ((cloudHash == localHash || cloudHash == topHash))
338 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
342 //The hashes DON'T match. We need to sync
343 var lastLocalTime = localFile.LastWriteTime;
344 var lastUpTime = cloudFile.Last_Modified;
346 //If the local file is newer upload it
347 if (lastUpTime <= lastLocalTime)
349 //It probably means it was changed while the app was down
350 UploadCloudFile(action);
354 //It the cloud file has a later date, it was modified by another user or computer.
355 //We need to check the local file's status
356 var status = StatusKeeper.GetFileStatus(downloadPath);
359 case FileStatus.Unchanged:
360 //If the local file's status is Unchanged, we can go on and download the newer cloud file
361 await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
363 case FileStatus.Modified:
364 //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
365 //We can't ensure that a file modified online since the last time will appear as Modified, unless we
366 //index all files before we start listening.
367 case FileStatus.Created:
368 //If the local file is Created, it means that the local and cloud files aren't related,
369 // yet they have the same name.
371 //In both cases we must mark the file as in conflict
372 ReportConflict(downloadPath);
375 //Other cases should never occur. Mark them as Conflict as well but log a warning
376 ReportConflict(downloadPath);
377 Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
378 downloadPath, action.CloudFile.Name);
384 private void ReportConflict(string downloadPath)
386 if (String.IsNullOrWhiteSpace(downloadPath))
387 throw new ArgumentNullException("downloadPath");
388 Contract.EndContractBlock();
390 StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
391 UpdateStatus(PithosStatus.HasConflicts);
392 var message = String.Format("Conflict detected for file {0}", downloadPath);
394 StatusNotification.NotifyChange(message, TraceLevel.Warning);
397 public void Post(CloudAction cloudAction)
399 if (cloudAction == null)
400 throw new ArgumentNullException("cloudAction");
401 if (cloudAction.AccountInfo==null)
402 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
403 Contract.EndContractBlock();
407 //If the action targets a local file, add a treehash calculation
408 if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
410 var accountInfo = cloudAction.AccountInfo;
411 var localFile = (FileInfo) cloudAction.LocalFile;
412 if (localFile.Length > accountInfo.BlockSize)
413 cloudAction.TopHash =
414 new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
415 accountInfo.BlockSize,
416 accountInfo.BlockHash, Settings.HashingParallelism).Result
417 .TopHash.ToHashString());
420 cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
425 //The hash for a directory is the empty string
426 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
429 if (cloudAction is CloudDeleteAction)
430 _deleteAgent.Post((CloudDeleteAction)cloudAction);
432 _agent.Post(cloudAction);
435 /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
437 public bool Equals(ObjectInfo x, ObjectInfo y)
439 return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
442 public int GetHashCode(ObjectInfo obj)
444 return obj.Name.ToLower().GetHashCode();
448 public void SynchNow()
451 _tcs.TrySetResult(true);
454 //TODO: This may be OK for testing purposes, but we have no guarantee that it will
455 //work properly in production
456 PollRemoteFiles(repeat:false);
460 //Remote files are polled periodically. Any changes are processed
461 public async Task PollRemoteFiles(DateTime? since = null,bool repeat=true)
463 UpdateStatus(PithosStatus.Syncing);
464 StatusNotification.Notify(new PollNotification());
466 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
468 //If this poll fails, we will retry with the same since value
469 var nextSince = since;
472 //Next time we will check for all changes since the current check minus 1 second
473 //This is done to ensure there are no discrepancies due to clock differences
474 DateTime current = DateTime.Now.AddSeconds(-1);
476 var tasks = from accountInfo in _accounts
477 select ProcessAccountFiles(accountInfo, since);
479 await TaskEx.WhenAll(tasks.ToList());
482 //Reschedule the poll with the current timestamp as a "since" value
490 Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
491 //In case of failure retry with the same "since" value
494 UpdateStatus(PithosStatus.InSynch);
495 //Wait for the polling interval to pass or the Manual flat to be toggled
496 nextSince = await WaitForScheduledOrManualPoll(nextSince);
498 PollRemoteFiles(nextSince);
503 private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
505 _tcs = new TaskCompletionSource<bool>();
506 var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
507 var signaledTask = await TaskEx.WhenAny(_tcs.Task, wait);
508 //If polling is signalled by SynchNow, ignore the since tag
509 if (signaledTask is Task<bool>)
514 public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
516 if (accountInfo==null)
517 throw new ArgumentNullException("accountInfo");
518 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
519 throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
520 Contract.EndContractBlock();
523 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
527 Log.Info("Scheduled");
528 var client = new CloudFilesClient(accountInfo)
530 Proxy = PithosMonitor.ProxyFromSettings(this.Settings)
533 var containers = client.ListContainers(accountInfo.UserName);
536 CreateContainerFolders(accountInfo, containers);
541 //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
542 //than delete a file that was created while we were executing the poll
543 var pollTime = DateTime.Now;
545 //Get the list of server objects changed since the last check
546 //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
547 var listObjects = (from container in containers
548 select Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
549 client.ListObjects(accountInfo.UserName,container.Name, since),container.Name)).ToList();
551 var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => client.ListSharedObjects(since), "shared");
552 listObjects.Add(listShared);
553 var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
555 using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
557 var dict = listTasks.ToDictionary(t => t.AsyncState);
559 //Get all non-trash objects. Remember, the container name is stored in AsyncState
560 var remoteObjects = from objectList in listTasks
561 where (string) objectList.AsyncState != "trash"
562 from obj in objectList.Result
565 //TODO: Change the way deleted objects are detected.
566 //The list operation returns all existing objects so we could detect deleted remote objects
567 //by detecting objects that exist only locally. There are several cases where this is NOT the case:
568 //1. The first time the application runs, as there may be files that were added while
569 // the application was down.
570 //2. An object that is currently being uploaded will not appear in the remote list
571 // until the upload finishes.
572 // SOLUTION 1: Check the upload/download queue for the file
573 // SOLUTION 2: Check the SQLite states for the file's entry. If it is being uploaded,
574 // or its last modification was after the current poll, don't delete it. This way we don't
575 // delete objects whose upload finished too late to be included in the list.
576 //We need to detect and protect against such situations
577 //TODO: Does FileState have a LastModification field?
578 //TODO: How do we update the LastModification field? Do we need to add SQLite triggers?
579 // Do we need to use a proper SQLite schema?
580 // We can create a trigger with
581 // CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW
583 // UPDATE FileState SET LastModification=datetime('now') WHERE Id=old.Id;
586 //NOTE: Some files may have been deleted remotely while the application was down.
587 // We DO have to delete those files. Checking the trash makes it easy to detect them,
588 // Otherwise, we can't be really sure whether we need to upload or delete
589 // the local-only files.
590 // SOLUTION 1: Ask the user when such a local-only file is detected during the first poll.
591 // SOLUTION 2: Mark conflict and ask the user as in #1
593 var trashObjects = dict["trash"].Result;
594 var sharedObjects = dict["shared"].Result;
596 //Items with the same name, hash may be both in the container and the trash
597 //Don't delete items that exist in the container
598 var realTrash = from trash in trashObjects
601 info => info.Name == trash.Name && info.Hash == trash.Hash)
603 ProcessTrashedFiles(accountInfo, realTrash);
606 var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
608 where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
609 !name.StartsWith(FolderConstants.CacheFolder + "/",
610 StringComparison.InvariantCultureIgnoreCase)
611 select info).ToList();
613 var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
615 ProcessDeletedFiles(accountInfo, differencer.Deleted, pollTime);
617 //Create a list of actions from the remote files
618 var allActions = ChangesToActions(accountInfo, differencer.Changed)
620 CreatesToActions(accountInfo,differencer.Created));
623 //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
625 //And remove those that are already being processed by the agent
626 var distinctActions = allActions
627 .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
630 //Queue all the actions
631 foreach (var message in distinctActions)
636 Log.Info("[LISTENER] End Processing");
641 Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
645 Log.Info("[LISTENER] Finished");
650 AccountsDifferencer _differencer= new AccountsDifferencer();
653 Dictionary<string, List<ObjectInfo>> _currentSnapshot = new Dictionary<string, List<ObjectInfo>>();
654 Dictionary<string, List<ObjectInfo>> _previousSnapshot = new Dictionary<string, List<ObjectInfo>>();
658 /// Deletes local files that are not found in the list of cloud files
660 /// <param name="accountInfo"></param>
661 /// <param name="cloudFiles"></param>
662 /// <param name="pollTime"></param>
663 private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
665 if (accountInfo == null)
666 throw new ArgumentNullException("accountInfo");
667 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
668 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
669 if (cloudFiles == null)
670 throw new ArgumentNullException("cloudFiles");
671 Contract.EndContractBlock();
676 //Only consider files that are not being modified, ie they are in the Unchanged state
677 var deleteCandidates = FileState.Queryable.Where(state =>
678 state.FilePath.StartsWith(accountInfo.AccountPath)
679 && state.FileStatus == FileStatus.Unchanged).ToList();
682 //TODO: filesToDelete must take into account the Others container
683 var filesToDelete = (from deleteCandidate in deleteCandidates
684 let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
685 let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
687 !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
688 select localFile).ToList();
692 //Set the status of missing files to Conflict
693 foreach (var item in filesToDelete)
695 //Try to acquire a gate on the file, to take into account files that have been dequeued
696 //and are being processed
697 using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
701 StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
704 UpdateStatus(PithosStatus.HasConflicts);
705 StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
706 StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info);
710 var deletedFiles = new List<FileSystemInfo>();
711 foreach (var objectInfo in cloudFiles)
713 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
714 var item = GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
717 //Try to acquire a gate on the file, to take into account files that have been dequeued
718 //and are being processed
719 //TODO: The gate is not enough. Perhaps we need to keep a journal of processed files and check against
722 using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
727 if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
729 item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
734 _lastSeen.TryRemove(item.FullName, out lastDate);
735 deletedFiles.Add(item);
740 StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted);
742 StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info);
747 private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
749 var containerPaths = from container in containers
750 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
751 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
752 select containerPath;
754 foreach (var path in containerPaths)
756 Directory.CreateDirectory(path);
760 //Creates an appropriate action for each server file
761 private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> changes)
764 throw new ArgumentNullException();
765 Contract.EndContractBlock();
766 var fileAgent = GetFileAgent(accountInfo);
768 //In order to avoid multiple iterations over the files, we iterate only once
769 //over the remote files
770 foreach (var objectInfo in changes)
772 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
773 //and remove any matching objects from the list, adding them to the commonObjects list
774 if (fileAgent.Exists(relativePath))
776 //If a directory object already exists, we don't need to perform any other action
777 var localFile = fileAgent.GetFileSystemInfo(relativePath);
778 if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
780 using (new SessionScope(FlushAction.Never))
782 var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
783 _lastSeen[localFile.FullName] = DateTime.Now;
784 //FileState.FindByFilePath(localFile.FullName);
785 //Common files should be checked on a per-case basis to detect differences, which is newer
787 yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
788 localFile, objectInfo, state, accountInfo.BlockSize,
789 accountInfo.BlockHash);
794 //Remote files should be downloaded
795 yield return new CloudDownloadAction(accountInfo,objectInfo);
800 private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> creates)
803 throw new ArgumentNullException();
804 Contract.EndContractBlock();
805 var fileAgent = GetFileAgent(accountInfo);
807 //In order to avoid multiple iterations over the files, we iterate only once
808 //over the remote files
809 foreach (var objectInfo in creates)
811 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
812 //and remove any matching objects from the list, adding them to the commonObjects list
813 if (fileAgent.Exists(relativePath))
815 //If the object already exists, we probably have a conflict
816 //If a directory object already exists, we don't need to perform any other action
817 var localFile = fileAgent.GetFileSystemInfo(relativePath);
818 StatusKeeper.SetFileState(localFile.FullName,FileStatus.Conflict,FileOverlayStatus.Conflict);
822 //Remote files should be downloaded
823 yield return new CloudDownloadAction(accountInfo,objectInfo);
828 //Creates an appropriate action for each server file
830 private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
833 throw new ArgumentNullException();
834 Contract.EndContractBlock();
835 var fileAgent = GetFileAgent(accountInfo);
837 //In order to avoid multiple iterations over the files, we iterate only once
838 //over the remote files
839 foreach (var objectInfo in remote)
841 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
842 //and remove any matching objects from the list, adding them to the commonObjects list
844 if (fileAgent.Exists(relativePath))
846 //If a directory object already exists, we don't need to perform any other action
847 var localFile = fileAgent.GetFileSystemInfo(relativePath);
848 if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
850 using (new SessionScope(FlushAction.Never))
852 var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
853 _lastSeen[localFile.FullName] = DateTime.Now;
854 //FileState.FindByFilePath(localFile.FullName);
855 //Common files should be checked on a per-case basis to detect differences, which is newer
857 yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
858 localFile, objectInfo, state, accountInfo.BlockSize,
859 accountInfo.BlockHash);
864 //If there is no match we add them to the localFiles list
865 //but only if the file is not marked for deletion
866 var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
867 var fileStatus = StatusKeeper.GetFileStatus(targetFile);
868 if (fileStatus != FileStatus.Deleted)
870 //Remote files should be downloaded
871 yield return new CloudDownloadAction(accountInfo,objectInfo);
878 private static FileAgent GetFileAgent(AccountInfo accountInfo)
880 return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
883 private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
885 var fileAgent = GetFileAgent(accountInfo);
886 foreach (var trashObject in trashObjects)
888 var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
889 //HACK: Assume only the "pithos" container is used. Must find out what happens when
890 //deleting a file from a different container
891 var relativePath = Path.Combine("pithos", barePath);
892 fileAgent.Delete(relativePath);
897 private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
899 if (accountInfo==null)
900 throw new ArgumentNullException("accountInfo");
902 throw new ArgumentNullException("action");
903 if (action.CloudFile==null)
904 throw new ArgumentException("CloudFile","action");
905 if (action.LocalFile==null)
906 throw new ArgumentException("LocalFile","action");
907 if (action.OldLocalFile==null)
908 throw new ArgumentException("OldLocalFile","action");
909 if (action.OldCloudFile==null)
910 throw new ArgumentException("OldCloudFile","action");
911 Contract.EndContractBlock();
914 var newFilePath = action.LocalFile.FullName;
916 //How do we handle concurrent renames and deletes/uploads/downloads?
917 //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
918 // This should never happen as the network agent executes only one action at a time
919 //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
920 // the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the
921 // same name will fail.
922 // This should never happen as the network agent executes only one action at a time.
923 //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
924 // to remove the rename from the queue.
925 // We can probably ignore this case. It will result in an error which should be ignored
928 //The local file is already renamed
929 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
932 var account = action.CloudFile.Account ?? accountInfo.UserName;
933 var container = action.CloudFile.Container;
935 var client = new CloudFilesClient(accountInfo);
936 //TODO: What code is returned when the source file doesn't exist?
937 client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
939 StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
940 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
941 NativeMethods.RaiseChangeNotification(newFilePath);
944 private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
946 if (accountInfo == null)
947 throw new ArgumentNullException("accountInfo");
949 throw new ArgumentNullException("cloudFile");
951 if (String.IsNullOrWhiteSpace(cloudFile.Container))
952 throw new ArgumentException("Invalid container", "cloudFile");
953 Contract.EndContractBlock();
955 var fileAgent = GetFileAgent(accountInfo);
957 using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
959 var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
960 var info = fileAgent.GetFileSystemInfo(fileName);
961 var fullPath = info.FullName.ToLower();
963 StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
965 var account = cloudFile.Account ?? accountInfo.UserName;
966 var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
968 var client = new CloudFilesClient(accountInfo);
969 client.DeleteObject(account, container, cloudFile.Name);
971 StatusKeeper.ClearFileStatus(fullPath);
976 private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
978 if (accountInfo == null)
979 throw new ArgumentNullException("accountInfo");
980 if (cloudFile == null)
981 throw new ArgumentNullException("cloudFile");
982 if (String.IsNullOrWhiteSpace(cloudFile.Account))
983 throw new ArgumentNullException("cloudFile");
984 if (String.IsNullOrWhiteSpace(cloudFile.Container))
985 throw new ArgumentNullException("cloudFile");
986 if (String.IsNullOrWhiteSpace(filePath))
987 throw new ArgumentNullException("filePath");
988 if (!Path.IsPathRooted(filePath))
989 throw new ArgumentException("The filePath must be rooted", "filePath");
990 Contract.EndContractBlock();
993 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
994 var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
996 var url = relativeUrl.ToString();
997 if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
1001 //Are we already downloading or uploading the file?
1002 using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
1006 //The file's hashmap will be stored in the same location with the extension .hashmap
1007 //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
1009 var client = new CloudFilesClient(accountInfo);
1010 var account = cloudFile.Account;
1011 var container = cloudFile.Container;
1013 if (cloudFile.Content_Type == @"application/directory")
1015 if (!Directory.Exists(localPath))
1016 Directory.CreateDirectory(localPath);
1020 //Retrieve the hashmap from the server
1021 var serverHash = await client.GetHashMap(account, container, url);
1022 //If it's a small file
1023 if (serverHash.Hashes.Count == 1)
1024 //Download it in one go
1026 DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
1027 //Otherwise download it block by block
1029 await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
1031 if (cloudFile.AllowedTo == "read")
1033 var attributes = File.GetAttributes(localPath);
1034 File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
1038 //Now we can store the object's metadata without worrying about ghost status entries
1039 StatusKeeper.StoreInfo(localPath, cloudFile);
1044 //Download a small file with a single GET operation
1045 private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
1048 throw new ArgumentNullException("client");
1049 if (cloudFile==null)
1050 throw new ArgumentNullException("cloudFile");
1051 if (relativeUrl == null)
1052 throw new ArgumentNullException("relativeUrl");
1053 if (String.IsNullOrWhiteSpace(filePath))
1054 throw new ArgumentNullException("filePath");
1055 if (!Path.IsPathRooted(filePath))
1056 throw new ArgumentException("The localPath must be rooted", "filePath");
1057 Contract.EndContractBlock();
1059 var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1060 //If the file already exists
1061 if (File.Exists(localPath))
1063 //First check with MD5 as this is a small file
1064 var localMD5 = Signature.CalculateMD5(localPath);
1065 var cloudHash=serverHash.TopHash.ToHashString();
1066 if (localMD5==cloudHash)
1068 //Then check with a treehash
1069 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
1070 var localHash = localTreeHash.TopHash.ToHashString();
1071 if (localHash==cloudHash)
1074 StatusNotification.Notify(new CloudNotification { Data = cloudFile });
1076 var fileAgent = GetFileAgent(accountInfo);
1077 //Calculate the relative file path for the new file
1078 var relativePath = relativeUrl.RelativeUriToFilePath();
1079 //The file will be stored in a temporary location while downloading with an extension .download
1080 var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
1081 //Make sure the target folder exists. DownloadFileTask will not create the folder
1082 var tempFolder = Path.GetDirectoryName(tempPath);
1083 if (!Directory.Exists(tempFolder))
1084 Directory.CreateDirectory(tempFolder);
1086 //Download the object to the temporary location
1087 await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
1089 //Create the local folder if it doesn't exist (necessary for shared objects)
1090 var localFolder = Path.GetDirectoryName(localPath);
1091 if (!Directory.Exists(localFolder))
1092 Directory.CreateDirectory(localFolder);
1093 //And move it to its actual location once downloading is finished
1094 if (File.Exists(localPath))
1095 File.Replace(tempPath,localPath,null,true);
1097 File.Move(tempPath,localPath);
1098 //Notify listeners that a local file has changed
1099 StatusNotification.NotifyChangedFile(localPath);
1104 //Download a file asynchronously using blocks
1105 public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
1108 throw new ArgumentNullException("client");
1109 if (cloudFile == null)
1110 throw new ArgumentNullException("cloudFile");
1111 if (relativeUrl == null)
1112 throw new ArgumentNullException("relativeUrl");
1113 if (String.IsNullOrWhiteSpace(filePath))
1114 throw new ArgumentNullException("filePath");
1115 if (!Path.IsPathRooted(filePath))
1116 throw new ArgumentException("The filePath must be rooted", "filePath");
1117 if (serverHash == null)
1118 throw new ArgumentNullException("serverHash");
1119 Contract.EndContractBlock();
1121 var fileAgent = GetFileAgent(accountInfo);
1122 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1124 //Calculate the relative file path for the new file
1125 var relativePath = relativeUrl.RelativeUriToFilePath();
1126 var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
1130 //Calculate the file's treehash
1131 var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
1133 //And compare it with the server's hash
1134 var upHashes = serverHash.GetHashesAsStrings();
1135 var localHashes = treeHash.HashDictionary;
1136 for (int i = 0; i < upHashes.Length; i++)
1138 //For every non-matching hash
1139 var upHash = upHashes[i];
1140 if (!localHashes.ContainsKey(upHash))
1142 StatusNotification.Notify(new CloudNotification { Data = cloudFile });
1144 if (blockUpdater.UseOrphan(i, upHash))
1146 Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
1149 Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
1150 var start = i*serverHash.BlockSize;
1151 //To download the last block just pass a null for the end of the range
1153 if (i < upHashes.Length - 1 )
1154 end= ((i + 1)*serverHash.BlockSize) ;
1156 //Download the missing block
1157 var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
1160 blockUpdater.StoreBlock(i, block);
1163 Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
1167 //Want to avoid notifications if no changes were made
1168 var hasChanges = blockUpdater.HasBlocks;
1169 blockUpdater.Commit();
1172 //Notify listeners that a local file has changed
1173 StatusNotification.NotifyChangedFile(localPath);
1175 Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
1179 private async Task UploadCloudFile(CloudAction action)
1182 throw new ArgumentNullException("action");
1183 Contract.EndContractBlock();
1187 var accountInfo = action.AccountInfo;
1189 var fileInfo = action.LocalFile;
1191 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1194 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1195 if (relativePath.StartsWith(FolderConstants.OthersFolder))
1197 var parts = relativePath.Split('\\');
1198 var accountName = parts[1];
1199 var oldName = accountInfo.UserName;
1200 var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1201 var nameIndex = absoluteUri.IndexOf(oldName);
1202 var root = absoluteUri.Substring(0, nameIndex);
1204 accountInfo = new AccountInfo
1206 UserName = accountName,
1207 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1208 StorageUri = new Uri(root + accountName),
1209 BlockHash = accountInfo.BlockHash,
1210 BlockSize = accountInfo.BlockSize,
1211 Token = accountInfo.Token
1216 var fullFileName = fileInfo.GetProperCapitalization();
1217 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1219 //Abort if the file is already being uploaded or downloaded
1223 var cloudFile = action.CloudFile;
1224 var account = cloudFile.Account ?? accountInfo.UserName;
1226 var client = new CloudFilesClient(accountInfo);
1227 //Even if GetObjectInfo times out, we can proceed with the upload
1228 var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1230 //If this is a read-only file, do not upload changes
1231 if (info.AllowedTo == "read")
1234 //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1235 if (fileInfo is DirectoryInfo)
1237 //If the directory doesn't exist the Hash property will be empty
1238 if (String.IsNullOrWhiteSpace(info.Hash))
1239 //Go on and create the directory
1240 await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1245 var cloudHash = info.Hash.ToLower();
1247 var hash = action.LocalHash.Value;
1248 var topHash = action.TopHash.Value;
1250 //If the file hashes match, abort the upload
1251 if (hash == cloudHash || topHash == cloudHash)
1253 //but store any metadata changes
1254 StatusKeeper.StoreInfo(fullFileName, info);
1255 Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1260 //Mark the file as modified while we upload it
1261 StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1262 //And then upload it
1264 //Upload even small files using the Hashmap. The server may already contain
1265 //the relevant block
1267 //First, calculate the tree hash
1268 var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1269 accountInfo.BlockHash, 2);
1271 await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1273 //If everything succeeds, change the file and overlay status to normal
1274 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1276 //Notify the Shell to update the overlays
1277 NativeMethods.RaiseChangeNotification(fullFileName);
1278 StatusNotification.NotifyChangedFile(fullFileName);
1280 catch (AggregateException ex)
1282 var exc = ex.InnerException as WebException;
1284 throw ex.InnerException;
1285 if (HandleUploadWebException(action, exc))
1289 catch (WebException ex)
1291 if (HandleUploadWebException(action, ex))
1295 catch (Exception ex)
1297 Log.Error("Unexpected error while uploading file", ex);
1303 //Returns true if an action concerns a file that was deleted
1304 private bool IsDeletedFile(CloudAction action)
1306 //Doesn't work for actions targeting shared files
1307 if (action.IsShared)
1309 var key = GetFileKey(action.CloudFile);
1311 if (_deletedFiles.TryGetValue(key, out entryDate))
1313 //If the delete entry was created after this action, abort the action
1314 if (entryDate > action.Created)
1316 //Otherwise, remove the stale entry
1317 _deletedFiles.TryRemove(key, out entryDate);
1322 private bool HandleUploadWebException(CloudAction action, WebException exc)
1324 var response = exc.Response as HttpWebResponse;
1325 if (response == null)
1327 if (response.StatusCode == HttpStatusCode.Unauthorized)
1329 Log.Error("Not allowed to upload file", exc);
1330 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1331 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1332 StatusNotification.NotifyChange(message, TraceLevel.Warning);
1338 public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1340 if (accountInfo == null)
1341 throw new ArgumentNullException("accountInfo");
1342 if (cloudFile==null)
1343 throw new ArgumentNullException("cloudFile");
1344 if (fileInfo == null)
1345 throw new ArgumentNullException("fileInfo");
1346 if (String.IsNullOrWhiteSpace(url))
1347 throw new ArgumentNullException(url);
1349 throw new ArgumentNullException("treeHash");
1350 if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1351 throw new ArgumentException("Invalid container","cloudFile");
1352 Contract.EndContractBlock();
1354 var fullFileName = fileInfo.GetProperCapitalization();
1356 var account = cloudFile.Account ?? accountInfo.UserName;
1357 var container = cloudFile.Container ;
1359 var client = new CloudFilesClient(accountInfo);
1360 //Send the hashmap to the server
1361 var missingHashes = await client.PutHashMap(account, container, url, treeHash);
1362 //If the server returns no missing hashes, we are done
1363 while (missingHashes.Count > 0)
1366 var buffer = new byte[accountInfo.BlockSize];
1367 foreach (var missingHash in missingHashes)
1369 //Find the proper block
1370 var blockIndex = treeHash.HashDictionary[missingHash];
1371 var offset = blockIndex*accountInfo.BlockSize;
1373 var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1377 //And upload the block
1378 await client.PostBlock(account, container, buffer, 0, read);
1379 Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1381 catch (Exception exc)
1383 Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1388 //Repeat until there are no more missing hashes
1389 missingHashes = await client.PutHashMap(account, container, url, treeHash);
1394 public void AddAccount(AccountInfo accountInfo)
1396 if (!_accounts.Contains(accountInfo))
1397 _accounts.Add(accountInfo);