Modified selective sync to propagate the creation of new local directories and their...
[pithos-ms-client] / trunk / Pithos.Core / Agents / NetworkAgent.cs
index 6e9c597..6431ffe 100644 (file)
-using System;
+#region
+/* -----------------------------------------------------------------------
+ * <copyright file="NetworkAgent.cs" company="GRNet">
+ * 
+ * Copyright 2011-2012 GRNET S.A. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above
+ *      copyright notice, this list of conditions and the following
+ *      disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above
+ *      copyright notice, this list of conditions and the following
+ *      disclaimer in the documentation and/or other materials
+ *      provided with the distribution.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+ * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * The views and conclusions contained in the software and
+ * documentation are those of the authors and should not be
+ * interpreted as representing official policies, either expressed
+ * or implied, of GRNET S.A.
+ * </copyright>
+ * -----------------------------------------------------------------------
+ */
+#endregion
+
+using System;
 using System.Collections.Generic;
 using System.ComponentModel.Composition;
 using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.IO;
 using System.Linq;
-using System.Text;
+using System.Net;
+using System.Reflection;
+using System.Threading;
 using System.Threading.Tasks;
+using Castle.ActiveRecord;
 using Pithos.Interfaces;
 using Pithos.Network;
+using log4net;
 
 namespace Pithos.Core.Agents
 {
     [Export]
     public class NetworkAgent
     {
+        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
         private Agent<CloudAction> _agent;
 
-        [Import]
+        [System.ComponentModel.Composition.Import]
+        private DeleteAgent DeleteAgent { get; set; }
+
+        [System.ComponentModel.Composition.Import]
         public IStatusKeeper StatusKeeper { get; set; }
-        
-        public IStatusNotification StatusNotification { get; set; }
-        [Import]
-        public ICloudClient CloudClient { get; set; }
 
-        [Import]
-        public FileAgent FileAgent {get;set;}
+        private IStatusNotification _statusNotification;
+        public IStatusNotification StatusNotification
+        {
+            get { return _statusNotification; }
+            set
+            {
+                _statusNotification = value;
+                DeleteAgent.StatusNotification = value;
+                Uploader.StatusNotification = value;
+                Downloader.StatusNotification = value;
+            }
+        }
+
 
-        /*
-        [Import]
-        public IPithosWorkflow Workflow { get; set; }
-*/
+        [System.ComponentModel.Composition.Import]
+        public IPithosSettings Settings { get; set; }
 
+        private Uploader _uploader;
 
-        private string _pithosContainer;
-        private string _trashContainer;
+        [System.ComponentModel.Composition.Import]
+        public Uploader Uploader
+        {
+            get { return _uploader; }
+            set
+            {
+                _uploader = value;
+                _uploader.UnpauseEvent = _unPauseEvent;                
+            }
+        }
 
-        private int _blockSize;
-        private string _blockHash;
+        private Downloader _downloader;
 
+        [System.ComponentModel.Composition.Import]
+        public Downloader Downloader
+        {
+            get { return _downloader; }
+            set
+            {
+                _downloader = value;
+                _downloader.UnpauseEvent = _unPauseEvent;
+            }
+        }
 
-        public void Start(string pithosContainer, string trashContainer, int blockSize, string blockHash)
+        [System.ComponentModel.Composition.Import]
+        public Selectives Selectives { get; set; }
+        
+        //The Proceed signals the poll agent that it can proceed with polling. 
+        //Essentially it stops the poll agent to give priority to the network agent
+        //Initially the event is signalled because we don't need to pause
+        private readonly AsyncManualResetEvent _proceedEvent = new AsyncManualResetEvent(true);
+        private Agents.Selectives _selectives;
+        private bool _pause;
+
+        public AsyncManualResetEvent ProceedEvent
         {
-            if (String.IsNullOrWhiteSpace(pithosContainer))
-                throw new ArgumentNullException("pithosContainer");
-            if (String.IsNullOrWhiteSpace(trashContainer))
-                throw new ArgumentNullException("trashContainer");
-            Contract.EndContractBlock();
+            get { return _proceedEvent; }
+        }
 
-            _pithosContainer = pithosContainer;
-            _trashContainer = trashContainer;
-            _blockSize = blockSize;
-            _blockHash = blockHash;
+        private readonly AsyncManualResetEvent _unPauseEvent = new AsyncManualResetEvent(true);
 
+        private CancellationTokenSource _currentOperationCancellation=new CancellationTokenSource();
+
+        public void CancelCurrentOperation()
+        {
+            //What does it mean to cancel the current upload/download?
+            //Obviously, the current operation will be cancelled by throwing
+            //a cancellation exception.
+            //
+            //The default behavior is to retry any operations that throw.
+            //Obviously this is not what we want in this situation.
+            //The cancelled operation should NOT bea retried. 
+            //
+            //This can be done by catching the cancellation exception
+            //and avoiding the retry.
+            //
+
+            //Have to reset the cancellation source - it is not possible to reset the source
+            //Have to prevent a case where an operation requests a token from the old source
+            var oldSource = Interlocked.Exchange(ref _currentOperationCancellation, new CancellationTokenSource());
+            oldSource.Cancel();
+            
+        }
+
+        public void Start()
+        {
+            if (_agent != null)
+                return;
+
+            if (Log.IsDebugEnabled)
+                Log.Debug("Starting Network Agent");
 
             _agent = Agent<CloudAction>.Start(inbox =>
             {
                 Action loop = null;
                 loop = () =>
                 {
+                    DeleteAgent.ProceedEvent.Wait();
+                    _unPauseEvent.Wait();
                     var message = inbox.Receive();
-                    var process = message.ContinueWith(t =>
-                    {
-                        var action = t.Result;
-                        
-                        Process(action);
-                        inbox.DoAsync(loop);
-                    });
-                    process.ContinueWith(t =>
-                    {
-                        inbox.DoAsync(loop);
-                        if (t.IsFaulted)
-                        {
-                            var ex = t.Exception.InnerException;
-                            if (ex is OperationCanceledException)
-                                inbox.Stop();
-                        }
-                    });
-
+                    var process=message.Then(Process,inbox.CancellationToken);
+                    inbox.LoopAsync(process, loop);
                 };
                 loop();
             });
-        }
 
+        }
 
-        public void Post(CloudAction cloudAction)
+        private async Task Process(CloudAction action)
         {
-            if (cloudAction == null)
-                throw new ArgumentNullException("cloudAction");
+            if (action == null)
+                throw new ArgumentNullException("action");
+            if (action.AccountInfo==null)
+                throw new ArgumentException("The action.AccountInfo is empty","action");
             Contract.EndContractBlock();
 
-            _agent.Post(cloudAction);
-        }
-
-        class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
-        {
-            public bool Equals(ObjectInfo x, ObjectInfo y)
-            {
-                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
-            }
 
-            public int GetHashCode(ObjectInfo obj)
-            {
-                return obj.Name.ToLower().GetHashCode();
-            }
-        }
 
-        public Task ProcessRemoteFiles(string accountPath,DateTime? since=null)
-        {            
 
-            Trace.CorrelationManager.StartLogicalOperation();
-            Trace.TraceInformation("[LISTENER] Scheduled");
-            var listObjects = Task.Factory.StartNewDelayed(10000).ContinueWith(t =>
-                CloudClient.ListObjects(_pithosContainer,since));
+            using (ThreadContext.Stacks["Operation"].Push(action.ToString()))
+            {                
 
-            DateTime nextSince = DateTime.Now.AddSeconds(-1);
+                var cloudFile = action.CloudFile;
+                var downloadPath = action.GetDownloadPath();
 
-            var enqueueFiles = listObjects.ContinueWith(task =>
-            {
-                //ListObjects failed at this point, need to reschedule
-                if (task.IsFaulted)
-                {
-                    Trace.TraceError("[FAIL] ListObjects in ProcessRemoteFiles with {0}",task.Exception);
-                    ProcessRemoteFiles(accountPath, since);
-                    return;
-                }
-                Trace.CorrelationManager.StartLogicalOperation("Listener");
-                Trace.TraceInformation("[LISTENER] Start Processing");
-
-                var remoteObjects = task.Result;
-
-                var remote=(from info in remoteObjects
-                                  let name=info.Name
-                                  where !name.EndsWith(".ignore",StringComparison.InvariantCultureIgnoreCase) &&
-                                  !name.StartsWith("fragments/",StringComparison.InvariantCultureIgnoreCase)
-                                select info)
-                                .Distinct(new ObjectInfoByNameComparer()).ToDictionary(info=> info.Name.ToLower(), info=>info);
-
-                var commonObjects = new List<Tuple<ObjectInfo, FileInfo>>();
-                var localFiles = new List<FileInfo>();
-                
-                //In order to avoid multiple iterations over the files, we iterate only once
-                foreach (var fileInfo in FileAgent.EnumerateFileInfos())
+                try
                 {
-                    var relativeUrl=fileInfo.AsRelativeUrlTo(FileAgent.RootPath);
-                    //and remove any matching objects from the list, adding them to the commonObjects list
-                    if (remote.ContainsKey(relativeUrl))
+                    StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing,"Processing");
+                    _proceedEvent.Reset();
+                    
+                    var accountInfo = action.AccountInfo;
+
+                    if (action.Action == CloudActionType.DeleteCloud)
+                    {                        
+                        //Redirect deletes to the delete agent 
+                        DeleteAgent.Post((CloudDeleteAction)action);
+                    }
+                    if (DeleteAgent.IsDeletedFile(action))
                     {
-                        commonObjects.Add(Tuple.Create(remote[relativeUrl], fileInfo));
-                        remote.Remove(relativeUrl);
+                        //Clear the status of already deleted files to avoid reprocessing
+                        if (action.LocalFile != null)
+                            StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
                     }
                     else
-                        //If there is no match we add them to the localFiles list
-                        localFiles.Add(fileInfo);
+                    {
+                        switch (action.Action)
+                        {
+                            case CloudActionType.UploadUnconditional:
+                                //Abort if the file was deleted before we reached this point
+                                var uploadAction = (CloudUploadAction) action;
+                                ProcessChildUploads(uploadAction);
+                                await Uploader.UploadCloudFile(uploadAction ,CurrentOperationCancelToken);
+                                break;
+                            case CloudActionType.DownloadUnconditional:
+                                await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath, CurrentOperationCancelToken);
+                                break;
+                            case CloudActionType.RenameCloud:
+                                var moveAction = (CloudMoveAction)action;
+                                RenameCloudFile(accountInfo, moveAction);
+                                break;
+                            case CloudActionType.RenameLocal:
+                                RenameLocalFile(accountInfo, action);
+                                break;
+                            case CloudActionType.MustSynch:
+                                if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
+                                {
+                                    await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath, CurrentOperationCancelToken);
+                                }
+                                else
+                                {
+                                    await SyncFiles(accountInfo, action);
+                                }
+                                break;
+                        }
+                    }
+                    Log.InfoFormat("End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
+                                           action.CloudFile.Name);
                 }
+/*
+                catch (WebException exc)
+                {                    
+                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
+                    
+                    
+                    //Actions that resulted in server errors should be retried                    
+                    var response = exc.Response as HttpWebResponse;
+                    if (response != null && response.StatusCode >= HttpStatusCode.InternalServerError)
+                    {
+                        _agent.Post(action);
+                        Log.WarnFormat("[REQUEUE] {0} : {1} -> {2}", action.Action, action.LocalFile, action.CloudFile);
+                    }
+                }
+*/
+                catch (OperationCanceledException ex)
+                {                    
+                    Log.WarnFormat("Cancelling [{0}]",ex);
+                }
+                catch (DirectoryNotFoundException)
+                {
+                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
+                        action.Action, action.LocalFile, action.CloudFile);
+                    //Post a delete action for the missing file
+                    Post(new CloudDeleteAction(action));
+                }
+                catch (FileNotFoundException)
+                {
+                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
+                        action.Action, action.LocalFile, action.CloudFile);
+                    //Post a delete action for the missing file
+                    Post(new CloudDeleteAction(action));
+                }
+                catch (Exception exc)
+                {
+                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
+                                     action.Action, action.LocalFile, action.CloudFile, exc);
 
-                //At the end of the iteration, the *remote* list will contain the files that exist 
-                //only on the server
+                    _agent.Post(action);
+                }
+                finally
+                {
+                    if (_agent.IsEmpty)
+                        _proceedEvent.Set();
+                    UpdateStatus(PithosStatus.LocalComplete);                                        
+                }
+            }
+        }
 
-                //Local files should be uploaded
-                var actionsForLocal = from localFile in localFiles
-                                select new CloudAction(CloudActionType.UploadUnconditional, 
-                                    localFile, 
-                                    ObjectInfo.Empty);                
+        private void ProcessChildUploads(CloudUploadAction uploadAction)
+        {
+            if (!uploadAction.IsCreation || !(uploadAction.LocalFile is DirectoryInfo)) 
+                return;
 
-                //Remote files should be downloaded
-                var actionsForRemote = from dictPair in remote
-                                       let upFile = dictPair.Value
-                                       select new CloudAction(CloudActionType.DownloadUnconditional, null, upFile);
+            var dirInfo = uploadAction.LocalFile as DirectoryInfo;
 
-                //Common files should be checked on a per-case basis to detect differences, which is newer
-                var actionsForCommon = from pair in commonObjects
-                                       let objectInfo = pair.Item1
-                                       let localFile = pair.Item2
-                                       select new CloudAction(CloudActionType.MustSynch, localFile, objectInfo);
+            var account = uploadAction.AccountInfo;
+            var actions = from file in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories)
+                          select
+                              new CloudUploadAction(account, file, null, account.BlockSize, account.BlockHash,
+                                                    uploadAction, true);
+            foreach (var action in actions)
+            {
+                var state=StatusKeeper.GetStateByFilePath(action.LocalFile.FullName);
+                if (state!=null)
+                    state.Delete();
+                //StatusKeeper.SetFileState(action.LocalFile.FullName,FileStatus.Created,FileOverlayStatus.Normal,String.Empty);
+                state=FileState.CreateFor(action.LocalFile);
+                //StatusKeeper.SetFileStatus();
+                state.FileStatus = FileStatus.Created;
+                state.OverlayStatus=FileOverlayStatus.Normal;
+                state.Create();
+                action.FileState = state;
+                Post(action);
+            }
+        }
 
-                //Collect all the actions
-                var allActions = actionsForLocal.Union(actionsForRemote).Union(actionsForCommon);
+        private CancellationToken CurrentOperationCancelToken
+        {
+            get { return _currentOperationCancellation.Token; }
+        }
 
-                //And remove those that are already being processed by the agent
-                var distinctActions =allActions
-                        .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
-                        .ToList();
 
-                //Queue all the actions
-                _agent.AddFromEnumerable(distinctActions);
+        private void UpdateStatus(PithosStatus status)
+        {
+            StatusNotification.SetPithosStatus(status);
+            //StatusNotification.Notify(new Notification());
+        }
 
-                StatusNotification.NotifyChange(String.Format("Processing {0} files", distinctActions.Count));
+        private void RenameLocalFile(AccountInfo accountInfo, CloudAction action)
+        {
+            if (accountInfo == null)
+                throw new ArgumentNullException("accountInfo");
+            if (action == null)
+                throw new ArgumentNullException("action");
+            if (action.LocalFile == null)
+                throw new ArgumentException("The action's local file is not specified", "action");
+            if (!Path.IsPathRooted(action.LocalFile.FullName))
+                throw new ArgumentException("The action's local file path must be absolute", "action");
+            if (action.CloudFile == null)
+                throw new ArgumentException("The action's cloud file is not specified", "action");
+            Contract.EndContractBlock();
+            using (ThreadContext.Stacks["Operation"].Push("RenameLocalFile"))
+            {
 
-                Trace.TraceInformation("[LISTENER] End Processing");
-                Trace.CorrelationManager.StopLogicalOperation();
+                //We assume that the local file already exists, otherwise the poll agent
+                //would have issued a download request
 
-            });
+                var currentInfo = action.CloudFile;
+                var previousInfo = action.CloudFile.Previous;
+                var fileAgent = FileAgent.GetFileAgent(accountInfo);
 
-            var loop = enqueueFiles.ContinueWith(t =>
+                var previousRelativepath = previousInfo.RelativeUrlToFilePath(accountInfo.UserName);
+                var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
+
+                //In every case we need to move the local file first
+                MoveLocalFile(accountInfo, previousFile, fileAgent, currentInfo);
+            }
+        }
+
+        private void MoveLocalFile(AccountInfo accountInfo, FileSystemInfo previousFile, FileAgent fileAgent,
+                                   ObjectInfo currentInfo)
+        {
+            var currentRelativepath = currentInfo.RelativeUrlToFilePath(accountInfo.UserName);
+            var newPath = Path.Combine(fileAgent.RootPath, currentRelativepath);
+
+            var isFile= (previousFile is FileInfo);
+            var previousFullPath = isFile? 
+                FileInfoExtensions.GetProperFilePathCapitalization(previousFile.FullName):
+                FileInfoExtensions.GetProperDirectoryCapitalization(previousFile.FullName);                
+            
+            using (NetworkGate.Acquire(previousFullPath, NetworkOperation.Renaming))
+            using (NetworkGate.Acquire(newPath,NetworkOperation.Renaming)) 
+            using (new SessionScope(FlushAction.Auto))
             {
-                if (t.IsFaulted)
-                {
-                    Trace.TraceError("[LISTENER] Exception: {0}", t.Exception);
-                }
+                if (isFile)
+                    (previousFile as FileInfo).MoveTo(newPath);
                 else
                 {
-                    Trace.TraceInformation("[LISTENER] Finished");
+                    (previousFile as DirectoryInfo).MoveTo(newPath);
                 }
-                ProcessRemoteFiles(accountPath, nextSince);
-                
-            });
-            return loop;
+                var state = StatusKeeper.GetStateByFilePath(previousFullPath);
+                state.FilePath = newPath;
+                state.SaveCopy();
+                StatusKeeper.SetFileState(previousFullPath,FileStatus.Deleted,FileOverlayStatus.Deleted, "Deleted");
+            }            
         }
 
-        
-
-
-        private void Process(CloudAction action)
+        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
         {
+            if (accountInfo == null)
+                throw new ArgumentNullException("accountInfo");
             if (action==null)
                 throw new ArgumentNullException("action");
+            if (action.LocalFile==null)
+                throw new ArgumentException("The action's local file is not specified","action");
+            if (!Path.IsPathRooted(action.LocalFile.FullName))
+                throw new ArgumentException("The action's local file path must be absolute","action");
+            if (action.CloudFile== null)
+                throw new ArgumentException("The action's cloud file is not specified", "action");
             Contract.EndContractBlock();
-
-            Trace.TraceInformation("[ACTION] Start Processing {0}:{1}->{2}", action.Action, action.LocalFile, action.CloudFile.Name);
-            var localFile = action.LocalFile;
-            var cloudFile = action.CloudFile;
-            var downloadPath = (cloudFile == null) ? String.Empty
-                                    : Path.Combine(FileAgent.RootPath, cloudFile.Name.RelativeUrlToFilePath());
-            
-            try
+            using (ThreadContext.Stacks["Operation"].Push("SyncFiles"))
             {
-                switch (action.Action)
-                {
-                    case CloudActionType.UploadUnconditional:
-                        UploadCloudFile(localFile, action.LocalHash.Value);
-                        break;
-                    case CloudActionType.DownloadUnconditional:
-                        DownloadCloudFile(_pithosContainer, new Uri(cloudFile.Name,UriKind.Relative), downloadPath);
-                        break;
-                    case CloudActionType.DeleteCloud:
-                        DeleteCloudFile(cloudFile.Name);
-                        break;
-                    case CloudActionType.RenameCloud:
-                        RenameCloudFile(action.OldFileName, action.NewPath, action.NewFileName);
-                        break;
-                    case CloudActionType.MustSynch:
-                        if (File.Exists(downloadPath))
-                        {
-                            var cloudHash = cloudFile.Hash;
-                            var localHash = action.LocalHash.Value;
-                            if (!cloudHash.Equals(localHash, StringComparison.InvariantCultureIgnoreCase))
-                            {
-                                var lastLocalTime = localFile.LastWriteTime;
-                                var lastUpTime = cloudFile.Last_Modified;
-                                if (lastUpTime <= lastLocalTime)
-                                {
-                                    //Local change while the app was down or Files in conflict
-                                    //Maybe need to store version as well, to check who has the latest version
 
-                                    //StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
-                                    UploadCloudFile(localFile, action.LocalHash.Value);
-                                }
-                                else
-                                {
-                                    var status = StatusKeeper.GetFileStatus(downloadPath);
-                                    switch (status)
-                                    {
-                                        case FileStatus.Unchanged:
-                                            //It he cloud file has a later date, it was modified by another user or computer.
-                                            //If the local file's status is Unchanged, we should go on and download the cloud file
-                                            DownloadCloudFile(_pithosContainer, new Uri(action.CloudFile.Name,UriKind.Relative), downloadPath);
-                                            break;
-                                        case FileStatus.Modified:
-                                            //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
-                                            //We can't ensure that a file modified online since the last time will appear as Modified, unless we 
-                                            //index all files before we start listening.
-                                            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
-                                            break;
-                                        case FileStatus.Created:
-                                            //If the local file is Created, it means that the local and cloud files aren't related yet have the same name
-                                            //In this case we must mark the file as in conflict
-                                            //Other cases should never occur. Mark them as Conflict as well but log a warning
-                                            StatusKeeper.SetFileOverlayStatus(downloadPath,FileOverlayStatus.Conflict);
-                                            break;
-                                        default:
-                                            //If the local file is Created, it means that the local and cloud files aren't related yet have the same name
-                                            //In this case we must mark the file as in conflict
-                                            //Other cases should never occur. Mark them as Conflict as well but log a warning
-                                            StatusKeeper.SetFileOverlayStatus(downloadPath,FileOverlayStatus.Conflict);
-                                            Trace.TraceWarning("Unexcepted status {0} for file {1}->{2}",status,downloadPath,action.CloudFile.Name);
-                                            break;
-                                    }
-                                }
-                            }
-                        }
-                        else
-                            DownloadCloudFile(_pithosContainer, new Uri(action.CloudFile.Name,UriKind.Relative), downloadPath);
-                        break;
-                }
-                Trace.TraceInformation("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile, action.CloudFile.Name);
-            }
-            catch (OperationCanceledException)
-            {
-                throw;
-            }
-            catch (Exception exc)
-            {
-                Trace.TraceError("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
-                                action.Action, action.LocalFile, action.CloudFile, exc);
+                //var localFile = action.LocalFile;
+                var cloudFile = action.CloudFile;
+                var downloadPath = action.LocalFile.GetProperCapitalization();
 
-                _agent.Post(action);
-            }
+                var cloudHash = cloudFile.Hash.ToLower();
+                var previousCloudHash = cloudFile.PreviousHash == null?null: cloudFile.PreviousHash.ToLower();
+                var localHash = action.TreeHash.Value.TopHash.ToHashString();// LocalHash.Value.ToLower();
+                //var topHash = action.TopHash.Value.ToLower();
 
-        }
+                if(cloudFile.IsDirectory && action.LocalFile is DirectoryInfo)
+                {
+                    Log.InfoFormat("Skipping folder {0} , exists in server", downloadPath);
+                    return;
+                }
 
-        
+                //At this point we know that an object has changed on the server and that a local
+                //file already exists. We need to decide whether the file has only changed on 
+                //the server or there is a conflicting change on the client.
+                //
 
-        private void RenameCloudFile(string oldFileName, string newPath, string newFileName)
-        {
-            if (String.IsNullOrWhiteSpace(oldFileName))
-                throw new ArgumentNullException("oldFileName");
-            if (String.IsNullOrWhiteSpace(oldFileName))
-                throw new ArgumentNullException("newPath");
-            if (String.IsNullOrWhiteSpace(oldFileName))
-                throw new ArgumentNullException("newFileName");
-            Contract.EndContractBlock();
-            //The local file is already renamed
-            this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Modified);
+                //If the hashes match, we are done
+                if (cloudFile != ObjectInfo.Empty && cloudHash == localHash)
+                {
+                    Log.InfoFormat("Skipping {0}, hashes match", downloadPath);
+                    return;
+                }
 
-            CloudClient.MoveObject(_pithosContainer, oldFileName, _pithosContainer, newFileName);
+                //If the local and remote files have 0 length their hashes will not match
+                if (!cloudFile.IsDirectory && cloudFile.Bytes==0 && action.LocalFile is FileInfo && (action.LocalFile as FileInfo).Length==0 )
+                {
+                    Log.InfoFormat("Skipping {0}, files are empty", downloadPath);
+                    return;
+                }
 
-            this.StatusKeeper.SetFileStatus(newPath, FileStatus.Unchanged);
-            this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Normal);
-            NativeMethods.RaiseChangeNotification(newPath);
+                //The hashes DON'T match. We need to sync
+
+                // If the previous tophash matches the local tophash, the file was only changed on the server. 
+                if (localHash == previousCloudHash)
+                {
+                    await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath, CurrentOperationCancelToken);
+                }
+                else
+                {
+                    //If the previous and local hash don't match, there was a local conflict
+                    //that was not uploaded to the server. We have a conflict
+                    ReportConflictForMismatch(downloadPath);
+                }
+            }
         }
 
-        private void DeleteCloudFile(string fileName)
-        {            
-            if (String.IsNullOrWhiteSpace(fileName))
-                throw new ArgumentNullException("fileName");
-            if (Path.IsPathRooted(fileName))
-                throw new ArgumentException("The fileName should not be rooted","fileName");
+        private void ReportConflictForMismatch(string downloadPath)
+        {
+            if (String.IsNullOrWhiteSpace(downloadPath))
+                throw new ArgumentNullException("downloadPath");
             Contract.EndContractBlock();
 
-            this.StatusKeeper.SetFileOverlayStatus(fileName, FileOverlayStatus.Modified);
-
-            CloudClient.MoveObject(_pithosContainer, fileName, _trashContainer, fileName);
-            this.StatusKeeper.ClearFileStatus(fileName);
-            this.StatusKeeper.RemoveFileOverlayStatus(fileName);
+            StatusKeeper.SetFileState(downloadPath,FileStatus.Conflict, FileOverlayStatus.Conflict,"File changed at the server");
+            UpdateStatus(PithosStatus.HasConflicts);
+            var message = String.Format("Conflict detected for file {0}", downloadPath);
+            Log.Warn(message);
+            StatusNotification.NotifyChange(message, TraceLevel.Warning);
         }
 
-        //Download a file.
-        private void DownloadCloudFile(string container, Uri relativeUrl, string localPath)
+        public void Post(CloudAction cloudAction)
         {
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
-            if (relativeUrl==null)
-                throw new ArgumentNullException("relativeUrl");
-
-            if (String.IsNullOrWhiteSpace(localPath))
-                throw new ArgumentNullException("localPath");
-            if (!Path.IsPathRooted(localPath))
-                throw new ArgumentException("The localPath must be rooted", "localPath");
+            if (cloudAction == null)
+                throw new ArgumentNullException("cloudAction");
+            if (cloudAction.AccountInfo==null)
+                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
             Contract.EndContractBlock();
 
-            var url = relativeUrl.ToString();
-            if (url.EndsWith(".ignore",StringComparison.InvariantCultureIgnoreCase))
-                return;
+            DeleteAgent.ProceedEvent.Wait();
+            
+            if (cloudAction is CloudDeleteAction)
+                DeleteAgent.Post((CloudDeleteAction)cloudAction);
+            else
+                _agent.Post(cloudAction);
+        }
+       
 
-            //Are we already downloading or uploading the file? 
-            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
-            {
-                if (gate.Failed)
-                    return;
-                //Calculate the relative file path for the new file
-                var relativePath = relativeUrl.RelativeUriToFilePath();
-                //The file will be stored in a temporary location while downloading with an extension .download
-                var tempPath = Path.Combine(FileAgent.FragmentsPath, relativePath + ".download");
-                //The file's hashmap will be stored in the same location with the extension .hashmap
-                var hashPath = Path.Combine(FileAgent.FragmentsPath, relativePath + ".hashmap");
-                
-                //Retrieve the hashmap from the server
-                var getHashMap = CloudClient.GetHashMap(container,url);
-                //And save it
-                var saveHashMap = getHashMap.ContinueWith(t =>
-                {
-                    var treeHash = t.Result;
-                    treeHash.Save(hashPath);
-                });
+        public IEnumerable<CloudAction> GetEnumerable()
+        {
+            return _agent.GetEnumerable();
+        }
 
-                //Make sure the target folder exists. DownloadFileTask will not create the folder
-                var directoryPath=Path.GetDirectoryName(tempPath);
-                if (!Directory.Exists(directoryPath))
-                    Directory.CreateDirectory(directoryPath);
+        public Task GetDeleteAwaiter()
+        {
+            return DeleteAgent.ProceedEvent.WaitAsync();
+        }
+        public CancellationToken CancellationToken
+        {
+            get { return _agent.CancellationToken; }
+        }
 
-                //Download the object to the temporary location
-                var getObject = CloudClient.GetObject(container, url, tempPath).ContinueWith(t =>
+        public bool Pause
+        {
+            get {
+                return _pause;
+            }
+            set {
+                _pause = value;
+                if (_pause)
+                    _unPauseEvent.Reset();
+                else
                 {
-                    //And move it to its actual location once downloading is finished
-                    if (File.Exists(localPath))
-                        File.Replace(tempPath,localPath,null,true);
-                    else
-                        File.Move(tempPath,localPath);
-                });
-                
-                //Retrieve the object's metadata
-                var getInfo = saveHashMap.ContinueWith(t => getObject).ContinueWith(t =>
-                            CloudClient.GetObjectInfo(container, url));
-                //And store it
-                var storeInfo = getInfo.ContinueWith(t =>
-                            StatusKeeper.StoreInfo(localPath, t.Result));
-
-                storeInfo.Wait();
-
+                    _unPauseEvent.Set();
+                }
             }
         }
 
-        private void UploadCloudFile(FileInfo fileInfo, string hash)
+
+        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
         {
-            if (fileInfo==null)
-                throw new ArgumentNullException("fileInfo");
-            if (String.IsNullOrWhiteSpace(hash))
-                throw new ArgumentNullException("hash");
+            if (accountInfo==null)
+                throw new ArgumentNullException("accountInfo");
+            if (action==null)
+                throw new ArgumentNullException("action");
+            if (action.CloudFile==null)
+                throw new ArgumentException("CloudFile","action");
+            if (action.LocalFile==null)
+                throw new ArgumentException("LocalFile","action");
+            if (action.OldLocalFile==null)
+                throw new ArgumentException("OldLocalFile","action");
+            if (action.OldCloudFile==null)
+                throw new ArgumentException("OldCloudFile","action");
             Contract.EndContractBlock();
 
-            if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
-                return;
-            
-            var url = fileInfo.AsRelativeUrlTo(FileAgent.RootPath);
-
-            using(var gate=NetworkGate.Acquire(fileInfo.FullName,NetworkOperation.Uploading))
+            using (ThreadContext.Stacks["Operation"].Push("RenameCloudFile"))
             {
-                //Abort if the file is already being uploaded or downloaded
-                if (gate.Failed)
-                    return;
 
+                var newFilePath = action.LocalFile.FullName;
 
-                //Even if GetObjectInfo times out, we can proceed with the upload            
-                var info = CloudClient.GetObjectInfo(_pithosContainer, url);
+                //How do we handle concurrent renames and deletes/uploads/downloads?
+                //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
+                //  This should never happen as the network agent executes only one action at a time
+                //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
+                //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
+                //  same name will fail.
+                //  This should never happen as the network agent executes only one action at a time.
+                //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
+                //  to remove the rename from the queue.
+                //  We can probably ignore this case. It will result in an error which should be ignored            
 
-                //If the file hashes match, abort the upload
-                if (hash.Equals(info.Hash, StringComparison.InvariantCultureIgnoreCase))
-                {
-                    //but store any metadata changes 
-                    this.StatusKeeper.StoreInfo(fileInfo.FullName, info);
-                    Trace.TraceInformation("Skip upload of {0}, hashes match", fileInfo.FullName);
-                    return;
-                }
 
-                //If the file was last modified by a hashmap operation, its hash will be a treehash
-                //We must load the local file's treehash and check it against the object's hash 
-                //The hash will be stored under the fragments path, in the same relative path as to
-                //the pithos root path
-                var relativePath = fileInfo.AsRelativeTo(FileAgent.RootPath);
-                var hashPath = Path.Combine(FileAgent.FragmentsPath, relativePath) + ".hashmap";                
-                //Load the hash or calculate a new one
-                var hashFileExists = File.Exists(hashPath);
-                var treeHash = hashFileExists ?
-                    TreeHash.LoadTreeHash(hashPath, Guid.NewGuid()).Result
-                    : Signature.CalculateTreeHash(fileInfo.FullName, _blockSize, _blockHash);
-                //If this is a new treehash, store it
-                if (!hashFileExists)
-                    treeHash.Save(hashPath);
-
-                var topHash = treeHash.TopHash.ToHashString();
-                if (topHash.Equals(info.Hash, StringComparison.InvariantCultureIgnoreCase))
-                {
-                    this.StatusKeeper.StoreInfo(fileInfo.FullName, info);
-                    Trace.TraceInformation("Skip upload of {0}, treehashes match", fileInfo.FullName);
-                    return;                    
-                }
-            
+                //The local file is already renamed
+                StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified).Wait();
 
 
+                var account = action.CloudFile.Account ?? accountInfo.UserName;
+                var container = action.CloudFile.Container;
 
-                //Does the object exist or not?
+                var client = new CloudFilesClient(accountInfo);
+                //TODO: What code is returned when the source file doesn't exist?
+                client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
 
-                //Calculate or load the file's hashmap                
-
-                /*
-                 if (fileInfo.Bytes > _blockSize)
-                 {
-                  var hashPath = Path.Combine(FileAgent.FragmentsPath, relativePath) + ".hashmap";
-                
-                //Load the existing hashPath, if we have one, or calculate a new one
-                var treeHash = File.Exists(hashPath) ?
-                    TreeHash.LoadTreeHash(hashPath, Guid.NewGuid()).Result 
-                    : Signature.CalculateTreeHash(fileInfo.FullName, _blockSize , _blockHash);
-                                
-                //Do the Hashmap Put
-                Task<string> putHashMap=CloudClient.PutHashMap(_pithosContainer,url, treeHash);
-                putHashMap.Wait();
-                 }*/                    
-
-            //
-
-
-                var putOrUpdate = Task.Factory.StartNew(() =>
-                {
-                    //Mark the file as modified while we upload it
-                    var setStatus = Task.Factory.StartNew(() =>
-                        StatusKeeper.SetFileOverlayStatus(fileInfo.FullName,FileOverlayStatus.Modified));
-                    //And then upload it
-                    var put = setStatus.ContinueWith(t =>
-                        CloudClient.PutObject(_pithosContainer,url,fileInfo.FullName, hash));
-                });
-                putOrUpdate.Wait();
-                //If everything succeeds, change the file and overlay status to normal
-                this.StatusKeeper.SetFileState(fileInfo.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
+                StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
+                StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal).Wait();
+                NativeMethods.RaiseChangeNotification(newFilePath);
             }
-            //Notify the Shell to update the overlays
-            NativeMethods.RaiseChangeNotification(fileInfo.FullName);
         }
 
 
+        
+
     }