-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.Diagnostics.Contracts;
using System.IO;
-using System.Linq;
-using System.Text;
+using System.Net;
+using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
+using Castle.ActiveRecord;
using Pithos.Interfaces;
using Pithos.Network;
+using log4net;
namespace Pithos.Core.Agents
{
[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; }
- public string PithosContainer { get; set; }
- public string TrashContainer { get; private set; }
+ [System.ComponentModel.Composition.Import]
+ public Uploader Uploader { get; set; }
- public int BlockSize { get; set; }
- public string BlockHash { get; set; }
+ [System.ComponentModel.Composition.Import]
+ public Downloader Downloader { 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);
- public void Start(string pithosContainer, string trashContainer, int blockSize, string blockHash)
+ public AsyncManualResetEvent ProceedEvent
{
- if (String.IsNullOrWhiteSpace(pithosContainer))
- throw new ArgumentNullException("pithosContainer");
- if (String.IsNullOrWhiteSpace(trashContainer))
- throw new ArgumentNullException("trashContainer");
- Contract.EndContractBlock();
+ get { return _proceedEvent; }
+ }
- 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();
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();
- Trace.TraceInformation("[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.Name.RelativeUrlToFilePath());
- try
- {
- switch (action.Action)
+
+
+ using (ThreadContext.Stacks["Operation"].Push(action.ToString()))
+ {
+
+ var cloudFile = action.CloudFile;
+ var downloadPath = action.GetDownloadPath();
+
+ try
{
- case CloudActionType.UploadUnconditional:
- UploadCloudFile(localFile, action.LocalHash.Value, action.TopHash.Value);
- break;
- case CloudActionType.DownloadUnconditional:
- DownloadCloudFile(PithosContainer, new Uri(cloudFile.Name, UriKind.Relative), downloadPath);
- break;
- case CloudActionType.DeleteCloud:
- DeleteCloudFile(cloudFile.Name);
- break;
- case CloudActionType.RenameCloud:
- RenameCloudFile(action.OldFileName, action.NewPath, action.NewFileName);
- break;
- case CloudActionType.MustSynch:
- if (File.Exists(downloadPath))
+ StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing,"Processing");
+ _proceedEvent.Reset();
+
+ var accountInfo = action.AccountInfo;
+
+ 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
+ {
+ switch (action.Action)
{
- var cloudHash = cloudFile.Hash;
- var localHash = action.LocalHash.Value;
- var topHash = action.TopHash.Value;
- //Not enough to compare only the local hashes, also have to compare the tophashes
- if (!cloudHash.Equals(localHash, StringComparison.InvariantCultureIgnoreCase) &&
- !cloudHash.Equals(topHash, StringComparison.InvariantCultureIgnoreCase))
- {
- var lastLocalTime = localFile.LastWriteTime;
- var lastUpTime = cloudFile.Last_Modified;
- if (lastUpTime <= lastLocalTime)
+ case CloudActionType.UploadUnconditional:
+ //Abort if the file was deleted before we reached this point
+ await Uploader.UploadCloudFile(action);
+ break;
+ case CloudActionType.DownloadUnconditional:
+ await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath);
+ 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))
{
- //Local change while the app was down or Files in conflict
- //Maybe need to store version as well, to check who has the latest version
-
- //StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
- UploadCloudFile(localFile, action.LocalHash.Value, action.TopHash.Value);
+ await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath);
}
else
{
- var status = StatusKeeper.GetFileStatus(downloadPath);
- switch (status)
- {
- case FileStatus.Unchanged:
- //It he cloud file has a later date, it was modified by another user or computer.
- //If the local file's status is Unchanged, we should go on and download the cloud file
- DownloadCloudFile(PithosContainer, new Uri(action.CloudFile.Name, UriKind.Relative), 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.
- StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
- break;
- case FileStatus.Created:
- //If the local file is Created, it means that the local and cloud files aren't related yet have the same name
- //In this case we must mark the file as in conflict
- //Other cases should never occur. Mark them as Conflict as well but log a warning
- StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
- break;
- default:
- //If the local file is Created, it means that the local and cloud files aren't related yet have the same name
- //In this case we must mark the file as in conflict
- //Other cases should never occur. Mark them as Conflict as well but log a warning
- StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
- Trace.TraceWarning("Unexcepted status {0} for file {1}->{2}", status, downloadPath, action.CloudFile.Name);
- break;
- }
+ await SyncFiles(accountInfo, action);
}
- }
+ break;
}
- else
- DownloadCloudFile(PithosContainer, new Uri(action.CloudFile.Name, UriKind.Relative), downloadPath);
- break;
+ }
+ Log.InfoFormat("End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
+ action.CloudFile.Name);
}
- 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.LocalFile, action.CloudFile, exc);
+/*
+ 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)
+ {
+ throw;
+ }
+ catch (DirectoryNotFoundException)
+ {
+ 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 (FileNotFoundException)
+ {
+ Log.ErrorFormat("{0} : {1} -> {2} failed because the file 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 (Exception exc)
+ {
+ Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
+ action.Action, action.LocalFile, action.CloudFile, exc);
- _agent.Post(action);
+ _agent.Post(action);
+ }
+ finally
+ {
+ if (_agent.IsEmpty)
+ _proceedEvent.Set();
+ UpdateStatus(PithosStatus.LocalComplete);
+ }
}
- return CompletedTask<object>.Default;
}
- public void Post(CloudAction cloudAction)
+ private void UpdateStatus(PithosStatus status)
{
- if (cloudAction == null)
- throw new ArgumentNullException("cloudAction");
- Contract.EndContractBlock();
-
- //If the action targets a local file, add a treehash calculation
- if (cloudAction.LocalFile != null)
- {
- cloudAction.TopHash = new Lazy<string>(() => Signature.CalculateTreeHashAsync(cloudAction.LocalFile,
- BlockSize, BlockHash).Result
- .TopHash.ToHashString());
-
- }
- _agent.Post(cloudAction);
+ StatusNotification.SetPithosStatus(status);
+ //StatusNotification.Notify(new Notification());
}
- class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
+ private void RenameLocalFile(AccountInfo accountInfo, CloudAction action)
{
- public bool Equals(ObjectInfo x, ObjectInfo y)
+ 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"))
{
- return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
- }
- public int GetHashCode(ObjectInfo obj)
- {
- return obj.Name.ToLower().GetHashCode();
+ //We assume that the local file already exists, otherwise the poll agent
+ //would have issued a download request
+
+ 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);
+
+ //In every case we need to move the local file first
+ MoveLocalFile(accountInfo, previousFile, fileAgent, currentInfo);
}
}
- //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);
- Contract.EndContractBlock();
-
- Trace.CorrelationManager.StartLogicalOperation();
- Trace.TraceInformation("[LISTENER] Scheduled");
-
- //Get the list of server objects changed since the last check
- var listObjects = Task<IList<ObjectInfo>>.Factory.StartNewDelayed(10000,()=>
- CloudClient.ListObjects(PithosContainer,since));
+ private void MoveLocalFile(AccountInfo accountInfo, FileSystemInfo previousFile, FileAgent fileAgent,
+ ObjectInfo currentInfo)
+ {
+ var currentRelativepath = currentInfo.RelativeUrlToFilePath(accountInfo.UserName);
+ var newPath = Path.Combine(fileAgent.RootPath, currentRelativepath);
- //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 isFile= (previousFile is FileInfo);
+ var previousFullPath = isFile?
+ FileInfoExtensions.GetProperFilePathCapitalization(previousFile.FullName):
+ FileInfoExtensions.GetProperDirectoryCapitalization(previousFile.FullName);
-
- var enqueueFiles = listObjects.ContinueWith(task =>
+ using (NetworkGate.Acquire(previousFullPath, NetworkOperation.Renaming))
+ using (NetworkGate.Acquire(newPath,NetworkOperation.Renaming))
+ using (new SessionScope(FlushAction.Auto))
{
- if (task.IsFaulted)
- {
- //ListObjects failed at this point, need to reschedule
- Trace.TraceError("[FAIL] ListObjects in ProcessRemoteFiles with {0}", task.Exception);
- ProcessRemoteFiles(accountPath, since);
- return;
- }
- Trace.CorrelationManager.StartLogicalOperation("Listener");
- Trace.TraceInformation("[LISTENER] Start Processing");
-
- var remoteObjects = task.Result;
-
- var remote=from info in remoteObjects
- let name=info.Name
- where !name.EndsWith(".ignore",StringComparison.InvariantCultureIgnoreCase) &&
- !name.StartsWith("fragments/",StringComparison.InvariantCultureIgnoreCase)
- select info;
-
- var commonObjects = new List<Tuple<ObjectInfo, FileInfo,FileState>>();
- var remoteOnly = new List<ObjectInfo>();
-
- //In order to avoid multiple iterations over the files, we iterate only once
- //over the remote files
- foreach (var objectInfo in remote)
+ if (isFile)
+ (previousFile as FileInfo).MoveTo(newPath);
+ else
{
- var relativePath= objectInfo.Name.RelativeUrlToFilePath();// fileInfo.AsRelativeUrlTo(FileAgent.RootPath);
- //and remove any matching objects from the list, adding them to the commonObjects list
- if (FileAgent.Exists(relativePath))
- {
- var localFile = FileAgent.GetFileInfo(relativePath);
- var state=FileState.FindByFilePath(localFile.FullName);
- commonObjects.Add(Tuple.Create(objectInfo, localFile,state));
- }
- else
- //If there is no match we add them to the localFiles list
- remoteOnly.Add(objectInfo);
+ (previousFile as DirectoryInfo).MoveTo(newPath);
}
+ var state = StatusKeeper.GetStateByFilePath(previousFullPath);
+ state.FilePath = newPath;
+ state.SaveCopy();
+ StatusKeeper.SetFileState(previousFullPath,FileStatus.Deleted,FileOverlayStatus.Deleted, "Deleted");
+ }
+ }
- //At the end of the iteration, the *remote* list will contain the files that exist
- //only on the server
-
- //Remote files should be downloaded
- var actionsForRemote = from upFile in remoteOnly
- select new CloudAction(CloudActionType.DownloadUnconditional,upFile);
+ private async Task SyncFiles(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("SyncFiles"))
+ {
- //Common files should be checked on a per-case basis to detect differences, which is newer
- var actionsForCommon = from pair in commonObjects
- let objectInfo = pair.Item1
- let localFile = pair.Item2
- let state=pair.Item3
- select new CloudAction(CloudActionType.MustSynch,
- localFile, objectInfo,state);
-
+ //var localFile = action.LocalFile;
+ var cloudFile = action.CloudFile;
+ var downloadPath = action.LocalFile.GetProperCapitalization();
- //Collect all the actions
- var allActions = actionsForRemote.Union(actionsForCommon);
+ var cloudHash = cloudFile.Hash.ToLower();
+ var previousCloudHash = cloudFile.PreviousHash.ToLower();
+ var localHash = action.TreeHash.Value.TopHash.ToHashString();// LocalHash.Value.ToLower();
+ //var topHash = action.TopHash.Value.ToLower();
- //And remove those that are already being processed by the agent
- var distinctActions =allActions
- .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
- .ToList();
+ //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.
+ //
- //Queue all the actions
- foreach (var message in distinctActions)
+ //If the hashes match, we are done
+ if (cloudFile != ObjectInfo.Empty && cloudHash == localHash)
{
- Post(message);
+ Log.InfoFormat("Skipping {0}, hashes match", downloadPath);
+ return;
}
+ //The hashes DON'T match. We need to sync
- if(remoteOnly.Count>0)
- StatusNotification.NotifyChange(String.Format("Processing {0} new files", remoteOnly.Count));
-
- Trace.TraceInformation("[LISTENER] End Processing");
- Trace.CorrelationManager.StopLogicalOperation();
-
- });
-
- var loop = enqueueFiles.ContinueWith(t =>
- {
- if (t.IsFaulted)
+ // If the previous tophash matches the local tophash, the file was only changed on the server.
+ if (localHash == previousCloudHash)
{
- Trace.TraceError("[LISTENER] Exception: {0}", t.Exception);
+ await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath);
}
else
{
- Trace.TraceInformation("[LISTENER] Finished");
+ //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);
}
- ProcessRemoteFiles(accountPath, nextSince);
-
- });
- return loop;
+ }
}
-
-
-
- private void RenameCloudFile(string oldFileName, string newPath, string newFileName)
+ private void ReportConflictForMismatch(string downloadPath)
{
- if (String.IsNullOrWhiteSpace(oldFileName))
- throw new ArgumentNullException("oldFileName");
- if (String.IsNullOrWhiteSpace(oldFileName))
- throw new ArgumentNullException("newPath");
- if (String.IsNullOrWhiteSpace(oldFileName))
- throw new ArgumentNullException("newFileName");
- Contract.EndContractBlock();
- //The local file is already renamed
- this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Modified);
-
- CloudClient.MoveObject(PithosContainer, oldFileName, PithosContainer, newFileName);
-
- this.StatusKeeper.SetFileStatus(newPath, FileStatus.Unchanged);
- this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Normal);
- NativeMethods.RaiseChangeNotification(newPath);
- }
-
- private void DeleteCloudFile(string fileName)
- {
- if (String.IsNullOrWhiteSpace(fileName))
- throw new ArgumentNullException("fileName");
- if (Path.IsPathRooted(fileName))
- throw new ArgumentException("The fileName should not be rooted","fileName");
+ if (String.IsNullOrWhiteSpace(downloadPath))
+ throw new ArgumentNullException("downloadPath");
Contract.EndContractBlock();
- this.StatusKeeper.SetFileOverlayStatus(fileName, FileOverlayStatus.Modified);
-
- CloudClient.MoveObject(PithosContainer, fileName, TrashContainer, fileName);
-
- this.StatusKeeper.ClearFileStatus(fileName);
- this.StatusKeeper.RemoveFileOverlayStatus(fileName);
+ StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
+ UpdateStatus(PithosStatus.HasConflicts);
+ var message = String.Format("Conflict detected for file {0}", downloadPath);
+ Log.Warn(message);
+ StatusNotification.NotifyChange(message, TraceLevel.Warning);
}
- //Download a file.
- private void DownloadCloudFile(string container, Uri relativeUrl, string localPath)
+ public void Post(CloudAction cloudAction)
{
- 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 (cloudAction == null)
+ throw new ArgumentNullException("cloudAction");
+ if (cloudAction.AccountInfo==null)
+ throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
Contract.EndContractBlock();
- var url = relativeUrl.ToString();
- if (url.EndsWith(".ignore",StringComparison.InvariantCultureIgnoreCase))
- return;
+ DeleteAgent.ProceedEvent.Wait();
+/*
- //Are we already downloading or uploading the file?
- using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
+ //If the action targets a local file, add a treehash calculation
+ if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
{
- if (gate.Failed)
- return;
- //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(container,url);
- var downloadTask= getHashMap.ContinueWith(t =>
+ var accountInfo = cloudAction.AccountInfo;
+ var localFile = (FileInfo) cloudAction.LocalFile;
+
+ if (localFile.Length > accountInfo.BlockSize)
+ cloudAction.TopHash =
+ new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
+ accountInfo.BlockSize,
+ accountInfo.BlockHash, Settings.HashingParallelism).Result
+ .TopHash.ToHashString());
+ else
{
- var serverHash=t.Result;
- //If it's a small file
- return serverHash.Hashes.Count == 1
- //Download it in one go
- ? DownloadEntireFile(container, relativeUrl, localPath)
- //Otherwise download it block by block
- : DownloadWithBlocks(container, relativeUrl, localPath, serverHash);
- });
-
-
-
- //Retrieve the object's metadata
- var getInfo = downloadTask.ContinueWith(t =>
- CloudClient.GetObjectInfo(container, url));
- //And store it
- var storeInfo = getInfo.ContinueWith(t =>
- StatusKeeper.StoreInfo(localPath, t.Result));
-
- storeInfo.Wait();
- StatusNotification.NotifyChangedFile(localPath);
+ cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
+ }
}
+ else
+ {
+ //The hash for a directory is the empty string
+ cloudAction.TopHash = new Lazy<string>(() => String.Empty);
+ }
+*/
+
+ if (cloudAction is CloudDeleteAction)
+ DeleteAgent.Post((CloudDeleteAction)cloudAction);
+ else
+ _agent.Post(cloudAction);
}
+
- //Download a small file with a single GET operation
- private Task DownloadEntireFile(string container, Uri relativeUrl, string localPath)
+ public IEnumerable<CloudAction> GetEnumerable()
{
- 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(container, relativeUrl.ToString(), tempPath).ContinueWith(t =>
- {
- //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 _agent.GetEnumerable();
}
- public Task DownloadWithBlocks(string container,Uri relativeUrl, string localPath,TreeHash serverHash)
+ public Task GetDeleteAwaiter()
{
- 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);
-
-
- return Task.Factory.StartNew(() =>
- {
- //Calculate the temp file's treehash
- var treeHash = Signature.CalculateTreeHashAsync(localPath, this.BlockSize,BlockHash).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
- if (!localHashes.ContainsKey(upHashes[i]))
- {
- Trace.TraceInformation("[BLOCK GET] START {0} of {1} for {2}",i,upHashes.Length,localPath);
- var start = i*BlockSize;
- long? end = null;
- if (i < upHashes.Length - 1 )
- end= ((i + 1)*BlockSize) ;
-
- //Get its block
- var block= CloudClient.GetBlock(container, relativeUrl,start, end);
-
- var store=block.Then(b => blockUpdater.StoreBlock(i, b));
- store.Wait();
-
- Trace.TraceInformation("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
- }
- }
-
- blockUpdater.Commit();
- Trace.TraceInformation("[BLOCK GET] COMPLETE {0}", localPath);
- });
+ return DeleteAgent.ProceedEvent.WaitAsync();
+ }
+ public CancellationToken CancellationToken
+ {
+ get { return _agent.CancellationToken; }
}
- private void UploadCloudFile(FileInfo fileInfo, string hash,string topHash)
+ private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
{
- if (fileInfo==null)
- throw new ArgumentNullException("fileInfo");
- if (String.IsNullOrWhiteSpace(hash))
- throw new ArgumentNullException("hash");
+ 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))
- return;
-
- 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)
- return;
+ var newFilePath = action.LocalFile.FullName;
- //Even if GetObjectInfo times out, we can proceed with the upload
- var info = CloudClient.GetObjectInfo(PithosContainer, 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);
- Trace.TraceInformation("Skip upload of {0}, hashes match", fullFileName);
- return;
- }
- //Mark the file as modified while we upload it
- var setStatus = Task.Factory.StartNew(() =>
- StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified));
- //And then upload it
+ //The local file is already renamed
+ StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
- //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);
-
- var putHashMap = setStatus.ContinueWith(t=>
- UploadWithHashMap(fileInfo,url,treeHash));
-
- putHashMap.Wait();
- }
- else
- {
- //Otherwise do a regular PUT
- var put = setStatus.ContinueWith(t =>
- CloudClient.PutObject(PithosContainer,url,fullFileName,hash));
- put.Wait();
- }
- //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 void UploadWithHashMap(FileInfo fileInfo,string url,Task<TreeHash> treeHash)
- {
- var fullFileName = fileInfo.FullName;
-
- //Send the hashmap to the server
- var hashPut = CloudClient.PutHashMap(PithosContainer, url, treeHash.Result);
- var missingHashes = hashPut.Result;
- if (missingHashes.Count == 0)
- return;
+ var account = action.CloudFile.Account ?? accountInfo.UserName;
+ var container = action.CloudFile.Container;
- var buffer = new byte[BlockSize];
- foreach (var missingHash in missingHashes)
- {
- int blockIndex = -1;
- try
- {
- //Find the proper block
- blockIndex = treeHash.Result.HashDictionary[missingHash];
- var offset = blockIndex*BlockSize;
+ 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);
- var read = fileInfo.Read(buffer, offset, BlockSize);
- if (read > 0)
- {
- //Copy the actual block data out of the buffer
- var data = new byte[read];
- Buffer.BlockCopy(buffer, 0, data, 0, read);
-
- //And POST them
- CloudClient.PostBlock(PithosContainer, data).Wait();
- Trace.TraceInformation("[BLOCK] Block {0} of {1} uploaded", blockIndex,
- fullFileName);
- }
- }
- catch (Exception exc)
- {
- Trace.TraceError("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
- }
+ StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
+ StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
+ NativeMethods.RaiseChangeNotification(newFilePath);
}
-
- UploadWithHashMap(fileInfo, url, treeHash);
-
}
+
}