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 var accountInfo = action.AccountInfo;
125 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
127 Log.InfoFormat("[ACTION] Start Processing {0}", action);
129 var cloudFile = action.CloudFile;
130 var downloadPath = action.GetDownloadPath();
135 if (action.Action == CloudActionType.DeleteCloud)
137 //Redirect deletes to the delete agent
138 _deleteAgent.Post((CloudDeleteAction)action);
140 if (IsDeletedFile(action))
142 //Clear the status of already deleted files to avoid reprocessing
143 if (action.LocalFile != null)
144 this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
148 switch (action.Action)
150 case CloudActionType.UploadUnconditional:
151 //Abort if the file was deleted before we reached this point
152 await UploadCloudFile(action);
154 case CloudActionType.DownloadUnconditional:
155 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
157 case CloudActionType.RenameCloud:
158 var moveAction = (CloudMoveAction) action;
159 RenameCloudFile(accountInfo, moveAction);
161 case CloudActionType.MustSynch:
162 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
164 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
168 await SyncFiles(accountInfo, action);
173 Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
174 action.CloudFile.Name);
176 catch (WebException exc)
178 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
180 catch (OperationCanceledException)
184 catch (DirectoryNotFoundException)
186 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
187 action.Action, action.LocalFile, action.CloudFile);
188 //Post a delete action for the missing file
189 Post(new CloudDeleteAction(action));
191 catch (FileNotFoundException)
193 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
194 action.Action, action.LocalFile, action.CloudFile);
195 //Post a delete action for the missing file
196 Post(new CloudDeleteAction(action));
198 catch (Exception exc)
200 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
201 action.Action, action.LocalFile, action.CloudFile, exc);
209 /// Processes cloud delete actions
211 /// <param name="action">The delete action to execute</param>
212 /// <returns></returns>
214 /// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download
215 /// operations that may be in progress.
217 /// A separate agent is used to process deletes because the main agent may be busy with a long operation.
220 private async Task ProcessDelete(CloudDeleteAction action)
223 throw new ArgumentNullException("action");
224 if (action.AccountInfo==null)
225 throw new ArgumentException("The action.AccountInfo is empty","action");
226 Contract.EndContractBlock();
228 var accountInfo = action.AccountInfo;
230 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
232 Log.InfoFormat("[ACTION] Start Processing {0}", action);
234 var cloudFile = action.CloudFile;
238 //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
240 using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
243 //Add the file URL to the deleted files list
244 var key = GetFileKey(action.CloudFile);
245 _deletedFiles[key] = DateTime.Now;
248 // and then delete the file from the server
249 DeleteCloudFile(accountInfo, cloudFile);
251 Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
252 action.CloudFile.Name);
255 catch (WebException exc)
257 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
259 catch (OperationCanceledException)
263 catch (DirectoryNotFoundException)
265 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
266 action.Action, action.LocalFile, action.CloudFile);
267 //Repost a delete action for the missing file
268 _deleteAgent.Post(action);
270 catch (FileNotFoundException)
272 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
273 action.Action, action.LocalFile, action.CloudFile);
274 //Post a delete action for the missing file
275 _deleteAgent.Post(action);
277 catch (Exception exc)
279 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
280 action.Action, action.LocalFile, action.CloudFile, exc);
282 _deleteAgent.Post(action);
286 if (_deleteAgent.InputCount == 0)
293 private static string GetFileKey(ObjectInfo info)
295 var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
299 private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
301 if (accountInfo == null)
302 throw new ArgumentNullException("accountInfo");
304 throw new ArgumentNullException("action");
305 if (action.LocalFile==null)
306 throw new ArgumentException("The action's local file is not specified","action");
307 if (!Path.IsPathRooted(action.LocalFile.FullName))
308 throw new ArgumentException("The action's local file path must be absolute","action");
309 if (action.CloudFile== null)
310 throw new ArgumentException("The action's cloud file is not specified", "action");
311 Contract.EndContractBlock();
313 var localFile = action.LocalFile;
314 var cloudFile = action.CloudFile;
315 var downloadPath=action.LocalFile.GetProperCapitalization();
317 var cloudHash = cloudFile.Hash.ToLower();
318 var localHash = action.LocalHash.Value.ToLower();
319 var topHash = action.TopHash.Value.ToLower();
321 //Not enough to compare only the local hashes, also have to compare the tophashes
323 //If any of the hashes match, we are done
324 if ((cloudHash == localHash || cloudHash == topHash))
326 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
330 //The hashes DON'T match. We need to sync
331 var lastLocalTime = localFile.LastWriteTime;
332 var lastUpTime = cloudFile.Last_Modified;
334 //If the local file is newer upload it
335 if (lastUpTime <= lastLocalTime)
337 //It probably means it was changed while the app was down
338 UploadCloudFile(action);
342 //It the cloud file has a later date, it was modified by another user or computer.
343 //We need to check the local file's status
344 var status = StatusKeeper.GetFileStatus(downloadPath);
347 case FileStatus.Unchanged:
348 //If the local file's status is Unchanged, we can go on and download the newer cloud file
349 await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
351 case FileStatus.Modified:
352 //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
353 //We can't ensure that a file modified online since the last time will appear as Modified, unless we
354 //index all files before we start listening.
355 case FileStatus.Created:
356 //If the local file is Created, it means that the local and cloud files aren't related,
357 // yet they have the same name.
359 //In both cases we must mark the file as in conflict
360 ReportConflict(downloadPath);
363 //Other cases should never occur. Mark them as Conflict as well but log a warning
364 ReportConflict(downloadPath);
365 Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
366 downloadPath, action.CloudFile.Name);
372 private void ReportConflict(string downloadPath)
374 if (String.IsNullOrWhiteSpace(downloadPath))
375 throw new ArgumentNullException("downloadPath");
376 Contract.EndContractBlock();
378 StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
379 var message = String.Format("Conflict detected for file {0}", downloadPath);
381 StatusNotification.NotifyChange(message, TraceLevel.Warning);
384 public void Post(CloudAction cloudAction)
386 if (cloudAction == null)
387 throw new ArgumentNullException("cloudAction");
388 if (cloudAction.AccountInfo==null)
389 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
390 Contract.EndContractBlock();
394 //If the action targets a local file, add a treehash calculation
395 if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
397 var accountInfo = cloudAction.AccountInfo;
398 var localFile = (FileInfo) cloudAction.LocalFile;
399 if (localFile.Length > accountInfo.BlockSize)
400 cloudAction.TopHash =
401 new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
402 accountInfo.BlockSize,
403 accountInfo.BlockHash).Result
404 .TopHash.ToHashString());
407 cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
412 //The hash for a directory is the empty string
413 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
416 if (cloudAction is CloudDeleteAction)
417 _deleteAgent.Post((CloudDeleteAction)cloudAction);
419 _agent.Post(cloudAction);
422 /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
424 public bool Equals(ObjectInfo x, ObjectInfo y)
426 return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
429 public int GetHashCode(ObjectInfo obj)
431 return obj.Name.ToLower().GetHashCode();
435 public void SynchNow()
438 _tcs.SetResult(true);
441 //TODO: This may be OK for testing purposes, but we have no guarantee that it will
442 //work properly in production
443 PollRemoteFiles(repeat:false);
447 //Remote files are polled periodically. Any changes are processed
448 public async Task PollRemoteFiles(DateTime? since = null,bool repeat=true)
451 _tcs = new TaskCompletionSource<bool>();
452 var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
453 var signaledTask=await TaskEx.WhenAny(_tcs.Task,wait);
454 //If polling is signalled by SynchNow, ignore the since tag
455 if (signaledTask is Task<bool>)
458 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
463 //Next time we will check for all changes since the current check minus 1 second
464 //This is done to ensure there are no discrepancies due to clock differences
465 DateTime nextSince = DateTime.Now.AddSeconds(-1);
467 var tasks = from accountInfo in _accounts
468 select ProcessAccountFiles(accountInfo, since);
470 await TaskEx.WhenAll(tasks.ToList());
474 PollRemoteFiles(nextSince);
478 Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
479 //In case of failure retry with the same parameter
480 PollRemoteFiles(since);
487 public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
489 if (accountInfo==null)
490 throw new ArgumentNullException("accountInfo");
491 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
492 throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
493 Contract.EndContractBlock();
495 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
497 Log.Info("Scheduled");
498 var client=new CloudFilesClient(accountInfo);
500 var containers = client.ListContainers(accountInfo.UserName);
502 CreateContainerFolders(accountInfo, containers);
507 //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
508 //than delete a file that was created while we were executing the poll
509 var pollTime = DateTime.Now;
511 //Get the list of server objects changed since the last check
512 //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
513 var listObjects = from container in containers
514 select Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
515 client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
518 var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
520 using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
522 var dict = listTasks.ToDictionary(t => t.AsyncState);
524 //Get all non-trash objects. Remember, the container name is stored in AsyncState
525 var remoteObjects = from objectList in listTasks
526 where (string) objectList.AsyncState != "trash"
527 from obj in objectList.Result
530 //TODO: Change the way deleted objects are detected.
531 //The list operation returns all existing objects so we could detect deleted remote objects
532 //by detecting objects that exist only locally. There are several cases where this is NOT the case:
533 //1. The first time the application runs, as there may be files that were added while
534 // the application was down.
535 //2. An object that is currently being uploaded will not appear in the remote list
536 // until the upload finishes.
537 // SOLUTION 1: Check the upload/download queue for the file
538 // SOLUTION 2: Check the SQLite states for the file's entry. If it is being uploaded,
539 // or its last modification was after the current poll, don't delete it. This way we don't
540 // delete objects whose upload finished too late to be included in the list.
541 //We need to detect and protect against such situations
542 //TODO: Does FileState have a LastModification field?
543 //TODO: How do we update the LastModification field? Do we need to add SQLite triggers?
544 // Do we need to use a proper SQLite schema?
545 // We can create a trigger with
546 // CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW
548 // UPDATE FileState SET LastModification=datetime('now') WHERE Id=old.Id;
551 //NOTE: Some files may have been deleted remotely while the application was down.
552 // We DO have to delete those files. Checking the trash makes it easy to detect them,
553 // Otherwise, we can't be really sure whether we need to upload or delete
554 // the local-only files.
555 // SOLUTION 1: Ask the user when such a local-only file is detected during the first poll.
556 // SOLUTION 2: Mark conflict and ask the user as in #1
558 var trashObjects = dict["trash"].Result;
559 //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
561 //Items with the same name, hash may be both in the container and the trash
562 //Don't delete items that exist in the container
563 var realTrash = from trash in trashObjects
566 info => info.Name == trash.Name && info.Hash == trash.Hash)
568 ProcessTrashedFiles(accountInfo, realTrash);
571 var cleanRemotes = (from info in remoteObjects
572 //.Union(sharedObjects)
574 where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
575 !name.StartsWith(FolderConstants.CacheFolder + "/",
576 StringComparison.InvariantCultureIgnoreCase)
577 select info).ToList();
581 ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
583 //Create a list of actions from the remote files
584 var allActions = ObjectsToActions(accountInfo, cleanRemotes);
587 //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
589 //And remove those that are already being processed by the agent
590 var distinctActions = allActions
591 .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
594 //Queue all the actions
595 foreach (var message in distinctActions)
600 Log.Info("[LISTENER] End Processing");
605 Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
609 Log.Info("[LISTENER] Finished");
615 /// Deletes local files that are not found in the list of cloud files
617 /// <param name="accountInfo"></param>
618 /// <param name="cloudFiles"></param>
619 /// <param name="pollTime"></param>
620 private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
622 if (accountInfo == null)
623 throw new ArgumentNullException("accountInfo");
624 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
625 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
626 if (cloudFiles == null)
627 throw new ArgumentNullException("cloudFiles");
628 Contract.EndContractBlock();
630 if (_firstPoll) return;
632 var deleteCandidates = from state in FileState.Queryable
633 let stateUrl = FileInfoExtensions.FromPath(state.FilePath)
634 .AsRelativeUrlTo(accountInfo.AccountPath)
635 where state.Modified <= pollTime &&
636 !cloudFiles.Any(r => r.Name == stateUrl)
639 foreach (var deleteCandidate in deleteCandidates)
641 File.Delete(deleteCandidate.FilePath);
642 StatusKeeper.ClearFileStatus(deleteCandidate.FilePath);
646 private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
648 var containerPaths = from container in containers
649 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
650 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
651 select containerPath;
653 foreach (var path in containerPaths)
655 Directory.CreateDirectory(path);
659 //Creates an appropriate action for each server file
660 private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
663 throw new ArgumentNullException();
664 Contract.EndContractBlock();
665 var fileAgent = GetFileAgent(accountInfo);
667 //In order to avoid multiple iterations over the files, we iterate only once
668 //over the remote files
669 foreach (var objectInfo in remote)
671 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
672 //and remove any matching objects from the list, adding them to the commonObjects list
674 if (fileAgent.Exists(relativePath))
676 //If a directory object already exists, we don't need to perform any other action
677 var localFile = fileAgent.GetFileSystemInfo(relativePath);
678 if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
680 using (new SessionScope(FlushAction.Never))
682 var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
683 //FileState.FindByFilePath(localFile.FullName);
684 //Common files should be checked on a per-case basis to detect differences, which is newer
686 yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
687 localFile, objectInfo, state, accountInfo.BlockSize,
688 accountInfo.BlockHash);
693 //If there is no match we add them to the localFiles list
694 //but only if the file is not marked for deletion
695 var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
696 var fileStatus = StatusKeeper.GetFileStatus(targetFile);
697 if (fileStatus != FileStatus.Deleted)
699 //Remote files should be downloaded
700 yield return new CloudDownloadAction(accountInfo,objectInfo);
706 private static FileAgent GetFileAgent(AccountInfo accountInfo)
708 return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
711 private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
713 var fileAgent = GetFileAgent(accountInfo);
714 foreach (var trashObject in trashObjects)
716 var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
717 //HACK: Assume only the "pithos" container is used. Must find out what happens when
718 //deleting a file from a different container
719 var relativePath = Path.Combine("pithos", barePath);
720 fileAgent.Delete(relativePath);
725 private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
727 if (accountInfo==null)
728 throw new ArgumentNullException("accountInfo");
730 throw new ArgumentNullException("action");
731 if (action.CloudFile==null)
732 throw new ArgumentException("CloudFile","action");
733 if (action.LocalFile==null)
734 throw new ArgumentException("LocalFile","action");
735 if (action.OldLocalFile==null)
736 throw new ArgumentException("OldLocalFile","action");
737 if (action.OldCloudFile==null)
738 throw new ArgumentException("OldCloudFile","action");
739 Contract.EndContractBlock();
742 var newFilePath = action.LocalFile.FullName;
744 //How do we handle concurrent renames and deletes/uploads/downloads?
745 //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
746 // This should never happen as the network agent executes only one action at a time
747 //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
748 // the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the
749 // same name will fail.
750 // This should never happen as the network agent executes only one action at a time.
751 //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
752 // to remove the rename from the queue.
753 // We can probably ignore this case. It will result in an error which should be ignored
756 //The local file is already renamed
757 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
760 var account = action.CloudFile.Account ?? accountInfo.UserName;
761 var container = action.CloudFile.Container;
763 var client = new CloudFilesClient(accountInfo);
764 //TODO: What code is returned when the source file doesn't exist?
765 client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
767 StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
768 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
769 NativeMethods.RaiseChangeNotification(newFilePath);
772 private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
774 if (accountInfo == null)
775 throw new ArgumentNullException("accountInfo");
777 throw new ArgumentNullException("cloudFile");
779 if (String.IsNullOrWhiteSpace(cloudFile.Container))
780 throw new ArgumentException("Invalid container", "cloudFile");
781 Contract.EndContractBlock();
783 var fileAgent = GetFileAgent(accountInfo);
785 using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
787 var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
788 var info = fileAgent.GetFileSystemInfo(fileName);
789 var fullPath = info.FullName.ToLower();
791 StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
793 var account = cloudFile.Account ?? accountInfo.UserName;
794 var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
796 var client = new CloudFilesClient(accountInfo);
797 client.DeleteObject(account, container, cloudFile.Name);
799 StatusKeeper.ClearFileStatus(fullPath);
804 private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
806 if (accountInfo == null)
807 throw new ArgumentNullException("accountInfo");
808 if (cloudFile == null)
809 throw new ArgumentNullException("cloudFile");
810 if (String.IsNullOrWhiteSpace(cloudFile.Account))
811 throw new ArgumentNullException("cloudFile");
812 if (String.IsNullOrWhiteSpace(cloudFile.Container))
813 throw new ArgumentNullException("cloudFile");
814 if (String.IsNullOrWhiteSpace(filePath))
815 throw new ArgumentNullException("filePath");
816 if (!Path.IsPathRooted(filePath))
817 throw new ArgumentException("The filePath must be rooted", "filePath");
818 Contract.EndContractBlock();
820 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
821 var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
823 var url = relativeUrl.ToString();
824 if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
828 //Are we already downloading or uploading the file?
829 using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
833 //The file's hashmap will be stored in the same location with the extension .hashmap
834 //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
836 var client = new CloudFilesClient(accountInfo);
837 var account = cloudFile.Account;
838 var container = cloudFile.Container;
840 if (cloudFile.Content_Type == @"application/directory")
842 if (!Directory.Exists(localPath))
843 Directory.CreateDirectory(localPath);
847 //Retrieve the hashmap from the server
848 var serverHash = await client.GetHashMap(account, container, url);
849 //If it's a small file
850 if (serverHash.Hashes.Count == 1)
851 //Download it in one go
853 DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
854 //Otherwise download it block by block
856 await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
858 if (cloudFile.AllowedTo == "read")
860 var attributes = File.GetAttributes(localPath);
861 File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
865 //Now we can store the object's metadata without worrying about ghost status entries
866 StatusKeeper.StoreInfo(localPath, cloudFile);
871 //Download a small file with a single GET operation
872 private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
875 throw new ArgumentNullException("client");
877 throw new ArgumentNullException("cloudFile");
878 if (relativeUrl == null)
879 throw new ArgumentNullException("relativeUrl");
880 if (String.IsNullOrWhiteSpace(filePath))
881 throw new ArgumentNullException("filePath");
882 if (!Path.IsPathRooted(filePath))
883 throw new ArgumentException("The localPath must be rooted", "filePath");
884 Contract.EndContractBlock();
886 var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
887 //If the file already exists
888 if (File.Exists(localPath))
890 //First check with MD5 as this is a small file
891 var localMD5 = Signature.CalculateMD5(localPath);
892 var cloudHash=serverHash.TopHash.ToHashString();
893 if (localMD5==cloudHash)
895 //Then check with a treehash
896 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
897 var localHash = localTreeHash.TopHash.ToHashString();
898 if (localHash==cloudHash)
902 var fileAgent = GetFileAgent(accountInfo);
903 //Calculate the relative file path for the new file
904 var relativePath = relativeUrl.RelativeUriToFilePath();
905 //The file will be stored in a temporary location while downloading with an extension .download
906 var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
907 //Make sure the target folder exists. DownloadFileTask will not create the folder
908 var tempFolder = Path.GetDirectoryName(tempPath);
909 if (!Directory.Exists(tempFolder))
910 Directory.CreateDirectory(tempFolder);
912 //Download the object to the temporary location
913 await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
915 //Create the local folder if it doesn't exist (necessary for shared objects)
916 var localFolder = Path.GetDirectoryName(localPath);
917 if (!Directory.Exists(localFolder))
918 Directory.CreateDirectory(localFolder);
919 //And move it to its actual location once downloading is finished
920 if (File.Exists(localPath))
921 File.Replace(tempPath,localPath,null,true);
923 File.Move(tempPath,localPath);
924 //Notify listeners that a local file has changed
925 StatusNotification.NotifyChangedFile(localPath);
930 //Download a file asynchronously using blocks
931 public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
934 throw new ArgumentNullException("client");
935 if (cloudFile == null)
936 throw new ArgumentNullException("cloudFile");
937 if (relativeUrl == null)
938 throw new ArgumentNullException("relativeUrl");
939 if (String.IsNullOrWhiteSpace(filePath))
940 throw new ArgumentNullException("filePath");
941 if (!Path.IsPathRooted(filePath))
942 throw new ArgumentException("The filePath must be rooted", "filePath");
943 if (serverHash == null)
944 throw new ArgumentNullException("serverHash");
945 Contract.EndContractBlock();
947 var fileAgent = GetFileAgent(accountInfo);
948 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
950 //Calculate the relative file path for the new file
951 var relativePath = relativeUrl.RelativeUriToFilePath();
952 var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
956 //Calculate the file's treehash
957 var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
959 //And compare it with the server's hash
960 var upHashes = serverHash.GetHashesAsStrings();
961 var localHashes = treeHash.HashDictionary;
962 for (int i = 0; i < upHashes.Length; i++)
964 //For every non-matching hash
965 var upHash = upHashes[i];
966 if (!localHashes.ContainsKey(upHash))
968 if (blockUpdater.UseOrphan(i, upHash))
970 Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
973 Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
974 var start = i*serverHash.BlockSize;
975 //To download the last block just pass a null for the end of the range
977 if (i < upHashes.Length - 1 )
978 end= ((i + 1)*serverHash.BlockSize) ;
980 //Download the missing block
981 var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
984 blockUpdater.StoreBlock(i, block);
987 Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
991 //Want to avoid notifications if no changes were made
992 var hasChanges = blockUpdater.HasBlocks;
993 blockUpdater.Commit();
996 //Notify listeners that a local file has changed
997 StatusNotification.NotifyChangedFile(localPath);
999 Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
1003 private async Task UploadCloudFile(CloudAction action)
1006 throw new ArgumentNullException("action");
1007 Contract.EndContractBlock();
1011 var accountInfo = action.AccountInfo;
1013 var fileInfo = action.LocalFile;
1015 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1018 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1019 if (relativePath.StartsWith(FolderConstants.OthersFolder))
1021 var parts = relativePath.Split('\\');
1022 var accountName = parts[1];
1023 var oldName = accountInfo.UserName;
1024 var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1025 var nameIndex = absoluteUri.IndexOf(oldName);
1026 var root = absoluteUri.Substring(0, nameIndex);
1028 accountInfo = new AccountInfo
1030 UserName = accountName,
1031 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1032 StorageUri = new Uri(root + accountName),
1033 BlockHash = accountInfo.BlockHash,
1034 BlockSize = accountInfo.BlockSize,
1035 Token = accountInfo.Token
1040 var fullFileName = fileInfo.GetProperCapitalization();
1041 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1043 //Abort if the file is already being uploaded or downloaded
1047 var cloudFile = action.CloudFile;
1048 var account = cloudFile.Account ?? accountInfo.UserName;
1050 var client = new CloudFilesClient(accountInfo);
1051 //Even if GetObjectInfo times out, we can proceed with the upload
1052 var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1054 //If this is a read-only file, do not upload changes
1055 if (info.AllowedTo == "read")
1058 //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1059 if (fileInfo is DirectoryInfo)
1061 //If the directory doesn't exist the Hash property will be empty
1062 if (String.IsNullOrWhiteSpace(info.Hash))
1063 //Go on and create the directory
1064 await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1069 var cloudHash = info.Hash.ToLower();
1071 var hash = action.LocalHash.Value;
1072 var topHash = action.TopHash.Value;
1074 //If the file hashes match, abort the upload
1075 if (hash == cloudHash || topHash == cloudHash)
1077 //but store any metadata changes
1078 StatusKeeper.StoreInfo(fullFileName, info);
1079 Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1084 //Mark the file as modified while we upload it
1085 StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1086 //And then upload it
1088 //Upload even small files using the Hashmap. The server may already contain
1089 //the relevant block
1091 //First, calculate the tree hash
1092 var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1093 accountInfo.BlockHash);
1095 await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1097 //If everything succeeds, change the file and overlay status to normal
1098 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1100 //Notify the Shell to update the overlays
1101 NativeMethods.RaiseChangeNotification(fullFileName);
1102 StatusNotification.NotifyChangedFile(fullFileName);
1104 catch (AggregateException ex)
1106 var exc = ex.InnerException as WebException;
1108 throw ex.InnerException;
1109 if (HandleUploadWebException(action, exc))
1113 catch (WebException ex)
1115 if (HandleUploadWebException(action, ex))
1119 catch (Exception ex)
1121 Log.Error("Unexpected error while uploading file", ex);
1127 private bool IsDeletedFile(CloudAction action)
1129 var key = GetFileKey(action.CloudFile);
1131 if (_deletedFiles.TryGetValue(key, out entryDate))
1133 //If the delete entry was created after this action, abort the action
1134 if (entryDate > action.Created)
1136 //Otherwise, remove the stale entry
1137 _deletedFiles.TryRemove(key, out entryDate);
1142 private bool HandleUploadWebException(CloudAction action, WebException exc)
1144 var response = exc.Response as HttpWebResponse;
1145 if (response == null)
1147 if (response.StatusCode == HttpStatusCode.Unauthorized)
1149 Log.Error("Not allowed to upload file", exc);
1150 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1151 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1152 StatusNotification.NotifyChange(message, TraceLevel.Warning);
1158 public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1160 if (accountInfo == null)
1161 throw new ArgumentNullException("accountInfo");
1162 if (cloudFile==null)
1163 throw new ArgumentNullException("cloudFile");
1164 if (fileInfo == null)
1165 throw new ArgumentNullException("fileInfo");
1166 if (String.IsNullOrWhiteSpace(url))
1167 throw new ArgumentNullException(url);
1169 throw new ArgumentNullException("treeHash");
1170 if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1171 throw new ArgumentException("Invalid container","cloudFile");
1172 Contract.EndContractBlock();
1174 var fullFileName = fileInfo.GetProperCapitalization();
1176 var account = cloudFile.Account ?? accountInfo.UserName;
1177 var container = cloudFile.Container ;
1179 var client = new CloudFilesClient(accountInfo);
1180 //Send the hashmap to the server
1181 var missingHashes = await client.PutHashMap(account, container, url, treeHash);
1182 //If the server returns no missing hashes, we are done
1183 while (missingHashes.Count > 0)
1186 var buffer = new byte[accountInfo.BlockSize];
1187 foreach (var missingHash in missingHashes)
1189 //Find the proper block
1190 var blockIndex = treeHash.HashDictionary[missingHash];
1191 var offset = blockIndex*accountInfo.BlockSize;
1193 var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1197 //And upload the block
1198 await client.PostBlock(account, container, buffer, 0, read);
1199 Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1201 catch (Exception exc)
1203 Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1208 //Repeat until there are no more missing hashes
1209 missingHashes = await client.PutHashMap(account, container, url, treeHash);
1214 public void AddAccount(AccountInfo accountInfo)
1216 if (!_accounts.Contains(accountInfo))
1217 _accounts.Add(accountInfo);