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>();
80 private bool _firstPoll = true;
84 _agent = Agent<CloudAction>.Start(inbox =>
90 var message = inbox.Receive();
91 var process=message.Then(Process,inbox.CancellationToken);
92 inbox.LoopAsync(process, loop);
97 _deleteAgent = new ActionBlock<CloudDeleteAction>(message =>ProcessDelete(message),new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism=4});
102 var message = inbox.Receive();
103 var process = message.Then(ProcessDelete,inbox.CancellationToken);
104 inbox.LoopAsync(process, loop);
111 private async Task Process(CloudAction action)
114 throw new ArgumentNullException("action");
115 if (action.AccountInfo==null)
116 throw new ArgumentException("The action.AccountInfo is empty","action");
117 Contract.EndContractBlock();
119 var accountInfo = action.AccountInfo;
121 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
123 Log.InfoFormat("[ACTION] Start Processing {0}", action);
125 var cloudFile = action.CloudFile;
126 var downloadPath = action.GetDownloadPath();
131 if (action.Action == CloudActionType.DeleteCloud)
133 //Redirect deletes to the delete agent
134 _deleteAgent.Post((CloudDeleteAction)action);
136 if (IsDeletedFile(action))
138 //Clear the status of already deleted files to avoid reprocessing
139 if (action.LocalFile != null)
140 this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
144 switch (action.Action)
146 case CloudActionType.UploadUnconditional:
147 //Abort if the file was deleted before we reached this point
148 await UploadCloudFile(action);
150 case CloudActionType.DownloadUnconditional:
151 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
153 case CloudActionType.RenameCloud:
154 var moveAction = (CloudMoveAction) action;
155 RenameCloudFile(accountInfo, moveAction);
157 case CloudActionType.MustSynch:
158 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
160 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
164 await SyncFiles(accountInfo, action);
169 Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
170 action.CloudFile.Name);
172 catch (WebException exc)
174 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
176 catch (OperationCanceledException)
180 catch (DirectoryNotFoundException)
182 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
183 action.Action, action.LocalFile, action.CloudFile);
184 //Post a delete action for the missing file
185 Post(new CloudDeleteAction(action));
187 catch (FileNotFoundException)
189 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
190 action.Action, action.LocalFile, action.CloudFile);
191 //Post a delete action for the missing file
192 Post(new CloudDeleteAction(action));
194 catch (Exception exc)
196 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
197 action.Action, action.LocalFile, action.CloudFile, exc);
205 /// Processes cloud delete actions
207 /// <param name="action">The delete action to execute</param>
208 /// <returns></returns>
210 /// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download
211 /// operations that may be in progress.
213 /// A separate agent is used to process deletes because the main agent may be busy with a long operation.
216 private async Task ProcessDelete(CloudDeleteAction action)
219 throw new ArgumentNullException("action");
220 if (action.AccountInfo==null)
221 throw new ArgumentException("The action.AccountInfo is empty","action");
222 Contract.EndContractBlock();
224 var accountInfo = action.AccountInfo;
226 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
228 Log.InfoFormat("[ACTION] Start Processing {0}", action);
230 var cloudFile = action.CloudFile;
234 //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
236 using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
239 //Add the file URL to the deleted files list
240 var key = GetFileKey(action.CloudFile);
241 _deletedFiles[key] = DateTime.Now;
244 // and then delete the file from the server
245 DeleteCloudFile(accountInfo, cloudFile);
247 Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
248 action.CloudFile.Name);
251 catch (WebException exc)
253 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
255 catch (OperationCanceledException)
259 catch (DirectoryNotFoundException)
261 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
262 action.Action, action.LocalFile, action.CloudFile);
263 //Repost a delete action for the missing file
264 _deleteAgent.Post(action);
266 catch (FileNotFoundException)
268 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
269 action.Action, action.LocalFile, action.CloudFile);
270 //Post a delete action for the missing file
271 _deleteAgent.Post(action);
273 catch (Exception exc)
275 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
276 action.Action, action.LocalFile, action.CloudFile, exc);
278 _deleteAgent.Post(action);
282 if (_deleteAgent.InputCount == 0)
289 private static string GetFileKey(ObjectInfo info)
291 var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
295 private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
297 if (accountInfo == null)
298 throw new ArgumentNullException("accountInfo");
300 throw new ArgumentNullException("action");
301 if (action.LocalFile==null)
302 throw new ArgumentException("The action's local file is not specified","action");
303 if (!Path.IsPathRooted(action.LocalFile.FullName))
304 throw new ArgumentException("The action's local file path must be absolute","action");
305 if (action.CloudFile== null)
306 throw new ArgumentException("The action's cloud file is not specified", "action");
307 Contract.EndContractBlock();
309 var localFile = action.LocalFile;
310 var cloudFile = action.CloudFile;
311 var downloadPath=action.LocalFile.GetProperCapitalization();
313 var cloudHash = cloudFile.Hash.ToLower();
314 var localHash = action.LocalHash.Value.ToLower();
315 var topHash = action.TopHash.Value.ToLower();
317 //Not enough to compare only the local hashes, also have to compare the tophashes
319 //If any of the hashes match, we are done
320 if ((cloudHash == localHash || cloudHash == topHash))
322 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
326 //The hashes DON'T match. We need to sync
327 var lastLocalTime = localFile.LastWriteTime;
328 var lastUpTime = cloudFile.Last_Modified;
330 //If the local file is newer upload it
331 if (lastUpTime <= lastLocalTime)
333 //It probably means it was changed while the app was down
334 UploadCloudFile(action);
338 //It the cloud file has a later date, it was modified by another user or computer.
339 //We need to check the local file's status
340 var status = StatusKeeper.GetFileStatus(downloadPath);
343 case FileStatus.Unchanged:
344 //If the local file's status is Unchanged, we can go on and download the newer cloud file
345 await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
347 case FileStatus.Modified:
348 //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
349 //We can't ensure that a file modified online since the last time will appear as Modified, unless we
350 //index all files before we start listening.
351 case FileStatus.Created:
352 //If the local file is Created, it means that the local and cloud files aren't related,
353 // yet they have the same name.
355 //In both cases we must mark the file as in conflict
356 ReportConflict(downloadPath);
359 //Other cases should never occur. Mark them as Conflict as well but log a warning
360 ReportConflict(downloadPath);
361 Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
362 downloadPath, action.CloudFile.Name);
368 private void ReportConflict(string downloadPath)
370 if (String.IsNullOrWhiteSpace(downloadPath))
371 throw new ArgumentNullException("downloadPath");
372 Contract.EndContractBlock();
374 StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
375 var message = String.Format("Conflict detected for file {0}", downloadPath);
377 StatusNotification.NotifyChange(message, TraceLevel.Warning);
380 public void Post(CloudAction cloudAction)
382 if (cloudAction == null)
383 throw new ArgumentNullException("cloudAction");
384 if (cloudAction.AccountInfo==null)
385 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
386 Contract.EndContractBlock();
390 //If the action targets a local file, add a treehash calculation
391 if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
393 var accountInfo = cloudAction.AccountInfo;
394 var localFile = (FileInfo) cloudAction.LocalFile;
395 if (localFile.Length > accountInfo.BlockSize)
396 cloudAction.TopHash =
397 new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
398 accountInfo.BlockSize,
399 accountInfo.BlockHash).Result
400 .TopHash.ToHashString());
403 cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
408 //The hash for a directory is the empty string
409 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
412 if (cloudAction is CloudDeleteAction)
413 _deleteAgent.Post((CloudDeleteAction)cloudAction);
415 _agent.Post(cloudAction);
418 /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
420 public bool Equals(ObjectInfo x, ObjectInfo y)
422 return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
425 public int GetHashCode(ObjectInfo obj)
427 return obj.Name.ToLower().GetHashCode();
433 //Remote files are polled periodically. Any changes are processed
434 public async Task ProcessRemoteFiles(DateTime? since = null)
436 await TaskEx.Delay(TimeSpan.FromSeconds(10),_agent.CancellationToken);
438 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
443 //Next time we will check for all changes since the current check minus 1 second
444 //This is done to ensure there are no discrepancies due to clock differences
445 DateTime nextSince = DateTime.Now.AddSeconds(-1);
447 var tasks = from accountInfo in _accounts
448 select ProcessAccountFiles(accountInfo, since);
450 await TaskEx.WhenAll(tasks.ToList());
453 ProcessRemoteFiles(nextSince);
457 Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
458 //In case of failure retry with the same parameter
459 ProcessRemoteFiles(since);
466 public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
468 if (accountInfo==null)
469 throw new ArgumentNullException("accountInfo");
470 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
471 throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
472 Contract.EndContractBlock();
474 using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
476 Log.Info("Scheduled");
477 var client=new CloudFilesClient(accountInfo);
479 var containers = client.ListContainers(accountInfo.UserName);
481 CreateContainerFolders(accountInfo, containers);
486 //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
487 //than delete a file that was created while we were executing the poll
488 var pollTime = DateTime.Now;
490 //Get the list of server objects changed since the last check
491 //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
492 var listObjects = from container in containers
493 select Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
494 client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
497 var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
499 using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
501 var dict = listTasks.ToDictionary(t => t.AsyncState);
503 //Get all non-trash objects. Remember, the container name is stored in AsyncState
504 var remoteObjects = from objectList in listTasks
505 where (string) objectList.AsyncState != "trash"
506 from obj in objectList.Result
509 //TODO: Change the way deleted objects are detected.
510 //The list operation returns all existing objects so we could detect deleted remote objects
511 //by detecting objects that exist only locally. There are several cases where this is NOT the case:
512 //1. The first time the application runs, as there may be files that were added while
513 // the application was down.
514 //2. An object that is currently being uploaded will not appear in the remote list
515 // until the upload finishes.
516 // SOLUTION 1: Check the upload/download queue for the file
517 // SOLUTION 2: Check the SQLite states for the file's entry. If it is being uploaded,
518 // or its last modification was after the current poll, don't delete it. This way we don't
519 // delete objects whose upload finished too late to be included in the list.
520 //We need to detect and protect against such situations
521 //TODO: Does FileState have a LastModification field?
522 //TODO: How do we update the LastModification field? Do we need to add SQLite triggers?
523 // Do we need to use a proper SQLite schema?
524 // We can create a trigger with
525 // CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW
527 // UPDATE FileState SET LastModification=datetime('now') WHERE Id=old.Id;
530 //NOTE: Some files may have been deleted remotely while the application was down.
531 // We DO have to delete those files. Checking the trash makes it easy to detect them,
532 // Otherwise, we can't be really sure whether we need to upload or delete
533 // the local-only files.
534 // SOLUTION 1: Ask the user when such a local-only file is detected during the first poll.
535 // SOLUTION 2: Mark conflict and ask the user as in #1
537 var trashObjects = dict["trash"].Result;
538 //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
540 //Items with the same name, hash may be both in the container and the trash
541 //Don't delete items that exist in the container
542 var realTrash = from trash in trashObjects
545 info => info.Name == trash.Name && info.Hash == trash.Hash)
547 ProcessTrashedFiles(accountInfo, realTrash);
550 var cleanRemotes = from info in remoteObjects
551 //.Union(sharedObjects)
553 where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
554 !name.StartsWith(FolderConstants.CacheFolder + "/",
555 StringComparison.InvariantCultureIgnoreCase)
562 //Create a list of actions from the remote files
563 var allActions = ObjectsToActions(accountInfo, cleanRemotes);
565 ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
566 //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
568 //And remove those that are already being processed by the agent
569 var distinctActions = allActions
570 .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
573 //Queue all the actions
574 foreach (var message in distinctActions)
579 Log.Info("[LISTENER] End Processing");
584 Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
588 Log.Info("[LISTENER] Finished");
594 /// Deletes local files that are not found in the list of cloud files
596 /// <param name="accountInfo"></param>
597 /// <param name="cloudFiles"></param>
598 /// <param name="pollTime"></param>
599 private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
601 if (accountInfo == null)
602 throw new ArgumentNullException("accountInfo");
603 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
604 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
605 if (cloudFiles == null)
606 throw new ArgumentNullException("cloudFiles");
607 Contract.EndContractBlock();
609 if (_firstPoll) return;
611 var deleteCandidates = from state in FileState.Queryable
612 let stateUrl = FileInfoExtensions.FromPath(state.FilePath)
613 .AsRelativeUrlTo(accountInfo.AccountPath)
614 where state.Modified <= pollTime &&
615 !cloudFiles.Any(r => r.Name == stateUrl)
618 foreach (var deleteCandidate in deleteCandidates)
620 File.Delete(deleteCandidate.FilePath);
621 StatusKeeper.ClearFileStatus(deleteCandidate.FilePath);
625 private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
627 var containerPaths = from container in containers
628 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
629 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
630 select containerPath;
632 foreach (var path in containerPaths)
634 Directory.CreateDirectory(path);
638 //Creates an appropriate action for each server file
639 private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
642 throw new ArgumentNullException();
643 Contract.EndContractBlock();
644 var fileAgent = GetFileAgent(accountInfo);
646 //In order to avoid multiple iterations over the files, we iterate only once
647 //over the remote files
648 foreach (var objectInfo in remote)
650 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
651 //and remove any matching objects from the list, adding them to the commonObjects list
653 if (fileAgent.Exists(relativePath))
655 //If a directory object already exists, we don't need to perform any other action
656 var localFile = fileAgent.GetFileSystemInfo(relativePath);
657 if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
659 using (new SessionScope(FlushAction.Never))
661 var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
662 //FileState.FindByFilePath(localFile.FullName);
663 //Common files should be checked on a per-case basis to detect differences, which is newer
665 yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
666 localFile, objectInfo, state, accountInfo.BlockSize,
667 accountInfo.BlockHash);
672 //If there is no match we add them to the localFiles list
673 //but only if the file is not marked for deletion
674 var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
675 var fileStatus = StatusKeeper.GetFileStatus(targetFile);
676 if (fileStatus != FileStatus.Deleted)
678 //Remote files should be downloaded
679 yield return new CloudDownloadAction(accountInfo,objectInfo);
685 private static FileAgent GetFileAgent(AccountInfo accountInfo)
687 return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
690 private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
692 var fileAgent = GetFileAgent(accountInfo);
693 foreach (var trashObject in trashObjects)
695 var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
696 //HACK: Assume only the "pithos" container is used. Must find out what happens when
697 //deleting a file from a different container
698 var relativePath = Path.Combine("pithos", barePath);
699 fileAgent.Delete(relativePath);
704 private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
706 if (accountInfo==null)
707 throw new ArgumentNullException("accountInfo");
709 throw new ArgumentNullException("action");
710 if (action.CloudFile==null)
711 throw new ArgumentException("CloudFile","action");
712 if (action.LocalFile==null)
713 throw new ArgumentException("LocalFile","action");
714 if (action.OldLocalFile==null)
715 throw new ArgumentException("OldLocalFile","action");
716 if (action.OldCloudFile==null)
717 throw new ArgumentException("OldCloudFile","action");
718 Contract.EndContractBlock();
721 var newFilePath = action.LocalFile.FullName;
723 //How do we handle concurrent renames and deletes/uploads/downloads?
724 //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
725 // This should never happen as the network agent executes only one action at a time
726 //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
727 // the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the
728 // same name will fail.
729 // This should never happen as the network agent executes only one action at a time.
730 //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
731 // to remove the rename from the queue.
732 // We can probably ignore this case. It will result in an error which should be ignored
735 //The local file is already renamed
736 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
739 var account = action.CloudFile.Account ?? accountInfo.UserName;
740 var container = action.CloudFile.Container;
742 var client = new CloudFilesClient(accountInfo);
743 //TODO: What code is returned when the source file doesn't exist?
744 client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
746 StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
747 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
748 NativeMethods.RaiseChangeNotification(newFilePath);
751 private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
753 if (accountInfo == null)
754 throw new ArgumentNullException("accountInfo");
756 throw new ArgumentNullException("cloudFile");
758 if (String.IsNullOrWhiteSpace(cloudFile.Container))
759 throw new ArgumentException("Invalid container", "cloudFile");
760 Contract.EndContractBlock();
762 var fileAgent = GetFileAgent(accountInfo);
764 using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
766 var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
767 var info = fileAgent.GetFileSystemInfo(fileName);
768 var fullPath = info.FullName.ToLower();
770 StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
772 var account = cloudFile.Account ?? accountInfo.UserName;
773 var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
775 var client = new CloudFilesClient(accountInfo);
776 client.DeleteObject(account, container, cloudFile.Name);
778 StatusKeeper.ClearFileStatus(fullPath);
783 private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
785 if (accountInfo == null)
786 throw new ArgumentNullException("accountInfo");
787 if (cloudFile == null)
788 throw new ArgumentNullException("cloudFile");
789 if (String.IsNullOrWhiteSpace(cloudFile.Account))
790 throw new ArgumentNullException("cloudFile");
791 if (String.IsNullOrWhiteSpace(cloudFile.Container))
792 throw new ArgumentNullException("cloudFile");
793 if (String.IsNullOrWhiteSpace(filePath))
794 throw new ArgumentNullException("filePath");
795 if (!Path.IsPathRooted(filePath))
796 throw new ArgumentException("The filePath must be rooted", "filePath");
797 Contract.EndContractBlock();
799 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
800 var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
802 var url = relativeUrl.ToString();
803 if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
807 //Are we already downloading or uploading the file?
808 using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
812 //The file's hashmap will be stored in the same location with the extension .hashmap
813 //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
815 var client = new CloudFilesClient(accountInfo);
816 var account = cloudFile.Account;
817 var container = cloudFile.Container;
819 if (cloudFile.Content_Type == @"application/directory")
821 if (!Directory.Exists(localPath))
822 Directory.CreateDirectory(localPath);
826 //Retrieve the hashmap from the server
827 var serverHash = await client.GetHashMap(account, container, url);
828 //If it's a small file
829 if (serverHash.Hashes.Count == 1)
830 //Download it in one go
832 DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
833 //Otherwise download it block by block
835 await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
837 if (cloudFile.AllowedTo == "read")
839 var attributes = File.GetAttributes(localPath);
840 File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
844 //Now we can store the object's metadata without worrying about ghost status entries
845 StatusKeeper.StoreInfo(localPath, cloudFile);
850 //Download a small file with a single GET operation
851 private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
854 throw new ArgumentNullException("client");
856 throw new ArgumentNullException("cloudFile");
857 if (relativeUrl == null)
858 throw new ArgumentNullException("relativeUrl");
859 if (String.IsNullOrWhiteSpace(filePath))
860 throw new ArgumentNullException("filePath");
861 if (!Path.IsPathRooted(filePath))
862 throw new ArgumentException("The localPath must be rooted", "filePath");
863 Contract.EndContractBlock();
865 var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
866 //If the file already exists
867 if (File.Exists(localPath))
869 //First check with MD5 as this is a small file
870 var localMD5 = Signature.CalculateMD5(localPath);
871 var cloudHash=serverHash.TopHash.ToHashString();
872 if (localMD5==cloudHash)
874 //Then check with a treehash
875 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
876 var localHash = localTreeHash.TopHash.ToHashString();
877 if (localHash==cloudHash)
881 var fileAgent = GetFileAgent(accountInfo);
882 //Calculate the relative file path for the new file
883 var relativePath = relativeUrl.RelativeUriToFilePath();
884 //The file will be stored in a temporary location while downloading with an extension .download
885 var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
886 //Make sure the target folder exists. DownloadFileTask will not create the folder
887 var tempFolder = Path.GetDirectoryName(tempPath);
888 if (!Directory.Exists(tempFolder))
889 Directory.CreateDirectory(tempFolder);
891 //Download the object to the temporary location
892 await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
894 //Create the local folder if it doesn't exist (necessary for shared objects)
895 var localFolder = Path.GetDirectoryName(localPath);
896 if (!Directory.Exists(localFolder))
897 Directory.CreateDirectory(localFolder);
898 //And move it to its actual location once downloading is finished
899 if (File.Exists(localPath))
900 File.Replace(tempPath,localPath,null,true);
902 File.Move(tempPath,localPath);
903 //Notify listeners that a local file has changed
904 StatusNotification.NotifyChangedFile(localPath);
909 //Download a file asynchronously using blocks
910 public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
913 throw new ArgumentNullException("client");
914 if (cloudFile == null)
915 throw new ArgumentNullException("cloudFile");
916 if (relativeUrl == null)
917 throw new ArgumentNullException("relativeUrl");
918 if (String.IsNullOrWhiteSpace(filePath))
919 throw new ArgumentNullException("filePath");
920 if (!Path.IsPathRooted(filePath))
921 throw new ArgumentException("The filePath must be rooted", "filePath");
922 if (serverHash == null)
923 throw new ArgumentNullException("serverHash");
924 Contract.EndContractBlock();
926 var fileAgent = GetFileAgent(accountInfo);
927 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
929 //Calculate the relative file path for the new file
930 var relativePath = relativeUrl.RelativeUriToFilePath();
931 var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
935 //Calculate the file's treehash
936 var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
938 //And compare it with the server's hash
939 var upHashes = serverHash.GetHashesAsStrings();
940 var localHashes = treeHash.HashDictionary;
941 for (int i = 0; i < upHashes.Length; i++)
943 //For every non-matching hash
944 var upHash = upHashes[i];
945 if (!localHashes.ContainsKey(upHash))
947 if (blockUpdater.UseOrphan(i, upHash))
949 Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
952 Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
953 var start = i*serverHash.BlockSize;
954 //To download the last block just pass a null for the end of the range
956 if (i < upHashes.Length - 1 )
957 end= ((i + 1)*serverHash.BlockSize) ;
959 //Download the missing block
960 var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
963 blockUpdater.StoreBlock(i, block);
966 Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
970 //Want to avoid notifications if no changes were made
971 var hasChanges = blockUpdater.HasBlocks;
972 blockUpdater.Commit();
975 //Notify listeners that a local file has changed
976 StatusNotification.NotifyChangedFile(localPath);
978 Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
982 private async Task UploadCloudFile(CloudAction action)
985 throw new ArgumentNullException("action");
986 Contract.EndContractBlock();
990 var accountInfo = action.AccountInfo;
992 var fileInfo = action.LocalFile;
994 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
997 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
998 if (relativePath.StartsWith(FolderConstants.OthersFolder))
1000 var parts = relativePath.Split('\\');
1001 var accountName = parts[1];
1002 var oldName = accountInfo.UserName;
1003 var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1004 var nameIndex = absoluteUri.IndexOf(oldName);
1005 var root = absoluteUri.Substring(0, nameIndex);
1007 accountInfo = new AccountInfo
1009 UserName = accountName,
1010 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1011 StorageUri = new Uri(root + accountName),
1012 BlockHash = accountInfo.BlockHash,
1013 BlockSize = accountInfo.BlockSize,
1014 Token = accountInfo.Token
1019 var fullFileName = fileInfo.GetProperCapitalization();
1020 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1022 //Abort if the file is already being uploaded or downloaded
1026 var cloudFile = action.CloudFile;
1027 var account = cloudFile.Account ?? accountInfo.UserName;
1029 var client = new CloudFilesClient(accountInfo);
1030 //Even if GetObjectInfo times out, we can proceed with the upload
1031 var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1033 //If this is a read-only file, do not upload changes
1034 if (info.AllowedTo == "read")
1037 //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1038 if (fileInfo is DirectoryInfo)
1040 //If the directory doesn't exist the Hash property will be empty
1041 if (String.IsNullOrWhiteSpace(info.Hash))
1042 //Go on and create the directory
1043 await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1048 var cloudHash = info.Hash.ToLower();
1050 var hash = action.LocalHash.Value;
1051 var topHash = action.TopHash.Value;
1053 //If the file hashes match, abort the upload
1054 if (hash == cloudHash || topHash == cloudHash)
1056 //but store any metadata changes
1057 StatusKeeper.StoreInfo(fullFileName, info);
1058 Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1063 //Mark the file as modified while we upload it
1064 StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1065 //And then upload it
1067 //Upload even small files using the Hashmap. The server may already contain
1068 //the relevant block
1070 //First, calculate the tree hash
1071 var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1072 accountInfo.BlockHash);
1074 await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1076 //If everything succeeds, change the file and overlay status to normal
1077 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1079 //Notify the Shell to update the overlays
1080 NativeMethods.RaiseChangeNotification(fullFileName);
1081 StatusNotification.NotifyChangedFile(fullFileName);
1083 catch (AggregateException ex)
1085 var exc = ex.InnerException as WebException;
1087 throw ex.InnerException;
1088 if (HandleUploadWebException(action, exc))
1092 catch (WebException ex)
1094 if (HandleUploadWebException(action, ex))
1098 catch (Exception ex)
1100 Log.Error("Unexpected error while uploading file", ex);
1106 private bool IsDeletedFile(CloudAction action)
1108 var key = GetFileKey(action.CloudFile);
1110 if (_deletedFiles.TryGetValue(key, out entryDate))
1112 //If the delete entry was created after this action, abort the action
1113 if (entryDate > action.Created)
1115 //Otherwise, remove the stale entry
1116 _deletedFiles.TryRemove(key, out entryDate);
1121 private bool HandleUploadWebException(CloudAction action, WebException exc)
1123 var response = exc.Response as HttpWebResponse;
1124 if (response == null)
1126 if (response.StatusCode == HttpStatusCode.Unauthorized)
1128 Log.Error("Not allowed to upload file", exc);
1129 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1130 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1131 StatusNotification.NotifyChange(message, TraceLevel.Warning);
1137 public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1139 if (accountInfo == null)
1140 throw new ArgumentNullException("accountInfo");
1141 if (cloudFile==null)
1142 throw new ArgumentNullException("cloudFile");
1143 if (fileInfo == null)
1144 throw new ArgumentNullException("fileInfo");
1145 if (String.IsNullOrWhiteSpace(url))
1146 throw new ArgumentNullException(url);
1148 throw new ArgumentNullException("treeHash");
1149 if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1150 throw new ArgumentException("Invalid container","cloudFile");
1151 Contract.EndContractBlock();
1153 var fullFileName = fileInfo.GetProperCapitalization();
1155 var account = cloudFile.Account ?? accountInfo.UserName;
1156 var container = cloudFile.Container ;
1158 var client = new CloudFilesClient(accountInfo);
1159 //Send the hashmap to the server
1160 var missingHashes = await client.PutHashMap(account, container, url, treeHash);
1161 //If the server returns no missing hashes, we are done
1162 while (missingHashes.Count > 0)
1165 var buffer = new byte[accountInfo.BlockSize];
1166 foreach (var missingHash in missingHashes)
1168 //Find the proper block
1169 var blockIndex = treeHash.HashDictionary[missingHash];
1170 var offset = blockIndex*accountInfo.BlockSize;
1172 var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1176 //And upload the block
1177 await client.PostBlock(account, container, buffer, 0, read);
1178 Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1180 catch (Exception exc)
1182 Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1187 //Repeat until there are no more missing hashes
1188 missingHashes = await client.PutHashMap(account, container, url, treeHash);
1193 public void AddAccount(AccountInfo accountInfo)
1195 if (!_accounts.Contains(accountInfo))
1196 _accounts.Add(accountInfo);