2 /* -----------------------------------------------------------------------
3 * <copyright file="PithosMonitor.cs" company="GRNet">
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
11 * 1. Redistributions of source code must retain the above
12 * copyright notice, this list of conditions and the following
15 * 2. Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials
18 * provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
34 * The views and conclusions contained in the software and
35 * documentation are those of the authors and should not be
36 * interpreted as representing official policies, either expressed
37 * or implied, of GRNET S.A.
39 * -----------------------------------------------------------------------
43 using System.Collections.Generic;
44 using System.ComponentModel.Composition;
45 using System.Diagnostics.Contracts;
48 using System.Reflection;
49 using System.Threading;
50 using System.Threading.Tasks;
51 using Pithos.Core.Agents;
52 using Pithos.Interfaces;
58 [Export(typeof(PithosMonitor))]
59 public class PithosMonitor:IDisposable
61 private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
63 private int _blockSize;
64 private string _blockHash;
67 public IPithosSettings Settings{get;set;}
69 private IStatusKeeper _statusKeeper;
72 public IStatusKeeper StatusKeeper
74 get { return _statusKeeper; }
77 _statusKeeper = value;
78 FileAgent.StatusKeeper = value;
85 private IPithosWorkflow _workflow;
88 public IPithosWorkflow Workflow
90 get { return _workflow; }
94 FileAgent.Workflow = value;
98 public ICloudClient CloudClient { get; set; }
100 public IStatusNotification StatusNotification { get; set; }
103 public FileAgent FileAgent { get; private set; }
105 private WorkflowAgent _workflowAgent;
108 public WorkflowAgent WorkflowAgent
110 get { return _workflowAgent; }
113 _workflowAgent = value;
114 FileAgent.WorkflowAgent = value;
119 public NetworkAgent NetworkAgent { get; set; }
121 public PollAgent PollAgent { get; set; }
123 private Selectives _selectives;
126 public Selectives Selectives
128 get { return _selectives; }
132 FileAgent.Selectives = value;
136 public string UserName { get; set; }
137 private string _apiKey;
140 get { return _apiKey; }
144 if (_accountInfo != null)
145 _accountInfo.Token = value;
149 private AccountInfo _accountInfo;
151 public AccountInfo Account
153 get { return _accountInfo; }
163 get { return FileAgent.Pause; }
166 FileAgent.Pause = value;
170 private string _rootPath;
171 public string RootPath
173 get { return _rootPath; }
176 _rootPath = String.IsNullOrWhiteSpace(value)
183 CancellationTokenSource _cancellationSource;
185 public PithosMonitor()
187 FileAgent = new FileAgent();
189 private bool _started;
193 if (String.IsNullOrWhiteSpace(ApiKey))
194 throw new InvalidOperationException("The ApiKey is empty");
195 if (String.IsNullOrWhiteSpace(UserName))
196 throw new InvalidOperationException("The UserName is empty");
197 if (String.IsNullOrWhiteSpace(AuthenticationUrl))
198 throw new InvalidOperationException("The Authentication url is empty");
199 Contract.EndContractBlock();
201 //If the account doesn't have a valid path, don't start monitoring but don't throw either
202 if (String.IsNullOrWhiteSpace(RootPath))
206 WorkflowAgent.StatusNotification = StatusNotification;
208 StatusNotification.NotifyChange("Starting");
211 if (!_cancellationSource.IsCancellationRequested)
214 _cancellationSource = new CancellationTokenSource();
218 CloudClient = new CloudFilesClient(UserName, ApiKey)
219 {UsePithos = true, AuthenticationUrl = AuthenticationUrl};
220 _accountInfo = CloudClient.Authenticate();
222 _accountInfo.SiteUri = AuthenticationUrl;
223 _accountInfo.AccountPath = RootPath;
226 var pithosFolder = Path.Combine(RootPath, FolderConstants.PithosContainer);
227 if (!Directory.Exists(pithosFolder))
228 Directory.CreateDirectory(pithosFolder);
229 //Create the cache folder and ensure it is hidden
230 CreateHiddenFolder(RootPath, FolderConstants.CacheFolder);
232 var policy=CloudClient.GetAccountPolicies(_accountInfo);
234 StatusNotification.NotifyAccount(policy);
235 EnsurePithosContainers();
237 StatusKeeper.BlockHash = _blockHash;
238 StatusKeeper.BlockSize = _blockSize;
240 StatusKeeper.StartProcessing(_cancellationSource.Token);
242 //Extract the URIs from the string collection
243 var settings = Settings.Accounts.First(s => s.AccountKey == _accountInfo.AccountKey );
245 var selectiveUrls=settings.SelectiveFolders.Cast<string>().Select(url => new Uri(url,UriKind.RelativeOrAbsolute))
246 .Where(uri=>uri.IsAbsoluteUri).ToArray();
248 SetSelectivePaths(selectiveUrls,null,null);
254 WorkflowAgent.RestartInterruptedFiles(_accountInfo);
258 private void EnsurePithosContainers()
261 //Create the two default containers if they are missing
262 var pithosContainers = new List<string>{ FolderConstants.TrashContainer,FolderConstants.PithosContainer};
263 foreach (var container in pithosContainers)
265 var info=CloudClient.GetContainerInfo(UserName, container);
266 if (info == ContainerInfo.Empty)
268 CloudClient.CreateContainer(UserName, container);
269 info = CloudClient.GetContainerInfo(UserName, container);
271 _blockSize = info.BlockSize;
272 _blockHash = info.BlockHash;
273 _accountInfo.BlockSize = _blockSize;
274 _accountInfo.BlockHash = _blockHash;
278 public string AuthenticationUrl { get; set; }
280 private void IndexLocalFiles()
282 using (ThreadContext.Stacks["Operation"].Push("Indexing local files"))
287 //StatusNotification.NotifyChange("Indexing Local Files");
288 Log.Info("Start local indexing");
289 StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing,"Indexing Local Files");
291 var cachePath = Path.Combine(RootPath, FolderConstants.CacheFolder);
292 var directory = new DirectoryInfo(RootPath);
294 from file in directory.EnumerateFiles("*", SearchOption.AllDirectories)
295 where !file.FullName.StartsWith(cachePath, StringComparison.InvariantCultureIgnoreCase) &&
296 !file.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase)
298 StatusKeeper.ProcessExistingFiles(files);
301 catch (Exception exc)
303 Log.Error("[ERROR]", exc);
309 StatusNotification.SetPithosStatus(PithosStatus.LocalComplete,"Indexing Completed");
317 /* private void StartWorkflowAgent()
319 WorkflowAgent.StatusNotification = StatusNotification;
321 /* //On Vista and up we can check for a network connection
322 bool connected=Environment.OSVersion.Version.Major < 6 || NetworkListManager.IsConnectedToInternet;
323 //If we are not connected retry later
326 Task.Factory.StartNewDelayed(10000, StartWorkflowAgent);
332 WorkflowAgent.Start();
336 //Faild to authenticate due to network or account error
337 //Retry after a while
338 Task.Factory.StartNewDelayed(10000, StartWorkflowAgent);
343 private void StartNetworkAgent()
345 NetworkAgent.StatusNotification = StatusNotification;
347 //TODO: The Network and Poll agents are not account specific
348 //They should be moved outside PithosMonitor
349 NetworkAgent.Start();
351 PollAgent.AddAccount(_accountInfo);
353 PollAgent.StatusNotification = StatusNotification;
355 PollAgent.PollRemoteFiles();
358 //Make sure a hidden cache folder exists to store partial downloads
359 private static void CreateHiddenFolder(string rootPath, string folderName)
361 if (String.IsNullOrWhiteSpace(rootPath))
362 throw new ArgumentNullException("rootPath");
363 if (!Path.IsPathRooted(rootPath))
364 throw new ArgumentException("rootPath");
365 if (String.IsNullOrWhiteSpace(folderName))
366 throw new ArgumentNullException("folderName");
367 Contract.EndContractBlock();
369 var folder = Path.Combine(rootPath, folderName);
370 if (!Directory.Exists(folder))
372 var info = Directory.CreateDirectory(folder);
373 info.Attributes |= FileAttributes.Hidden;
375 Log.InfoFormat("Created cache Folder: {0}", folder);
379 var info = new DirectoryInfo(folder);
380 if ((info.Attributes & FileAttributes.Hidden) == 0)
382 info.Attributes |= FileAttributes.Hidden;
383 Log.InfoFormat("Reset cache folder to hidden: {0}", folder);
391 private void StartWatcherAgent()
393 if (Log.IsDebugEnabled)
394 Log.DebugFormat("Start Folder Monitoring [{0}]",RootPath);
396 AgentLocator<FileAgent>.Register(FileAgent,RootPath);
398 FileAgent.IdleTimeout = Settings.FileIdleTimeout;
399 FileAgent.StatusKeeper = StatusKeeper;
400 FileAgent.StatusNotification = StatusNotification;
401 FileAgent.Workflow = Workflow;
402 FileAgent.CachePath = Path.Combine(RootPath, FolderConstants.CacheFolder);
403 FileAgent.Start(_accountInfo, RootPath);
408 AgentLocator<FileAgent>.Remove(RootPath);
421 public void Dispose()
424 GC.SuppressFinalize(this);
427 protected virtual void Dispose(bool disposing)
436 public void MoveFileStates(string oldPath, string newPath)
438 if (String.IsNullOrWhiteSpace(oldPath))
439 throw new ArgumentNullException("oldPath");
440 if (!Path.IsPathRooted(oldPath))
441 throw new ArgumentException("oldPath must be an absolute path","oldPath");
442 if (string.IsNullOrWhiteSpace(newPath))
443 throw new ArgumentNullException("newPath");
444 if (!Path.IsPathRooted(newPath))
445 throw new ArgumentException("newPath must be an absolute path","newPath");
446 Contract.EndContractBlock();
448 StatusKeeper.ChangeRoots(oldPath, newPath);
451 public void SetSelectivePaths(Uri[] uris,Uri[] added, Uri[] removed)
453 //Convert the uris to paths
454 var selectivePaths = UrisToFilePaths(uris);
456 var selectiveUri = uris.ToList();
457 this.Selectives.SetSelectedUris(_accountInfo,selectiveUri);
459 var removedPaths = UrisToFilePaths(removed);
460 UnversionSelectivePaths(removedPaths);
465 /// Mark all unselected paths as Unversioned
467 /// <param name="removed"></param>
468 private void UnversionSelectivePaths(List<string> removed)
473 //Ensure we remove any file state below the deleted folders
474 FileState.UnversionPaths(removed);
479 /// Return a list of absolute filepaths from a list of Uris
481 /// <param name="uris"></param>
482 /// <returns></returns>
483 private List<string> UrisToFilePaths(IEnumerable<Uri> uris)
486 return new List<string>();
488 var own = (from uri in uris
489 where uri.ToString().StartsWith(_accountInfo.StorageUri.ToString())
490 let relativePath = _accountInfo.StorageUri.MakeRelativeUri(uri).RelativeUriToFilePath()
491 //Trim the account name
492 select Path.Combine(RootPath, relativePath.After(_accountInfo.UserName + '\\'))).ToList();
493 var others= (from uri in uris
494 where !uri.ToString().StartsWith(_accountInfo.StorageUri.ToString())
495 let relativePath = _accountInfo.StorageUri.MakeRelativeUri(uri).RelativeUriToFilePath()
496 //Trim the account name
497 select Path.Combine(RootPath,"others-shared", relativePath)).ToList();
498 return own.Union(others).ToList();
502 public ObjectInfo GetObjectInfo(string filePath)
504 if (String.IsNullOrWhiteSpace(filePath))
505 throw new ArgumentNullException("filePath");
506 Contract.EndContractBlock();
508 var file=new FileInfo(filePath);
509 string relativeUrl;//=file.AsRelativeUrlTo(this.RootPath);
510 var relativePath = file.AsRelativeTo(RootPath);
512 string accountName,container;
514 var parts=relativePath.Split('\\');
516 var accountInfo = _accountInfo;
517 if (relativePath.StartsWith(FolderConstants.OthersFolder))
519 accountName = parts[1];
520 container = parts[2];
521 relativeUrl = String.Join("/", parts.Splice(3));
522 //Create the root URL for the target account
523 var oldName = UserName;
524 var absoluteUri = _accountInfo.StorageUri.AbsoluteUri;
525 var nameIndex=absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
526 var root=absoluteUri.Substring(0, nameIndex);
528 accountInfo = new AccountInfo
530 UserName = accountName,
531 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
532 StorageUri = new Uri(root + accountName),
533 BlockHash=accountInfo.BlockHash,
534 BlockSize=accountInfo.BlockSize,
535 Token=accountInfo.Token
540 accountName = UserName;
541 container = parts[0];
542 relativeUrl = String.Join("/", parts.Splice(1));
545 var client = new CloudFilesClient(accountInfo);
546 var objectInfo=client.GetObjectInfo(accountName, container, relativeUrl);
550 public Task<ContainerInfo> GetContainerInfo(string filePath)
552 if (String.IsNullOrWhiteSpace(filePath))
553 throw new ArgumentNullException("filePath");
554 Contract.EndContractBlock();
556 var file=new FileInfo(filePath);
557 var relativePath = file.AsRelativeTo(RootPath);
559 string accountName,container;
561 var parts=relativePath.Split('\\');
563 var accountInfo = _accountInfo;
564 if (relativePath.StartsWith(FolderConstants.OthersFolder))
566 accountName = parts[1];
567 container = parts[2];
568 //Create the root URL for the target account
569 var oldName = UserName;
570 var absoluteUri = _accountInfo.StorageUri.AbsoluteUri;
571 var nameIndex=absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
572 var root=absoluteUri.Substring(0, nameIndex);
574 accountInfo = new AccountInfo
576 UserName = accountName,
577 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
578 StorageUri = new Uri(root + accountName),
579 BlockHash=accountInfo.BlockHash,
580 BlockSize=accountInfo.BlockSize,
581 Token=accountInfo.Token
586 accountName = UserName;
587 container = parts[0];
590 return Task.Factory.StartNew(() =>
592 var client = new CloudFilesClient(accountInfo);
593 var containerInfo = client.GetContainerInfo(accountName, container);
594 return containerInfo;