Replaced Merkle hash with MD5 for change checking
[pithos-ms-client] / trunk / Pithos.Core / Agents / NetworkAgent.cs
index 0e7069b..47e0ddc 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 Agent<CloudAction> _agent;
+        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 
-        [Import]
-        public IStatusKeeper StatusKeeper { get; set; }
-        
-        public IStatusNotification StatusNotification { get; set; }
-        [Import]
-        public ICloudClient CloudClient { get; set; }
-        [Import]
-        public IPithosWorkflow Workflow { get; set; }
+        //private Agent<CloudAction> _agent;
 
-        private string _rootPath;
-        private string _pithosContainer;
-        private string _trashContainer;
+        [System.ComponentModel.Composition.Import]
+        public DeleteAgent DeleteAgent { get; set; }
 
+        [System.ComponentModel.Composition.Import]
+        public IStatusKeeper StatusKeeper { get; set; }
 
-        public void Start(string rootPath,string pithosContainer,string trashContainer)
+        private IStatusNotification _statusNotification;
+        public IStatusNotification StatusNotification
         {
-            if (String.IsNullOrWhiteSpace(rootPath))
-                throw new ArgumentNullException("rootPath");
-            if (String.IsNullOrWhiteSpace(pithosContainer))
-                throw new ArgumentNullException("pithosContainer");
-            if (String.IsNullOrWhiteSpace(trashContainer))
-                throw new ArgumentNullException("trashContainer");
-            Contract.EndContractBlock();
-
-            _rootPath = rootPath;
-            _pithosContainer = pithosContainer;
-            _trashContainer = trashContainer;
-
-            _agent = Agent<CloudAction>.Start(inbox =>
+            get { return _statusNotification; }
+            set
             {
-                Action loop = null;
-                loop = () =>
-                {
-                    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();
-                        }
-                    });
-
-                };
-                loop();
-            });
-        }
-
-        public void Post(CloudAction cloudAction)
-        {
-            if (cloudAction == null)
-                throw new ArgumentNullException("cloudAction");
-            Contract.EndContractBlock();
-
-            _agent.Post(cloudAction);
+                _statusNotification = value;
+                DeleteAgent.StatusNotification = value;
+                Uploader.StatusNotification = value;
+                Downloader.StatusNotification = value;
+            }
         }
 
-        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));
+        [System.ComponentModel.Composition.Import]
+        public IPithosSettings Settings { get; set; }
 
-            DateTime nextSince = DateTime.Now.AddSeconds(-1);
+        private Uploader _uploader;
 
-            var enqueueFiles = listObjects.ContinueWith(task =>
+        [System.ComponentModel.Composition.Import]
+        public Uploader Uploader
+        {
+            get { return _uploader; }
+            set
             {
-                Trace.CorrelationManager.StartLogicalOperation("Listener");
-                Trace.TraceInformation("[LISTENER] Start Processing");
-
-                var remoteObjects = task.Result;
-
-                var pithosDir = new DirectoryInfo(accountPath);
-
-                var remoteFiles = from info in remoteObjects
-                                  select info.Name.ToLower();
+                _uploader = value;
+                _uploader.UnpauseEvent = _unPauseEvent;                
+            }
+        }
 
-                var onlyLocal = from localFile in pithosDir.EnumerateFiles()
-                                where !remoteFiles.Contains(localFile.Name.ToLower())
-                                select new CloudAction(CloudActionType.UploadUnconditional, localFile, ObjectInfo.Empty);
+        private Downloader _downloader;
 
-                var localNames = from info in pithosDir.EnumerateFiles()
-                                 select info.Name.ToLower();
+        [System.ComponentModel.Composition.Import]
+        public Downloader Downloader
+        {
+            get { return _downloader; }
+            set
+            {
+                _downloader = value;
+                _downloader.UnpauseEvent = _unPauseEvent;
+            }
+        }
 
-                var onlyRemote = from upFile in remoteObjects
-                                 where !localNames.Contains(upFile.Name.ToLower())
-                                 select new CloudAction(CloudActionType.DownloadUnconditional, null, upFile);
+        [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 bool _pause;
 
-                
-                var commonObjects = from upFile in remoteObjects
-                                    join localFile in pithosDir.EnumerateFiles()
-                                        on upFile.Name.ToLower() equals localFile.Name.ToLower()
-                                    select new CloudAction(CloudActionType.MustSynch, localFile, upFile);
+        public AsyncManualResetEvent ProceedEvent
+        {
+            get { return _proceedEvent; }
+        }
 
-                var uniques =
-                    onlyLocal.Union(onlyRemote).Union(commonObjects)
-                        .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
-                        .ToList();
+        private readonly AsyncManualResetEvent _unPauseEvent = new AsyncManualResetEvent(true);
 
-                _agent.AddFromEnumerable(uniques);
+        private CancellationTokenSource _currentOperationCancellation=new CancellationTokenSource();
 
-                StatusNotification.NotifyChange(String.Format("Processing {0} files", uniques.Count));
+        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();
+            
+        }
 
-                Trace.TraceInformation("[LISTENER] End Processing");
-                Trace.CorrelationManager.StopLogicalOperation();
+        /*public void Start()
+        {
+            if (_agent != null)
+                return;
 
-            });
+            if (Log.IsDebugEnabled)
+                Log.Debug("Starting Network Agent");
 
-            var loop = enqueueFiles.ContinueWith(t =>
+            _agent = Agent<CloudAction>.Start(inbox =>
             {
-                if (t.IsFaulted)
-                {
-                    Trace.TraceError("[LISTENER] Exception: {0}", t.Exception);
-                }
-                else
+                Action loop = null;
+                loop = () =>
                 {
-                    Trace.TraceInformation("[LISTENER] Finished");
-                }
-                ProcessRemoteFiles(accountPath,nextSince);
+                    DeleteAgent.ProceedEvent.Wait();
+                    _unPauseEvent.Wait();
+                    var message = inbox.Receive();
+                    var process=message.Then(Process,inbox.CancellationToken);
+                    inbox.LoopAsync(process, loop);
+                };
+                loop();
             });
-            return loop;
-        }
-
 
+        }*/
 
-        private void Process(CloudAction action)
+/*
+        private async Task Process(CloudAction action)
         {
-            if (action==null)
+            if (action == null)
                 throw new ArgumentNullException("action");
+            if (action.AccountInfo==null)
+                throw new ArgumentException("The action.AccountInfo is empty","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(_rootPath, cloudFile.Name);
-            try
-            {
-                switch (action.Action)
+
+
+
+            using (ThreadContext.Stacks["Operation"].Push(action.ToString()))
+            {                
+
+                var cloudFile = action.CloudFile;
+                var downloadPath = action.GetDownloadPath();
+
+                try
                 {
-                    case CloudActionType.UploadUnconditional:
-                        UploadCloudFile(localFile.Name, localFile.FullName, action.LocalHash.Value);
-                        break;
-                    case CloudActionType.DownloadUnconditional:
-                        DownloadCloudFile(_pithosContainer, cloudFile.Name, 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))
+                    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))
+                    {
+                        //Clear the status of already deleted files to avoid reprocessing
+                        if (action.LocalFile != null)
+                            StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
+                    }
+                    else
+                    {
+                        switch (action.Action)
                         {
-                            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)
+                            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))
                                 {
-                                    //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.Name, localFile.FullName, action.LocalHash.Value);
+                                    await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath, CurrentOperationCancelToken);
                                 }
                                 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, action.CloudFile.Name, 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;
-                                    }
+                                    await SyncFiles(accountInfo, action);
                                 }
-                            }
+                                break;
                         }
-                        else
-                            DownloadCloudFile(_pithosContainer, action.CloudFile.Name, downloadPath);
-                        break;
+                    }
+                    Log.InfoFormat("End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
+                                           action.CloudFile.Name);
                 }
-                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);
+/*
+                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);
+                    }
+                }
+#1#
+                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);
 
-                _agent.Post(action);
+                    _agent.Post(action);
+                }
+                finally
+                {
+                    if (_agent.IsEmpty)
+                        _proceedEvent.Set();
+                    UpdateStatus(PithosStatus.LocalComplete);                                        
+                }
             }
-
         }
+*/
 
-        
-
-        private void RenameCloudFile(string oldFileName, string newPath, string newFileName)
+    /*    private void ProcessChildUploads(CloudUploadAction uploadAction)
         {
-            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);
-
-            CloudClient.MoveObject(_pithosContainer, oldFileName, _pithosContainer, newFileName);
+            if (!uploadAction.IsCreation || !(uploadAction.LocalFile is DirectoryInfo)) 
+                return;
 
-            this.StatusKeeper.SetFileStatus(newPath, FileStatus.Unchanged);
-            this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Normal);
-            Workflow.RaiseChangeNotification(newPath);
+            var dirInfo = uploadAction.LocalFile as DirectoryInfo;
+
+            var account = uploadAction.AccountInfo;
+            var folderActions = from info in dirInfo.EnumerateDirectories("*", SearchOption.AllDirectories)                          
+                          select
+                              new CloudUploadAction(account, info, null, account.BlockSize, account.BlockHash,
+                                                    uploadAction, true);
+            var fileActions = from info in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories)                          
+                          select
+                              new CloudUploadAction(account, info, null, account.BlockSize, account.BlockHash,
+                                                    uploadAction, true);            
+            //Post folder actions first, to ensure the selective folders are updated
+            folderActions.ApplyAction(PostUploadAction);
+            fileActions.ApplyAction(PostUploadAction);            
         }
+*/
+/*
+        private void PostUploadAction(CloudUploadAction action)
+        {
+            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);
+        }
+*/
 
-        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");
-            Contract.EndContractBlock();
+        public CancellationToken CurrentOperationCancelToken
+        {
+            get { return _currentOperationCancellation.Token; }
+        }
 
-            this.StatusKeeper.SetFileOverlayStatus(fileName, FileOverlayStatus.Modified);
 
-            CloudClient.MoveObject(_pithosContainer, fileName, _trashContainer, fileName);
-            this.StatusKeeper.ClearFileStatus(fileName);
-            this.StatusKeeper.RemoveFileOverlayStatus(fileName);
+        private void UpdateStatus(PithosStatus status)
+        {
+            StatusNotification.SetPithosStatus(status);
+            //StatusNotification.Notify(new Notification());
         }
 
-        private void DownloadCloudFile(string container, string fileName, string localPath)
+        private void RenameLocalFile(AccountInfo accountInfo, CloudAction action)
         {
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
-            if (String.IsNullOrWhiteSpace(fileName))
-                throw new ArgumentNullException("fileName");
-            if (String.IsNullOrWhiteSpace(localPath))
-                throw new ArgumentNullException("localPath");
-            if (!Path.IsPathRooted(localPath))
-                throw new ArgumentException("The localPath must be rooted", "localPath");
+            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"))
+            {
 
-            var state = StatusKeeper.GetNetworkState(localPath);
-            //Abort if the file is already being uploaded or downloaded
-            if (state != NetworkState.None)
-                return;
-
-            StatusKeeper.SetNetworkState(localPath, NetworkState.Downloading);
-
-            var tempPath = Path.GetTempFileName();
+                //We assume that the local file already exists, otherwise the poll agent
+                //would have issued a download request
 
-            var getObject = CloudClient.GetObject(container, fileName, tempPath).ContinueWith(t =>
-                            File.Move(tempPath, localPath));
+                var currentInfo = action.CloudFile;
+                var previousInfo = action.CloudFile.Previous;
+                var fileAgent = FileAgent.GetFileAgent(accountInfo);
 
-            var getInfo = getObject.ContinueWith(t =>
-                            CloudClient.GetObjectInfo(container, fileName));
-            var storeInfo = getInfo.ContinueWith(t =>
-                            StatusKeeper.StoreInfo(fileName, t.Result));
+                var previousRelativepath = previousInfo.RelativeUrlToFilePath(accountInfo.UserName);
+                var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
 
-            storeInfo.Wait();
+                //In every case we need to move the local file first
+                MoveLocalFile(accountInfo, previousFile, fileAgent, currentInfo);
+            }
+        }
 
-            StatusKeeper.SetNetworkState(localPath, NetworkState.None);
+        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 (isFile)
+                    (previousFile as FileInfo).MoveTo(newPath);
+                else
+                {
+                    (previousFile as DirectoryInfo).MoveTo(newPath);
+                }
+                var state = StatusKeeper.GetStateByFilePath(previousFullPath);
+                state.FilePath = newPath;
+                state.SaveCopy();
+                StatusKeeper.SetFileState(previousFullPath,FileStatus.Deleted,FileOverlayStatus.Deleted, "Deleted");
+            }            
         }
 
-        private void UploadCloudFile(string fileName, string path, string hash)
+/*        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
         {
-            if (String.IsNullOrWhiteSpace(fileName))
-                throw new ArgumentNullException("fileName");
-            if (Path.IsPathRooted(fileName))
-                throw new ArgumentException("The fileName should not be rooted", "fileName");
-            if (String.IsNullOrWhiteSpace(path))
-                throw new ArgumentNullException("path");
-            if (String.IsNullOrWhiteSpace(hash))
-                throw new ArgumentNullException("hash");
+            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("SyncFiles"))
+            {
 
-            var state = StatusKeeper.GetNetworkState(path);
-            //Abort if the file is already being uploaded or downloaded
-            if (state != NetworkState.None)
-                return;
+                //var localFile = action.LocalFile;
+                var cloudFile = action.CloudFile;
+                var downloadPath = action.LocalFile.GetProperCapitalization();
 
-            StatusKeeper.SetNetworkState(path, NetworkState.Uploading);
+                var cloudHash = cloudFile.X_Object_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();
 
-            //Even if GetObjectInfo times out, we can proceed with the upload            
-            var info = CloudClient.GetObjectInfo(_pithosContainer, fileName);
+                if(cloudFile.IsDirectory && action.LocalFile is DirectoryInfo)
+                {
+                    Log.InfoFormat("Skipping folder {0} , exists in server", downloadPath);
+                    return;
+                }
 
-            var putOrUpdate = Task.Factory.StartNew(() =>
-            {
-                if (!hash.Equals(info.Hash, StringComparison.InvariantCultureIgnoreCase))
+                //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.
+                //
+
+                //If the hashes match, we are done
+                if (cloudFile != ObjectInfo.Empty && cloudHash == localHash)
                 {
-                    var setStatus = Task.Factory.StartNew(() =>
-                            StatusKeeper.SetFileOverlayStatus(path, FileOverlayStatus.Modified));
-                    var put = setStatus.ContinueWith(t =>
-                            CloudClient.PutObject(_pithosContainer, fileName, path, hash));
+                    Log.InfoFormat("Skipping {0}, hashes match", downloadPath);
+                    return;
+                }
+
+                //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;
+                }
+
+                //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
                 {
-                    this.StatusKeeper.StoreInfo(path, info);
+                    //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);
                 }
-            });
-            putOrUpdate.Wait();
+            }
+        }*/
 
-            this.StatusKeeper.SetFileState(path, FileStatus.Unchanged, FileOverlayStatus.Normal);
-            this.StatusKeeper.SetNetworkState(path, NetworkState.None);
-            Workflow.RaiseChangeNotification(path);
-        }
+        private void ReportConflictForMismatch(string downloadPath)
+        {
+            if (String.IsNullOrWhiteSpace(downloadPath))
+                throw new ArgumentNullException("downloadPath");
+            Contract.EndContractBlock();
 
+            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);
+        }
 
-    }
+/*
+        public void Post(CloudAction cloudAction)
+        {
+            if (cloudAction == null)
+                throw new ArgumentNullException("cloudAction");
+            if (cloudAction.AccountInfo==null)
+                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
+            Contract.EndContractBlock();
 
-    public class CloudAction
-    {
-        public CloudActionType Action { get; set; }
-        public FileInfo LocalFile { get; set; }
-        public ObjectInfo CloudFile { get; set; }
+            DeleteAgent.ProceedEvent.Wait();
+            
+            if (cloudAction is CloudDeleteAction)
+                DeleteAgent.Post((CloudDeleteAction)cloudAction);
+            else
+                _agent.Post(cloudAction);
+        }
+*/
+       
 
-        public Lazy<string> LocalHash { get; set; }
+/*
+        public IEnumerable<CloudAction> GetEnumerable()
+        {
+            return _agent.GetEnumerable();
+        }
+*/
 
-        public string OldFileName { get; set; }
-        public string OldPath { get; set; }
-        public string NewFileName { get; set; }
-        public string NewPath { get; set; }
+        public Task GetDeleteAwaiter()
+        {
+            return DeleteAgent.ProceedEvent.WaitAsync();
+        }
+/*
+        public CancellationToken CancellationToken
+        {
+            get { return _agent.CancellationToken; }
+        }
+*/
 
-        public CloudAction(CloudActionType action, string oldPath, string oldFileName, string newFileName, string newPath)
+        public bool Pause
         {
-            Action = action;
-            OldFileName = oldFileName;
-            OldPath = oldPath;
-            NewFileName = newFileName;
-            NewPath = newPath;
+            get {
+                return _pause;
+            }
+            set {
+                _pause = value;
+                if (_pause)
+                    _unPauseEvent.Reset();
+                else
+                {
+                    _unPauseEvent.Set();
+                }
+            }
         }
 
-        public CloudAction(CloudActionType action, FileInfo localFile, ObjectInfo cloudFile)
+
+        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
         {
-            Action = action;
-            LocalFile = localFile;
-            CloudFile = cloudFile;
-            if (LocalFile != null)
-                LocalHash = new Lazy<string>(() => Signature.CalculateMD5(LocalFile.FullName), LazyThreadSafetyMode.ExecutionAndPublication);
+            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();
+
+            using (ThreadContext.Stacks["Operation"].Push("RenameCloudFile"))
+            {
+
+                var newFilePath = action.LocalFile.FullName;
+
+                //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            
+
+
+                //The local file is already renamed
+                StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified).Wait();
+
+
+                var account = action.CloudFile.Account ?? accountInfo.UserName;
+                var container = action.CloudFile.Container;
+
+                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);
+
+                StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
+                StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal).Wait();
+                NativeMethods.RaiseChangeNotification(newFilePath);
+            }
         }
 
-    }
 
-    public enum CloudActionType
-    {
-        MustSynch,
-        UploadUnconditional,
-        DownloadUnconditional,
-        DeleteLocal,
-        DeleteCloud,
-        RenameCloud
+        
+
     }
 
+   
+
 
 }