Modified selective sync to propagate the creation of new local directories and their...
[pithos-ms-client] / trunk / Pithos.Core / Agents / NetworkAgent.cs
index b8c9dcc..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; }
 
-        public string PithosContainer { get; set; }
-        public string TrashContainer { get; private set; }
+        private Uploader _uploader;
 
-        public int BlockSize { get; set; }
-        public string BlockHash { get; set; }
+        [System.ComponentModel.Composition.Import]
+        public Uploader Uploader
+        {
+            get { return _uploader; }
+            set
+            {
+                _uploader = value;
+                _uploader.UnpauseEvent = _unPauseEvent;                
+            }
+        }
 
+        private Downloader _downloader;
 
-        public void Start(string pithosContainer, string trashContainer, int blockSize, string blockHash)
+        [System.ComponentModel.Composition.Import]
+        public Downloader Downloader
         {
-            if (String.IsNullOrWhiteSpace(pithosContainer))
-                throw new ArgumentNullException("pithosContainer");
-            if (String.IsNullOrWhiteSpace(trashContainer))
-                throw new ArgumentNullException("trashContainer");
-            Contract.EndContractBlock();
+            get { return _downloader; }
+            set
+            {
+                _downloader = value;
+                _downloader.UnpauseEvent = _unPauseEvent;
+            }
+        }
+
+        [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
+        {
+            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=Process(message);
+                    var process=message.Then(Process,inbox.CancellationToken);
                     inbox.LoopAsync(process, loop);
-*/
-
-/*
-                    process1.ContinueWith(t =>
-                    {
-                        inbox.DoAsync(loop);
-                        if (t.IsFaulted)
-                        {
-                            var ex = t.Exception.InnerException;
-                            if (ex is OperationCanceledException)
-                                inbox.Stop();
-                        }
-                    });
-*/
-                    //inbox.DoAsync(loop);
-
-
-                    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)
+        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();
-            
-            //If the action targets a local file, add a treehash calculation
-            if (cloudAction.LocalFile != null)
-            {
-                cloudAction.TopHash = new Lazy<string>(() => Signature.CalculateTreeHashAsync(cloudAction.LocalFile, 
-                                    BlockSize, BlockHash).Result
-                                     .TopHash.ToHashString());
 
-            }
-            _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 =>
-            {
-                if (task.IsFaulted)
-                {
-                    //ListObjects failed at this point, need to reschedule
-                    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;
-
-                var commonObjects = new List<Tuple<ObjectInfo, FileInfo,FileState>>();
-                var remoteOnly = new List<ObjectInfo>();
-                
-                //In order to avoid multiple iterations over the files, we iterate only once
-                //over the remote files
-                foreach (var objectInfo in remote)
+                try
                 {
-                    var relativePath= objectInfo.Name.RelativeUrlToFilePath();// fileInfo.AsRelativeUrlTo(FileAgent.RootPath);
-                    //and remove any matching objects from the list, adding them to the commonObjects list
-                    if (FileAgent.Exists(relativePath))
+                    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))
                     {
-                        var localFile = FileAgent.GetFileInfo(relativePath);
-                        var state=FileState.FindByFilePath(localFile.FullName);                        
-                        commonObjects.Add(Tuple.Create(objectInfo, localFile,state));
+                        //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
-                        remoteOnly.Add(objectInfo);
+                    {
+                        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);
                 }
-
-                //At the end of the iteration, the *remote* list will contain the files that exist 
-                //only on the server
-
-                //Remote files should be downloaded
-                var actionsForRemote = from upFile in remoteOnly
-                                       select new CloudAction(CloudActionType.DownloadUnconditional,upFile);
-
-                //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
-                                       let state=pair.Item3
-                                       select new CloudAction(CloudActionType.MustSynch, 
-                                           localFile, objectInfo,state);
-                
-
-                //Collect all the actions
-                var allActions = actionsForRemote.Union(actionsForCommon);
-
-                //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
-                foreach (var message in distinctActions)
+/*
+                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)
                 {
-                    Post(message);
+                    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));
                 }
-
-
-                if(remoteOnly.Count>0)
-                    StatusNotification.NotifyChange(String.Format("Processing {0} new files", remoteOnly.Count));
-
-                Trace.TraceInformation("[LISTENER] End Processing");
-                Trace.CorrelationManager.StopLogicalOperation();
-
-            });
-
-            var loop = enqueueFiles.ContinueWith(t =>
-            {
-                if (t.IsFaulted)
+                catch (FileNotFoundException)
                 {
-                    Trace.TraceError("[LISTENER] Exception: {0}", t.Exception);
+                    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));
                 }
-                else
+                catch (Exception exc)
                 {
-                    Trace.TraceInformation("[LISTENER] Finished");
+                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
+                                     action.Action, action.LocalFile, action.CloudFile, exc);
+
+                    _agent.Post(action);
                 }
-                ProcessRemoteFiles(accountPath, nextSince);
-                
-            });
-            return loop;
+                finally
+                {
+                    if (_agent.IsEmpty)
+                        _proceedEvent.Set();
+                    UpdateStatus(PithosStatus.LocalComplete);                                        
+                }
+            }
         }
 
-        
-        private Task Process(Task<CloudAction> action)
+        private void ProcessChildUploads(CloudUploadAction uploadAction)
         {
-            return action.ContinueWith(t=> Process(t.Result));
-        }
+            if (!uploadAction.IsCreation || !(uploadAction.LocalFile is DirectoryInfo)) 
+                return;
 
+            var dirInfo = uploadAction.LocalFile as DirectoryInfo;
 
-        private void Process(CloudAction action)
-        {
-            if (action==null)
-                throw new ArgumentNullException("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
+            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)
             {
-                switch (action.Action)
-                {
-                    case CloudActionType.UploadUnconditional:
-                        UploadCloudFile(localFile, action.LocalHash.Value,action.TopHash.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;
-                            var topHash = action.TopHash.Value;
-                            //Not enough to compare only the local hashes, also have to compare the tophashes
-                            if (!cloudHash.Equals(localHash, StringComparison.InvariantCultureIgnoreCase) &&
-                                !cloudHash.Equals(topHash, 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,action.TopHash.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;
+                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);
             }
-            catch (Exception exc)
-            {
-                Trace.TraceError("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
-                                action.Action, action.LocalFile, action.CloudFile, exc);
-
-                _agent.Post(action);
-            }
-
         }
 
-        
-
-        private void RenameCloudFile(string oldFileName, string newPath, string newFileName)
+        private CancellationToken CurrentOperationCancelToken
         {
-            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);
-
-            this.StatusKeeper.SetFileStatus(newPath, FileStatus.Unchanged);
-            this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Normal);
-            NativeMethods.RaiseChangeNotification(newPath);
+            get { return _currentOperationCancellation.Token; }
         }
 
-        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();
-
-            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());
         }
 
-        //Download a file.
-        private void DownloadCloudFile(string container, Uri relativeUrl, string localPath)
+        private void RenameLocalFile(AccountInfo accountInfo, CloudAction action)
         {
-            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 (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 url = relativeUrl.ToString();
-            if (url.EndsWith(".ignore",StringComparison.InvariantCultureIgnoreCase))
-                return;
+                //We assume that the local file already exists, otherwise the poll agent
+                //would have issued a download request
 
-            //Are we already downloading or uploading the file? 
-            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
-            {
-                if (gate.Failed)
-                    return;
-                //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);                
-                var downloadTask= getHashMap.ContinueWith(t =>
-                {
-                    var serverHash=t.Result;
-                    //If it's a small file
-                    return serverHash.Hashes.Count == 1 
-                        //Download it in one go
-                        ? DownloadEntireFile(container, relativeUrl, localPath) 
-                        //Otherwise download it block by block
-                        : DownloadWithBlocks(container, relativeUrl, localPath, serverHash);
-                });
-
-                
-
-                //Retrieve the object's metadata
-                var getInfo = downloadTask.ContinueWith(t =>
-                            CloudClient.GetObjectInfo(container, url));
-                //And store it
-                var storeInfo = getInfo.ContinueWith(t =>
-                            StatusKeeper.StoreInfo(localPath, t.Result));
-
-                storeInfo.Wait();
-                StatusNotification.NotifyChangedFile(localPath);
+                var currentInfo = action.CloudFile;
+                var previousInfo = action.CloudFile.Previous;
+                var fileAgent = FileAgent.GetFileAgent(accountInfo);
+
+                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);
             }
         }
 
-        //Download a small file with a single GET operation
-        private Task DownloadEntireFile(string container, Uri relativeUrl, string localPath)
+        private void MoveLocalFile(AccountInfo accountInfo, FileSystemInfo previousFile, FileAgent fileAgent,
+                                   ObjectInfo currentInfo)
         {
-            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");
-            Contract.EndContractBlock();
+            var currentRelativepath = currentInfo.RelativeUrlToFilePath(accountInfo.UserName);
+            var newPath = Path.Combine(fileAgent.RootPath, currentRelativepath);
 
-            //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");
-            //Make sure the target folder exists. DownloadFileTask will not create the folder
-            var directoryPath = Path.GetDirectoryName(tempPath);
-            if (!Directory.Exists(directoryPath))
-                Directory.CreateDirectory(directoryPath);
-
-            //Download the object to the temporary location
-            var getObject = CloudClient.GetObject(container, relativeUrl.ToString(), tempPath).ContinueWith(t =>
+            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))
             {
-                //And move it to its actual location once downloading is finished
-                if (File.Exists(localPath))
-                    File.Replace(tempPath,localPath,null,true);
+                if (isFile)
+                    (previousFile as FileInfo).MoveTo(newPath);
                 else
-                    File.Move(tempPath,localPath);
-            });
-            return getObject;
+                {
+                    (previousFile as DirectoryInfo).MoveTo(newPath);
+                }
+                var state = StatusKeeper.GetStateByFilePath(previousFullPath);
+                state.FilePath = newPath;
+                state.SaveCopy();
+                StatusKeeper.SetFileState(previousFullPath,FileStatus.Deleted,FileOverlayStatus.Deleted, "Deleted");
+            }            
         }
 
-        public Task DownloadWithBlocks(string container,Uri relativeUrl, string localPath,TreeHash serverHash)
+        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
         {
-            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(serverHash==null)
-                throw new ArgumentNullException("serverHash");
+            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"))
+            {
 
-            //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");
-            var directoryPath = Path.GetDirectoryName(tempPath);
-            if (!Directory.Exists(directoryPath))
-                Directory.CreateDirectory(directoryPath);
-            
-            //If the local file exists we should make a copy of it to the
-            //fragments folder, unless a newer temp copy already exists, which
-            //means there is an interrupted download
-            if (ShouldCopy(localPath, tempPath))
-                File.Copy(localPath, tempPath, true);    
+                //var localFile = action.LocalFile;
+                var cloudFile = action.CloudFile;
+                var downloadPath = action.LocalFile.GetProperCapitalization();
 
-            //Set the size of the file to the size specified in the treehash
-            //This will also create an empty file if the file doesn't exist            
-            SetFileSize(tempPath, serverHash.Bytes);
+                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();
 
-            return Task.Factory.StartNew(() =>
-            {
-                //Calculate the temp file's treehash
-                var treeHash = Signature.CalculateTreeHashAsync(tempPath, this.BlockSize,BlockHash).Result;
-                
-                //And compare it with the server's hash
-                var upHashes = serverHash.GetHashesAsStrings();
-                var localHashes = treeHash.HashDictionary;
-                for (int i = 0; i < upHashes.Length; i++)
+                if(cloudFile.IsDirectory && action.LocalFile is DirectoryInfo)
                 {
-                    //For every non-matching hash
-                    if (!localHashes.ContainsKey(upHashes[i]))
-                    {
-                        Trace.TraceInformation("[BLOCK GET] START {0} of {1} for {2}",i,upHashes.Length,localPath);
-                        var start = i*BlockSize;
-                        long? end = null;
-                        if (i < upHashes.Length - 1 )
-                            end= ((i + 1)*BlockSize) ;
-                            
-                        //Get its block
-                        var blockTask = CloudClient.GetBlock(container, relativeUrl,
-                                                            start, end);
-
-                        blockTask.ContinueWith(b =>
-                        {
-                            //And apply it to the temp file
-                            var buffer = b.Result;
-                            var stream =FileAsync.OpenWrite(tempPath);
-                            stream.Seek(start,SeekOrigin.Begin);
-                            return stream.WriteAsync(buffer, 0, buffer.Length)
-                                .ContinueWith(s => stream.Close());
-
-                        }).Unwrap()
-                        .Wait();
-                        Trace.TraceInformation("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
-                    }
+                    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.
+                //
+
+                //If the hashes match, we are done
+                if (cloudFile != ObjectInfo.Empty && cloudHash == localHash)
+                {
+                    Log.InfoFormat("Skipping {0}, hashes match", downloadPath);
+                    return;
                 }
-                
 
-                //Replace the existing file with the temp
-                if (File.Exists(localPath))
-                    File.Replace(tempPath, localPath, null, true);
-                else
-                    File.Move(tempPath, localPath);
-                Trace.TraceInformation("[BLOCK GET] COMPLETE {0}", localPath);
-            });
-        }
+                //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;
+                }
 
-        //Change the file's size, possibly truncating or adding to it
-        private static void SetFileSize(string filePath, long fileSize)
-        {
-            if (String.IsNullOrWhiteSpace(filePath))
-                throw new ArgumentNullException("filePath");
-            if (!Path.IsPathRooted(filePath))
-                throw new ArgumentException("The filePath must be rooted", "filePath");
-            if (fileSize<0)
-                throw new ArgumentOutOfRangeException("fileSize");
-            Contract.EndContractBlock();
+                //The hashes DON'T match. We need to sync
 
-            using (var stream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write))
-            {
-                stream.SetLength(fileSize);
+                // 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);
+                }
             }
         }
 
-        //Check whether we should copy the local file to a temp path        
-        private static bool ShouldCopy(string localPath, string tempPath)
+        private void ReportConflictForMismatch(string downloadPath)
         {
-            //No need to copy if there is no file
-            if (!File.Exists(localPath))            
-                return false;
-
-            //If there is no temp file, go ahead and copy
-            if (!File.Exists(tempPath))                
-                return true;
+            if (String.IsNullOrWhiteSpace(downloadPath))
+                throw new ArgumentNullException("downloadPath");
+            Contract.EndContractBlock();
 
-            //If there is a temp file and is newer than the actual file, don't copy
-            var localLastWrite = File.GetLastWriteTime(localPath);
-            var tempLastWrite = File.GetLastWriteTime(tempPath);
-            
-            //This could mean there is an interrupted download in progress
-            return (tempLastWrite < localLastWrite);
+            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);
         }
 
-        private void UploadCloudFile(FileInfo fileInfo, string hash,string topHash)
+        public void Post(CloudAction cloudAction)
         {
-            if (fileInfo==null)
-                throw new ArgumentNullException("fileInfo");
-            if (String.IsNullOrWhiteSpace(hash))
-                throw new ArgumentNullException("hash");
+            if (cloudAction == null)
+                throw new ArgumentNullException("cloudAction");
+            if (cloudAction.AccountInfo==null)
+                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
             Contract.EndContractBlock();
 
-            if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
-                return;
+            DeleteAgent.ProceedEvent.Wait();
             
-            var url = fileInfo.AsRelativeUrlTo(FileAgent.RootPath);
-
-            var fullFileName = fileInfo.FullName;
-            using(var gate=NetworkGate.Acquire(fullFileName,NetworkOperation.Uploading))
-            {
-                //Abort if the file is already being uploaded or downloaded
-                if (gate.Failed)
-                    return;
-
-
-                //Even if GetObjectInfo times out, we can proceed with the upload            
-                var info = CloudClient.GetObjectInfo(PithosContainer, url);
+            if (cloudAction is CloudDeleteAction)
+                DeleteAgent.Post((CloudDeleteAction)cloudAction);
+            else
+                _agent.Post(cloudAction);
+        }
+       
 
-                //If the file hashes match, abort the upload
-                if (hash.Equals(info.Hash, StringComparison.InvariantCultureIgnoreCase) ||
-                    topHash.Equals(info.Hash, StringComparison.InvariantCultureIgnoreCase))
-                {
-                    //but store any metadata changes 
-                    this.StatusKeeper.StoreInfo(fullFileName, info);
-                    Trace.TraceInformation("Skip upload of {0}, hashes match", fullFileName);
-                    return;
-                }
+        public IEnumerable<CloudAction> GetEnumerable()
+        {
+            return _agent.GetEnumerable();
+        }
 
-                //Mark the file as modified while we upload it
-                var setStatus = Task.Factory.StartNew(() =>
-                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified));
-                //And then upload it
+        public Task GetDeleteAwaiter()
+        {
+            return DeleteAgent.ProceedEvent.WaitAsync();
+        }
+        public CancellationToken CancellationToken
+        {
+            get { return _agent.CancellationToken; }
+        }
 
-                //If the file is larger than the block size, try a hashmap PUT
-                if (fileInfo.Length > BlockSize )
-                {
-                    //To upload using a hashmap
-                    //First, calculate the tree hash
-                    var treeHash = Signature.CalculateTreeHashAsync(fileInfo.FullName, BlockSize, BlockHash);                    
-                    
-                    var putHashMap = setStatus.ContinueWith(t=>
-                        UploadWithHashMap(fileInfo,url,treeHash));
-                    
-                    putHashMap.Wait();
-                }
+        public bool Pause
+        {
+            get {
+                return _pause;
+            }
+            set {
+                _pause = value;
+                if (_pause)
+                    _unPauseEvent.Reset();
                 else
                 {
-                    //Otherwise do a regular PUT
-                    var put = setStatus.ContinueWith(t =>
-                        CloudClient.PutObject(PithosContainer,url,fullFileName,hash));
-                    put.Wait();
+                    _unPauseEvent.Set();
                 }
-                //If everything succeeds, change the file and overlay status to normal
-                this.StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
             }
-            //Notify the Shell to update the overlays
-            NativeMethods.RaiseChangeNotification(fullFileName);
-            StatusNotification.NotifyChangedFile(fullFileName);
         }
 
-        public void UploadWithHashMap(FileInfo fileInfo,string url,Task<TreeHash> treeHash)
-        {
-            var fullFileName = fileInfo.FullName;
 
-            //Send the hashmap to the server            
-            var hashPut = CloudClient.PutHashMap(PithosContainer, url, treeHash.Result);
-            var missingHashes = hashPut.Result;
-            if (missingHashes.Count == 0)
-                return;
+        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
+        {
+            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();
 
-            var buffer = new byte[BlockSize];                      
-            foreach (var missingHash in missingHashes)
+            using (ThreadContext.Stacks["Operation"].Push("RenameCloudFile"))
             {
-                int blockIndex = -1;
-                try
-                {
-                    //Find the proper block
-                    blockIndex = treeHash.Result.HashDictionary[missingHash];
-                    var offset = blockIndex*BlockSize;
 
-                    var read = fileInfo.Read(buffer, offset, BlockSize);
-                    if (read > 0)
-                    {
-                        //Copy the actual block data out of the buffer
-                        var data = new byte[read];
-                        Buffer.BlockCopy(buffer, 0, data, 0, read);
-
-                        //And POST them
-                        CloudClient.PostBlock(PithosContainer, data).Wait();
-                        Trace.TraceInformation("[BLOCK] Block {0} of {1} uploaded", blockIndex,
-                            fullFileName);
-                    }
-                }
-                catch (Exception exc)
-                {
-                    Trace.TraceError("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
-                }
-            }
+                var newFilePath = action.LocalFile.FullName;
 
-            UploadWithHashMap(fileInfo, url, treeHash);
-            
+                //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);
+            }
         }
 
 
+        
+
     }