1 // -----------------------------------------------------------------------
2 // <copyright file="NetworkAgent.cs" company="GRNET">
3 // Copyright 2011 GRNET S.A. All rights reserved.
5 // Redistribution and use in source and binary forms, with or
6 // without modification, are permitted provided that the following
9 // 1. Redistributions of source code must retain the above
10 // copyright notice, this list of conditions and the following
13 // 2. Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following
15 // disclaimer in the documentation and/or other materials
16 // provided with the distribution.
18 // THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 // USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 // POSSIBILITY OF SUCH DAMAGE.
31 // The views and conclusions contained in the software and
32 // documentation are those of the authors and should not be
33 // interpreted as representing official policies, either expressed
34 // or implied, of GRNET S.A.
36 // -----------------------------------------------------------------------
39 using System.Collections.Concurrent;
40 using System.Collections.Generic;
41 using System.ComponentModel.Composition;
42 using System.Diagnostics;
43 using System.Diagnostics.Contracts;
47 using System.Threading;
48 using System.Threading.Tasks;
49 using System.Threading.Tasks.Dataflow;
50 using Castle.ActiveRecord;
51 using Pithos.Interfaces;
55 namespace Pithos.Core.Agents
57 //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
59 public class NetworkAgent
61 private Agent<CloudAction> _agent;
63 //A separate agent is used to execute delete actions immediatelly;
64 private ActionBlock<CloudDeleteAction> _deleteAgent;
65 readonly ConcurrentDictionary<string,DateTime> _deletedFiles=new ConcurrentDictionary<string, DateTime>();
68 private readonly ManualResetEventSlim _pauseAgent = new ManualResetEventSlim(true);
70 [System.ComponentModel.Composition.Import]
71 public IStatusKeeper StatusKeeper { get; set; }
73 public IStatusNotification StatusNotification { get; set; }
75 private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
77 private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
79 [System.ComponentModel.Composition.Import]
80 public IPithosSettings Settings { get; set; }
82 private bool _firstPoll = true;
83 private TaskCompletionSource<bool> _tcs;
88 _agent = Agent<CloudAction>.Start(inbox =>
94 var message = inbox.Receive();
95 var process=message.Then(Process,inbox.CancellationToken);
96 inbox.LoopAsync(process, loop);
101 _deleteAgent = new ActionBlock<CloudDeleteAction>(message =>ProcessDelete(message),new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism=4});
106 var message = inbox.Receive();
107 var process = message.Then(ProcessDelete,inbox.CancellationToken);
108 inbox.LoopAsync(process, loop);
115 private async Task Process(CloudAction action)
118 throw new ArgumentNullException("action");
119 if (action.AccountInfo==null)
120 throw new ArgumentException("The action.AccountInfo is empty","action");
121 Contract.EndContractBlock();
123 StatusKeeper.SetPithosStatus(PithosStatus.Syncing);
124 var accountInfo = action.AccountInfo;
126 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
128 Log.InfoFormat("[ACTION] Start Processing {0}", action);
130 var cloudFile = action.CloudFile;
131 var downloadPath = action.GetDownloadPath();
136 if (action.Action == CloudActionType.DeleteCloud)
138 //Redirect deletes to the delete agent
139 _deleteAgent.Post((CloudDeleteAction)action);
141 if (IsDeletedFile(action))
143 //Clear the status of already deleted files to avoid reprocessing
144 if (action.LocalFile != null)
145 this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
149 switch (action.Action)
151 case CloudActionType.UploadUnconditional:
152 //Abort if the file was deleted before we reached this point
153 await UploadCloudFile(action);
155 case CloudActionType.DownloadUnconditional:
156 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
158 case CloudActionType.RenameCloud:
159 var moveAction = (CloudMoveAction)action;
160 RenameCloudFile(accountInfo, moveAction);
162 case CloudActionType.MustSynch:
163 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
165 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
169 await SyncFiles(accountInfo, action);
174 Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
175 action.CloudFile.Name);
177 catch (WebException exc)
179 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
181 catch (OperationCanceledException)
185 catch (DirectoryNotFoundException)
187 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
188 action.Action, action.LocalFile, action.CloudFile);
189 //Post a delete action for the missing file
190 Post(new CloudDeleteAction(action));
192 catch (FileNotFoundException)
194 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
195 action.Action, action.LocalFile, action.CloudFile);
196 //Post a delete action for the missing file
197 Post(new CloudDeleteAction(action));
199 catch (Exception exc)
201 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
202 action.Action, action.LocalFile, action.CloudFile, exc);
208 StatusKeeper.SetPithosStatus(PithosStatus.InSynch);
214 /// Processes cloud delete actions
216 /// <param name="action">The delete action to execute</param>
217 /// <returns></returns>
219 /// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download
220 /// operations that may be in progress.
222 /// A separate agent is used to process deletes because the main agent may be busy with a long operation.
225 private async Task ProcessDelete(CloudDeleteAction action)
228 throw new ArgumentNullException("action");
229 if (action.AccountInfo==null)
230 throw new ArgumentException("The action.AccountInfo is empty","action");
231 Contract.EndContractBlock();
233 var accountInfo = action.AccountInfo;
235 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
237 Log.InfoFormat("[ACTION] Start Processing {0}", action);
239 var cloudFile = action.CloudFile;
243 //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
245 using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
248 //Add the file URL to the deleted files list
249 var key = GetFileKey(action.CloudFile);
250 _deletedFiles[key] = DateTime.Now;
253 // and then delete the file from the server
254 DeleteCloudFile(accountInfo, cloudFile);
256 Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
257 action.CloudFile.Name);
260 catch (WebException exc)
262 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
264 catch (OperationCanceledException)
268 catch (DirectoryNotFoundException)
270 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
271 action.Action, action.LocalFile, action.CloudFile);
272 //Repost a delete action for the missing file
273 _deleteAgent.Post(action);
275 catch (FileNotFoundException)
277 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
278 action.Action, action.LocalFile, action.CloudFile);
279 //Post a delete action for the missing file
280 _deleteAgent.Post(action);
282 catch (Exception exc)
284 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
285 action.Action, action.LocalFile, action.CloudFile, exc);
287 _deleteAgent.Post(action);
291 if (_deleteAgent.InputCount == 0)
298 private static string GetFileKey(ObjectInfo info)
300 var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
304 private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
306 if (accountInfo == null)
307 throw new ArgumentNullException("accountInfo");
309 throw new ArgumentNullException("action");
310 if (action.LocalFile==null)
311 throw new ArgumentException("The action's local file is not specified","action");
312 if (!Path.IsPathRooted(action.LocalFile.FullName))
313 throw new ArgumentException("The action's local file path must be absolute","action");
314 if (action.CloudFile== null)
315 throw new ArgumentException("The action's cloud file is not specified", "action");
316 Contract.EndContractBlock();
318 var localFile = action.LocalFile;
319 var cloudFile = action.CloudFile;
320 var downloadPath=action.LocalFile.GetProperCapitalization();
322 var cloudHash = cloudFile.Hash.ToLower();
323 var localHash = action.LocalHash.Value.ToLower();
324 var topHash = action.TopHash.Value.ToLower();
326 //Not enough to compare only the local hashes, also have to compare the tophashes
328 //If any of the hashes match, we are done
329 if ((cloudHash == localHash || cloudHash == topHash))
331 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
335 //The hashes DON'T match. We need to sync
336 var lastLocalTime = localFile.LastWriteTime;
337 var lastUpTime = cloudFile.Last_Modified;
339 //If the local file is newer upload it
340 if (lastUpTime <= lastLocalTime)
342 //It probably means it was changed while the app was down
343 UploadCloudFile(action);
347 //It the cloud file has a later date, it was modified by another user or computer.
348 //We need to check the local file's status
349 var status = StatusKeeper.GetFileStatus(downloadPath);
352 case FileStatus.Unchanged:
353 //If the local file's status is Unchanged, we can go on and download the newer cloud file
354 await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
356 case FileStatus.Modified:
357 //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
358 //We can't ensure that a file modified online since the last time will appear as Modified, unless we
359 //index all files before we start listening.
360 case FileStatus.Created:
361 //If the local file is Created, it means that the local and cloud files aren't related,
362 // yet they have the same name.
364 //In both cases we must mark the file as in conflict
365 ReportConflict(downloadPath);
368 //Other cases should never occur. Mark them as Conflict as well but log a warning
369 ReportConflict(downloadPath);
370 Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
371 downloadPath, action.CloudFile.Name);
377 private void ReportConflict(string downloadPath)
379 if (String.IsNullOrWhiteSpace(downloadPath))
380 throw new ArgumentNullException("downloadPath");
381 Contract.EndContractBlock();
383 StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
384 StatusKeeper.SetPithosStatus(PithosStatus.HasConflicts);
385 var message = String.Format("Conflict detected for file {0}", downloadPath);
387 StatusNotification.NotifyChange(message, TraceLevel.Warning);
390 public void Post(CloudAction cloudAction)
392 if (cloudAction == null)
393 throw new ArgumentNullException("cloudAction");
394 if (cloudAction.AccountInfo==null)
395 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
396 Contract.EndContractBlock();
400 //If the action targets a local file, add a treehash calculation
401 if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
403 var accountInfo = cloudAction.AccountInfo;
404 var localFile = (FileInfo) cloudAction.LocalFile;
405 if (localFile.Length > accountInfo.BlockSize)
406 cloudAction.TopHash =
407 new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
408 accountInfo.BlockSize,
409 accountInfo.BlockHash).Result
410 .TopHash.ToHashString());
413 cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
418 //The hash for a directory is the empty string
419 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
422 if (cloudAction is CloudDeleteAction)
423 _deleteAgent.Post((CloudDeleteAction)cloudAction);
425 _agent.Post(cloudAction);
428 /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
430 public bool Equals(ObjectInfo x, ObjectInfo y)
432 return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
435 public int GetHashCode(ObjectInfo obj)
437 return obj.Name.ToLower().GetHashCode();
441 public void SynchNow()
444 _tcs.SetResult(true);
447 //TODO: This may be OK for testing purposes, but we have no guarantee that it will
448 //work properly in production
449 PollRemoteFiles(repeat:false);
453 //Remote files are polled periodically. Any changes are processed
454 public async Task PollRemoteFiles(DateTime? since = null,bool repeat=true)
456 StatusNotification.Notify(new Notification{Title="Polling Pithos"});
457 StatusKeeper.SetPithosStatus(PithosStatus.Syncing);
459 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
461 //If this poll fails, we will retry with the same since value
462 var nextSince = since;
465 //Next time we will check for all changes since the current check minus 1 second
466 //This is done to ensure there are no discrepancies due to clock differences
467 DateTime current = DateTime.Now.AddSeconds(-1);
469 var tasks = from accountInfo in _accounts
470 select ProcessAccountFiles(accountInfo, since);
472 await TaskEx.WhenAll(tasks.ToList());
475 //Reschedule the poll with the current timestamp as a "since" value
483 Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
484 //In case of failure retry with the same "since" value
487 //Wait for the polling interval to pass or the Manual flat to be toggled
488 nextSince = await WaitForScheduledOrManualPoll(nextSince);
490 PollRemoteFiles(nextSince);
495 private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
497 _tcs = new TaskCompletionSource<bool>();
498 var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
499 var signaledTask = await TaskEx.WhenAny(_tcs.Task, wait);
500 //If polling is signalled by SynchNow, ignore the since tag
501 if (signaledTask is Task<bool>)
506 public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
508 if (accountInfo==null)
509 throw new ArgumentNullException("accountInfo");
510 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
511 throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
512 Contract.EndContractBlock();
514 StatusNotification.Notify(new Notification{Title=String.Format("Polling {0}",accountInfo.UserName)});
516 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
518 Log.Info("Scheduled");
519 var client=new CloudFilesClient(accountInfo);
521 var containers = client.ListContainers(accountInfo.UserName);
523 CreateContainerFolders(accountInfo, containers);
528 //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
529 //than delete a file that was created while we were executing the poll
530 var pollTime = DateTime.Now;
532 //Get the list of server objects changed since the last check
533 //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
534 var listObjects = from container in containers
535 select Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
536 client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
539 var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
541 using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
543 var dict = listTasks.ToDictionary(t => t.AsyncState);
545 //Get all non-trash objects. Remember, the container name is stored in AsyncState
546 var remoteObjects = from objectList in listTasks
547 where (string) objectList.AsyncState != "trash"
548 from obj in objectList.Result
551 //TODO: Change the way deleted objects are detected.
552 //The list operation returns all existing objects so we could detect deleted remote objects
553 //by detecting objects that exist only locally. There are several cases where this is NOT the case:
554 //1. The first time the application runs, as there may be files that were added while
555 // the application was down.
556 //2. An object that is currently being uploaded will not appear in the remote list
557 // until the upload finishes.
558 // SOLUTION 1: Check the upload/download queue for the file
559 // SOLUTION 2: Check the SQLite states for the file's entry. If it is being uploaded,
560 // or its last modification was after the current poll, don't delete it. This way we don't
561 // delete objects whose upload finished too late to be included in the list.
562 //We need to detect and protect against such situations
563 //TODO: Does FileState have a LastModification field?
564 //TODO: How do we update the LastModification field? Do we need to add SQLite triggers?
565 // Do we need to use a proper SQLite schema?
566 // We can create a trigger with
567 // CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW
569 // UPDATE FileState SET LastModification=datetime('now') WHERE Id=old.Id;
572 //NOTE: Some files may have been deleted remotely while the application was down.
573 // We DO have to delete those files. Checking the trash makes it easy to detect them,
574 // Otherwise, we can't be really sure whether we need to upload or delete
575 // the local-only files.
576 // SOLUTION 1: Ask the user when such a local-only file is detected during the first poll.
577 // SOLUTION 2: Mark conflict and ask the user as in #1
579 var trashObjects = dict["trash"].Result;
580 //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
582 //Items with the same name, hash may be both in the container and the trash
583 //Don't delete items that exist in the container
584 var realTrash = from trash in trashObjects
587 info => info.Name == trash.Name && info.Hash == trash.Hash)
589 ProcessTrashedFiles(accountInfo, realTrash);
592 var cleanRemotes = (from info in remoteObjects
593 //.Union(sharedObjects)
595 where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
596 !name.StartsWith(FolderConstants.CacheFolder + "/",
597 StringComparison.InvariantCultureIgnoreCase)
598 select info).ToList();
602 ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
604 //Create a list of actions from the remote files
605 var allActions = ObjectsToActions(accountInfo, cleanRemotes);
608 //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
610 //And remove those that are already being processed by the agent
611 var distinctActions = allActions
612 .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
615 if (distinctActions.Any())
617 StatusNotification.Notify(new Notification {Title = "Changes Detected",Message=String.Format("{0} files were modified",distinctActions.Count)});
619 //Queue all the actions
620 foreach (var message in distinctActions)
625 Log.Info("[LISTENER] End Processing");
630 Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
634 Log.Info("[LISTENER] Finished");
640 /// Deletes local files that are not found in the list of cloud files
642 /// <param name="accountInfo"></param>
643 /// <param name="cloudFiles"></param>
644 /// <param name="pollTime"></param>
645 private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
647 if (accountInfo == null)
648 throw new ArgumentNullException("accountInfo");
649 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
650 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
651 if (cloudFiles == null)
652 throw new ArgumentNullException("cloudFiles");
653 Contract.EndContractBlock();
655 //Check the Modified date to ensure that were just created and haven't been uploaded yet
656 //NOTE: The NHibernate LINQ provider doesn't support custom functions so we need to break the query
658 //NOTE: DON'T return files that are already in conflict. The first poll would mark them as
659 //"In Conflict" but subsequent polls would delete them
660 /* var t=FileState.Find(new Guid("{cd664c9a-5f17-47c9-b27f-3bcbcb0595ff}"));
662 var d0 = FileState.Queryable
664 state.FilePath.StartsWith(accountInfo.AccountPath)).ToList();
666 var d1 = FileState.Queryable
667 .Where(state => state.Modified <= pollTime).ToList();
668 var d2= FileState.Queryable
669 .Where(state => state.Modified <= pollTime
671 state.FilePath.StartsWith(accountInfo.AccountPath)).ToList();*/
673 var deleteCandidates = FileState.Queryable
674 .Where(state => state.Modified <= pollTime
676 state.FilePath.StartsWith(accountInfo.AccountPath)
677 && state.FileStatus != FileStatus.Conflict).ToList();
679 var deleteCandidates = (from state in FileState.Queryable
681 state.Modified <= pollTime
682 && state.FilePath.StartsWith(accountInfo.AccountPath)
683 && state.FileStatus != FileStatus.Conflict
684 select state).ToList();
687 var filesToDelete = (from deleteCandidate in deleteCandidates
688 let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
689 let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
690 where !cloudFiles.Any(r => Path.Combine(r.Container, r.Name) == relativeFilePath)
691 select localFile).ToList();
696 //Set the status of missing files to Conflict
697 foreach (var item in filesToDelete)
699 StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
701 StatusKeeper.SetPithosStatus(PithosStatus.HasConflicts);
702 StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
706 foreach (var item in filesToDelete)
709 StatusKeeper.ClearFileStatus(item.FullName);
711 StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted",filesToDelete.Count),TraceLevel.Info);
716 private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
718 var containerPaths = from container in containers
719 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
720 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
721 select containerPath;
723 foreach (var path in containerPaths)
725 Directory.CreateDirectory(path);
729 //Creates an appropriate action for each server file
730 private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
733 throw new ArgumentNullException();
734 Contract.EndContractBlock();
735 var fileAgent = GetFileAgent(accountInfo);
737 //In order to avoid multiple iterations over the files, we iterate only once
738 //over the remote files
739 foreach (var objectInfo in remote)
741 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
742 //and remove any matching objects from the list, adding them to the commonObjects list
744 if (fileAgent.Exists(relativePath))
746 //If a directory object already exists, we don't need to perform any other action
747 var localFile = fileAgent.GetFileSystemInfo(relativePath);
748 if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
750 using (new SessionScope(FlushAction.Never))
752 var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
753 //FileState.FindByFilePath(localFile.FullName);
754 //Common files should be checked on a per-case basis to detect differences, which is newer
756 yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
757 localFile, objectInfo, state, accountInfo.BlockSize,
758 accountInfo.BlockHash);
763 //If there is no match we add them to the localFiles list
764 //but only if the file is not marked for deletion
765 var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
766 var fileStatus = StatusKeeper.GetFileStatus(targetFile);
767 if (fileStatus != FileStatus.Deleted)
769 //Remote files should be downloaded
770 yield return new CloudDownloadAction(accountInfo,objectInfo);
776 private static FileAgent GetFileAgent(AccountInfo accountInfo)
778 return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
781 private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
783 var fileAgent = GetFileAgent(accountInfo);
784 foreach (var trashObject in trashObjects)
786 var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
787 //HACK: Assume only the "pithos" container is used. Must find out what happens when
788 //deleting a file from a different container
789 var relativePath = Path.Combine("pithos", barePath);
790 fileAgent.Delete(relativePath);
795 private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
797 if (accountInfo==null)
798 throw new ArgumentNullException("accountInfo");
800 throw new ArgumentNullException("action");
801 if (action.CloudFile==null)
802 throw new ArgumentException("CloudFile","action");
803 if (action.LocalFile==null)
804 throw new ArgumentException("LocalFile","action");
805 if (action.OldLocalFile==null)
806 throw new ArgumentException("OldLocalFile","action");
807 if (action.OldCloudFile==null)
808 throw new ArgumentException("OldCloudFile","action");
809 Contract.EndContractBlock();
812 var newFilePath = action.LocalFile.FullName;
814 //How do we handle concurrent renames and deletes/uploads/downloads?
815 //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
816 // This should never happen as the network agent executes only one action at a time
817 //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
818 // the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the
819 // same name will fail.
820 // This should never happen as the network agent executes only one action at a time.
821 //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
822 // to remove the rename from the queue.
823 // We can probably ignore this case. It will result in an error which should be ignored
826 //The local file is already renamed
827 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
830 var account = action.CloudFile.Account ?? accountInfo.UserName;
831 var container = action.CloudFile.Container;
833 var client = new CloudFilesClient(accountInfo);
834 //TODO: What code is returned when the source file doesn't exist?
835 client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
837 StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
838 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
839 NativeMethods.RaiseChangeNotification(newFilePath);
842 private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
844 if (accountInfo == null)
845 throw new ArgumentNullException("accountInfo");
847 throw new ArgumentNullException("cloudFile");
849 if (String.IsNullOrWhiteSpace(cloudFile.Container))
850 throw new ArgumentException("Invalid container", "cloudFile");
851 Contract.EndContractBlock();
853 var fileAgent = GetFileAgent(accountInfo);
855 using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
857 var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
858 var info = fileAgent.GetFileSystemInfo(fileName);
859 var fullPath = info.FullName.ToLower();
861 StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
863 var account = cloudFile.Account ?? accountInfo.UserName;
864 var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
866 var client = new CloudFilesClient(accountInfo);
867 client.DeleteObject(account, container, cloudFile.Name);
869 StatusKeeper.ClearFileStatus(fullPath);
874 private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
876 if (accountInfo == null)
877 throw new ArgumentNullException("accountInfo");
878 if (cloudFile == null)
879 throw new ArgumentNullException("cloudFile");
880 if (String.IsNullOrWhiteSpace(cloudFile.Account))
881 throw new ArgumentNullException("cloudFile");
882 if (String.IsNullOrWhiteSpace(cloudFile.Container))
883 throw new ArgumentNullException("cloudFile");
884 if (String.IsNullOrWhiteSpace(filePath))
885 throw new ArgumentNullException("filePath");
886 if (!Path.IsPathRooted(filePath))
887 throw new ArgumentException("The filePath must be rooted", "filePath");
888 Contract.EndContractBlock();
890 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
891 var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
893 var url = relativeUrl.ToString();
894 if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
898 //Are we already downloading or uploading the file?
899 using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
903 //The file's hashmap will be stored in the same location with the extension .hashmap
904 //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
906 var client = new CloudFilesClient(accountInfo);
907 var account = cloudFile.Account;
908 var container = cloudFile.Container;
910 if (cloudFile.Content_Type == @"application/directory")
912 if (!Directory.Exists(localPath))
913 Directory.CreateDirectory(localPath);
917 //Retrieve the hashmap from the server
918 var serverHash = await client.GetHashMap(account, container, url);
919 //If it's a small file
920 if (serverHash.Hashes.Count == 1)
921 //Download it in one go
923 DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
924 //Otherwise download it block by block
926 await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
928 if (cloudFile.AllowedTo == "read")
930 var attributes = File.GetAttributes(localPath);
931 File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
935 //Now we can store the object's metadata without worrying about ghost status entries
936 StatusKeeper.StoreInfo(localPath, cloudFile);
941 //Download a small file with a single GET operation
942 private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
945 throw new ArgumentNullException("client");
947 throw new ArgumentNullException("cloudFile");
948 if (relativeUrl == null)
949 throw new ArgumentNullException("relativeUrl");
950 if (String.IsNullOrWhiteSpace(filePath))
951 throw new ArgumentNullException("filePath");
952 if (!Path.IsPathRooted(filePath))
953 throw new ArgumentException("The localPath must be rooted", "filePath");
954 Contract.EndContractBlock();
956 var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
957 //If the file already exists
958 if (File.Exists(localPath))
960 //First check with MD5 as this is a small file
961 var localMD5 = Signature.CalculateMD5(localPath);
962 var cloudHash=serverHash.TopHash.ToHashString();
963 if (localMD5==cloudHash)
965 //Then check with a treehash
966 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
967 var localHash = localTreeHash.TopHash.ToHashString();
968 if (localHash==cloudHash)
972 var fileAgent = GetFileAgent(accountInfo);
973 //Calculate the relative file path for the new file
974 var relativePath = relativeUrl.RelativeUriToFilePath();
975 //The file will be stored in a temporary location while downloading with an extension .download
976 var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
977 //Make sure the target folder exists. DownloadFileTask will not create the folder
978 var tempFolder = Path.GetDirectoryName(tempPath);
979 if (!Directory.Exists(tempFolder))
980 Directory.CreateDirectory(tempFolder);
982 //Download the object to the temporary location
983 await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
985 //Create the local folder if it doesn't exist (necessary for shared objects)
986 var localFolder = Path.GetDirectoryName(localPath);
987 if (!Directory.Exists(localFolder))
988 Directory.CreateDirectory(localFolder);
989 //And move it to its actual location once downloading is finished
990 if (File.Exists(localPath))
991 File.Replace(tempPath,localPath,null,true);
993 File.Move(tempPath,localPath);
994 //Notify listeners that a local file has changed
995 StatusNotification.NotifyChangedFile(localPath);
1000 //Download a file asynchronously using blocks
1001 public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
1004 throw new ArgumentNullException("client");
1005 if (cloudFile == null)
1006 throw new ArgumentNullException("cloudFile");
1007 if (relativeUrl == null)
1008 throw new ArgumentNullException("relativeUrl");
1009 if (String.IsNullOrWhiteSpace(filePath))
1010 throw new ArgumentNullException("filePath");
1011 if (!Path.IsPathRooted(filePath))
1012 throw new ArgumentException("The filePath must be rooted", "filePath");
1013 if (serverHash == null)
1014 throw new ArgumentNullException("serverHash");
1015 Contract.EndContractBlock();
1017 var fileAgent = GetFileAgent(accountInfo);
1018 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1020 //Calculate the relative file path for the new file
1021 var relativePath = relativeUrl.RelativeUriToFilePath();
1022 var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
1026 //Calculate the file's treehash
1027 var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
1029 //And compare it with the server's hash
1030 var upHashes = serverHash.GetHashesAsStrings();
1031 var localHashes = treeHash.HashDictionary;
1032 for (int i = 0; i < upHashes.Length; i++)
1034 //For every non-matching hash
1035 var upHash = upHashes[i];
1036 if (!localHashes.ContainsKey(upHash))
1038 if (blockUpdater.UseOrphan(i, upHash))
1040 Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
1043 Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
1044 var start = i*serverHash.BlockSize;
1045 //To download the last block just pass a null for the end of the range
1047 if (i < upHashes.Length - 1 )
1048 end= ((i + 1)*serverHash.BlockSize) ;
1050 //Download the missing block
1051 var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
1054 blockUpdater.StoreBlock(i, block);
1057 Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
1061 //Want to avoid notifications if no changes were made
1062 var hasChanges = blockUpdater.HasBlocks;
1063 blockUpdater.Commit();
1066 //Notify listeners that a local file has changed
1067 StatusNotification.NotifyChangedFile(localPath);
1069 Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
1073 private async Task UploadCloudFile(CloudAction action)
1076 throw new ArgumentNullException("action");
1077 Contract.EndContractBlock();
1081 var accountInfo = action.AccountInfo;
1083 var fileInfo = action.LocalFile;
1085 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1088 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1089 if (relativePath.StartsWith(FolderConstants.OthersFolder))
1091 var parts = relativePath.Split('\\');
1092 var accountName = parts[1];
1093 var oldName = accountInfo.UserName;
1094 var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1095 var nameIndex = absoluteUri.IndexOf(oldName);
1096 var root = absoluteUri.Substring(0, nameIndex);
1098 accountInfo = new AccountInfo
1100 UserName = accountName,
1101 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1102 StorageUri = new Uri(root + accountName),
1103 BlockHash = accountInfo.BlockHash,
1104 BlockSize = accountInfo.BlockSize,
1105 Token = accountInfo.Token
1110 var fullFileName = fileInfo.GetProperCapitalization();
1111 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1113 //Abort if the file is already being uploaded or downloaded
1117 var cloudFile = action.CloudFile;
1118 var account = cloudFile.Account ?? accountInfo.UserName;
1120 var client = new CloudFilesClient(accountInfo);
1121 //Even if GetObjectInfo times out, we can proceed with the upload
1122 var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1124 //If this is a read-only file, do not upload changes
1125 if (info.AllowedTo == "read")
1128 //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1129 if (fileInfo is DirectoryInfo)
1131 //If the directory doesn't exist the Hash property will be empty
1132 if (String.IsNullOrWhiteSpace(info.Hash))
1133 //Go on and create the directory
1134 await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1139 var cloudHash = info.Hash.ToLower();
1141 var hash = action.LocalHash.Value;
1142 var topHash = action.TopHash.Value;
1144 //If the file hashes match, abort the upload
1145 if (hash == cloudHash || topHash == cloudHash)
1147 //but store any metadata changes
1148 StatusKeeper.StoreInfo(fullFileName, info);
1149 Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1154 //Mark the file as modified while we upload it
1155 StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1156 //And then upload it
1158 //Upload even small files using the Hashmap. The server may already contain
1159 //the relevant block
1161 //First, calculate the tree hash
1162 var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1163 accountInfo.BlockHash);
1165 await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1167 //If everything succeeds, change the file and overlay status to normal
1168 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1170 //Notify the Shell to update the overlays
1171 NativeMethods.RaiseChangeNotification(fullFileName);
1172 StatusNotification.NotifyChangedFile(fullFileName);
1174 catch (AggregateException ex)
1176 var exc = ex.InnerException as WebException;
1178 throw ex.InnerException;
1179 if (HandleUploadWebException(action, exc))
1183 catch (WebException ex)
1185 if (HandleUploadWebException(action, ex))
1189 catch (Exception ex)
1191 Log.Error("Unexpected error while uploading file", ex);
1197 private bool IsDeletedFile(CloudAction action)
1199 var key = GetFileKey(action.CloudFile);
1201 if (_deletedFiles.TryGetValue(key, out entryDate))
1203 //If the delete entry was created after this action, abort the action
1204 if (entryDate > action.Created)
1206 //Otherwise, remove the stale entry
1207 _deletedFiles.TryRemove(key, out entryDate);
1212 private bool HandleUploadWebException(CloudAction action, WebException exc)
1214 var response = exc.Response as HttpWebResponse;
1215 if (response == null)
1217 if (response.StatusCode == HttpStatusCode.Unauthorized)
1219 Log.Error("Not allowed to upload file", exc);
1220 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1221 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1222 StatusNotification.NotifyChange(message, TraceLevel.Warning);
1228 public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1230 if (accountInfo == null)
1231 throw new ArgumentNullException("accountInfo");
1232 if (cloudFile==null)
1233 throw new ArgumentNullException("cloudFile");
1234 if (fileInfo == null)
1235 throw new ArgumentNullException("fileInfo");
1236 if (String.IsNullOrWhiteSpace(url))
1237 throw new ArgumentNullException(url);
1239 throw new ArgumentNullException("treeHash");
1240 if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1241 throw new ArgumentException("Invalid container","cloudFile");
1242 Contract.EndContractBlock();
1244 var fullFileName = fileInfo.GetProperCapitalization();
1246 var account = cloudFile.Account ?? accountInfo.UserName;
1247 var container = cloudFile.Container ;
1249 var client = new CloudFilesClient(accountInfo);
1250 //Send the hashmap to the server
1251 var missingHashes = await client.PutHashMap(account, container, url, treeHash);
1252 //If the server returns no missing hashes, we are done
1253 while (missingHashes.Count > 0)
1256 var buffer = new byte[accountInfo.BlockSize];
1257 foreach (var missingHash in missingHashes)
1259 //Find the proper block
1260 var blockIndex = treeHash.HashDictionary[missingHash];
1261 var offset = blockIndex*accountInfo.BlockSize;
1263 var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1267 //And upload the block
1268 await client.PostBlock(account, container, buffer, 0, read);
1269 Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1271 catch (Exception exc)
1273 Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1278 //Repeat until there are no more missing hashes
1279 missingHashes = await client.PutHashMap(account, container, url, treeHash);
1284 public void AddAccount(AccountInfo accountInfo)
1286 if (!_accounts.Contains(accountInfo))
1287 _accounts.Add(accountInfo);