2 /* -----------------------------------------------------------------------
\r
3 * <copyright file="PollAgent.cs" company="GRNet">
\r
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
\r
7 * Redistribution and use in source and binary forms, with or
\r
8 * without modification, are permitted provided that the following
\r
9 * conditions are met:
\r
11 * 1. Redistributions of source code must retain the above
\r
12 * copyright notice, this list of conditions and the following
\r
15 * 2. Redistributions in binary form must reproduce the above
\r
16 * copyright notice, this list of conditions and the following
\r
17 * disclaimer in the documentation and/or other materials
\r
18 * provided with the distribution.
\r
21 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
\r
22 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
\r
23 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
\r
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
\r
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
\r
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
\r
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
\r
28 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
\r
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
\r
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
\r
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
\r
32 * POSSIBILITY OF SUCH DAMAGE.
\r
34 * The views and conclusions contained in the software and
\r
35 * documentation are those of the authors and should not be
\r
36 * interpreted as representing official policies, either expressed
\r
37 * or implied, of GRNET S.A.
\r
39 * -----------------------------------------------------------------------
\r
43 using System.Collections.Concurrent;
\r
44 using System.ComponentModel.Composition;
\r
45 using System.Diagnostics;
\r
46 using System.Diagnostics.Contracts;
\r
48 using System.Linq.Expressions;
\r
49 using System.Reflection;
\r
50 using System.Security.Cryptography;
\r
51 using System.Threading;
\r
52 using System.Threading.Tasks;
\r
53 using System.Threading.Tasks.Dataflow;
\r
54 using Castle.ActiveRecord;
\r
55 using Pithos.Interfaces;
\r
56 using Pithos.Network;
\r
59 namespace Pithos.Core.Agents
\r
62 using System.Collections.Generic;
\r
65 /*public class PollRequest
\r
67 public DateTime? Since { get; set; }
\r
68 public IEnumerable<string> Batch { get; set; }
\r
73 /// PollAgent periodically polls the server to detect object changes. The agent retrieves a listing of all
\r
74 /// objects and compares it with a previously cached version to detect differences.
\r
75 /// New files are downloaded, missing files are deleted from the local file system and common files are compared
\r
76 /// to determine the appropriate action
\r
79 public class PollAgent
\r
81 private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
\r
83 [System.ComponentModel.Composition.Import]
\r
84 public IStatusKeeper StatusKeeper { get; set; }
\r
86 [System.ComponentModel.Composition.Import]
\r
87 public IPithosSettings Settings { get; set; }
\r
89 [System.ComponentModel.Composition.Import]
\r
90 public NetworkAgent NetworkAgent { get; set; }
\r
92 [System.ComponentModel.Composition.Import]
\r
93 public Selectives Selectives { get; set; }
\r
95 public IStatusNotification StatusNotification { get; set; }
\r
97 private CancellationTokenSource _currentOperationCancellation = new CancellationTokenSource();
\r
99 public void CancelCurrentOperation()
\r
101 //What does it mean to cancel the current upload/download?
\r
102 //Obviously, the current operation will be cancelled by throwing
\r
103 //a cancellation exception.
\r
105 //The default behavior is to retry any operations that throw.
\r
106 //Obviously this is not what we want in this situation.
\r
107 //The cancelled operation should NOT bea retried.
\r
109 //This can be done by catching the cancellation exception
\r
110 //and avoiding the retry.
\r
113 //Have to reset the cancellation source - it is not possible to reset the source
\r
114 //Have to prevent a case where an operation requests a token from the old source
\r
115 var oldSource = Interlocked.Exchange(ref _currentOperationCancellation, new CancellationTokenSource());
\r
116 oldSource.Cancel();
\r
128 _unPauseEvent.Set();
\r
131 _unPauseEvent.Reset();
\r
136 private bool _firstPoll = true;
\r
138 //The Sync Event signals a manual synchronisation
\r
139 private readonly AsyncManualResetEvent _syncEvent = new AsyncManualResetEvent();
\r
141 private readonly AsyncManualResetEvent _unPauseEvent = new AsyncManualResetEvent(true);
\r
143 private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();
\r
144 private readonly ConcurrentDictionary<Uri, AccountInfo> _accounts = new ConcurrentDictionary<Uri,AccountInfo>();
\r
146 //private readonly ActionBlock<PollRequest> _pollAction;
\r
148 readonly HashSet<string> _knownContainers = new HashSet<string>();
\r
152 /// Start a manual synchronization
\r
154 public void SynchNow(IEnumerable<string> paths=null)
\r
156 _batchQueue.Enqueue(paths);
\r
159 //_pollAction.Post(new PollRequest {Batch = paths});
\r
162 readonly ConcurrentQueue<IEnumerable<string>> _batchQueue=new ConcurrentQueue<IEnumerable<string>>();
\r
165 /// Remote files are polled periodically. Any changes are processed
\r
167 /// <param name="since"></param>
\r
168 /// <returns></returns>
\r
169 public void PollRemoteFiles(DateTime? since = null)
\r
171 if (Log.IsDebugEnabled)
\r
172 Log.DebugFormat("Polling changes after [{0}]",since);
\r
174 Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");
\r
178 using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
\r
180 //If this poll fails, we will retry with the same since value
\r
181 var nextSince = since;
\r
184 _unPauseEvent.Wait();
\r
185 UpdateStatus(PithosStatus.PollSyncing);
\r
187 var accountBatches=new Dictionary<Uri, IEnumerable<string>>();
\r
188 IEnumerable<string> batch = null;
\r
189 if (_batchQueue.TryDequeue(out batch) && batch != null)
\r
190 foreach (var account in _accounts.Values)
\r
192 var accountBatch = batch.Where(path => path.IsAtOrBelow(account.AccountPath));
\r
193 accountBatches[account.AccountKey] = accountBatch;
\r
196 var tasks = new List<Task<DateTime?>>();
\r
197 foreach(var accountInfo in _accounts.Values)
\r
199 IEnumerable<string> accountBatch ;
\r
200 accountBatches.TryGetValue(accountInfo.AccountKey,out accountBatch);
\r
201 var t=ProcessAccountFiles (accountInfo, accountBatch, since);
\r
205 var nextTimes=TaskEx.WhenAll(tasks.ToList()).Result;
\r
207 _firstPoll = false;
\r
208 //Reschedule the poll with the current timestamp as a "since" value
\r
210 if (nextTimes.Length>0)
\r
211 nextSince = nextTimes.Min();
\r
212 if (Log.IsDebugEnabled)
\r
213 Log.DebugFormat("Next Poll at [{0}]",nextSince);
\r
215 catch (Exception ex)
\r
217 Log.ErrorFormat("Error while processing accounts\r\n{0}", ex);
\r
218 //In case of failure retry with the same "since" value
\r
221 UpdateStatus(PithosStatus.PollComplete);
\r
222 //The multiple try blocks are required because we can't have an await call
\r
223 //inside a finally block
\r
224 //TODO: Find a more elegant solution for reschedulling in the event of an exception
\r
227 //Wait for the polling interval to pass or the Sync event to be signalled
\r
228 nextSince = WaitForScheduledOrManualPoll(nextSince).Result;
\r
232 //Ensure polling is scheduled even in case of error
\r
233 TaskEx.Run(()=>PollRemoteFiles(nextSince));
\r
234 //_pollAction.Post(new PollRequest {Since = nextSince});
\r
240 /// Wait for the polling period to expire or a manual sync request
\r
242 /// <param name="since"></param>
\r
243 /// <returns></returns>
\r
244 private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
\r
246 var sync = _syncEvent.WaitAsync();
\r
247 var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval));
\r
249 var signaledTask = await TaskEx.WhenAny(sync, wait).ConfigureAwait(false);
\r
251 //Pausing takes precedence over manual sync or awaiting
\r
252 _unPauseEvent.Wait();
\r
254 //Wait for network processing to finish before polling
\r
255 var pauseTask=NetworkAgent.ProceedEvent.WaitAsync();
\r
256 await TaskEx.WhenAll(signaledTask, pauseTask).ConfigureAwait(false);
\r
258 //If polling is signalled by SynchNow, ignore the since tag
\r
259 if (sync.IsCompleted)
\r
261 _syncEvent.Reset();
\r
269 public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, IEnumerable<string> accountBatch, DateTime? since = null)
\r
271 if (accountInfo == null)
\r
272 throw new ArgumentNullException("accountInfo");
\r
273 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
\r
274 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
\r
275 Contract.EndContractBlock();
\r
278 using (ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
\r
281 await NetworkAgent.GetDeleteAwaiter().ConfigureAwait(false);
\r
283 Log.Info("Scheduled");
\r
284 var client = new CloudFilesClient(accountInfo);
\r
286 //We don't need to check the trash container
\r
287 var containers = client.ListContainers(accountInfo.UserName)
\r
288 .Where(c=>c.Name!="trash")
\r
292 CreateContainerFolders(accountInfo, containers);
\r
294 //The nextSince time fallback time is the same as the current.
\r
295 //If polling succeeds, the next Since time will be the smallest of the maximum modification times
\r
296 //of the shared and account objects
\r
297 var nextSince = since;
\r
301 //Wait for any deletions to finish
\r
302 await NetworkAgent.GetDeleteAwaiter().ConfigureAwait(false);
\r
303 //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
\r
304 //than delete a file that was created while we were executing the poll
\r
306 //Get the list of server objects changed since the last check
\r
307 //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
\r
308 var listObjects = (from container in containers
\r
309 select Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
\r
310 client.ListObjects(accountInfo.UserName, container.Name, since), container.Name)).ToList();
\r
312 var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
\r
313 client.ListSharedObjects(_knownContainers,since), "shared");
\r
314 listObjects.Add(listShared);
\r
315 var listTasks = await Task.Factory.WhenAll(listObjects.ToArray()).ConfigureAwait(false);
\r
317 using (ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
\r
319 var dict = listTasks.ToDictionary(t => t.AsyncState);
\r
321 //Get all non-trash objects. Remember, the container name is stored in AsyncState
\r
322 var remoteObjects = (from objectList in listTasks
\r
323 where (string)objectList.AsyncState != "trash"
\r
324 from obj in objectList.Result
\r
325 orderby obj.Bytes ascending
\r
326 select obj).ToList();
\r
328 //Get the latest remote object modification date, only if it is after
\r
329 //the original since date
\r
330 nextSince = GetLatestDateAfter(nextSince, remoteObjects);
\r
332 var sharedObjects = dict["shared"].Result;
\r
334 //DON'T process trashed files
\r
335 //If some files are deleted and added again to a folder, they will be deleted
\r
336 //even though they are new.
\r
337 //We would have to check file dates and hashes to ensure that a trashed file
\r
338 //can be deleted safely from the local hard drive.
\r
340 //Items with the same name, hash may be both in the container and the trash
\r
341 //Don't delete items that exist in the container
\r
342 var realTrash = from trash in trashObjects
\r
344 !remoteObjects.Any(
\r
345 info => info.Name == trash.Name && info.Hash == trash.Hash)
\r
347 ProcessTrashedFiles(accountInfo, realTrash);
\r
350 var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
\r
351 let name = info.Name??""
\r
352 where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
\r
353 !name.StartsWith(FolderConstants.CacheFolder + "/",
\r
354 StringComparison.InvariantCultureIgnoreCase)
\r
355 select info).ToList();
\r
358 StatusKeeper.CleanupOrphanStates();
\r
360 var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
\r
361 var currentRemotes = differencer.Current.ToList();
\r
362 StatusKeeper.CleanupStaleStates(accountInfo, currentRemotes);
\r
364 //var filterUris = Selectives.SelectiveUris[accountInfo.AccountKey];
\r
366 //May have to wait if the FileAgent has asked for a Pause, due to local changes
\r
367 await _unPauseEvent.WaitAsync().ConfigureAwait(false);
\r
369 //Get the local files here
\r
370 var agent = AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
\r
371 var files = LoadLocalFileTuples(accountInfo, accountBatch);
\r
373 var states = FileState.Queryable.ToList();
\r
375 var infos = (from remote in currentRemotes
\r
376 let path = remote.RelativeUrlToFilePath(accountInfo.UserName)
\r
377 let info=agent.GetFileSystemInfo(path)
\r
378 select Tuple.Create(info.FullName,remote))
\r
381 var token = _currentOperationCancellation.Token;
\r
383 var tuples = MergeSources(infos, files, states).ToList();
\r
385 //Process only the changes in the batch file, if one exists
\r
386 var stateTuples = accountBatch==null?tuples:tuples.Where(t => accountBatch.Contains(t.FilePath));
\r
387 foreach (var tuple in stateTuples.Where(s=>!s.Locked))
\r
389 await _unPauseEvent.WaitAsync().ConfigureAwait(false);
\r
391 //Set the Merkle Hash
\r
392 //SetMerkleHash(accountInfo, tuple);
\r
394 await SyncSingleItem(accountInfo, tuple, agent, token).ConfigureAwait(false);
\r
403 MarkSuspectedDeletes(accountInfo, cleanRemotes);
\r
408 Log.Info("[LISTENER] End Processing");
\r
411 catch (Exception ex)
\r
413 Log.ErrorFormat("[FAIL] ListObjects for {0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
\r
417 Log.Info("[LISTENER] Finished");
\r
423 private static void SetMerkleHash(AccountInfo accountInfo, StateTuple tuple)
\r
425 //The Merkle hash for directories is that of an empty buffer
\r
426 if (tuple.FileInfo is DirectoryInfo)
\r
427 tuple.C = MERKLE_EMPTY;
\r
428 else if (tuple.FileState != null && tuple.MD5 == tuple.FileState.ETag)
\r
430 //If there is a state whose MD5 matches, load the merkle hash from the file state
\r
431 //insteaf of calculating it
\r
432 tuple.C = tuple.FileState.Checksum;
\r
436 tuple.Merkle = Signature.CalculateTreeHashAsync((FileInfo)tuple.FileInfo, accountInfo.BlockSize, accountInfo.BlockHash,1,progress);
\r
437 //tuple.C=tuple.Merkle.TopHash.ToHashString();
\r
442 private IEnumerable<FileSystemInfo> LoadLocalFileTuples(AccountInfo accountInfo,IEnumerable<string> batch )
\r
444 using (ThreadContext.Stacks["Account Files Hashing"].Push(accountInfo.UserName))
\r
446 var batchPaths = (batch==null)?new List<string>():batch.ToList();
\r
447 IEnumerable<FileSystemInfo> localInfos=AgentLocator<FileAgent>.Get(accountInfo.AccountPath)
\r
448 .EnumerateFileSystemInfos();
\r
449 if (batchPaths.Count>0)
\r
450 localInfos= localInfos.Where(fi => batchPaths.Contains(fi.FullName));
\r
457 /// Wait and Pause the agent while waiting
\r
459 /// <param name="backoff"></param>
\r
460 /// <returns></returns>
\r
461 private async Task PauseFor(int backoff)
\r
465 await TaskEx.Delay(backoff).ConfigureAwait(false);
\r
469 private async Task SyncSingleItem(AccountInfo accountInfo, StateTuple tuple, FileAgent agent, CancellationToken token)
\r
471 Log.DebugFormat("Sync [{0}] C:[{1}] L:[{2}] S:[{3}]", tuple.FilePath, tuple.C, tuple.L, tuple.S);
\r
476 var localFilePath = tuple.FilePath;
\r
477 //Don't use the tuple info, it may have been deleted
\r
478 var localInfo = FileInfoExtensions.FromPath(localFilePath);
\r
481 var isUnselectedRootFolder = agent.IsUnselectedRootFolder(tuple.FilePath);
\r
483 //Unselected root folders that have not yet been uploaded should be uploaded and added to the
\r
484 //selective folders
\r
486 if (!Selectives.IsSelected(accountInfo, localFilePath) &&
\r
487 !(isUnselectedRootFolder && tuple.ObjectInfo == null))
\r
490 // Local file unchanged? If both C and L are null, make sure it's because
\r
491 //both the file is missing and the state checksum is not missing
\r
492 if (tuple.C == tuple.L /*&& (localInfo.Exists || tuple.FileState == null)*/)
\r
495 //Server unchanged?
\r
496 if (tuple.S == tuple.L)
\r
498 // No server changes
\r
499 //Has the file been renamed on the server?
\r
500 MoveForServerMove(accountInfo, tuple);
\r
504 //Different from server
\r
505 //Does the server file exist?
\r
506 if (tuple.S == null)
\r
508 //Server file doesn't exist
\r
509 //deleteObjectFromLocal()
\r
511 StatusNotification.GetNotifier("Deleting local {0}", "Deleted local {0}",
\r
512 Path.GetFileName(localFilePath)))
\r
514 StatusKeeper.SetFileState(localFilePath, FileStatus.Deleted,
\r
515 FileOverlayStatus.Deleted, "");
\r
516 using (NetworkGate.Acquire(localFilePath, NetworkOperation.Deleting))
\r
518 agent.Delete(localFilePath);
\r
520 //updateRecord(Remove C, L)
\r
521 StatusKeeper.ClearFileStatus(localFilePath);
\r
526 //Server file exists
\r
527 //downloadServerObject() // Result: L = S
\r
528 //If the file has moved on the server, move it locally before downloading
\r
530 StatusNotification.GetNotifier("Downloading {0}", "Downloaded {0}",
\r
531 Path.GetFileName(localFilePath)))
\r
533 var targetPath = MoveForServerMove(accountInfo, tuple);
\r
535 StatusKeeper.SetFileState(targetPath, FileStatus.Modified, FileOverlayStatus.Modified,
\r
539 NetworkAgent.Downloader.DownloadCloudFile(accountInfo, tuple.ObjectInfo, targetPath,
\r
541 .ConfigureAwait(false);
\r
542 //updateRecord( L = S )
\r
543 StatusKeeper.UpdateFileChecksum(targetPath, tuple.ObjectInfo.ETag,
\r
544 tuple.ObjectInfo.X_Object_Hash);
\r
546 StatusKeeper.StoreInfo(targetPath, tuple.ObjectInfo);
\r
550 StatusKeeper.SetFileState(targetPath, FileStatus.Unchanged,
\r
551 FileOverlayStatus.Normal, "");
\r
559 //Local changes found
\r
561 //Server unchanged?
\r
562 if (tuple.S == tuple.L)
\r
564 //The FileAgent selective sync checks for new root folder files
\r
565 if (!agent.Ignore(localFilePath))
\r
567 if ((tuple.C == null || !localInfo.Exists) && tuple.ObjectInfo != null)
\r
569 //deleteObjectFromServer()
\r
570 DeleteCloudFile(accountInfo, tuple);
\r
571 //updateRecord( Remove L, S)
\r
575 //uploadLocalObject() // Result: S = C, L = S
\r
576 var progress = new Progress<double>(d =>
\r
577 StatusNotification.Notify(new StatusNotification(String.Format("Merkle Hashing for Upload {0:p} of {1}", d, localInfo.Name))));
\r
579 //Debug.Assert(tuple.FileState !=null);
\r
580 var action = new CloudUploadAction(accountInfo, localInfo, tuple.FileState,
\r
581 accountInfo.BlockSize, accountInfo.BlockHash,
\r
582 "Poll", isUnselectedRootFolder,progress);
\r
584 StatusNotification.GetNotifier("Uploading {0}", "Uploaded {0}",
\r
585 Path.GetFileName(localFilePath)))
\r
587 await NetworkAgent.Uploader.UploadCloudFile(action, token).ConfigureAwait(false);
\r
590 //updateRecord( S = C )
\r
591 //State updated by the uploader
\r
593 if (isUnselectedRootFolder)
\r
595 ProcessChildren(accountInfo, tuple, agent, token);
\r
602 if (tuple.C == tuple.S)
\r
604 // (Identical Changes) Result: L = S
\r
607 //Don't update anything for nonexistend server files
\r
608 if (tuple.S != null)
\r
610 //Detect server moves
\r
611 var targetPath = MoveForServerMove(accountInfo, tuple);
\r
612 StatusKeeper.StoreInfo(targetPath, tuple.ObjectInfo);
\r
616 //Log the null tuple for investigation
\r
617 Log.WarnFormat("Null tuple detected Path:[{0}], State:[{1}],LocalFile:[{2}]",tuple.FilePath,tuple.FileState,tuple.FileInfo);
\r
622 if ((tuple.C == null || !localInfo.Exists) && tuple.ObjectInfo != null)
\r
624 //deleteObjectFromServer()
\r
625 DeleteCloudFile(accountInfo, tuple);
\r
626 //updateRecord(Remove L, S)
\r
628 //If both the local and server files are missing, the state is stale
\r
629 else if (!localInfo.Exists && (tuple.S == null || tuple.ObjectInfo == null))
\r
631 StatusKeeper.ClearFileStatus(localInfo.FullName);
\r
635 ReportConflictForMismatch(localFilePath);
\r
636 //identifyAsConflict() // Manual action required
\r
642 catch (Exception exc)
\r
644 //In case of error log and retry with the next poll
\r
645 Log.ErrorFormat("[SYNC] Failed for file {0}. Will Retry.\r\n{1}",tuple.FilePath,exc);
\r
651 private string MoveForServerMove(AccountInfo accountInfo, StateTuple tuple)
\r
653 if (tuple.ObjectInfo == null)
\r
655 var relativePath = tuple.ObjectInfo.RelativeUrlToFilePath(accountInfo.UserName);
\r
656 var serverPath = Path.Combine(accountInfo.AccountPath, relativePath);
\r
658 //Compare Case Insensitive
\r
659 if (String.Equals(tuple.FilePath ,serverPath,StringComparison.InvariantCultureIgnoreCase))
\r
662 if (tuple.FileInfo.Exists)
\r
664 using (StatusNotification.GetNotifier("Moving local {0}", "Moved local {0}", Path.GetFileName(tuple.FilePath)))
\r
665 using(NetworkGate.Acquire(tuple.FilePath,NetworkOperation.Renaming))
\r
667 var fi = tuple.FileInfo as FileInfo;
\r
669 fi.MoveTo(serverPath);
\r
670 var di = tuple.FileInfo as DirectoryInfo;
\r
672 di.MoveTo(serverPath);
\r
674 StatusKeeper.StoreInfo(serverPath, tuple.ObjectInfo);
\r
678 Debug.Assert(false, "File does not exist");
\r
683 private void DeleteCloudFile(AccountInfo accountInfo, StateTuple tuple)
\r
685 using (StatusNotification.GetNotifier("Deleting server {0}", "Deleted server {0}", Path.GetFileName(tuple.FilePath)))
\r
688 StatusKeeper.SetFileState(tuple.FilePath, FileStatus.Deleted,
\r
689 FileOverlayStatus.Deleted, "");
\r
690 NetworkAgent.DeleteAgent.DeleteCloudFile(accountInfo, tuple.ObjectInfo);
\r
691 StatusKeeper.ClearFileStatus(tuple.FilePath);
\r
695 private void ProcessChildren(AccountInfo accountInfo, StateTuple tuple, FileAgent agent, CancellationToken token)
\r
698 var dirInfo = tuple.FileInfo as DirectoryInfo;
\r
699 var folderTuples = from folder in dirInfo.EnumerateDirectories("*", SearchOption.AllDirectories)
\r
700 select new StateTuple(folder);
\r
701 var fileTuples = from file in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories)
\r
702 select new StateTuple(file);
\r
704 //Process folders first, to ensure folders appear on the sever as soon as possible
\r
705 folderTuples.ApplyAction(async t =>await SyncSingleItem(accountInfo, t, agent, token).ConfigureAwait(false));
\r
707 fileTuples.ApplyAction(async t => await SyncSingleItem(accountInfo, t, agent, token).ConfigureAwait(false));
\r
712 * //Use the queue to retry locked file hashing
\r
713 var fileQueue = new ConcurrentQueue<FileSystemInfo>(localInfos);
\r
716 var results = new List<Tuple<FileSystemInfo, string>>();
\r
718 while (fileQueue.Count > 0)
\r
720 FileSystemInfo file;
\r
721 fileQueue.TryDequeue(out file);
\r
722 using (ThreadContext.Stacks["File"].Push(file.FullName))
\r
726 //Replace MD5 here, do the calc while syncing individual files
\r
728 if (file is DirectoryInfo)
\r
732 //Wait in case the FileAgent has requested a Pause
\r
733 await _unPauseEvent.WaitAsync().ConfigureAwait(false);
\r
735 using (StatusNotification.GetNotifier("Hashing {0}", "", file.Name))
\r
737 hash = ((FileInfo)file).ComputeShortHash(StatusNotification);
\r
741 results.Add(Tuple.Create(file, hash));
\r
743 catch (IOException exc)
\r
745 Log.WarnFormat("[HASH] File in use, will retry [{0}]", exc);
\r
746 fileQueue.Enqueue(file);
\r
747 //If this is the only enqueued file
\r
748 if (fileQueue.Count != 1) continue;
\r
754 //Pause Polling for the specified time
\r
757 await PauseFor(backoff).ConfigureAwait(false);
\r
764 private IEnumerable<StateTuple> MergeSources(
\r
765 IEnumerable<Tuple<string, ObjectInfo>> infos,
\r
766 IEnumerable<FileSystemInfo> files,
\r
767 IEnumerable<FileState> states)
\r
769 var tuplesByPath = files.ToDictionary(f => f.FullName, f => new StateTuple {FileInfo = f}); new Dictionary<string, StateTuple>();
\r
771 //For files that have state
\r
772 foreach (var state in states)
\r
774 StateTuple hashTuple;
\r
775 if (tuplesByPath.TryGetValue(state.FilePath, out hashTuple))
\r
777 hashTuple.FileState = state;
\r
778 UpdateMD5(hashTuple);
\r
782 var fsInfo = FileInfoExtensions.FromPath(state.FilePath);
\r
783 hashTuple = new StateTuple {FileInfo = fsInfo, FileState = state};
\r
784 tuplesByPath[state.FilePath] = hashTuple;
\r
787 //for files that don't have state
\r
788 foreach (var tuple in tuplesByPath.Values.Where(t => t.FileState == null))
\r
793 var tuplesByID = tuplesByPath.Values
\r
794 .Where(tuple => tuple.FileState != null && tuple.FileState.ObjectID!=null)
\r
795 .ToDictionary(tuple=>tuple.FileState.ObjectID,tuple=>tuple);//new Dictionary<Guid, StateTuple>();
\r
797 foreach (var info in infos)
\r
799 StateTuple hashTuple;
\r
800 var filePath = info.Item1;
\r
801 var objectInfo = info.Item2;
\r
802 var objectID = objectInfo.UUID;
\r
804 if (tuplesByID.TryGetValue(objectID, out hashTuple))
\r
806 hashTuple.ObjectInfo = objectInfo;
\r
808 else if (tuplesByPath.TryGetValue(filePath, out hashTuple))
\r
810 hashTuple.ObjectInfo = objectInfo;
\r
814 var fsInfo = FileInfoExtensions.FromPath(filePath);
\r
815 hashTuple= new StateTuple {FileInfo = fsInfo, ObjectInfo = objectInfo};
\r
816 tuplesByPath[filePath] = hashTuple;
\r
817 tuplesByID[objectInfo.UUID] = hashTuple;
\r
820 Debug.Assert(tuplesByPath.Values.All(t => t.HashesValid()));
\r
821 return tuplesByPath.Values;
\r
824 private void UpdateMD5(StateTuple hashTuple)
\r
829 var hash = Signature.MD5_EMPTY;
\r
830 if (hashTuple.FileInfo is FileInfo)
\r
832 var file = hashTuple.FileInfo as FileInfo;
\r
833 var stateDate = hashTuple.NullSafe(h => h.FileState).NullSafe(s => s.LastWriteDate) ??
\r
835 if (file.LastWriteTime - stateDate < TimeSpan.FromSeconds(1) &&
\r
836 hashTuple.FileState.LastLength == file.Length)
\r
838 hash = hashTuple.FileState.LastMD5;
\r
842 //Modified, must calculate hash
\r
843 hash = file.ComputeShortHash(StatusNotification);
\r
844 StatusKeeper.UpdateLastMD5(file, hash);
\r
847 hashTuple.C = hash;
\r
848 hashTuple.MD5 = hash;
\r
850 catch (IOException)
\r
852 hashTuple.Locked = true;
\r
857 /// Returns the latest LastModified date from the list of objects, but only if it is before
\r
858 /// than the threshold value
\r
860 /// <param name="threshold"></param>
\r
861 /// <param name="cloudObjects"></param>
\r
862 /// <returns></returns>
\r
863 private static DateTime? GetLatestDateBefore(DateTime? threshold, IList<ObjectInfo> cloudObjects)
\r
865 DateTime? maxDate = null;
\r
866 if (cloudObjects!=null && cloudObjects.Count > 0)
\r
867 maxDate = cloudObjects.Max(obj => obj.Last_Modified);
\r
868 if (maxDate == null || maxDate == DateTime.MinValue)
\r
870 if (threshold == null || threshold == DateTime.MinValue || threshold > maxDate)
\r
876 /// Returns the latest LastModified date from the list of objects, but only if it is after
\r
877 /// the threshold value
\r
879 /// <param name="threshold"></param>
\r
880 /// <param name="cloudObjects"></param>
\r
881 /// <returns></returns>
\r
882 private static DateTime? GetLatestDateAfter(DateTime? threshold, IList<ObjectInfo> cloudObjects)
\r
884 DateTime? maxDate = null;
\r
885 if (cloudObjects!=null && cloudObjects.Count > 0)
\r
886 maxDate = cloudObjects.Max(obj => obj.Last_Modified);
\r
887 if (maxDate == null || maxDate == DateTime.MinValue)
\r
889 if (threshold == null || threshold == DateTime.MinValue || threshold < maxDate)
\r
894 readonly AccountsDifferencer _differencer = new AccountsDifferencer();
\r
895 private bool _pause;
\r
897 const string MERKLE_EMPTY = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
\r
900 private void ReportConflictForMismatch(string localFilePath)
\r
902 if (String.IsNullOrWhiteSpace(localFilePath))
\r
903 throw new ArgumentNullException("localFilePath");
\r
904 Contract.EndContractBlock();
\r
906 StatusKeeper.SetFileState(localFilePath, FileStatus.Conflict, FileOverlayStatus.Conflict, "File changed at the server");
\r
907 UpdateStatus(PithosStatus.HasConflicts);
\r
908 var message = String.Format("Conflict detected for file {0}", localFilePath);
\r
910 StatusNotification.NotifyChange(message, TraceLevel.Warning);
\r
915 /// Notify the UI to update the visual status
\r
917 /// <param name="status"></param>
\r
918 private void UpdateStatus(PithosStatus status)
\r
922 StatusNotification.SetPithosStatus(status);
\r
923 //StatusNotification.Notify(new Notification());
\r
925 catch (Exception exc)
\r
927 //Failure is not critical, just log it
\r
928 Log.Warn("Error while updating status", exc);
\r
932 private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
\r
934 var containerPaths = from container in containers
\r
935 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
\r
936 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
\r
937 select containerPath;
\r
939 foreach (var path in containerPaths)
\r
941 Directory.CreateDirectory(path);
\r
945 public void AddAccount(AccountInfo accountInfo)
\r
947 //Avoid adding a duplicate accountInfo
\r
948 _accounts.TryAdd(accountInfo.AccountKey, accountInfo);
\r
951 public void RemoveAccount(AccountInfo accountInfo)
\r
953 AccountInfo account;
\r
954 _accounts.TryRemove(accountInfo.AccountKey, out account);
\r
956 SnapshotDifferencer differencer;
\r
957 _differencer.Differencers.TryRemove(accountInfo.AccountKey, out differencer);
\r