-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; }
- private string _pithosContainer;
- private string _trashContainer;
+ [System.ComponentModel.Composition.Import]
+ public Uploader Uploader { get; set; }
- private int _blockSize;
- private string _blockHash;
+ [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.ContinueWith(t =>
- {
- var action = t.Result;
-
- Process(action);
- inbox.DoAsync(loop);
- });
- process.ContinueWith(t =>
- {
- inbox.DoAsync(loop);
- if (t.IsFaulted)
- {
- var ex = t.Exception.InnerException;
- if (ex is OperationCanceledException)
- inbox.Stop();
- }
- });
-
+ var process=message.Then(Process,inbox.CancellationToken);
+ inbox.LoopAsync(process, loop);
};
loop();
});
- }
+ }
- public void Post(CloudAction cloudAction)
+ private async Task Process(CloudAction action)
{
- if (cloudAction == null)
- throw new ArgumentNullException("cloudAction");
+ if (action == null)
+ throw new ArgumentNullException("action");
+ if (action.AccountInfo==null)
+ throw new ArgumentException("The action.AccountInfo is empty","action");
Contract.EndContractBlock();
- _agent.Post(cloudAction);
- }
- class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
- {
- 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();
- }
- }
-
- public Task ProcessRemoteFiles(string accountPath,DateTime? since=null)
- {
- Trace.CorrelationManager.StartLogicalOperation();
- Trace.TraceInformation("[LISTENER] Scheduled");
- var listObjects = Task.Factory.StartNewDelayed(10000).ContinueWith(t =>
- CloudClient.ListObjects(_pithosContainer,since));
+ using (ThreadContext.Stacks["Operation"].Push(action.ToString()))
+ {
- DateTime nextSince = DateTime.Now.AddSeconds(-1);
+ var cloudFile = action.CloudFile;
+ var downloadPath = action.GetDownloadPath();
- var enqueueFiles = listObjects.ContinueWith(task =>
- {
- if (task.IsFaulted)
+ try
{
- //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)
- {
- 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))
+ 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))
{
- var localFile = FileAgent.GetFileInfo(relativePath);
- var state=FileState.FindByFilePath(localFile.FullName);
- commonObjects.Add(Tuple.Create(objectInfo, localFile,state));
+ //Clear the status of already deleted files to avoid reprocessing
+ if (action.LocalFile != null)
+ StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
}
else
- //If there is no match we add them to the localFiles list
- remoteOnly.Add(objectInfo);
+ {
+ switch (action.Action)
+ {
+ 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))
+ {
+ await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath);
+ }
+ else
+ {
+ await SyncFiles(accountInfo, action);
+ }
+ break;
+ }
+ }
+ Log.InfoFormat("End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
+ action.CloudFile.Name);
}
+/*
+ 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);
- //At the end of the iteration, the *remote* list will contain the files that exist
- //only on the server
+ _agent.Post(action);
+ }
+ finally
+ {
+ if (_agent.IsEmpty)
+ _proceedEvent.Set();
+ UpdateStatus(PithosStatus.LocalComplete);
+ }
+ }
+ }
- //Remote files should be downloaded
- var actionsForRemote = from upFile in remoteOnly
- select new CloudAction(CloudActionType.DownloadUnconditional,upFile);
- //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);
-
+ private void UpdateStatus(PithosStatus status)
+ {
+ StatusNotification.SetPithosStatus(status);
+ //StatusNotification.Notify(new Notification());
+ }
- //Collect all the actions
- var allActions = actionsForRemote.Union(actionsForCommon);
+ 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"))
+ {
- //And remove those that are already being processed by the agent
- var distinctActions =allActions
- .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
- .ToList();
+ //We assume that the local file already exists, otherwise the poll agent
+ //would have issued a download request
- //Queue all the actions
- _agent.AddFromEnumerable(distinctActions);
+ var currentInfo = action.CloudFile;
+ var previousInfo = action.CloudFile.Previous;
+ var fileAgent = FileAgent.GetFileAgent(accountInfo);
- if(remoteOnly.Count>0)
- StatusNotification.NotifyChange(String.Format("Processing {0} new files", remoteOnly.Count));
+ var previousRelativepath = previousInfo.RelativeUrlToFilePath(accountInfo.UserName);
+ var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
- Trace.TraceInformation("[LISTENER] End Processing");
- Trace.CorrelationManager.StopLogicalOperation();
+ //In every case we need to move the local file first
+ MoveLocalFile(accountInfo, previousFile, fileAgent, currentInfo);
+ }
+ }
- });
+ private void MoveLocalFile(AccountInfo accountInfo, FileSystemInfo previousFile, FileAgent fileAgent,
+ ObjectInfo currentInfo)
+ {
+ var currentRelativepath = currentInfo.RelativeUrlToFilePath(accountInfo.UserName);
+ var newPath = Path.Combine(fileAgent.RootPath, currentRelativepath);
- var loop = enqueueFiles.ContinueWith(t =>
+ var isFile= (previousFile is FileInfo);
+ var previousFullPath = isFile?
+ FileInfoExtensions.GetProperFilePathCapitalization(previousFile.FullName):
+ FileInfoExtensions.GetProperDirectoryCapitalization(previousFile.FullName);
+
+ using (NetworkGate.Acquire(previousFullPath, NetworkOperation.Renaming))
+ using (NetworkGate.Acquire(newPath,NetworkOperation.Renaming))
+ using (new SessionScope(FlushAction.Auto))
{
- if (t.IsFaulted)
- {
- Trace.TraceError("[LISTENER] Exception: {0}", t.Exception);
- }
+ if (isFile)
+ (previousFile as FileInfo).MoveTo(newPath);
else
{
- Trace.TraceInformation("[LISTENER] Finished");
+ (previousFile as DirectoryInfo).MoveTo(newPath);
}
- ProcessRemoteFiles(accountPath, nextSince);
-
- });
- return loop;
+ var state = StatusKeeper.GetStateByFilePath(previousFullPath);
+ state.FilePath = newPath;
+ state.SaveCopy();
+ StatusKeeper.SetFileState(previousFullPath,FileStatus.Deleted,FileOverlayStatus.Deleted, "Deleted");
+ }
}
-
-
-
- private void Process(CloudAction action)
+ 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();
-
- 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
+ using (ThreadContext.Stacks["Operation"].Push("SyncFiles"))
{
- switch (action.Action)
- {
- 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))
- {
- 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)
- {
- //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);
- }
- 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;
- }
- }
- }
- }
- else
- DownloadCloudFile(_pithosContainer, new Uri(action.CloudFile.Name,UriKind.Relative), downloadPath);
- break;
- }
- 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);
-
- _agent.Post(action);
- }
+ //var localFile = action.LocalFile;
+ var cloudFile = action.CloudFile;
+ var downloadPath = action.LocalFile.GetProperCapitalization();
- }
+ 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();
-
+ //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.
+ //
- private void RenameCloudFile(string oldFileName, string newPath, string newFileName)
- {
- 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);
+ //If the hashes match, we are done
+ if (cloudFile != ObjectInfo.Empty && cloudHash == localHash)
+ {
+ Log.InfoFormat("Skipping {0}, hashes match", downloadPath);
+ return;
+ }
- CloudClient.MoveObject(_pithosContainer, oldFileName, _pithosContainer, newFileName);
+ //The hashes DON'T match. We need to sync
- this.StatusKeeper.SetFileStatus(newPath, FileStatus.Unchanged);
- this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Normal);
- NativeMethods.RaiseChangeNotification(newPath);
+ // If the previous tophash matches the local tophash, the file was only changed on the server.
+ if (localHash == previousCloudHash)
+ {
+ await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath);
+ }
+ else
+ {
+ //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 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");
+ private void ReportConflictForMismatch(string downloadPath)
+ {
+ 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;
- //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");
- //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);
- //And save it
- var saveHashMap = getHashMap.ContinueWith(t =>
- {
- var treeHash = t.Result;
- treeHash.Save(hashPath);
- });
-
- //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, url, tempPath).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
{
- //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);
- });
-
- //Retrieve the object's metadata
- var getInfo = saveHashMap.ContinueWith(t => getObject).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);
}
+
- private void UploadCloudFile(FileInfo fileInfo, string hash,string topHash)
+ public IEnumerable<CloudAction> GetEnumerable()
{
- if (fileInfo==null)
- throw new ArgumentNullException("fileInfo");
- if (String.IsNullOrWhiteSpace(hash))
- throw new ArgumentNullException("hash");
- Contract.EndContractBlock();
-
- if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
- return;
-
- var url = fileInfo.AsRelativeUrlTo(FileAgent.RootPath);
+ return _agent.GetEnumerable();
+ }
- var fullFileName = fileInfo.FullName;
- using(var gate=NetworkGate.Acquire(fullFileName,NetworkOperation.Uploading))
- {
- //Abort if the file is already being uploaded or downloaded
- if (gate.Failed)
- return;
+ public Task GetDeleteAwaiter()
+ {
+ return DeleteAgent.ProceedEvent.WaitAsync();
+ }
+ public CancellationToken CancellationToken
+ {
+ get { return _agent.CancellationToken; }
+ }
- //Even if GetObjectInfo times out, we can proceed with the upload
- var info = CloudClient.GetObjectInfo(_pithosContainer, url);
- //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;
- }
+ private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
+ {
+ 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 the file was last modified by a hashmap operation, its hash will be a treehash
- //We must load the local file's treehash and check it against the object's hash
- //The hash will be stored under the fragments path, in the same relative path as to
- //the pithos root path
- var relativePath = fileInfo.AsRelativeTo(FileAgent.RootPath);
-/*
- var hashPath = Path.Combine(FileAgent.FragmentsPath, relativePath) + ".hashmap";
- //Load the hash or calculate a new one
- var hashFileExists = File.Exists(hashPath);
- var treeHash = hashFileExists ?
- TreeHash.LoadTreeHash(hashPath, Guid.NewGuid()).Result
- : Signature.CalculateTreeHash(fileInfo.FullName, _blockSize, _blockHash);
- //If this is a new treehash, store it
- if (!hashFileExists)
- treeHash.Save(hashPath);
-
- var topHash = treeHash.TopHash.ToHashString();
- if (topHash.Equals(info.Hash, StringComparison.InvariantCultureIgnoreCase))
- {
- this.StatusKeeper.StoreInfo(fileInfo.FullName, info);
- Trace.TraceInformation("Skip upload of {0}, treehashes match", fileInfo.FullName);
- return;
- }
-*/
-
+ using (ThreadContext.Stacks["Operation"].Push("RenameCloudFile"))
+ {
+ var newFilePath = action.LocalFile.FullName;
+ //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
- //Does the object exist or not?
- //Calculate or load the file's hashmap
+ //The local file is already renamed
+ StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
- /*
- if (fileInfo.Bytes > _blockSize)
- {
- var hashPath = Path.Combine(FileAgent.FragmentsPath, relativePath) + ".hashmap";
-
- //Load the existing hashPath, if we have one, or calculate a new one
- var treeHash = File.Exists(hashPath) ?
- TreeHash.LoadTreeHash(hashPath, Guid.NewGuid()).Result
- : Signature.CalculateTreeHash(fileInfo.FullName, _blockSize , _blockHash);
-
- //Do the Hashmap Put
- Task<string> putHashMap=CloudClient.PutHashMap(_pithosContainer,url, treeHash);
- putHashMap.Wait();
- }*/
- //
+ var account = action.CloudFile.Account ?? accountInfo.UserName;
+ var container = action.CloudFile.Container;
+ 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 putOrUpdate = Task.Factory.StartNew(() =>
- {
- //Mark the file as modified while we upload it
- var setStatus = Task.Factory.StartNew(() =>
- StatusKeeper.SetFileOverlayStatus(fullFileName,FileOverlayStatus.Modified));
- //And then upload it
- var put = setStatus.ContinueWith(t =>
- CloudClient.PutObject(_pithosContainer,url,fullFileName, hash));
- });
- putOrUpdate.Wait();
- //If everything succeeds, change the file and overlay status to normal
- this.StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
+ StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
+ StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
+ NativeMethods.RaiseChangeNotification(newFilePath);
}
- //Notify the Shell to update the overlays
- NativeMethods.RaiseChangeNotification(fullFileName);
- StatusNotification.NotifyChangedFile(fullFileName);
}
+
}