+#region
+/* -----------------------------------------------------------------------
+ * <copyright file="PithosMonitor.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.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
-using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
-using System.Net.NetworkInformation;
-using System.Security.Cryptography;
-using System.ServiceModel.Description;
-using System.Text;
+using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
-using Castle.ActiveRecord.Queries;
-using Microsoft.WindowsAPICodePack.Net;
using Pithos.Core.Agents;
using Pithos.Interfaces;
-using System.ServiceModel;
+using Pithos.Network;
+using log4net;
namespace Pithos.Core
{
[Export(typeof(PithosMonitor))]
public class PithosMonitor:IDisposable
{
- private const string PithosContainer = "pithos";
- private const string TrashContainer = "trash";
+ private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
+ private int _blockSize;
+ private string _blockHash;
[Import]
public IPithosSettings Settings{get;set;}
- [Import]
- public IStatusKeeper StatusKeeper { get; set; }
+ private IStatusKeeper _statusKeeper;
[Import]
- public IPithosWorkflow Workflow { get; set; }
+ public IStatusKeeper StatusKeeper
+ {
+ get { return _statusKeeper; }
+ set
+ {
+ _statusKeeper = value;
+ FileAgent.StatusKeeper = value;
+ }
+ }
- [Import]
- public ICloudClient CloudClient { get; set; }
+
+ private IPithosWorkflow _workflow;
[Import]
- public ICloudClient CloudListeningClient { get; set; }
+ public IPithosWorkflow Workflow
+ {
+ get { return _workflow; }
+ set
+ {
+ _workflow = value;
+ FileAgent.Workflow = value;
+ }
+ }
+
+ public ICloudClient CloudClient { get; set; }
public IStatusNotification StatusNotification { get; set; }
+ //[Import]
+ public FileAgent FileAgent { get; private set; }
+
+ private WorkflowAgent _workflowAgent;
+
[Import]
- public FileWatcherAgent FileWatcherAgent { get; set; }
-
- [Import]
- public WorkflowAgent WorkflowAgent { get; set; }
+ public WorkflowAgent WorkflowAgent
+ {
+ get { return _workflowAgent; }
+ set
+ {
+ _workflowAgent = value;
+ FileAgent.WorkflowAgent = value;
+ }
+ }
[Import]
public NetworkAgent NetworkAgent { get; set; }
-
+ [Import]
+ public PollAgent PollAgent { get; set; }
public string UserName { get; set; }
- public string ApiKey { get; set; }
+ private string _apiKey;
+ public string ApiKey
+ {
+ get { return _apiKey; }
+ set
+ {
+ _apiKey = value;
+ if (_accountInfo != null)
+ _accountInfo.Token = value;
+ }
+ }
+
+ private AccountInfo _accountInfo;
+
+
+
- private ServiceHost _statusService { get; set; }
public bool Pause
{
- get { return FileWatcherAgent.Pause; }
+ get { return FileAgent.Pause; }
set
{
- FileWatcherAgent.Pause = value;
+ FileAgent.Pause = value;
if (value)
{
StatusKeeper.SetPithosStatus(PithosStatus.SyncPaused);
}
}
- public string RootPath { get; set; }
+ private string _rootPath;
+ public string RootPath
+ {
+ get { return _rootPath; }
+ set
+ {
+ _rootPath = String.IsNullOrWhiteSpace(value)
+ ? String.Empty
+ : value.ToLower();
+ }
+ }
CancellationTokenSource _cancellationSource;
+ public PithosMonitor()
+ {
+ FileAgent = new FileAgent();
+ }
+ private bool _started;
public void Start()
- {
+ {
+ if (String.IsNullOrWhiteSpace(ApiKey))
+ throw new InvalidOperationException("The ApiKey is empty");
+ if (String.IsNullOrWhiteSpace(UserName))
+ throw new InvalidOperationException("The UserName is empty");
+ if (String.IsNullOrWhiteSpace(AuthenticationUrl))
+ throw new InvalidOperationException("The Authentication url is empty");
+ Contract.EndContractBlock();
+
+ //If the account doesn't have a valid path, don't start monitoring but don't throw either
+ if (String.IsNullOrWhiteSpace(RootPath))
+ //TODO; Warn user?
+ return;
+
+ WorkflowAgent.StatusNotification = StatusNotification;
+
StatusNotification.NotifyChange("Starting");
- if (_cancellationSource != null)
+ if (_started)
{
if (!_cancellationSource.IsCancellationRequested)
return;
}
_cancellationSource = new CancellationTokenSource();
- var proxyUri = ProxyFromSettings();
- CloudClient.Proxy = proxyUri;
- CloudClient.UsePithos = this.UsePithos;
-
+
+ CloudClient = new CloudFilesClient(UserName, ApiKey)
+ {UsePithos = true, AuthenticationUrl = AuthenticationUrl};
+
+
+ _accountInfo = CloudClient.Authenticate();
+ _accountInfo.SiteUri = AuthenticationUrl;
+ _accountInfo.AccountPath = RootPath;
+
+
+ var pithosFolder = Path.Combine(RootPath, FolderConstants.PithosContainer);
+ if (!Directory.Exists(pithosFolder))
+ Directory.CreateDirectory(pithosFolder);
+ //Create the cache folder and ensure it is hidden
+ CreateHiddenFolder(RootPath, FolderConstants.CacheFolder);
+
+ var policy=CloudClient.GetAccountPolicies(_accountInfo);
+
+ StatusNotification.NotifyAccount(policy);
EnsurePithosContainers();
- StatusKeeper.BlockHash = "sha256";
+ StatusKeeper.BlockHash = _blockHash;
+ StatusKeeper.BlockSize = _blockSize;
StatusKeeper.StartProcessing(_cancellationSource.Token);
- IndexLocalFiles(RootPath);
- StartWatcherAgent(RootPath);
- StartStatusService();
- StartWorkflowAgent();
- WorkflowAgent.RestartInterruptedFiles();
+ IndexLocalFiles();
+ //Extract the URIs from the string collection
+ var settings = Settings.Accounts.First(s => s.AccountName == _accountInfo.UserName);
+ var selectiveUrls=settings.SelectiveFolders.Cast<string>().Select(url => new Uri(url)).ToArray();
+
+ SetSelectivePaths(selectiveUrls,null,null);
+
+ StartWatcherAgent();
+
+ StartNetworkAgent();
+
+ WorkflowAgent.RestartInterruptedFiles(_accountInfo);
+ _started = true;
}
private void EnsurePithosContainers()
{
- CloudClient.UsePithos = this.UsePithos;
- CloudClient.AuthenticationUrl = this.AuthenticationUrl;
- CloudClient.Authenticate(UserName, ApiKey);
- var pithosContainers = new[] {PithosContainer, TrashContainer};
+ //Create the two default containers if they are missing
+ var pithosContainers = new List<string>{ FolderConstants.TrashContainer,FolderConstants.PithosContainer};
foreach (var container in pithosContainers)
- {
- if (!CloudClient.ContainerExists(container))
- CloudClient.CreateContainer(container);
+ {
+ var info=CloudClient.GetContainerInfo(UserName, container);
+ if (info == ContainerInfo.Empty)
+ {
+ CloudClient.CreateContainer(UserName, container);
+ info = CloudClient.GetContainerInfo(UserName, container);
+ }
+ _blockSize = info.BlockSize;
+ _blockHash = info.BlockHash;
+ _accountInfo.BlockSize = _blockSize;
+ _accountInfo.BlockHash = _blockHash;
}
}
public string AuthenticationUrl { get; set; }
- private Uri ProxyFromSettings()
- {
- if (Settings.UseManualProxy)
+ private void IndexLocalFiles()
+ {
+ StatusNotification.NotifyChange("Indexing Local Files");
+ using (ThreadContext.Stacks["Monitor"].Push("Indexing local files"))
{
- var proxyUri = new UriBuilder
- {
- Host = Settings.ProxyServer,
- Port = Settings.ProxyPort
- };
- if (Settings.ProxyAuthentication)
+ Log.Info("START");
+ try
{
- proxyUri.UserName = Settings.ProxyUsername;
- proxyUri.Password = Settings.ProxyPassword;
- }
- return proxyUri.Uri;
- }
- return null;
- }
+ var cachePath = Path.Combine(RootPath, FolderConstants.CacheFolder);
+ var directory = new DirectoryInfo(RootPath);
+ var files =
+ from file in directory.EnumerateFiles("*", SearchOption.AllDirectories)
+ where !file.FullName.StartsWith(cachePath, StringComparison.InvariantCultureIgnoreCase) &&
+ !file.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase)
+ select file;
+ StatusKeeper.ProcessExistingFiles(files);
- private void IndexLocalFiles(string path)
- {
- StatusNotification.NotifyChange("Indexing Local Files",TraceLevel.Info);
- Trace.TraceInformation("[START] Index Local");
- try
- {
- var files =
- from filePath in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).AsParallel()
- select filePath.ToLower();
- StatusKeeper.StoreUnversionedFiles(files);
-
- }
- catch (Exception exc)
- {
- Trace.TraceError("[ERROR] Index Local - {0}", exc);
- }
- finally
- {
- Trace.TraceInformation("[END] Inxed Local");
+ }
+ catch (Exception exc)
+ {
+ Log.Error("[ERROR]", exc);
+ }
+ finally
+ {
+ Log.Info("[END]");
+ }
}
}
- private void StartStatusService()
- {
- // Create a ServiceHost for the CalculatorService type and provide the base address.
- var baseAddress = new Uri("net.pipe://localhost/pithos");
- _statusService = new ServiceHost(typeof(StatusService), baseAddress);
-
- var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
-
- _statusService.AddServiceEndpoint(typeof(IStatusService), binding, "net.pipe://localhost/pithos/statuscache");
- _statusService.AddServiceEndpoint(typeof (ISettingsService), binding, "net.pipe://localhost/pithos/settings");
-
-
- //// Add a mex endpoint
- var smb = new ServiceMetadataBehavior
- {
- HttpGetEnabled = true,
- HttpGetUrl = new Uri("http://localhost:30000/pithos/mex")
- };
- _statusService.Description.Behaviors.Add(smb);
+
- _statusService.Open();
- }
-
- private void StopStatusService()
+ /* private void StartWorkflowAgent()
{
- if (_statusService == null)
- return;
+ WorkflowAgent.StatusNotification = StatusNotification;
- if (_statusService.State == CommunicationState.Faulted)
- _statusService.Abort();
- else if (_statusService.State != CommunicationState.Closed)
- _statusService.Close();
- _statusService = null;
-
- }
-
-
- private void StartWorkflowAgent()
- {
-
- bool connected = NetworkListManager.IsConnectedToInternet;
+/* //On Vista and up we can check for a network connection
+ bool connected=Environment.OSVersion.Version.Major < 6 || NetworkListManager.IsConnectedToInternet;
//If we are not connected retry later
if (!connected)
{
Task.Factory.StartNewDelayed(10000, StartWorkflowAgent);
return;
- }
+ }#1#
try
{
- CloudClient.UsePithos = this.UsePithos;
- CloudClient.AuthenticationUrl = this.AuthenticationUrl;
- CloudClient.Authenticate(UserName, ApiKey);
-
- StartNetworkAgent(RootPath);
-
- WorkflowAgent.StatusNotification = StatusNotification;
WorkflowAgent.Start();
}
catch (Exception)
//Retry after a while
Task.Factory.StartNewDelayed(10000, StartWorkflowAgent);
}
- }
-
- public bool UsePithos { get; set; }
-
-
+ }*/
internal class LocalFileComparer:EqualityComparer<CloudAction>
{
return false;
if (x.LocalFile != null && y.LocalFile != null && !x.LocalFile.FullName.Equals(y.LocalFile.FullName))
return false;
- if (x.CloudFile != null && y.CloudFile != null && !x.CloudFile.Hash.Equals(y.CloudFile.Hash))
- return false;
+ if (x.CloudFile != null && y.CloudFile != null )
+ {
+ if (x.CloudFile.Hash == null & y.CloudFile.Hash != null)
+ return false;
+ if (x.CloudFile.Hash != null & y.CloudFile.Hash == null)
+ return false;
+ if (x.CloudFile.Hash == null & y.CloudFile.Hash == null)
+ return (x.CloudFile.Name == y.CloudFile.Name);
+ if (!x.CloudFile.Hash.Equals(y.CloudFile.Hash))
+ return false;
+ }
if (x.CloudFile == null ^ y.CloudFile == null ||
x.LocalFile == null ^ y.LocalFile == null)
return false;
public override int GetHashCode(CloudAction obj)
{
+ if (obj == null)
+ return 0;
var hash1 = (obj.LocalFile == null) ? int.MaxValue : obj.LocalFile.FullName.GetHashCode();
- var hash2 = (obj.CloudFile == null) ? int.MaxValue : obj.CloudFile.Hash.GetHashCode();
+ var hash2 = (obj.CloudFile == null) ? int.MaxValue : (obj.CloudFile.Hash ?? obj.CloudFile.Name??"").GetHashCode();
var hash3 = obj.Action.GetHashCode();
return hash1 ^ hash2 & hash3;
}
}
- private Timer timer;
-
- private void StartNetworkAgent(string accountPath)
+ private void StartNetworkAgent()
{
+
NetworkAgent.StatusNotification = StatusNotification;
-
- NetworkAgent.Start(RootPath, PithosContainer,TrashContainer);
+
+ NetworkAgent.Start();
+
+ PollAgent.AddAccount(_accountInfo);
+
+ PollAgent.StatusNotification = StatusNotification;
+
+ PollAgent.PollRemoteFiles();
+ }
+
+ //Make sure a hidden cache folder exists to store partial downloads
+ private static void CreateHiddenFolder(string rootPath, string folderName)
+ {
+ if (String.IsNullOrWhiteSpace(rootPath))
+ throw new ArgumentNullException("rootPath");
+ if (!Path.IsPathRooted(rootPath))
+ throw new ArgumentException("rootPath");
+ if (String.IsNullOrWhiteSpace(folderName))
+ throw new ArgumentNullException("folderName");
+ Contract.EndContractBlock();
+
+ var folder = Path.Combine(rootPath, folderName);
+ if (!Directory.Exists(folder))
+ {
+ var info = Directory.CreateDirectory(folder);
+ info.Attributes |= FileAttributes.Hidden;
- NetworkAgent.ProcessRemoteFiles(accountPath);
+ Log.InfoFormat("Created cache Folder: {0}", folder);
+ }
+ else
+ {
+ var info = new DirectoryInfo(folder);
+ if ((info.Attributes & FileAttributes.Hidden) == 0)
+ {
+ info.Attributes |= FileAttributes.Hidden;
+ Log.InfoFormat("Reset cache folder to hidden: {0}", folder);
+ }
+ }
}
- private void StartWatcherAgent(string path)
+ private void StartWatcherAgent()
{
- FileWatcherAgent.StatusKeeper = StatusKeeper;
- FileWatcherAgent.Workflow = Workflow;
- FileWatcherAgent.Start(path);
+ AgentLocator<FileAgent>.Register(FileAgent,RootPath);
+
+ FileAgent.StatusKeeper = StatusKeeper;
+ FileAgent.Workflow = Workflow;
+ FileAgent.CachePath = Path.Combine(RootPath, FolderConstants.CacheFolder);
+ FileAgent.Start(_accountInfo, RootPath);
}
public void Stop()
- {
- FileWatcherAgent.Stop();
- if (timer != null)
- timer.Dispose();
- timer = null;
- StopStatusService();
+ {
+ AgentLocator<FileAgent>.Remove(RootPath);
+
+ if (FileAgent!=null)
+ FileAgent.Stop();
+ FileAgent = null;
}
}
- }
+ public void MoveFileStates(string oldPath, string newPath)
+ {
+ if (String.IsNullOrWhiteSpace(oldPath))
+ throw new ArgumentNullException("oldPath");
+ if (!Path.IsPathRooted(oldPath))
+ throw new ArgumentException("oldPath must be an absolute path","oldPath");
+ if (string.IsNullOrWhiteSpace(newPath))
+ throw new ArgumentNullException("newPath");
+ if (!Path.IsPathRooted(newPath))
+ throw new ArgumentException("newPath must be an absolute path","newPath");
+ Contract.EndContractBlock();
+
+ StatusKeeper.ChangeRoots(oldPath, newPath);
+ }
+
+ public void SetSelectivePaths(Uri[] uris,Uri[] added, Uri[] removed)
+ {
+ //Convert the uris to paths
+ var selectivePaths = UrisToFilePaths(uris);
+
+ FileAgent.SelectivePaths=selectivePaths;
+ PollAgent.SetSyncUris(uris);
+
+ var removedPaths = UrisToFilePaths(removed);
+ UnversionSelectivePaths(removedPaths);
+
+ }
+
+ /// <summary>
+ /// Mark all unselected paths as Unversioned
+ /// </summary>
+ /// <param name="removed"></param>
+ private void UnversionSelectivePaths(List<string> removed)
+ {
+ if (removed == null)
+ return;
+
+ //Ensure we remove any file state below the deleted folders
+ FileState.UnversionPaths(removed);
+ }
+
+
+ /// <summary>
+ /// Return a list of absolute filepaths from a list of Uris
+ /// </summary>
+ /// <param name="uris"></param>
+ /// <returns></returns>
+ private List<string> UrisToFilePaths(IEnumerable<Uri> uris)
+ {
+ if (uris == null)
+ return new List<string>();
+
+ return (from uri in uris
+ let relativePath = _accountInfo.StorageUri
+ .MakeRelativeUri(uri)
+ .RelativeUriToFilePath()
+ //Trim the account name
+ select Path.Combine(RootPath, relativePath.After(_accountInfo.UserName + '\\'))).ToList();
+ }
+
+
+ public ObjectInfo GetObjectInfo(string filePath)
+ {
+ if (String.IsNullOrWhiteSpace(filePath))
+ throw new ArgumentNullException("filePath");
+ Contract.EndContractBlock();
- public interface IStatusNotification
- {
- void NotifyChange(string status,TraceLevel level=TraceLevel.Info);
+ var file=new FileInfo(filePath);
+ string relativeUrl;//=file.AsRelativeUrlTo(this.RootPath);
+ var relativePath = file.AsRelativeTo(RootPath);
+
+ string accountName,container;
+
+ var parts=relativePath.Split('\\');
+
+ var accountInfo = _accountInfo;
+ if (relativePath.StartsWith(FolderConstants.OthersFolder))
+ {
+ accountName = parts[1];
+ container = parts[2];
+ relativeUrl = String.Join("/", parts.Splice(3));
+ //Create the root URL for the target account
+ var oldName = UserName;
+ var absoluteUri = _accountInfo.StorageUri.AbsoluteUri;
+ var nameIndex=absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
+ var root=absoluteUri.Substring(0, nameIndex);
+
+ accountInfo = new AccountInfo
+ {
+ UserName = accountName,
+ AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
+ StorageUri = new Uri(root + accountName),
+ BlockHash=accountInfo.BlockHash,
+ BlockSize=accountInfo.BlockSize,
+ Token=accountInfo.Token
+ };
+ }
+ else
+ {
+ accountName = UserName;
+ container = parts[0];
+ relativeUrl = String.Join("/", parts.Splice(1));
+ }
+
+ var client = new CloudFilesClient(accountInfo);
+ var objectInfo=client.GetObjectInfo(accountName, container, relativeUrl);
+ return objectInfo;
+ }
+
+ public Task<ContainerInfo> GetContainerInfo(string filePath)
+ {
+ if (String.IsNullOrWhiteSpace(filePath))
+ throw new ArgumentNullException("filePath");
+ Contract.EndContractBlock();
+
+ var file=new FileInfo(filePath);
+ var relativePath = file.AsRelativeTo(RootPath);
+
+ string accountName,container;
+
+ var parts=relativePath.Split('\\');
+
+ var accountInfo = _accountInfo;
+ if (relativePath.StartsWith(FolderConstants.OthersFolder))
+ {
+ accountName = parts[1];
+ container = parts[2];
+ //Create the root URL for the target account
+ var oldName = UserName;
+ var absoluteUri = _accountInfo.StorageUri.AbsoluteUri;
+ var nameIndex=absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
+ var root=absoluteUri.Substring(0, nameIndex);
+
+ accountInfo = new AccountInfo
+ {
+ UserName = accountName,
+ AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
+ StorageUri = new Uri(root + accountName),
+ BlockHash=accountInfo.BlockHash,
+ BlockSize=accountInfo.BlockSize,
+ Token=accountInfo.Token
+ };
+ }
+ else
+ {
+ accountName = UserName;
+ container = parts[0];
+ }
+
+ return Task.Factory.StartNew(() =>
+ {
+ var client = new CloudFilesClient(accountInfo);
+ var containerInfo = client.GetContainerInfo(accountName, container);
+ return containerInfo;
+ });
+ }
}
}