-using System;
+#region
+/* -----------------------------------------------------------------------
+ * <copyright file="NetworkAgent.cs" company="GRNet">
+ *
+ * Copyright 2011-2012 GRNET S.A. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+ * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * The views and conclusions contained in the software and
+ * documentation are those of the authors and should not be
+ * interpreted as representing official policies, either expressed
+ * or implied, of GRNET S.A.
+ * </copyright>
+ * -----------------------------------------------------------------------
+ */
+#endregion
+
+using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
-using System.Text;
+using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
+using Castle.ActiveRecord;
using Pithos.Interfaces;
using Pithos.Network;
using log4net;
[Export]
public class NetworkAgent
{
+ private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
private Agent<CloudAction> _agent;
- [Import]
+ [System.ComponentModel.Composition.Import]
+ private DeleteAgent DeleteAgent { get; set; }
+
+ [System.ComponentModel.Composition.Import]
public IStatusKeeper StatusKeeper { get; set; }
-
- public IStatusNotification StatusNotification { get; set; }
- [Import]
- public ICloudClient CloudClient { get; set; }
- [Import]
- public FileAgent FileAgent {get;set;}
+ private IStatusNotification _statusNotification;
+ public IStatusNotification StatusNotification
+ {
+ get { return _statusNotification; }
+ set
+ {
+ _statusNotification = value;
+ DeleteAgent.StatusNotification = value;
+ Uploader.StatusNotification = value;
+ Downloader.StatusNotification = value;
+ }
+ }
- /*
- [Import]
- public IPithosWorkflow Workflow { get; set; }
-*/
+ [System.ComponentModel.Composition.Import]
+ public IPithosSettings Settings { get; set; }
+
+ private Uploader _uploader;
+
+ [System.ComponentModel.Composition.Import]
+ public Uploader Uploader
+ {
+ get { return _uploader; }
+ set
+ {
+ _uploader = value;
+ _uploader.UnpauseEvent = _unPauseEvent;
+ }
+ }
+
+ private Downloader _downloader;
- public string PithosContainer { get; set; }
- public string TrashContainer { get; private set; }
- public IList<string> Containers { get; private set; }
+ [System.ComponentModel.Composition.Import]
+ public Downloader Downloader
+ {
+ get { return _downloader; }
+ set
+ {
+ _downloader = value;
+ _downloader.UnpauseEvent = _unPauseEvent;
+ }
+ }
- public int BlockSize { get; set; }
- public string BlockHash { get; set; }
+ [System.ComponentModel.Composition.Import]
+ public Selectives Selectives { get; set; }
+
+ //The Proceed signals the poll agent that it can proceed with polling.
+ //Essentially it stops the poll agent to give priority to the network agent
+ //Initially the event is signalled because we don't need to pause
+ private readonly AsyncManualResetEvent _proceedEvent = new AsyncManualResetEvent(true);
+ private Agents.Selectives _selectives;
+ private bool _pause;
+
+ public AsyncManualResetEvent ProceedEvent
+ {
+ get { return _proceedEvent; }
+ }
- private static readonly ILog Log = LogManager.GetLogger(typeof(NetworkAgent));
+ private readonly AsyncManualResetEvent _unPauseEvent = new AsyncManualResetEvent(true);
+ private CancellationTokenSource _currentOperationCancellation=new CancellationTokenSource();
- public void Start(string pithosContainer, string trashContainer, int blockSize, string blockHash)
+ public void CancelCurrentOperation()
{
- if (String.IsNullOrWhiteSpace(pithosContainer))
- throw new ArgumentNullException("pithosContainer");
- if (String.IsNullOrWhiteSpace(trashContainer))
- throw new ArgumentNullException("trashContainer");
- Contract.EndContractBlock();
+ //What does it mean to cancel the current upload/download?
+ //Obviously, the current operation will be cancelled by throwing
+ //a cancellation exception.
+ //
+ //The default behavior is to retry any operations that throw.
+ //Obviously this is not what we want in this situation.
+ //The cancelled operation should NOT bea retried.
+ //
+ //This can be done by catching the cancellation exception
+ //and avoiding the retry.
+ //
+
+ //Have to reset the cancellation source - it is not possible to reset the source
+ //Have to prevent a case where an operation requests a token from the old source
+ var oldSource = Interlocked.Exchange(ref _currentOperationCancellation, new CancellationTokenSource());
+ oldSource.Cancel();
+
+ }
- PithosContainer = pithosContainer;
- TrashContainer = trashContainer;
- BlockSize = blockSize;
- BlockHash = blockHash;
+ public void Start()
+ {
+ if (_agent != null)
+ return;
+ if (Log.IsDebugEnabled)
+ Log.Debug("Starting Network Agent");
_agent = Agent<CloudAction>.Start(inbox =>
{
Action loop = null;
loop = () =>
{
+ DeleteAgent.ProceedEvent.Wait();
+ _unPauseEvent.Wait();
var message = inbox.Receive();
var process=message.Then(Process,inbox.CancellationToken);
inbox.LoopAsync(process, loop);
};
loop();
});
+
}
- private Task<object> Process(CloudAction action)
+ private async Task Process(CloudAction action)
{
if (action == null)
throw new ArgumentNullException("action");
+ if (action.AccountInfo==null)
+ throw new ArgumentException("The action.AccountInfo is empty","action");
Contract.EndContractBlock();
- using (log4net.LogicalThreadContext.Stacks["NETWORK"].Push("PROCESS"))
+
+
+
+ using (ThreadContext.Stacks["Operation"].Push(action.ToString()))
{
- Log.InfoFormat("[ACTION] Start Processing {0}:{1}->{2}", action.Action, action.LocalFile,
- action.CloudFile.Name);
- var localFile = action.LocalFile;
var cloudFile = action.CloudFile;
- var downloadPath = (cloudFile == null)
- ? String.Empty
- : Path.Combine(FileAgent.RootPath, cloudFile.RelativeUrlToFilePath(CloudClient.UserName));
+ var downloadPath = action.GetDownloadPath();
try
{
- var account = action.CloudFile.Account ?? CloudClient.UserName;
- var container = action.CloudFile.Container ?? PithosContainer;
+ StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing,"Processing");
+ _proceedEvent.Reset();
+
+ var accountInfo = action.AccountInfo;
- switch (action.Action)
+ if (action.Action == CloudActionType.DeleteCloud)
+ {
+ //Redirect deletes to the delete agent
+ DeleteAgent.Post((CloudDeleteAction)action);
+ }
+ if (DeleteAgent.IsDeletedFile(action))
+ {
+ //Clear the status of already deleted files to avoid reprocessing
+ if (action.LocalFile != null)
+ StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
+ }
+ else
{
- case CloudActionType.UploadUnconditional:
- UploadCloudFile(account, container, localFile, action.LocalHash.Value, action.TopHash.Value);
- break;
- case CloudActionType.DownloadUnconditional:
-
- DownloadCloudFile(account, container, new Uri(cloudFile.Name, UriKind.Relative),
- downloadPath);
- break;
- case CloudActionType.DeleteCloud:
- DeleteCloudFile(account, container, cloudFile.Name);
- break;
- case CloudActionType.RenameCloud:
- var moveAction = (CloudMoveAction)action;
- RenameCloudFile(account, container, moveAction.OldFileName, moveAction.NewPath,
- moveAction.NewFileName);
- break;
- case CloudActionType.MustSynch:
-
- if (!File.Exists(downloadPath))
- {
- var cloudUri = new Uri(action.CloudFile.Name, UriKind.Relative);
- DownloadCloudFile(account, container, cloudUri, downloadPath);
- }
- else
- {
- SyncFiles(action);
- }
- break;
+ switch (action.Action)
+ {
+ case CloudActionType.UploadUnconditional:
+ //Abort if the file was deleted before we reached this point
+ var uploadAction = (CloudUploadAction) action;
+ ProcessChildUploads(uploadAction);
+ await Uploader.UploadCloudFile(uploadAction ,CurrentOperationCancelToken);
+ break;
+ case CloudActionType.DownloadUnconditional:
+ await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath, CurrentOperationCancelToken);
+ break;
+ case CloudActionType.RenameCloud:
+ var moveAction = (CloudMoveAction)action;
+ RenameCloudFile(accountInfo, moveAction);
+ break;
+ case CloudActionType.RenameLocal:
+ RenameLocalFile(accountInfo, action);
+ break;
+ case CloudActionType.MustSynch:
+ if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
+ {
+ await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath, CurrentOperationCancelToken);
+ }
+ else
+ {
+ await SyncFiles(accountInfo, action);
+ }
+ break;
+ }
}
- Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
+ Log.InfoFormat("End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
action.CloudFile.Name);
}
- catch (OperationCanceledException)
+/*
+ catch (WebException exc)
+ {
+ Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
+
+
+ //Actions that resulted in server errors should be retried
+ var response = exc.Response as HttpWebResponse;
+ if (response != null && response.StatusCode >= HttpStatusCode.InternalServerError)
+ {
+ _agent.Post(action);
+ Log.WarnFormat("[REQUEUE] {0} : {1} -> {2}", action.Action, action.LocalFile, action.CloudFile);
+ }
+ }
+*/
+ catch (OperationCanceledException ex)
+ {
+ Log.WarnFormat("Cancelling [{0}]",ex);
+ }
+ catch (DirectoryNotFoundException)
{
- throw;
+ Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
+ action.Action, action.LocalFile, action.CloudFile);
+ //Post a delete action for the missing file
+ Post(new CloudDeleteAction(action));
}
- catch (System.IO.FileNotFoundException exc)
+ catch (FileNotFoundException)
{
Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
- action.Action, action.LocalFile, action.CloudFile, exc);
- Post(new CloudAction(CloudActionType.DeleteCloud,action.CloudFile));
+ action.Action, action.LocalFile, action.CloudFile);
+ //Post a delete action for the missing file
+ Post(new CloudDeleteAction(action));
}
catch (Exception exc)
{
_agent.Post(action);
}
- return CompletedTask<object>.Default;
+ finally
+ {
+ if (_agent.IsEmpty)
+ _proceedEvent.Set();
+ UpdateStatus(PithosStatus.LocalComplete);
+ }
}
}
- private void SyncFiles(CloudAction action)
+ private void ProcessChildUploads(CloudUploadAction uploadAction)
{
- if (action==null)
- throw new ArgumentNullException("action");
- if (action.LocalFile==null)
- throw new ArgumentException("The action's local file is not specified","action");
- if (!Path.IsPathRooted(action.LocalFile.FullName))
- throw new ArgumentException("The action's local file path must be absolute","action");
- if (action.CloudFile== null)
- throw new ArgumentException("The action's cloud file is not specified", "action");
- Contract.EndContractBlock();
-
- var localFile = action.LocalFile;
- var cloudFile = action.CloudFile;
- var downloadPath=action.LocalFile.FullName.ToLower();
-
- var account = cloudFile.Account;
- //Use "pithos" by default if no container is specified
- var container = cloudFile.Container ?? PithosContainer;
-
- var cloudUri = new Uri(cloudFile.Name, UriKind.Relative);
- var cloudHash = cloudFile.Hash.ToLower();
- var localHash = action.LocalHash.Value.ToLower();
- var topHash = action.TopHash.Value.ToLower();
-
- //Not enough to compare only the local hashes, also have to compare the tophashes
-
- //If any of the hashes match, we are done
- if ((cloudHash == localHash || cloudHash == topHash))
- {
- Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
+ if (!uploadAction.IsCreation || !(uploadAction.LocalFile is DirectoryInfo))
return;
- }
- //The hashes DON'T match. We need to sync
- var lastLocalTime = localFile.LastWriteTime;
- var lastUpTime = cloudFile.Last_Modified;
-
- //If the local file is newer upload it
- if (lastUpTime <= lastLocalTime)
+ var dirInfo = uploadAction.LocalFile as DirectoryInfo;
+
+ var account = uploadAction.AccountInfo;
+ var actions = from file in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories)
+ select
+ new CloudUploadAction(account, file, null, account.BlockSize, account.BlockHash,
+ uploadAction, true);
+ foreach (var action in actions)
{
- //It probably means it was changed while the app was down
- UploadCloudFile(account, container, localFile, action.LocalHash.Value,
- action.TopHash.Value);
- }
- else
- {
- //It the cloud file has a later date, it was modified by another user or computer.
- //We need to check the local file's status
- var status = StatusKeeper.GetFileStatus(downloadPath);
- switch (status)
- {
- case FileStatus.Unchanged:
- //If the local file's status is Unchanged, we can go on and download the newer cloud file
- DownloadCloudFile(account, container,cloudUri,downloadPath);
- break;
- case FileStatus.Modified:
- //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
- //We can't ensure that a file modified online since the last time will appear as Modified, unless we
- //index all files before we start listening.
- case FileStatus.Created:
- //If the local file is Created, it means that the local and cloud files aren't related,
- // yet they have the same name.
-
- //In both cases we must mark the file as in conflict
- ReportConflict(downloadPath);
- break;
- default:
- //Other cases should never occur. Mark them as Conflict as well but log a warning
- ReportConflict(downloadPath);
- Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
- downloadPath, action.CloudFile.Name);
- break;
- }
+ var state=StatusKeeper.GetStateByFilePath(action.LocalFile.FullName);
+ if (state!=null)
+ state.Delete();
+ //StatusKeeper.SetFileState(action.LocalFile.FullName,FileStatus.Created,FileOverlayStatus.Normal,String.Empty);
+ state=FileState.CreateFor(action.LocalFile);
+ //StatusKeeper.SetFileStatus();
+ state.FileStatus = FileStatus.Created;
+ state.OverlayStatus=FileOverlayStatus.Normal;
+ state.Create();
+ action.FileState = state;
+ Post(action);
}
}
- private void ReportConflict(string downloadPath)
+ private CancellationToken CurrentOperationCancelToken
{
- if (String.IsNullOrWhiteSpace(downloadPath))
- throw new ArgumentNullException("downloadPath");
- Contract.EndContractBlock();
+ get { return _currentOperationCancellation.Token; }
+ }
- StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
- var message = String.Format("Conflict detected for file {0}", downloadPath);
- Log.Warn(message);
- StatusNotification.NotifyChange(message, TraceLevel.Warning);
+
+ private void UpdateStatus(PithosStatus status)
+ {
+ StatusNotification.SetPithosStatus(status);
+ //StatusNotification.Notify(new Notification());
}
-/*
- private Task<object> Process(CloudMoveAction action)
+ private void RenameLocalFile(AccountInfo accountInfo, CloudAction action)
{
+ if (accountInfo == null)
+ throw new ArgumentNullException("accountInfo");
if (action == null)
throw new ArgumentNullException("action");
+ if (action.LocalFile == null)
+ throw new ArgumentException("The action's local file is not specified", "action");
+ if (!Path.IsPathRooted(action.LocalFile.FullName))
+ throw new ArgumentException("The action's local file path must be absolute", "action");
+ if (action.CloudFile == null)
+ throw new ArgumentException("The action's cloud file is not specified", "action");
Contract.EndContractBlock();
+ using (ThreadContext.Stacks["Operation"].Push("RenameLocalFile"))
+ {
- Trace.TraceInformation("[ACTION] Start Processing {0}:{1}->{2}", action.Action, action.LocalFile, action.CloudFile.Name);
+ //We assume that the local file already exists, otherwise the poll agent
+ //would have issued a download request
- try
- {
- RenameCloudFile(action.OldFileName, action.NewPath, action.NewFileName);
- Trace.TraceInformation("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile, action.CloudFile.Name);
- }
- catch (OperationCanceledException)
- {
- throw;
- }
- catch (Exception exc)
- {
- Trace.TraceError("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
- action.Action, action.OldFileName, action.NewFileName, exc);
+ var currentInfo = action.CloudFile;
+ var previousInfo = action.CloudFile.Previous;
+ var fileAgent = FileAgent.GetFileAgent(accountInfo);
+
+ var previousRelativepath = previousInfo.RelativeUrlToFilePath(accountInfo.UserName);
+ var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
- _agent.Post(action);
+ //In every case we need to move the local file first
+ MoveLocalFile(accountInfo, previousFile, fileAgent, currentInfo);
}
- return CompletedTask<object>.Default;
}
-*/
-
- public void Post(CloudAction cloudAction)
+ private void MoveLocalFile(AccountInfo accountInfo, FileSystemInfo previousFile, FileAgent fileAgent,
+ ObjectInfo currentInfo)
{
- if (cloudAction == null)
- throw new ArgumentNullException("cloudAction");
- Contract.EndContractBlock();
+ var currentRelativepath = currentInfo.RelativeUrlToFilePath(accountInfo.UserName);
+ var newPath = Path.Combine(fileAgent.RootPath, currentRelativepath);
+
+ var isFile= (previousFile is FileInfo);
+ var previousFullPath = isFile?
+ FileInfoExtensions.GetProperFilePathCapitalization(previousFile.FullName):
+ FileInfoExtensions.GetProperDirectoryCapitalization(previousFile.FullName);
- //If the action targets a local file, add a treehash calculation
- if (cloudAction.LocalFile != null)
+ using (NetworkGate.Acquire(previousFullPath, NetworkOperation.Renaming))
+ using (NetworkGate.Acquire(newPath,NetworkOperation.Renaming))
+ using (new SessionScope(FlushAction.Auto))
{
-
- if (cloudAction.LocalFile.Length>BlockSize)
- cloudAction.TopHash = new Lazy<string>(() => Signature.CalculateTreeHashAsync(cloudAction.LocalFile,
- BlockSize, BlockHash).Result
- .TopHash.ToHashString());
+ if (isFile)
+ (previousFile as FileInfo).MoveTo(newPath);
else
{
- cloudAction.TopHash=new Lazy<string>(()=> cloudAction.LocalHash.Value);
+ (previousFile as DirectoryInfo).MoveTo(newPath);
}
-
- }
- _agent.Post(cloudAction);
+ var state = StatusKeeper.GetStateByFilePath(previousFullPath);
+ state.FilePath = newPath;
+ state.SaveCopy();
+ StatusKeeper.SetFileState(previousFullPath,FileStatus.Deleted,FileOverlayStatus.Deleted, "Deleted");
+ }
}
- class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
+ private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
{
- public bool Equals(ObjectInfo x, ObjectInfo y)
- {
- return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
- }
-
- public int GetHashCode(ObjectInfo obj)
- {
- return obj.Name.ToLower().GetHashCode();
- }
- }
-
- //Remote files are polled periodically. Any changes are processed
- public Task ProcessRemoteFiles(string accountPath,DateTime? since=null)
- {
- if (String.IsNullOrWhiteSpace(accountPath))
- throw new ArgumentNullException(accountPath);
+ if (accountInfo == null)
+ throw new ArgumentNullException("accountInfo");
+ if (action==null)
+ throw new ArgumentNullException("action");
+ if (action.LocalFile==null)
+ throw new ArgumentException("The action's local file is not specified","action");
+ if (!Path.IsPathRooted(action.LocalFile.FullName))
+ throw new ArgumentException("The action's local file path must be absolute","action");
+ if (action.CloudFile== null)
+ throw new ArgumentException("The action's cloud file is not specified", "action");
Contract.EndContractBlock();
-
- using (log4net.LogicalThreadContext.Stacks["SCHEDULE"].Push("Retrieve Remote"))
+ using (ThreadContext.Stacks["Operation"].Push("SyncFiles"))
{
- Log.Info("[LISTENER] Scheduled");
-
- //Get the list of server objects changed since the last check
- var listObjects = Task<IList<ObjectInfo>>.Factory.StartNewDelayed(10000, () =>
- CloudClient.ListObjects(CloudClient.UserName, PithosContainer, since));
- //Get the list of deleted objects since the last check
- var listTrash = Task<IList<ObjectInfo>>.Factory.StartNewDelayed(10000, () =>
- CloudClient.ListObjects(CloudClient.UserName, TrashContainer, since));
-
- var listShared = Task<IList<ObjectInfo>>.Factory.StartNewDelayed(10000, () =>
- CloudClient.ListSharedObjects(since));
- var listAll = Task.Factory.TrackedSequence(
- () => listObjects,
- () => listTrash,
- () => listShared);
-
- //Next time we will check for all changes since the current check minus 1 second
- //This is done to ensure there are no discrepancies due to clock differences
- DateTime nextSince = DateTime.Now.AddSeconds(-1);
+ //var localFile = action.LocalFile;
+ var cloudFile = action.CloudFile;
+ var downloadPath = action.LocalFile.GetProperCapitalization();
+ var cloudHash = cloudFile.Hash.ToLower();
+ var previousCloudHash = cloudFile.PreviousHash == null?null: cloudFile.PreviousHash.ToLower();
+ var localHash = action.TreeHash.Value.TopHash.ToHashString();// LocalHash.Value.ToLower();
+ //var topHash = action.TopHash.Value.ToLower();
- var enqueueFiles = listAll.ContinueWith(task =>
+ if(cloudFile.IsDirectory && action.LocalFile is DirectoryInfo)
{
- if (task.IsFaulted)
- {
- //ListObjects failed at this point, need to reschedule
- Log.ErrorFormat("[FAIL] ListObjects in ProcessRemoteFiles with {0}", task.Exception);
- ProcessRemoteFiles(accountPath, since);
- return;
- }
- using (log4net.LogicalThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
- {
- var remoteObjects = ((Task<IList<ObjectInfo>>) task.Result[0]).Result;
- var trashObjects = ((Task<IList<ObjectInfo>>) task.Result[1]).Result;
- var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
-
- //Items with the same name, hash may be both in the container and the trash
- //Don't delete items that exist in the container
- var realTrash = from trash in trashObjects
- where !remoteObjects.Any(info => info.Hash == trash.Hash)
- select trash;
- ProcessDeletedFiles(realTrash);
-
-
- var remote = from info in remoteObjects.Union(sharedObjects)
- let name = info.Name
- where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
- !name.StartsWith("fragments/", StringComparison.InvariantCultureIgnoreCase)
- select info;
-
- //Create a list of actions from the remote files
- var allActions = ObjectsToActions(remote);
-
- //And remove those that are already being processed by the agent
- var distinctActions = allActions
- .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
- .ToList();
-
- //Queue all the actions
- foreach (var message in distinctActions)
- {
- Post(message);
- }
-
- //Report the number of new files
- var remoteCount = distinctActions.Count(action=>
- action.Action==CloudActionType.DownloadUnconditional);
- if ( remoteCount > 0)
- StatusNotification.NotifyChange(String.Format("Processing {0} new files", remoteCount));
+ Log.InfoFormat("Skipping folder {0} , exists in server", downloadPath);
+ return;
+ }
- Log.Info("[LISTENER] End Processing");
- }
- });
+ //At this point we know that an object has changed on the server and that a local
+ //file already exists. We need to decide whether the file has only changed on
+ //the server or there is a conflicting change on the client.
+ //
- var loop = enqueueFiles.ContinueWith(t =>
- {
- if (t.IsFaulted)
- {
- Log.Error("[LISTENER] Exception", t.Exception);
- }
- else
- {
- Log.Info("[LISTENER] Finished");
- }
- ProcessRemoteFiles(accountPath, nextSince);
+ //If the hashes match, we are done
+ if (cloudFile != ObjectInfo.Empty && cloudHash == localHash)
+ {
+ Log.InfoFormat("Skipping {0}, hashes match", downloadPath);
+ return;
+ }
- });
- return loop;
- }
- }
+ //If the local and remote files have 0 length their hashes will not match
+ if (!cloudFile.IsDirectory && cloudFile.Bytes==0 && action.LocalFile is FileInfo && (action.LocalFile as FileInfo).Length==0 )
+ {
+ Log.InfoFormat("Skipping {0}, files are empty", downloadPath);
+ return;
+ }
- //Creates an appropriate action for each server file
- private IEnumerable<CloudAction> ObjectsToActions(IEnumerable<ObjectInfo> remote)
- {
- if (remote==null)
- throw new ArgumentNullException();
- Contract.EndContractBlock();
+ //The hashes DON'T match. We need to sync
- //In order to avoid multiple iterations over the files, we iterate only once
- //over the remote files
- foreach (var objectInfo in remote)
- {
- var relativePath = objectInfo.RelativeUrlToFilePath(CloudClient.UserName);
- //and remove any matching objects from the list, adding them to the commonObjects list
- if (FileAgent.Exists(relativePath))
+ // If the previous tophash matches the local tophash, the file was only changed on the server.
+ if (localHash == previousCloudHash)
{
- var localFile = FileAgent.GetFileInfo(relativePath);
- var state = FileState.FindByFilePath(localFile.FullName);
- //Common files should be checked on a per-case basis to detect differences, which is newer
-
- yield return new CloudAction(CloudActionType.MustSynch,
- localFile, objectInfo, state, BlockSize, BlockHash);
+ await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath, CurrentOperationCancelToken);
}
else
{
- //If there is no match we add them to the localFiles list
- //but only if the file is not marked for deletion
- var targetFile = Path.Combine(FileAgent.RootPath, relativePath);
- var fileStatus = StatusKeeper.GetFileStatus(targetFile);
- if (fileStatus != FileStatus.Deleted)
- {
- //Remote files should be downloaded
- yield return new CloudAction(CloudActionType.DownloadUnconditional, objectInfo);
- }
+ //If the previous and local hash don't match, there was a local conflict
+ //that was not uploaded to the server. We have a conflict
+ ReportConflictForMismatch(downloadPath);
}
- }
- }
-
- private void ProcessDeletedFiles(IEnumerable<ObjectInfo> trashObjects)
- {
- foreach (var trashObject in trashObjects)
- {
- var relativePath = trashObject.RelativeUrlToFilePath(CloudClient.UserName);
- //and remove any matching objects from the list, adding them to the commonObjects list
- FileAgent.Delete(relativePath);
}
}
-
- private void RenameCloudFile(string account, string container,string oldFileName, string newPath, string newFileName)
+ private void ReportConflictForMismatch(string downloadPath)
{
- if (String.IsNullOrWhiteSpace(account))
- throw new ArgumentNullException("account");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
- if (String.IsNullOrWhiteSpace(oldFileName))
- throw new ArgumentNullException("oldFileName");
- if (String.IsNullOrWhiteSpace(oldFileName))
- throw new ArgumentNullException("newPath");
- if (String.IsNullOrWhiteSpace(oldFileName))
- throw new ArgumentNullException("newFileName");
+ if (String.IsNullOrWhiteSpace(downloadPath))
+ throw new ArgumentNullException("downloadPath");
Contract.EndContractBlock();
- //The local file is already renamed
- this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Modified);
-
- CloudClient.MoveObject(account, container, oldFileName, container, newFileName);
- this.StatusKeeper.SetFileStatus(newPath, FileStatus.Unchanged);
- this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Normal);
- NativeMethods.RaiseChangeNotification(newPath);
+ StatusKeeper.SetFileState(downloadPath,FileStatus.Conflict, FileOverlayStatus.Conflict,"File changed at the server");
+ UpdateStatus(PithosStatus.HasConflicts);
+ var message = String.Format("Conflict detected for file {0}", downloadPath);
+ Log.Warn(message);
+ StatusNotification.NotifyChange(message, TraceLevel.Warning);
}
- private void DeleteCloudFile(string account,string container, string fileName)
+ public void Post(CloudAction cloudAction)
{
- if (String.IsNullOrWhiteSpace(account))
- throw new ArgumentNullException("account");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
-
- if (String.IsNullOrWhiteSpace(fileName))
- throw new ArgumentNullException("fileName");
- if (Path.IsPathRooted(fileName))
- throw new ArgumentException("The fileName should not be rooted","fileName");
+ if (cloudAction == null)
+ throw new ArgumentNullException("cloudAction");
+ if (cloudAction.AccountInfo==null)
+ throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
Contract.EndContractBlock();
- using ( log4net.LogicalThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
- {
- var info = FileAgent.GetFileInfo(fileName);
- var path = info.FullName.ToLower();
- this.StatusKeeper.SetFileOverlayStatus(path, FileOverlayStatus.Modified);
-
- CloudClient.DeleteObject(account, container, fileName, TrashContainer);
-
- this.StatusKeeper.ClearFileStatus(path);
- }
- }
-
- //Download a file.
- private void DownloadCloudFile(string account,string container, Uri relativeUrl, string localPath)
- {
- if (String.IsNullOrWhiteSpace(account))
- throw new ArgumentNullException("account");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
- if (relativeUrl == null)
- throw new ArgumentNullException("relativeUrl");
- if (String.IsNullOrWhiteSpace(localPath))
- throw new ArgumentNullException("localPath");
- if (!Path.IsPathRooted(localPath))
- throw new ArgumentException("The localPath must be rooted", "localPath");
- Contract.EndContractBlock();
+ DeleteAgent.ProceedEvent.Wait();
- var download=Task.Factory.Iterate(DownloadIterator(account,container, relativeUrl, localPath));
- download.Wait();
+ if (cloudAction is CloudDeleteAction)
+ DeleteAgent.Post((CloudDeleteAction)cloudAction);
+ else
+ _agent.Post(cloudAction);
}
+
- private IEnumerable<Task> DownloadIterator(string account,string container, Uri relativeUrl, string localPath)
+ public IEnumerable<CloudAction> GetEnumerable()
{
- if (String.IsNullOrWhiteSpace(account))
- throw new ArgumentNullException("account");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
- if (relativeUrl==null)
- throw new ArgumentNullException("relativeUrl");
- if (String.IsNullOrWhiteSpace(localPath))
- throw new ArgumentNullException("localPath");
- if (!Path.IsPathRooted(localPath))
- throw new ArgumentException("The localPath must be rooted", "localPath");
- Contract.EndContractBlock();
-
- var url = relativeUrl.ToString();
- if (url.EndsWith(".ignore",StringComparison.InvariantCultureIgnoreCase))
- yield break;
-
- //Are we already downloading or uploading the file?
- using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
- {
- if (gate.Failed)
- yield break;
- //The file's hashmap will be stored in the same location with the extension .hashmap
- //var hashPath = Path.Combine(FileAgent.FragmentsPath, relativePath + ".hashmap");
-
- //Retrieve the hashmap from the server
- var getHashMap = CloudClient.GetHashMap(account, container, url);
- yield return getHashMap;
-
- var serverHash=getHashMap.Result;
- //If it's a small file
- var downloadTask=(serverHash.Hashes.Count == 1 )
- //Download it in one go
- ? DownloadEntireFile(account,container, relativeUrl, localPath)
- //Otherwise download it block by block
- : DownloadWithBlocks(account,container, relativeUrl, localPath, serverHash);
-
- yield return downloadTask;
-
-
- //Retrieve the object's metadata
- var info=CloudClient.GetObjectInfo(account, container, url);
- //And store it
- StatusKeeper.StoreInfo(localPath, info);
-
- //Notify listeners that a local file has changed
- StatusNotification.NotifyChangedFile(localPath);
-
- }
+ return _agent.GetEnumerable();
}
- //Download a small file with a single GET operation
- private Task DownloadEntireFile(string account,string container, Uri relativeUrl, string localPath)
+ public Task GetDeleteAwaiter()
{
- if (String.IsNullOrWhiteSpace(account))
- throw new ArgumentNullException("account");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
- if (relativeUrl == null)
- throw new ArgumentNullException("relativeUrl");
- if (String.IsNullOrWhiteSpace(localPath))
- throw new ArgumentNullException("localPath");
- if (!Path.IsPathRooted(localPath))
- throw new ArgumentException("The localPath must be rooted", "localPath");
- Contract.EndContractBlock();
-
- //Calculate the relative file path for the new file
- var relativePath = relativeUrl.RelativeUriToFilePath();
- //The file will be stored in a temporary location while downloading with an extension .download
- var tempPath = Path.Combine(FileAgent.FragmentsPath, relativePath + ".download");
- //Make sure the target folder exists. DownloadFileTask will not create the folder
- var directoryPath = Path.GetDirectoryName(tempPath);
- if (!Directory.Exists(directoryPath))
- Directory.CreateDirectory(directoryPath);
-
- //Download the object to the temporary location
- var getObject = CloudClient.GetObject(account, container, relativeUrl.ToString(), tempPath).ContinueWith(t =>
- {
- t.PropagateExceptions();
- //And move it to its actual location once downloading is finished
- if (File.Exists(localPath))
- File.Replace(tempPath,localPath,null,true);
- else
- File.Move(tempPath,localPath);
- });
- return getObject;
+ return DeleteAgent.ProceedEvent.WaitAsync();
}
-
- //Download a file asynchronously using blocks
- public Task DownloadWithBlocks(string account,string container, Uri relativeUrl, string localPath, TreeHash serverHash)
+ public CancellationToken CancellationToken
{
- if (String.IsNullOrWhiteSpace(account))
- throw new ArgumentNullException("account");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
- if (relativeUrl == null)
- throw new ArgumentNullException("relativeUrl");
- if (String.IsNullOrWhiteSpace(localPath))
- throw new ArgumentNullException("localPath");
- if (!Path.IsPathRooted(localPath))
- throw new ArgumentException("The localPath must be rooted", "localPath");
- if (serverHash == null)
- throw new ArgumentNullException("serverHash");
- Contract.EndContractBlock();
-
- return Task.Factory.Iterate(BlockDownloadIterator(account,container, relativeUrl, localPath, serverHash));
+ get { return _agent.CancellationToken; }
}
-
- private IEnumerable<Task> BlockDownloadIterator(string account,string container,Uri relativeUrl, string localPath,TreeHash serverHash)
- {
- if (String.IsNullOrWhiteSpace(account))
- throw new ArgumentNullException("account");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
- if (relativeUrl == null)
- throw new ArgumentNullException("relativeUrl");
- if (String.IsNullOrWhiteSpace(localPath))
- throw new ArgumentNullException("localPath");
- if (!Path.IsPathRooted(localPath))
- throw new ArgumentException("The localPath must be rooted", "localPath");
- if(serverHash==null)
- throw new ArgumentNullException("serverHash");
- Contract.EndContractBlock();
-
- //Calculate the relative file path for the new file
- var relativePath = relativeUrl.RelativeUriToFilePath();
- var blockUpdater = new BlockUpdater(FileAgent.FragmentsPath, localPath, relativePath, serverHash);
-
-
-
- //Calculate the file's treehash
- var calcHash = Signature.CalculateTreeHashAsync(localPath, this.BlockSize,BlockHash);
- yield return calcHash;
- var treeHash = calcHash.Result;
-
- //And compare it with the server's hash
- var upHashes = serverHash.GetHashesAsStrings();
- var localHashes = treeHash.HashDictionary;
- for (int i = 0; i < upHashes.Length; i++)
- {
- //For every non-matching hash
- var upHash = upHashes[i];
- if (!localHashes.ContainsKey(upHash))
+ public bool Pause
+ {
+ get {
+ return _pause;
+ }
+ set {
+ _pause = value;
+ if (_pause)
+ _unPauseEvent.Reset();
+ else
{
- if (blockUpdater.UseOrphan(i, upHash))
- {
- Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
- continue;
- }
- Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
- var start = i*BlockSize;
- //To download the last block just pass a null for the end of the range
- long? end = null;
- if (i < upHashes.Length - 1 )
- end= ((i + 1)*BlockSize) ;
-
- //Download the missing block
- var getBlock = CloudClient.GetBlock(account, container, relativeUrl, start, end);
- yield return getBlock;
- var block = getBlock.Result;
-
- //and store it
- yield return blockUpdater.StoreBlock(i, block);
-
-
- Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
+ _unPauseEvent.Set();
}
}
-
- blockUpdater.Commit();
- Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
}
- private void UploadCloudFile(string account,string container,FileInfo fileInfo, string hash,string topHash)
- {
- if (String.IsNullOrWhiteSpace(account))
- throw new ArgumentNullException("account");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
- if (fileInfo == null)
- throw new ArgumentNullException("fileInfo");
- if (String.IsNullOrWhiteSpace(hash))
- throw new ArgumentNullException("hash");
- if (topHash == null)
- throw new ArgumentNullException("topHash");
- Contract.EndContractBlock();
-
- var upload = Task.Factory.Iterate(UploadIterator(account,container,fileInfo, hash, topHash));
- upload.Wait();
- }
-
- private IEnumerable<Task> UploadIterator(string account,string container,FileInfo fileInfo, string hash,string topHash)
+ private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
{
- if (String.IsNullOrWhiteSpace(account))
- throw new ArgumentNullException("account");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
- if (fileInfo == null)
- throw new ArgumentNullException("fileInfo");
- if (String.IsNullOrWhiteSpace(hash))
- throw new ArgumentNullException("hash");
- if (topHash == null)
- throw new ArgumentNullException("topHash");
+ if (accountInfo==null)
+ throw new ArgumentNullException("accountInfo");
+ if (action==null)
+ throw new ArgumentNullException("action");
+ if (action.CloudFile==null)
+ throw new ArgumentException("CloudFile","action");
+ if (action.LocalFile==null)
+ throw new ArgumentException("LocalFile","action");
+ if (action.OldLocalFile==null)
+ throw new ArgumentException("OldLocalFile","action");
+ if (action.OldCloudFile==null)
+ throw new ArgumentException("OldCloudFile","action");
Contract.EndContractBlock();
- if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
- yield break;
-
- var url = fileInfo.AsRelativeUrlTo(FileAgent.RootPath);
-
- var fullFileName = fileInfo.FullName;
- using(var gate=NetworkGate.Acquire(fullFileName,NetworkOperation.Uploading))
+ using (ThreadContext.Stacks["Operation"].Push("RenameCloudFile"))
{
- //Abort if the file is already being uploaded or downloaded
- if (gate.Failed)
- yield break;
+ var newFilePath = action.LocalFile.FullName;
- //Even if GetObjectInfo times out, we can proceed with the upload
- var info = CloudClient.GetObjectInfo(account, container, url);
+ //How do we handle concurrent renames and deletes/uploads/downloads?
+ //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
+ // This should never happen as the network agent executes only one action at a time
+ //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
+ // the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the
+ // same name will fail.
+ // This should never happen as the network agent executes only one action at a time.
+ //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
+ // to remove the rename from the queue.
+ // We can probably ignore this case. It will result in an error which should be ignored
- //If the file hashes match, abort the upload
- if (hash.Equals(info.Hash, StringComparison.InvariantCultureIgnoreCase) ||
- topHash.Equals(info.Hash, StringComparison.InvariantCultureIgnoreCase))
- {
- //but store any metadata changes
- this.StatusKeeper.StoreInfo(fullFileName, info);
- Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
- yield break;
- }
- //Mark the file as modified while we upload it
- StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
- //And then upload it
+ //The local file is already renamed
+ StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified).Wait();
- //If the file is larger than the block size, try a hashmap PUT
- if (fileInfo.Length > BlockSize )
- {
- //To upload using a hashmap
- //First, calculate the tree hash
- var treeHash = Signature.CalculateTreeHashAsync(fileInfo.FullName, BlockSize, BlockHash);
- yield return treeHash;
-
- yield return Task.Factory.Iterate(UploadWithHashMap(account,container,fileInfo,url,treeHash));
-
- }
- else
- {
- //Otherwise do a regular PUT
- yield return CloudClient.PutObject(account, container, url, fullFileName, hash);
- }
- //If everything succeeds, change the file and overlay status to normal
- this.StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
- }
- //Notify the Shell to update the overlays
- NativeMethods.RaiseChangeNotification(fullFileName);
- StatusNotification.NotifyChangedFile(fullFileName);
- }
-
- public IEnumerable<Task> UploadWithHashMap(string account,string container,FileInfo fileInfo,string url,Task<TreeHash> treeHash)
- {
- if (String.IsNullOrWhiteSpace(account))
- throw new ArgumentNullException("account");
- if (String.IsNullOrWhiteSpace(container))
- throw new ArgumentNullException("container");
- if (fileInfo == null)
- throw new ArgumentNullException("fileInfo");
- if (String.IsNullOrWhiteSpace(url))
- throw new ArgumentNullException(url);
- if (treeHash==null)
- throw new ArgumentNullException("treeHash");
- Contract.EndContractBlock();
-
- var fullFileName = fileInfo.FullName;
-
- //Send the hashmap to the server
- var hashPut = CloudClient.PutHashMap(account, container, url, treeHash.Result);
- yield return hashPut;
-
- var missingHashes = hashPut.Result;
- //If the server returns no missing hashes, we are done
- while (missingHashes.Count > 0)
- {
-
- var buffer = new byte[BlockSize];
- foreach (var missingHash in missingHashes)
- {
- //Find the proper block
- var blockIndex = treeHash.Result.HashDictionary[missingHash];
- var offset = blockIndex*BlockSize;
- var read = fileInfo.Read(buffer, offset, BlockSize);
+ var account = action.CloudFile.Account ?? accountInfo.UserName;
+ var container = action.CloudFile.Container;
- //And upload the block
- var postBlock = CloudClient.PostBlock(account, container, buffer, 0, read);
+ var client = new CloudFilesClient(accountInfo);
+ //TODO: What code is returned when the source file doesn't exist?
+ client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
- //We have to handle possible exceptions in a continuation because
- //*yield return* can't appear inside a try block
- yield return postBlock.ContinueWith(t =>
- t.ReportExceptions(
- exc => Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc),
- ()=>Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex,fullFileName)));
- }
-
- //Repeat until there are no more missing hashes
- hashPut = CloudClient.PutHashMap(account, container, url, treeHash.Result);
- yield return hashPut;
- missingHashes = hashPut.Result;
+ StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
+ StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal).Wait();
+ NativeMethods.RaiseChangeNotification(newFilePath);
}
}
+
+
}