Fixed incorrect account key in PollAgent.cs
[pithos-ms-client] / trunk / Pithos.Core / Agents / PollAgent.cs
index 2089da7..55f1a4d 100644 (file)
@@ -87,7 +87,7 @@ namespace Pithos.Core.Agents
         private readonly AsyncManualResetEvent _syncEvent = new AsyncManualResetEvent();\r
 \r
         private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();\r
-        private readonly ConcurrentDictionary<string, AccountInfo> _accounts = new ConcurrentDictionary<string,AccountInfo>();\r
+        private readonly ConcurrentDictionary<Uri, AccountInfo> _accounts = new ConcurrentDictionary<Uri,AccountInfo>();\r
 \r
 \r
         /// <summary>\r
@@ -105,10 +105,11 @@ namespace Pithos.Core.Agents
         /// <returns></returns>\r
         public async Task PollRemoteFiles(DateTime? since = null)\r
         {\r
-            Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");\r
+            if (Log.IsDebugEnabled)\r
+                Log.DebugFormat("Polling changes after [{0}]",since);\r
 \r
-            UpdateStatus(PithosStatus.Syncing);\r
-            StatusNotification.Notify(new PollNotification());\r
+            Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");\r
+            \r
 \r
             using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))\r
             {\r
@@ -116,18 +117,20 @@ namespace Pithos.Core.Agents
                 var nextSince = since;\r
                 try\r
                 {\r
-                    //Next time we will check for all changes since the current check minus 1 second\r
-                    //This is done to ensure there are no discrepancies due to clock differences\r
-                    var current = DateTime.Now.AddSeconds(-1);\r
+                    UpdateStatus(PithosStatus.PollSyncing);\r
 \r
                     var tasks = from accountInfo in _accounts.Values\r
                                 select ProcessAccountFiles(accountInfo, since);\r
 \r
-                    await TaskEx.WhenAll(tasks.ToList());\r
+                    var nextTimes=await TaskEx.WhenAll(tasks.ToList());\r
 \r
                     _firstPoll = false;\r
                     //Reschedule the poll with the current timestamp as a "since" value\r
-                    nextSince = current;\r
+\r
+                    if (nextTimes.Length>0)\r
+                        nextSince = nextTimes.Min();\r
+                    if (Log.IsDebugEnabled)\r
+                        Log.DebugFormat("Next Poll at [{0}]",nextSince);\r
                 }\r
                 catch (Exception ex)\r
                 {\r
@@ -135,7 +138,7 @@ namespace Pithos.Core.Agents
                     //In case of failure retry with the same "since" value\r
                 }\r
 \r
-                UpdateStatus(PithosStatus.InSynch);\r
+                UpdateStatus(PithosStatus.PollComplete);\r
                 //The multiple try blocks are required because we can't have an await call\r
                 //inside a finally block\r
                 //TODO: Find a more elegant solution for reschedulling in the event of an exception\r
@@ -177,7 +180,7 @@ namespace Pithos.Core.Agents
             return since;\r
         }\r
 \r
-        public async Task ProcessAccountFiles(AccountInfo accountInfo, DateTime? since = null)\r
+        public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, DateTime? since = null)\r
         {\r
             if (accountInfo == null)\r
                 throw new ArgumentNullException("accountInfo");\r
@@ -186,8 +189,9 @@ namespace Pithos.Core.Agents
             Contract.EndContractBlock();\r
 \r
 \r
-            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))\r
+            using (ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))\r
             {\r
+\r
                 await NetworkAgent.GetDeleteAwaiter();\r
 \r
                 Log.Info("Scheduled");\r
@@ -201,6 +205,11 @@ namespace Pithos.Core.Agents
 \r
                 CreateContainerFolders(accountInfo, containers);\r
 \r
+                //The nextSince time fallback time is the same as the current.\r
+                //If polling succeeds, the next Since time will be the smallest of the maximum modification times\r
+                //of the shared and account objects\r
+                var nextSince = since;\r
+\r
                 try\r
                 {\r
                     //Wait for any deletions to finish\r
@@ -219,17 +228,22 @@ namespace Pithos.Core.Agents
                     listObjects.Add(listShared);\r
                     var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());\r
 \r
-                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))\r
+                    using (ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))\r
                     {\r
                         var dict = listTasks.ToDictionary(t => t.AsyncState);\r
 \r
                         //Get all non-trash objects. Remember, the container name is stored in AsyncState\r
-                        var remoteObjects = from objectList in listTasks\r
+                        var remoteObjects = (from objectList in listTasks\r
                                             where (string)objectList.AsyncState != "trash"\r
                                             from obj in objectList.Result\r
-                                            select obj;\r
+                                            select obj).ToList();\r
+                        \r
+                        //Get the latest remote object modification date, only if it is after\r
+                        //the original since date\r
+                        nextSince = GetLatestDateAfter(nextSince, remoteObjects);\r
 \r
                         var sharedObjects = dict["shared"].Result;\r
+                        nextSince = GetLatestDateBefore(nextSince, sharedObjects);\r
 \r
                         //DON'T process trashed files\r
                         //If some files are deleted and added again to a folder, they will be deleted\r
@@ -256,22 +270,25 @@ namespace Pithos.Core.Agents
 \r
                         var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);\r
 \r
-                        ProcessDeletedFiles(accountInfo, differencer.Deleted.FilterDirectlyBelow(SelectiveUris));\r
+                        var filterUris = SelectiveUris[accountInfo.AccountKey];\r
+\r
+                        ProcessDeletedFiles(accountInfo, differencer.Deleted.FilterDirectlyBelow(filterUris));\r
 \r
                         // @@@ NEED To add previous state here as well, To compare with previous hash\r
 \r
                         \r
 \r
                         //Create a list of actions from the remote files\r
-                        var allActions = MovesToActions(accountInfo,differencer.Moved.FilterDirectlyBelow(SelectiveUris))\r
+                        \r
+                        var allActions = MovesToActions(accountInfo,differencer.Moved.FilterDirectlyBelow(filterUris))\r
                                         .Union(\r
-                                        ChangesToActions(accountInfo, differencer.Changed.FilterDirectlyBelow(SelectiveUris)))\r
+                                        ChangesToActions(accountInfo, differencer.Changed.FilterDirectlyBelow(filterUris)))\r
                                         .Union(\r
-                                        CreatesToActions(accountInfo, differencer.Created.FilterDirectlyBelow(SelectiveUris)));\r
+                                        CreatesToActions(accountInfo, differencer.Created.FilterDirectlyBelow(filterUris)));\r
 \r
                         //And remove those that are already being processed by the agent\r
                         var distinctActions = allActions\r
-                            .Except(NetworkAgent.GetEnumerable(), new PithosMonitor.LocalFileComparer())\r
+                            .Except(NetworkAgent.GetEnumerable(), new LocalFileComparer())\r
                             .ToList();\r
 \r
                         //Queue all the actions\r
@@ -286,16 +303,54 @@ namespace Pithos.Core.Agents
                 catch (Exception ex)\r
                 {\r
                     Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);\r
-                    return;\r
+                    return nextSince;\r
                 }\r
 \r
                 Log.Info("[LISTENER] Finished");\r
-\r
+                return nextSince;\r
             }\r
         }\r
 \r
+        /// <summary>\r
+        /// Returns the latest LastModified date from the list of objects, but only if it is before\r
+        /// than the threshold value\r
+        /// </summary>\r
+        /// <param name="threshold"></param>\r
+        /// <param name="cloudObjects"></param>\r
+        /// <returns></returns>\r
+        private static DateTime? GetLatestDateBefore(DateTime? threshold, IList<ObjectInfo> cloudObjects)\r
+        {\r
+            DateTime? maxDate = null;\r
+            if (cloudObjects!=null &&  cloudObjects.Count > 0)\r
+                maxDate = cloudObjects.Max(obj => obj.Last_Modified);\r
+            if (maxDate == null || maxDate == DateTime.MinValue)\r
+                return threshold;\r
+            if (threshold == null || threshold == DateTime.MinValue || threshold > maxDate)\r
+                return maxDate;\r
+            return threshold;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns the latest LastModified date from the list of objects, but only if it is after\r
+        /// the threshold value\r
+        /// </summary>\r
+        /// <param name="threshold"></param>\r
+        /// <param name="cloudObjects"></param>\r
+        /// <returns></returns>\r
+        private static DateTime? GetLatestDateAfter(DateTime? threshold, IList<ObjectInfo> cloudObjects)\r
+        {\r
+            DateTime? maxDate = null;\r
+            if (cloudObjects!=null &&  cloudObjects.Count > 0)\r
+                maxDate = cloudObjects.Max(obj => obj.Last_Modified);\r
+            if (maxDate == null || maxDate == DateTime.MinValue)\r
+                return threshold;\r
+            if (threshold == null || threshold == DateTime.MinValue || threshold < maxDate)\r
+                return maxDate;\r
+            return threshold;\r
+        }\r
+\r
         readonly AccountsDifferencer _differencer = new AccountsDifferencer();\r
-        private List<Uri> _selectiveUris=new List<Uri>();\r
+        private Dictionary<Uri, List<Uri>> _selectiveUris = new Dictionary<Uri, List<Uri>>();\r
 \r
         /// <summary>\r
         /// Deletes local files that are not found in the list of cloud files\r
@@ -352,10 +407,12 @@ namespace Pithos.Core.Agents
                 var deletedFiles = new List<FileSystemInfo>();\r
                 foreach (var objectInfo in cloudFiles)\r
                 {\r
-                    Log.DebugFormat("Handle deleted [{0}]",objectInfo.Uri);\r
+                    if (Log.IsDebugEnabled)\r
+                        Log.DebugFormat("Handle deleted [{0}]",objectInfo.Uri);\r
                     var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);\r
                     var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);\r
-                    Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName,objectInfo.Uri);\r
+                    if (Log.IsDebugEnabled)\r
+                        Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName,objectInfo.Uri);\r
                     if (item.Exists)\r
                     {\r
                         if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)\r
@@ -363,6 +420,10 @@ namespace Pithos.Core.Agents
                             item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;\r
 \r
                         }\r
+                        \r
+                        \r
+                        Log.DebugFormat("Deleting {0}", item.FullName);\r
+\r
                         var directory = item as DirectoryInfo;\r
                         if (directory!=null)\r
                             directory.Delete(true);\r
@@ -488,10 +549,14 @@ namespace Pithos.Core.Agents
             //over the remote files\r
             foreach (var objectInfo in creates)\r
             {\r
+                if (Log.IsDebugEnabled)\r
+                    Log.DebugFormat("[NEW INFO] {0}",objectInfo.Uri);\r
+\r
                 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);\r
                 //If the object already exists, we probably have a conflict\r
                 if (fileAgent.Exists(relativePath))\r
                 {\r
+                    Log.DebugFormat("[SKIP EXISTING] {0}", objectInfo.Uri);\r
                     //If a directory object already exists, we don't need to perform any other action                    \r
                     var localFile = fileAgent.GetFileSystemInfo(relativePath);\r
                     StatusKeeper.SetFileState(localFile.FullName, FileStatus.Conflict, FileOverlayStatus.Conflict);\r
@@ -512,8 +577,8 @@ namespace Pithos.Core.Agents
         {\r
             try\r
             {\r
-                StatusKeeper.SetPithosStatus(status);\r
-                StatusNotification.Notify(new Notification());\r
+                StatusNotification.SetPithosStatus(status);\r
+                //StatusNotification.Notify(new Notification());\r
             }\r
             catch (Exception exc)\r
             {\r
@@ -535,12 +600,12 @@ namespace Pithos.Core.Agents
             }\r
         }\r
 \r
-        public void SetSyncUris(Uri[] uris)\r
+        public void SetSyncUris(Uri accountKey, Uri[] uris)\r
         {            \r
-            SelectiveUris=uris.ToList();\r
+            SelectiveUris[accountKey]=uris.ToList();\r
         }\r
 \r
-        protected List<Uri> SelectiveUris\r
+        protected Dictionary<Uri,List<Uri>> SelectiveUris\r
         {\r
             get { return _selectiveUris;}\r
             set { _selectiveUris = value; }\r
@@ -549,13 +614,15 @@ namespace Pithos.Core.Agents
         public void AddAccount(AccountInfo accountInfo)\r
         {\r
             //Avoid adding a duplicate accountInfo\r
-            _accounts.TryAdd(accountInfo.UserName, accountInfo);\r
+            _accounts.TryAdd(accountInfo.AccountKey, accountInfo);\r
         }\r
 \r
         public void RemoveAccount(AccountInfo accountInfo)\r
         {\r
             AccountInfo account;\r
-            _accounts.TryRemove(accountInfo.UserName,out account);\r
+            _accounts.TryRemove(accountInfo.AccountKey, out account);\r
+            SnapshotDifferencer differencer;\r
+            _differencer.Differencers.TryRemove(accountInfo.AccountKey, out differencer);\r
         }\r
     }\r
 }\r