2 /* -----------------------------------------------------------------------
3 * <copyright file="FileAgent.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;
46 using System.Diagnostics.Contracts;
50 using System.Threading.Tasks;
51 using Pithos.Interfaces;
56 namespace Pithos.Core.Agents
59 public class FileAgent
61 Agent<WorkflowState> _agent;
62 private FileSystemWatcher _watcher;
63 private FileSystemWatcherAdapter _adapter;
66 public IStatusKeeper StatusKeeper { get; set; }
68 public IPithosWorkflow Workflow { get; set; }
70 public WorkflowAgent WorkflowAgent { get; set; }
72 private AccountInfo AccountInfo { get; set; }
74 private string RootPath { get; set; }
76 private static readonly ILog Log = LogManager.GetLogger("FileAgent");
78 public void Start(AccountInfo accountInfo,string rootPath)
80 if (accountInfo==null)
81 throw new ArgumentNullException("accountInfo");
82 if (String.IsNullOrWhiteSpace(rootPath))
83 throw new ArgumentNullException("rootPath");
84 if (!Path.IsPathRooted(rootPath))
85 throw new ArgumentException("rootPath must be an absolute path","rootPath");
86 Contract.EndContractBlock();
88 AccountInfo = accountInfo;
90 _watcher = new FileSystemWatcher(rootPath) {IncludeSubdirectories = true};
91 _adapter = new FileSystemWatcherAdapter(_watcher);
93 _adapter.Changed += OnFileEvent;
94 _adapter.Created += OnFileEvent;
95 _adapter.Deleted += OnFileEvent;
96 _adapter.Renamed += OnRenameEvent;
97 _adapter.Moved += OnMoveEvent;
98 _watcher.EnableRaisingEvents = true;
101 _agent = Agent<WorkflowState>.Start(inbox =>
106 var message = inbox.Receive();
107 var process=message.Then(Process,inbox.CancellationToken);
108 inbox.LoopAsync(process,loop,ex=>
109 Log.ErrorFormat("[ERROR] File Event Processing:\r{0}", ex));
115 private Task<object> Process(WorkflowState state)
118 throw new ArgumentNullException("state");
119 Contract.EndContractBlock();
121 if (Ignore(state.Path))
122 return CompletedTask<object>.Default;
124 var networkState = NetworkGate.GetNetworkState(state.Path);
125 //Skip if the file is already being downloaded or uploaded and
126 //the change is create or modify
127 if (networkState != NetworkOperation.None &&
129 state.TriggeringChange == WatcherChangeTypes.Created ||
130 state.TriggeringChange == WatcherChangeTypes.Changed
132 return CompletedTask<object>.Default;
136 UpdateFileStatus(state);
137 UpdateOverlayStatus(state);
138 UpdateFileChecksum(state);
139 WorkflowAgent.Post(state);
141 catch (IOException exc)
143 if (File.Exists(state.Path))
145 Log.WarnFormat("File access error occured, retrying {0}\n{1}", state.Path, exc);
150 Log.WarnFormat("File {0} does not exist. Will be ignored\n{1}", state.Path, exc);
153 catch (Exception exc)
155 Log.WarnFormat("Error occured while indexing{0}. The file will be skipped\n{1}",
158 return CompletedTask<object>.Default;
163 get { return _watcher == null || !_watcher.EnableRaisingEvents; }
166 if (_watcher != null)
167 _watcher.EnableRaisingEvents = !value;
171 public string CachePath { get; set; }
173 private List<string> _selectivePaths = new List<string>();
174 public List<string> SelectivePaths
176 get { return _selectivePaths; }
177 set { _selectivePaths = value; }
181 public void Post(WorkflowState workflowState)
183 if (workflowState == null)
184 throw new ArgumentNullException("workflowState");
185 Contract.EndContractBlock();
187 _agent.Post(workflowState);
192 if (_watcher != null)
194 _watcher.Changed -= OnFileEvent;
195 _watcher.Created -= OnFileEvent;
196 _watcher.Deleted -= OnFileEvent;
197 _watcher.Renamed -= OnRenameEvent;
206 // Enumerate all files in the Pithos directory except those in the Fragment folder
207 // and files with a .ignore extension
208 public IEnumerable<string> EnumerateFiles(string searchPattern="*")
210 var monitoredFiles = from filePath in Directory.EnumerateFileSystemEntries(RootPath, searchPattern, SearchOption.AllDirectories)
211 where !Ignore(filePath)
213 return monitoredFiles;
216 public IEnumerable<FileInfo> EnumerateFileInfos(string searchPattern="*")
218 var rootDir = new DirectoryInfo(RootPath);
219 var monitoredFiles = from file in rootDir.EnumerateFiles(searchPattern, SearchOption.AllDirectories)
220 where !Ignore(file.FullName)
222 return monitoredFiles;
225 public IEnumerable<string> EnumerateFilesAsRelativeUrls(string searchPattern="*")
227 var rootDir = new DirectoryInfo(RootPath);
228 var monitoredFiles = from file in rootDir.EnumerateFiles(searchPattern, SearchOption.AllDirectories)
229 where !Ignore(file.FullName)
230 select file.AsRelativeUrlTo(RootPath);
231 return monitoredFiles;
234 public IEnumerable<string> EnumerateFilesSystemInfosAsRelativeUrls(string searchPattern="*")
236 var rootDir = new DirectoryInfo(RootPath);
237 var monitoredFiles = from file in rootDir.EnumerateFileSystemInfos(searchPattern, SearchOption.AllDirectories)
238 where !Ignore(file.FullName)
239 select file.AsRelativeUrlTo(RootPath);
240 return monitoredFiles;
246 private bool Ignore(string filePath)
248 //Ignore all first-level directories and files (ie at the container folders level)
249 if (FoundBelowRoot(filePath, RootPath,1))
252 //Ignore first-level items under the "others" folder (ie at the accounts folders level).
253 var othersPath = Path.Combine(RootPath, FolderConstants.OthersFolder);
254 if (FoundBelowRoot(filePath, othersPath,1))
257 //Ignore second-level (container) folders under the "others" folder (ie at the container folders level).
258 if (FoundBelowRoot(filePath, othersPath,2))
262 //Ignore anything happening in the cache path
263 if (filePath.StartsWith(CachePath))
265 if (_ignoreFiles.ContainsKey(filePath.ToLower()))
268 //If selective synchronization is defined,
269 if (SelectivePaths.Count>0)
271 //Abort if the file is not located under any of the selected folders
272 if (!SelectivePaths.Any(filePath.StartsWith))
279 /* private static bool FoundInRoot(string filePath, string rootPath)
281 //var rootDirectory = new DirectoryInfo(rootPath);
283 //If the paths are equal, return true
284 if (filePath.Equals(rootPath, StringComparison.InvariantCultureIgnoreCase))
287 //If the filepath is below the root path
288 if (filePath.StartsWith(rootPath,StringComparison.InvariantCulture))
290 //Get the relative path
291 var relativePath = filePath.Substring(rootPath.Length + 1);
292 //If the relativePath does NOT contains a path separator, we found a match
293 return (!relativePath.Contains(@"\"));
296 //If the filepath is not under the root path, return false
301 private static bool FoundBelowRoot(string filePath, string rootPath,int level)
303 //var rootDirectory = new DirectoryInfo(rootPath);
305 //If the paths are equal, return true
306 if (filePath.Equals(rootPath, StringComparison.InvariantCultureIgnoreCase))
309 //If the filepath is below the root path
310 if (filePath.StartsWith(rootPath,StringComparison.InvariantCulture))
312 //Get the relative path
313 var relativePath = filePath.Substring(rootPath.Length + 1);
314 //If the relativePath does NOT contains a path separator, we found a match
315 var levels=relativePath.ToCharArray().Count(c=>c=='\\')+1;
316 return levels==level;
319 //If the filepath is not under the root path, return false
323 //Post a Change message for all events except rename
324 void OnFileEvent(object sender, FileSystemEventArgs e)
326 //Ignore events that affect the cache folder
327 var filePath = e.FullPath;
328 if (Ignore(filePath))
331 _agent.Post(new WorkflowState{AccountInfo=AccountInfo, Path = filePath, FileName = e.Name, TriggeringChange = e.ChangeType });
335 //Post a Change message for renames containing the old and new names
336 void OnRenameEvent(object sender, RenamedEventArgs e)
338 var oldFullPath = e.OldFullPath;
339 var fullPath = e.FullPath;
340 if (Ignore(oldFullPath) || Ignore(fullPath))
343 _agent.Post(new WorkflowState
345 AccountInfo=AccountInfo,
346 OldPath = oldFullPath,
347 OldFileName = e.OldName,
350 TriggeringChange = e.ChangeType
354 //Post a Change message for renames containing the old and new names
355 void OnMoveEvent(object sender, MovedEventArgs e)
357 var oldFullPath = e.OldFullPath;
358 var fullPath = e.FullPath;
359 if (Ignore(oldFullPath) || Ignore(fullPath))
362 _agent.Post(new WorkflowState
364 AccountInfo=AccountInfo,
365 OldPath = oldFullPath,
366 OldFileName = e.OldName,
369 TriggeringChange = e.ChangeType
375 private Dictionary<WatcherChangeTypes, FileStatus> _statusDict = new Dictionary<WatcherChangeTypes, FileStatus>
377 {WatcherChangeTypes.Created,FileStatus.Created},
378 {WatcherChangeTypes.Changed,FileStatus.Modified},
379 {WatcherChangeTypes.Deleted,FileStatus.Deleted},
380 {WatcherChangeTypes.Renamed,FileStatus.Renamed}
383 private Dictionary<string, string> _ignoreFiles=new Dictionary<string, string>();
385 private WorkflowState UpdateFileStatus(WorkflowState state)
388 throw new ArgumentNullException("state");
389 if (String.IsNullOrWhiteSpace(state.Path))
390 throw new ArgumentException("The state's Path can't be empty","state");
391 Contract.EndContractBlock();
393 var path = state.Path;
394 var status = _statusDict[state.TriggeringChange];
395 var oldStatus = Workflow.StatusKeeper.GetFileStatus(path);
396 if (status == oldStatus)
398 state.Status = status;
402 if (state.Status == FileStatus.Renamed)
403 Workflow.ClearFileStatus(path);
405 state.Status = Workflow.SetFileStatus(path, status);
409 private WorkflowState UpdateOverlayStatus(WorkflowState state)
412 throw new ArgumentNullException("state");
413 Contract.EndContractBlock();
418 switch (state.Status)
420 case FileStatus.Created:
421 case FileStatus.Modified:
422 this.StatusKeeper.SetFileOverlayStatus(state.Path, FileOverlayStatus.Modified);
424 case FileStatus.Deleted:
425 //this.StatusAgent.RemoveFileOverlayStatus(state.Path);
427 case FileStatus.Renamed:
428 this.StatusKeeper.ClearFileStatus(state.OldPath);
429 this.StatusKeeper.SetFileOverlayStatus(state.Path, FileOverlayStatus.Modified);
431 case FileStatus.Unchanged:
432 this.StatusKeeper.SetFileOverlayStatus(state.Path, FileOverlayStatus.Normal);
436 if (state.Status == FileStatus.Deleted)
437 NativeMethods.RaiseChangeNotification(Path.GetDirectoryName(state.Path));
439 NativeMethods.RaiseChangeNotification(state.Path);
444 private WorkflowState UpdateFileChecksum(WorkflowState state)
449 if (state.Status == FileStatus.Deleted)
452 var path = state.Path;
453 //Skip calculation for folders
454 if (Directory.Exists(path))
457 var info = new FileInfo(path);
458 string hash = info.CalculateHash(StatusKeeper.BlockSize,StatusKeeper.BlockHash);
459 StatusKeeper.UpdateFileChecksum(path, hash);
465 //Does the file exist in the container's local folder?
466 public bool Exists(string relativePath)
468 if (String.IsNullOrWhiteSpace(relativePath))
469 throw new ArgumentNullException("relativePath");
470 //A RootPath must be set before calling this method
471 if (String.IsNullOrWhiteSpace(RootPath))
472 throw new InvalidOperationException("RootPath was not set");
473 Contract.EndContractBlock();
474 //Create the absolute path by combining the RootPath with the relativePath
475 var absolutePath=Path.Combine(RootPath, relativePath);
476 //Is this a valid file?
477 if (File.Exists(absolutePath))
480 if (Directory.Exists(absolutePath))
482 //Fail if it is neither
486 public static FileAgent GetFileAgent(AccountInfo accountInfo)
488 return GetFileAgent(accountInfo.AccountPath);
491 public static FileAgent GetFileAgent(string rootPath)
493 return AgentLocator<FileAgent>.Get(rootPath.ToLower());
497 public FileSystemInfo GetFileSystemInfo(string relativePath)
499 if (String.IsNullOrWhiteSpace(relativePath))
500 throw new ArgumentNullException("relativePath");
501 //A RootPath must be set before calling this method
502 if (String.IsNullOrWhiteSpace(RootPath))
503 throw new InvalidOperationException("RootPath was not set");
504 Contract.EndContractBlock();
506 var absolutePath = Path.Combine(RootPath, relativePath);
508 if (Directory.Exists(absolutePath))
509 return new DirectoryInfo(absolutePath).WithProperCapitalization();
511 return new FileInfo(absolutePath).WithProperCapitalization();
515 public void Delete(string relativePath)
517 var absolutePath = Path.Combine(RootPath, relativePath).ToLower();
518 if (File.Exists(absolutePath))
522 File.Delete(absolutePath);
524 //The file may have been deleted by another thread. Just ignore the relevant exception
525 catch (FileNotFoundException) { }
527 else if (Directory.Exists(absolutePath))
531 Directory.Delete(absolutePath, true);
533 //The directory may have been deleted by another thread. Just ignore the relevant exception
534 catch (DirectoryNotFoundException){}
537 //_ignoreFiles[absolutePath] = absolutePath;
538 StatusKeeper.ClearFileStatus(absolutePath);