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 //Set the event when all delete actions are processed
292 if (_deleteAgent.InputCount == 0)
299 private static string GetFileKey(ObjectInfo info)
301 var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
305 private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
307 if (accountInfo == null)
308 throw new ArgumentNullException("accountInfo");
310 throw new ArgumentNullException("action");
311 if (action.LocalFile==null)
312 throw new ArgumentException("The action's local file is not specified","action");
313 if (!Path.IsPathRooted(action.LocalFile.FullName))
314 throw new ArgumentException("The action's local file path must be absolute","action");
315 if (action.CloudFile== null)
316 throw new ArgumentException("The action's cloud file is not specified", "action");
317 Contract.EndContractBlock();
319 var localFile = action.LocalFile;
320 var cloudFile = action.CloudFile;
321 var downloadPath=action.LocalFile.GetProperCapitalization();
323 var cloudHash = cloudFile.Hash.ToLower();
324 var localHash = action.LocalHash.Value.ToLower();
325 var topHash = action.TopHash.Value.ToLower();
327 //Not enough to compare only the local hashes, also have to compare the tophashes
329 //If any of the hashes match, we are done
330 if ((cloudHash == localHash || cloudHash == topHash))
332 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
336 //The hashes DON'T match. We need to sync
337 var lastLocalTime = localFile.LastWriteTime;
338 var lastUpTime = cloudFile.Last_Modified;
340 //If the local file is newer upload it
341 if (lastUpTime <= lastLocalTime)
343 //It probably means it was changed while the app was down
344 UploadCloudFile(action);
348 //It the cloud file has a later date, it was modified by another user or computer.
349 //We need to check the local file's status
350 var status = StatusKeeper.GetFileStatus(downloadPath);
353 case FileStatus.Unchanged:
354 //If the local file's status is Unchanged, we can go on and download the newer cloud file
355 await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
357 case FileStatus.Modified:
358 //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
359 //We can't ensure that a file modified online since the last time will appear as Modified, unless we
360 //index all files before we start listening.
361 case FileStatus.Created:
362 //If the local file is Created, it means that the local and cloud files aren't related,
363 // yet they have the same name.
365 //In both cases we must mark the file as in conflict
366 ReportConflict(downloadPath);
369 //Other cases should never occur. Mark them as Conflict as well but log a warning
370 ReportConflict(downloadPath);
371 Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
372 downloadPath, action.CloudFile.Name);
378 private void ReportConflict(string downloadPath)
380 if (String.IsNullOrWhiteSpace(downloadPath))
381 throw new ArgumentNullException("downloadPath");
382 Contract.EndContractBlock();
384 StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
385 StatusKeeper.SetPithosStatus(PithosStatus.HasConflicts);
386 var message = String.Format("Conflict detected for file {0}", downloadPath);
388 StatusNotification.NotifyChange(message, TraceLevel.Warning);
391 public void Post(CloudAction cloudAction)
393 if (cloudAction == null)
394 throw new ArgumentNullException("cloudAction");
395 if (cloudAction.AccountInfo==null)
396 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
397 Contract.EndContractBlock();
401 //If the action targets a local file, add a treehash calculation
402 if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
404 var accountInfo = cloudAction.AccountInfo;
405 var localFile = (FileInfo) cloudAction.LocalFile;
406 if (localFile.Length > accountInfo.BlockSize)
407 cloudAction.TopHash =
408 new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
409 accountInfo.BlockSize,
410 accountInfo.BlockHash).Result
411 .TopHash.ToHashString());
414 cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
419 //The hash for a directory is the empty string
420 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
423 if (cloudAction is CloudDeleteAction)
424 _deleteAgent.Post((CloudDeleteAction)cloudAction);
426 _agent.Post(cloudAction);
429 /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
431 public bool Equals(ObjectInfo x, ObjectInfo y)
433 return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
436 public int GetHashCode(ObjectInfo obj)
438 return obj.Name.ToLower().GetHashCode();
442 public void SynchNow()
445 _tcs.SetResult(true);
448 //TODO: This may be OK for testing purposes, but we have no guarantee that it will
449 //work properly in production
450 PollRemoteFiles(repeat:false);
454 //Remote files are polled periodically. Any changes are processed
455 public async Task PollRemoteFiles(DateTime? since = null,bool repeat=true)
457 StatusNotification.Notify(new Notification{Title="Polling Pithos"});
458 StatusKeeper.SetPithosStatus(PithosStatus.Syncing);
460 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
462 //If this poll fails, we will retry with the same since value
463 var nextSince = since;
466 //Next time we will check for all changes since the current check minus 1 second
467 //This is done to ensure there are no discrepancies due to clock differences
468 DateTime current = DateTime.Now.AddSeconds(-1);
470 var tasks = from accountInfo in _accounts
471 select ProcessAccountFiles(accountInfo, since);
473 await TaskEx.WhenAll(tasks.ToList());
476 //Reschedule the poll with the current timestamp as a "since" value
484 Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
485 //In case of failure retry with the same "since" value
488 //Wait for the polling interval to pass or the Manual flat to be toggled
489 nextSince = await WaitForScheduledOrManualPoll(nextSince);
491 PollRemoteFiles(nextSince);
496 private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
498 _tcs = new TaskCompletionSource<bool>();
499 var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
500 var signaledTask = await TaskEx.WhenAny(_tcs.Task, wait);
501 //If polling is signalled by SynchNow, ignore the since tag
502 if (signaledTask is Task<bool>)
507 public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
509 if (accountInfo==null)
510 throw new ArgumentNullException("accountInfo");
511 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
512 throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
513 Contract.EndContractBlock();
515 StatusNotification.Notify(new Notification{Title=String.Format("Polling {0}",accountInfo.UserName)});
517 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
521 Log.Info("Scheduled");
522 var client=new CloudFilesClient(accountInfo);
524 var containers = client.ListContainers(accountInfo.UserName);
527 CreateContainerFolders(accountInfo, containers);
532 //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
533 //than delete a file that was created while we were executing the poll
534 var pollTime = DateTime.Now;
536 //Get the list of server objects changed since the last check
537 //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
538 var listObjects = (from container in containers
539 select Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
540 client.ListObjects(accountInfo.UserName,container.Name, since),container.Name)).ToList();
542 var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => client.ListSharedObjects(since), "shared");
543 listObjects.Add(listShared);
544 var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
546 using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
548 var dict = listTasks.ToDictionary(t => t.AsyncState);
550 //Get all non-trash objects. Remember, the container name is stored in AsyncState
551 var remoteObjects = from objectList in listTasks
552 where (string) objectList.AsyncState != "trash"
553 from obj in objectList.Result
556 //TODO: Change the way deleted objects are detected.
557 //The list operation returns all existing objects so we could detect deleted remote objects
558 //by detecting objects that exist only locally. There are several cases where this is NOT the case:
559 //1. The first time the application runs, as there may be files that were added while
560 // the application was down.
561 //2. An object that is currently being uploaded will not appear in the remote list
562 // until the upload finishes.
563 // SOLUTION 1: Check the upload/download queue for the file
564 // SOLUTION 2: Check the SQLite states for the file's entry. If it is being uploaded,
565 // or its last modification was after the current poll, don't delete it. This way we don't
566 // delete objects whose upload finished too late to be included in the list.
567 //We need to detect and protect against such situations
568 //TODO: Does FileState have a LastModification field?
569 //TODO: How do we update the LastModification field? Do we need to add SQLite triggers?
570 // Do we need to use a proper SQLite schema?
571 // We can create a trigger with
572 // CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW
574 // UPDATE FileState SET LastModification=datetime('now') WHERE Id=old.Id;
577 //NOTE: Some files may have been deleted remotely while the application was down.
578 // We DO have to delete those files. Checking the trash makes it easy to detect them,
579 // Otherwise, we can't be really sure whether we need to upload or delete
580 // the local-only files.
581 // SOLUTION 1: Ask the user when such a local-only file is detected during the first poll.
582 // SOLUTION 2: Mark conflict and ask the user as in #1
584 var trashObjects = dict["trash"].Result;
585 var sharedObjects = dict["shared"].Result;
587 //Items with the same name, hash may be both in the container and the trash
588 //Don't delete items that exist in the container
589 var realTrash = from trash in trashObjects
592 info => info.Name == trash.Name && info.Hash == trash.Hash)
594 ProcessTrashedFiles(accountInfo, realTrash);
597 var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
599 where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
600 !name.StartsWith(FolderConstants.CacheFolder + "/",
601 StringComparison.InvariantCultureIgnoreCase)
602 select info).ToList();
606 ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
608 //Create a list of actions from the remote files
609 var allActions = ObjectsToActions(accountInfo, cleanRemotes);
612 //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
614 //And remove those that are already being processed by the agent
615 var distinctActions = allActions
616 .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
619 if (distinctActions.Any())
621 StatusNotification.Notify(new Notification {Title = "Changes Detected",Message=String.Format("{0} files were modified",distinctActions.Count)});
623 //Queue all the actions
624 foreach (var message in distinctActions)
629 Log.Info("[LISTENER] End Processing");
634 Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
638 Log.Info("[LISTENER] Finished");
644 /// Deletes local files that are not found in the list of cloud files
646 /// <param name="accountInfo"></param>
647 /// <param name="cloudFiles"></param>
648 /// <param name="pollTime"></param>
649 private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
651 if (accountInfo == null)
652 throw new ArgumentNullException("accountInfo");
653 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
654 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
655 if (cloudFiles == null)
656 throw new ArgumentNullException("cloudFiles");
657 Contract.EndContractBlock();
659 //Check the Modified date to ensure that were just created and haven't been uploaded yet
660 //NOTE: The NHibernate LINQ provider doesn't support custom functions so we need to break the query
662 //NOTE: DON'T return files that are already in conflict. The first poll would mark them as
663 //"In Conflict" but subsequent polls would delete them
664 /* var t=FileState.Find(new Guid("{cd664c9a-5f17-47c9-b27f-3bcbcb0595ff}"));
666 var d0 = FileState.Queryable
668 state.FilePath.StartsWith(accountInfo.AccountPath)).ToList();
670 var d1 = FileState.Queryable
671 .Where(state => state.Modified <= pollTime).ToList();
672 var d2= FileState.Queryable
673 .Where(state => state.Modified <= pollTime
675 state.FilePath.StartsWith(accountInfo.AccountPath)).ToList();*/
678 var deleteCandidates = FileState.Queryable
679 .Where(state => state.Modified <= pollTime
681 state.FilePath.StartsWith(accountInfo.AccountPath)
682 && state.FileStatus != FileStatus.Conflict).ToList();
684 //TODO: filesToDelete must take into account the Others container
685 var filesToDelete = (from deleteCandidate in deleteCandidates
686 let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
687 let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
688 where !cloudFiles.Any(r =>
689 Path.Combine(r.Container, r.Name) == relativeFilePath || //Own file
690 Path.Combine(FolderConstants.OthersFolder,r.Account, r.Container, r.Name) == relativeFilePath //Shared file
692 select localFile).ToList();
697 //Set the status of missing files to Conflict
698 foreach (var item in filesToDelete)
700 StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
702 StatusKeeper.SetPithosStatus(PithosStatus.HasConflicts);
703 StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
707 foreach (var item in filesToDelete)
711 if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
713 item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
718 StatusKeeper.ClearFileStatus(item.FullName);
720 StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted",filesToDelete.Count),TraceLevel.Info);
725 private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
727 var containerPaths = from container in containers
728 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
729 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
730 select containerPath;
732 foreach (var path in containerPaths)
734 Directory.CreateDirectory(path);
738 //Creates an appropriate action for each server file
739 private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
742 throw new ArgumentNullException();
743 Contract.EndContractBlock();
744 var fileAgent = GetFileAgent(accountInfo);
746 //In order to avoid multiple iterations over the files, we iterate only once
747 //over the remote files
748 foreach (var objectInfo in remote)
750 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
751 //and remove any matching objects from the list, adding them to the commonObjects list
753 if (fileAgent.Exists(relativePath))
755 //If a directory object already exists, we don't need to perform any other action
756 var localFile = fileAgent.GetFileSystemInfo(relativePath);
757 if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
759 using (new SessionScope(FlushAction.Never))
761 var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
762 //FileState.FindByFilePath(localFile.FullName);
763 //Common files should be checked on a per-case basis to detect differences, which is newer
765 yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
766 localFile, objectInfo, state, accountInfo.BlockSize,
767 accountInfo.BlockHash);
772 //If there is no match we add them to the localFiles list
773 //but only if the file is not marked for deletion
774 var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
775 var fileStatus = StatusKeeper.GetFileStatus(targetFile);
776 if (fileStatus != FileStatus.Deleted)
778 //Remote files should be downloaded
779 yield return new CloudDownloadAction(accountInfo,objectInfo);
785 private static FileAgent GetFileAgent(AccountInfo accountInfo)
787 return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
790 private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
792 var fileAgent = GetFileAgent(accountInfo);
793 foreach (var trashObject in trashObjects)
795 var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
796 //HACK: Assume only the "pithos" container is used. Must find out what happens when
797 //deleting a file from a different container
798 var relativePath = Path.Combine("pithos", barePath);
799 fileAgent.Delete(relativePath);
804 private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
806 if (accountInfo==null)
807 throw new ArgumentNullException("accountInfo");
809 throw new ArgumentNullException("action");
810 if (action.CloudFile==null)
811 throw new ArgumentException("CloudFile","action");
812 if (action.LocalFile==null)
813 throw new ArgumentException("LocalFile","action");
814 if (action.OldLocalFile==null)
815 throw new ArgumentException("OldLocalFile","action");
816 if (action.OldCloudFile==null)
817 throw new ArgumentException("OldCloudFile","action");
818 Contract.EndContractBlock();
821 var newFilePath = action.LocalFile.FullName;
823 //How do we handle concurrent renames and deletes/uploads/downloads?
824 //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
825 // This should never happen as the network agent executes only one action at a time
826 //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
827 // the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the
828 // same name will fail.
829 // This should never happen as the network agent executes only one action at a time.
830 //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
831 // to remove the rename from the queue.
832 // We can probably ignore this case. It will result in an error which should be ignored
835 //The local file is already renamed
836 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
839 var account = action.CloudFile.Account ?? accountInfo.UserName;
840 var container = action.CloudFile.Container;
842 var client = new CloudFilesClient(accountInfo);
843 //TODO: What code is returned when the source file doesn't exist?
844 client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
846 StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
847 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
848 NativeMethods.RaiseChangeNotification(newFilePath);
851 private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
853 if (accountInfo == null)
854 throw new ArgumentNullException("accountInfo");
856 throw new ArgumentNullException("cloudFile");
858 if (String.IsNullOrWhiteSpace(cloudFile.Container))
859 throw new ArgumentException("Invalid container", "cloudFile");
860 Contract.EndContractBlock();
862 var fileAgent = GetFileAgent(accountInfo);
864 using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
866 var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
867 var info = fileAgent.GetFileSystemInfo(fileName);
868 var fullPath = info.FullName.ToLower();
870 StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
872 var account = cloudFile.Account ?? accountInfo.UserName;
873 var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
875 var client = new CloudFilesClient(accountInfo);
876 client.DeleteObject(account, container, cloudFile.Name);
878 StatusKeeper.ClearFileStatus(fullPath);
883 private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
885 if (accountInfo == null)
886 throw new ArgumentNullException("accountInfo");
887 if (cloudFile == null)
888 throw new ArgumentNullException("cloudFile");
889 if (String.IsNullOrWhiteSpace(cloudFile.Account))
890 throw new ArgumentNullException("cloudFile");
891 if (String.IsNullOrWhiteSpace(cloudFile.Container))
892 throw new ArgumentNullException("cloudFile");
893 if (String.IsNullOrWhiteSpace(filePath))
894 throw new ArgumentNullException("filePath");
895 if (!Path.IsPathRooted(filePath))
896 throw new ArgumentException("The filePath must be rooted", "filePath");
897 Contract.EndContractBlock();
899 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
900 var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
902 var url = relativeUrl.ToString();
903 if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
907 //Are we already downloading or uploading the file?
908 using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
912 //The file's hashmap will be stored in the same location with the extension .hashmap
913 //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
915 var client = new CloudFilesClient(accountInfo);
916 var account = cloudFile.Account;
917 var container = cloudFile.Container;
919 if (cloudFile.Content_Type == @"application/directory")
921 if (!Directory.Exists(localPath))
922 Directory.CreateDirectory(localPath);
926 //Retrieve the hashmap from the server
927 var serverHash = await client.GetHashMap(account, container, url);
928 //If it's a small file
929 if (serverHash.Hashes.Count == 1)
930 //Download it in one go
932 DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
933 //Otherwise download it block by block
935 await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
937 if (cloudFile.AllowedTo == "read")
939 var attributes = File.GetAttributes(localPath);
940 File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
944 //Now we can store the object's metadata without worrying about ghost status entries
945 StatusKeeper.StoreInfo(localPath, cloudFile);
950 //Download a small file with a single GET operation
951 private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
954 throw new ArgumentNullException("client");
956 throw new ArgumentNullException("cloudFile");
957 if (relativeUrl == null)
958 throw new ArgumentNullException("relativeUrl");
959 if (String.IsNullOrWhiteSpace(filePath))
960 throw new ArgumentNullException("filePath");
961 if (!Path.IsPathRooted(filePath))
962 throw new ArgumentException("The localPath must be rooted", "filePath");
963 Contract.EndContractBlock();
965 var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
966 //If the file already exists
967 if (File.Exists(localPath))
969 //First check with MD5 as this is a small file
970 var localMD5 = Signature.CalculateMD5(localPath);
971 var cloudHash=serverHash.TopHash.ToHashString();
972 if (localMD5==cloudHash)
974 //Then check with a treehash
975 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
976 var localHash = localTreeHash.TopHash.ToHashString();
977 if (localHash==cloudHash)
981 var fileAgent = GetFileAgent(accountInfo);
982 //Calculate the relative file path for the new file
983 var relativePath = relativeUrl.RelativeUriToFilePath();
984 //The file will be stored in a temporary location while downloading with an extension .download
985 var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
986 //Make sure the target folder exists. DownloadFileTask will not create the folder
987 var tempFolder = Path.GetDirectoryName(tempPath);
988 if (!Directory.Exists(tempFolder))
989 Directory.CreateDirectory(tempFolder);
991 //Download the object to the temporary location
992 await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
994 //Create the local folder if it doesn't exist (necessary for shared objects)
995 var localFolder = Path.GetDirectoryName(localPath);
996 if (!Directory.Exists(localFolder))
997 Directory.CreateDirectory(localFolder);
998 //And move it to its actual location once downloading is finished
999 if (File.Exists(localPath))
1000 File.Replace(tempPath,localPath,null,true);
1002 File.Move(tempPath,localPath);
1003 //Notify listeners that a local file has changed
1004 StatusNotification.NotifyChangedFile(localPath);
1009 //Download a file asynchronously using blocks
1010 public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
1013 throw new ArgumentNullException("client");
1014 if (cloudFile == null)
1015 throw new ArgumentNullException("cloudFile");
1016 if (relativeUrl == null)
1017 throw new ArgumentNullException("relativeUrl");
1018 if (String.IsNullOrWhiteSpace(filePath))
1019 throw new ArgumentNullException("filePath");
1020 if (!Path.IsPathRooted(filePath))
1021 throw new ArgumentException("The filePath must be rooted", "filePath");
1022 if (serverHash == null)
1023 throw new ArgumentNullException("serverHash");
1024 Contract.EndContractBlock();
1026 var fileAgent = GetFileAgent(accountInfo);
1027 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1029 //Calculate the relative file path for the new file
1030 var relativePath = relativeUrl.RelativeUriToFilePath();
1031 var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
1035 //Calculate the file's treehash
1036 var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
1038 //And compare it with the server's hash
1039 var upHashes = serverHash.GetHashesAsStrings();
1040 var localHashes = treeHash.HashDictionary;
1041 for (int i = 0; i < upHashes.Length; i++)
1043 //For every non-matching hash
1044 var upHash = upHashes[i];
1045 if (!localHashes.ContainsKey(upHash))
1047 if (blockUpdater.UseOrphan(i, upHash))
1049 Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
1052 Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
1053 var start = i*serverHash.BlockSize;
1054 //To download the last block just pass a null for the end of the range
1056 if (i < upHashes.Length - 1 )
1057 end= ((i + 1)*serverHash.BlockSize) ;
1059 //Download the missing block
1060 var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
1063 blockUpdater.StoreBlock(i, block);
1066 Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
1070 //Want to avoid notifications if no changes were made
1071 var hasChanges = blockUpdater.HasBlocks;
1072 blockUpdater.Commit();
1075 //Notify listeners that a local file has changed
1076 StatusNotification.NotifyChangedFile(localPath);
1078 Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
1082 private async Task UploadCloudFile(CloudAction action)
1085 throw new ArgumentNullException("action");
1086 Contract.EndContractBlock();
1090 var accountInfo = action.AccountInfo;
1092 var fileInfo = action.LocalFile;
1094 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1097 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1098 if (relativePath.StartsWith(FolderConstants.OthersFolder))
1100 var parts = relativePath.Split('\\');
1101 var accountName = parts[1];
1102 var oldName = accountInfo.UserName;
1103 var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1104 var nameIndex = absoluteUri.IndexOf(oldName);
1105 var root = absoluteUri.Substring(0, nameIndex);
1107 accountInfo = new AccountInfo
1109 UserName = accountName,
1110 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1111 StorageUri = new Uri(root + accountName),
1112 BlockHash = accountInfo.BlockHash,
1113 BlockSize = accountInfo.BlockSize,
1114 Token = accountInfo.Token
1119 var fullFileName = fileInfo.GetProperCapitalization();
1120 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1122 //Abort if the file is already being uploaded or downloaded
1126 var cloudFile = action.CloudFile;
1127 var account = cloudFile.Account ?? accountInfo.UserName;
1129 var client = new CloudFilesClient(accountInfo);
1130 //Even if GetObjectInfo times out, we can proceed with the upload
1131 var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1133 //If this is a read-only file, do not upload changes
1134 if (info.AllowedTo == "read")
1137 //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1138 if (fileInfo is DirectoryInfo)
1140 //If the directory doesn't exist the Hash property will be empty
1141 if (String.IsNullOrWhiteSpace(info.Hash))
1142 //Go on and create the directory
1143 await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1148 var cloudHash = info.Hash.ToLower();
1150 var hash = action.LocalHash.Value;
1151 var topHash = action.TopHash.Value;
1153 //If the file hashes match, abort the upload
1154 if (hash == cloudHash || topHash == cloudHash)
1156 //but store any metadata changes
1157 StatusKeeper.StoreInfo(fullFileName, info);
1158 Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1163 //Mark the file as modified while we upload it
1164 StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1165 //And then upload it
1167 //Upload even small files using the Hashmap. The server may already contain
1168 //the relevant block
1170 //First, calculate the tree hash
1171 var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1172 accountInfo.BlockHash);
1174 await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1176 //If everything succeeds, change the file and overlay status to normal
1177 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1179 //Notify the Shell to update the overlays
1180 NativeMethods.RaiseChangeNotification(fullFileName);
1181 StatusNotification.NotifyChangedFile(fullFileName);
1183 catch (AggregateException ex)
1185 var exc = ex.InnerException as WebException;
1187 throw ex.InnerException;
1188 if (HandleUploadWebException(action, exc))
1192 catch (WebException ex)
1194 if (HandleUploadWebException(action, ex))
1198 catch (Exception ex)
1200 Log.Error("Unexpected error while uploading file", ex);
1206 private bool IsDeletedFile(CloudAction action)
1208 var key = GetFileKey(action.CloudFile);
1210 if (_deletedFiles.TryGetValue(key, out entryDate))
1212 //If the delete entry was created after this action, abort the action
1213 if (entryDate > action.Created)
1215 //Otherwise, remove the stale entry
1216 _deletedFiles.TryRemove(key, out entryDate);
1221 private bool HandleUploadWebException(CloudAction action, WebException exc)
1223 var response = exc.Response as HttpWebResponse;
1224 if (response == null)
1226 if (response.StatusCode == HttpStatusCode.Unauthorized)
1228 Log.Error("Not allowed to upload file", exc);
1229 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1230 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1231 StatusNotification.NotifyChange(message, TraceLevel.Warning);
1237 public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1239 if (accountInfo == null)
1240 throw new ArgumentNullException("accountInfo");
1241 if (cloudFile==null)
1242 throw new ArgumentNullException("cloudFile");
1243 if (fileInfo == null)
1244 throw new ArgumentNullException("fileInfo");
1245 if (String.IsNullOrWhiteSpace(url))
1246 throw new ArgumentNullException(url);
1248 throw new ArgumentNullException("treeHash");
1249 if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1250 throw new ArgumentException("Invalid container","cloudFile");
1251 Contract.EndContractBlock();
1253 var fullFileName = fileInfo.GetProperCapitalization();
1255 var account = cloudFile.Account ?? accountInfo.UserName;
1256 var container = cloudFile.Container ;
1258 var client = new CloudFilesClient(accountInfo);
1259 //Send the hashmap to the server
1260 var missingHashes = await client.PutHashMap(account, container, url, treeHash);
1261 //If the server returns no missing hashes, we are done
1262 while (missingHashes.Count > 0)
1265 var buffer = new byte[accountInfo.BlockSize];
1266 foreach (var missingHash in missingHashes)
1268 //Find the proper block
1269 var blockIndex = treeHash.HashDictionary[missingHash];
1270 var offset = blockIndex*accountInfo.BlockSize;
1272 var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1276 //And upload the block
1277 await client.PostBlock(account, container, buffer, 0, read);
1278 Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1280 catch (Exception exc)
1282 Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1287 //Repeat until there are no more missing hashes
1288 missingHashes = await client.PutHashMap(account, container, url, treeHash);
1293 public void AddAccount(AccountInfo accountInfo)
1295 if (!_accounts.Contains(accountInfo))
1296 _accounts.Add(accountInfo);