DirectoryWatchers.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. using MediaBrowser.Common.ScheduledTasks;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.IO;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Server.Implementations.ScheduledTasks;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Server.Implementations.IO
  16. {
  17. /// <summary>
  18. /// Class DirectoryWatchers
  19. /// </summary>
  20. public class DirectoryWatchers : IDirectoryWatchers
  21. {
  22. /// <summary>
  23. /// The file system watchers
  24. /// </summary>
  25. private ConcurrentBag<FileSystemWatcher> _fileSystemWatchers = new ConcurrentBag<FileSystemWatcher>();
  26. /// <summary>
  27. /// The update timer
  28. /// </summary>
  29. private Timer _updateTimer;
  30. /// <summary>
  31. /// The affected paths
  32. /// </summary>
  33. private readonly ConcurrentDictionary<string, string> _affectedPaths = new ConcurrentDictionary<string, string>();
  34. /// <summary>
  35. /// A dynamic list of paths that should be ignored. Added to during our own file sytem modifications.
  36. /// </summary>
  37. private readonly ConcurrentDictionary<string,string> _tempIgnoredPaths = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  38. /// <summary>
  39. /// The timer lock
  40. /// </summary>
  41. private readonly object _timerLock = new object();
  42. /// <summary>
  43. /// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
  44. /// </summary>
  45. /// <param name="path">The path.</param>
  46. public void TemporarilyIgnore(string path)
  47. {
  48. _tempIgnoredPaths[path] = path;
  49. }
  50. /// <summary>
  51. /// Removes the temp ignore.
  52. /// </summary>
  53. /// <param name="path">The path.</param>
  54. public void RemoveTempIgnore(string path)
  55. {
  56. string val;
  57. _tempIgnoredPaths.TryRemove(path, out val);
  58. }
  59. /// <summary>
  60. /// Gets or sets the logger.
  61. /// </summary>
  62. /// <value>The logger.</value>
  63. private ILogger Logger { get; set; }
  64. /// <summary>
  65. /// Gets or sets the task manager.
  66. /// </summary>
  67. /// <value>The task manager.</value>
  68. private ITaskManager TaskManager { get; set; }
  69. private ILibraryManager LibraryManager { get; set; }
  70. private IServerConfigurationManager ConfigurationManager { get; set; }
  71. /// <summary>
  72. /// Initializes a new instance of the <see cref="DirectoryWatchers" /> class.
  73. /// </summary>
  74. public DirectoryWatchers(ILogManager logManager, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager)
  75. {
  76. if (taskManager == null)
  77. {
  78. throw new ArgumentNullException("taskManager");
  79. }
  80. LibraryManager = libraryManager;
  81. TaskManager = taskManager;
  82. Logger = logManager.GetLogger("DirectoryWatchers");
  83. ConfigurationManager = configurationManager;
  84. }
  85. /// <summary>
  86. /// Starts this instance.
  87. /// </summary>
  88. public void Start()
  89. {
  90. LibraryManager.LibraryChanged += Instance_LibraryChanged;
  91. var pathsToWatch = new List<string> { LibraryManager.RootFolder.Path };
  92. var paths = LibraryManager.RootFolder.Children.OfType<Folder>()
  93. .SelectMany(f =>
  94. {
  95. try
  96. {
  97. // Accessing ResolveArgs could involve file system access
  98. return f.ResolveArgs.PhysicalLocations;
  99. }
  100. catch (IOException)
  101. {
  102. return new string[] {};
  103. }
  104. })
  105. .Where(Path.IsPathRooted);
  106. foreach (var path in paths)
  107. {
  108. if (!ContainsParentFolder(pathsToWatch, path))
  109. {
  110. pathsToWatch.Add(path);
  111. }
  112. }
  113. foreach (var path in pathsToWatch)
  114. {
  115. StartWatchingPath(path);
  116. }
  117. }
  118. /// <summary>
  119. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  120. /// the provided path.
  121. /// </summary>
  122. /// <param name="lst">The LST.</param>
  123. /// <param name="path">The path.</param>
  124. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  125. /// <exception cref="System.ArgumentNullException">path</exception>
  126. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  127. {
  128. if (string.IsNullOrEmpty(path))
  129. {
  130. throw new ArgumentNullException("path");
  131. }
  132. path = path.TrimEnd(Path.DirectorySeparatorChar);
  133. return lst.Any(str =>
  134. {
  135. //this should be a little quicker than examining each actual parent folder...
  136. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  137. return (path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar));
  138. });
  139. }
  140. /// <summary>
  141. /// Starts the watching path.
  142. /// </summary>
  143. /// <param name="path">The path.</param>
  144. private void StartWatchingPath(string path)
  145. {
  146. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  147. Task.Run(() =>
  148. {
  149. var newWatcher = new FileSystemWatcher(path, "*") { IncludeSubdirectories = true, InternalBufferSize = 32767 };
  150. newWatcher.Created += watcher_Changed;
  151. newWatcher.Deleted += watcher_Changed;
  152. newWatcher.Renamed += watcher_Changed;
  153. newWatcher.Changed += watcher_Changed;
  154. newWatcher.Error += watcher_Error;
  155. try
  156. {
  157. newWatcher.EnableRaisingEvents = true;
  158. _fileSystemWatchers.Add(newWatcher);
  159. Logger.Info("Watching directory " + path);
  160. }
  161. catch (IOException ex)
  162. {
  163. Logger.ErrorException("Error watching path: {0}", ex, path);
  164. }
  165. catch (PlatformNotSupportedException ex)
  166. {
  167. Logger.ErrorException("Error watching path: {0}", ex, path);
  168. }
  169. });
  170. }
  171. /// <summary>
  172. /// Stops the watching path.
  173. /// </summary>
  174. /// <param name="path">The path.</param>
  175. private void StopWatchingPath(string path)
  176. {
  177. var watcher = _fileSystemWatchers.FirstOrDefault(f => f.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  178. if (watcher != null)
  179. {
  180. DisposeWatcher(watcher);
  181. }
  182. }
  183. /// <summary>
  184. /// Disposes the watcher.
  185. /// </summary>
  186. /// <param name="watcher">The watcher.</param>
  187. private void DisposeWatcher(FileSystemWatcher watcher)
  188. {
  189. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  190. watcher.EnableRaisingEvents = false;
  191. watcher.Dispose();
  192. var watchers = _fileSystemWatchers.ToList();
  193. watchers.Remove(watcher);
  194. _fileSystemWatchers = new ConcurrentBag<FileSystemWatcher>(watchers);
  195. }
  196. /// <summary>
  197. /// Handles the LibraryChanged event of the Kernel
  198. /// </summary>
  199. /// <param name="sender">The source of the event.</param>
  200. /// <param name="e">The <see cref="MediaBrowser.Controller.Library.ChildrenChangedEventArgs" /> instance containing the event data.</param>
  201. void Instance_LibraryChanged(object sender, ChildrenChangedEventArgs e)
  202. {
  203. if (e.Folder is AggregateFolder && e.HasAddOrRemoveChange)
  204. {
  205. if (e.ItemsRemoved != null)
  206. {
  207. foreach (var item in e.ItemsRemoved.OfType<Folder>())
  208. {
  209. StopWatchingPath(item.Path);
  210. }
  211. }
  212. if (e.ItemsAdded != null)
  213. {
  214. foreach (var item in e.ItemsAdded.OfType<Folder>())
  215. {
  216. StartWatchingPath(item.Path);
  217. }
  218. }
  219. }
  220. }
  221. /// <summary>
  222. /// Handles the Error event of the watcher control.
  223. /// </summary>
  224. /// <param name="sender">The source of the event.</param>
  225. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  226. async void watcher_Error(object sender, ErrorEventArgs e)
  227. {
  228. var ex = e.GetException();
  229. var dw = (FileSystemWatcher) sender;
  230. Logger.ErrorException("Error in Directory watcher for: "+dw.Path, ex);
  231. if (ex.Message.Contains("network name is no longer available"))
  232. {
  233. //Network either dropped or, we are coming out of sleep and it hasn't reconnected yet - wait and retry
  234. Logger.Warn("Network connection lost - will retry...");
  235. var retries = 0;
  236. var success = false;
  237. while (!success && retries < 10)
  238. {
  239. await Task.Delay(500).ConfigureAwait(false);
  240. try
  241. {
  242. dw.EnableRaisingEvents = false;
  243. dw.EnableRaisingEvents = true;
  244. success = true;
  245. }
  246. catch (IOException)
  247. {
  248. Logger.Warn("Network still unavailable...");
  249. retries++;
  250. }
  251. }
  252. if (!success)
  253. {
  254. Logger.Warn("Unable to access network. Giving up.");
  255. DisposeWatcher(dw);
  256. }
  257. }
  258. else
  259. {
  260. if (!ex.Message.Contains("BIOS command limit"))
  261. {
  262. Logger.Info("Attempting to re-start watcher.");
  263. dw.EnableRaisingEvents = false;
  264. dw.EnableRaisingEvents = true;
  265. }
  266. }
  267. }
  268. /// <summary>
  269. /// Handles the Changed event of the watcher control.
  270. /// </summary>
  271. /// <param name="sender">The source of the event.</param>
  272. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  273. void watcher_Changed(object sender, FileSystemEventArgs e)
  274. {
  275. if (e.ChangeType == WatcherChangeTypes.Created && e.Name == "New folder")
  276. {
  277. return;
  278. }
  279. if (_tempIgnoredPaths.ContainsKey(e.FullPath))
  280. {
  281. Logger.Info("Watcher requested to ignore change to " + e.FullPath);
  282. return;
  283. }
  284. Logger.Info("Watcher sees change of type " + e.ChangeType.ToString() + " to " + e.FullPath);
  285. //Since we're watching created, deleted and renamed we always want the parent of the item to be the affected path
  286. var affectedPath = e.FullPath;
  287. _affectedPaths.AddOrUpdate(affectedPath, affectedPath, (key, oldValue) => affectedPath);
  288. lock (_timerLock)
  289. {
  290. if (_updateTimer == null)
  291. {
  292. _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  293. }
  294. else
  295. {
  296. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  297. }
  298. }
  299. }
  300. /// <summary>
  301. /// Timers the stopped.
  302. /// </summary>
  303. /// <param name="stateInfo">The state info.</param>
  304. private async void TimerStopped(object stateInfo)
  305. {
  306. lock (_timerLock)
  307. {
  308. // Extend the timer as long as any of the paths are still being written to.
  309. if (_affectedPaths.Any(p => IsFileLocked(p.Key)))
  310. {
  311. Logger.Info("Timer extended.");
  312. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  313. return;
  314. }
  315. Logger.Info("Timer stopped.");
  316. _updateTimer.Dispose();
  317. _updateTimer = null;
  318. }
  319. var paths = _affectedPaths.Keys.ToList();
  320. _affectedPaths.Clear();
  321. await ProcessPathChanges(paths).ConfigureAwait(false);
  322. }
  323. /// <summary>
  324. /// Try and determine if a file is locked
  325. /// This is not perfect, and is subject to race conditions, so I'd rather not make this a re-usable library method.
  326. /// </summary>
  327. /// <param name="path">The path.</param>
  328. /// <returns><c>true</c> if [is file locked] [the specified path]; otherwise, <c>false</c>.</returns>
  329. private bool IsFileLocked(string path)
  330. {
  331. try
  332. {
  333. var data = FileSystem.GetFileData(path);
  334. if (!data.HasValue || data.Value.IsDirectory)
  335. {
  336. return false;
  337. }
  338. }
  339. catch (IOException)
  340. {
  341. return false;
  342. }
  343. FileStream stream = null;
  344. try
  345. {
  346. stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
  347. }
  348. catch
  349. {
  350. //the file is unavailable because it is:
  351. //still being written to
  352. //or being processed by another thread
  353. //or does not exist (has already been processed)
  354. return true;
  355. }
  356. finally
  357. {
  358. if (stream != null)
  359. stream.Close();
  360. }
  361. //file is not locked
  362. return false;
  363. }
  364. /// <summary>
  365. /// Processes the path changes.
  366. /// </summary>
  367. /// <param name="paths">The paths.</param>
  368. /// <returns>Task.</returns>
  369. private async Task ProcessPathChanges(List<string> paths)
  370. {
  371. var itemsToRefresh = paths.Select(Path.GetDirectoryName)
  372. .Select(GetAffectedBaseItem)
  373. .Where(item => item != null)
  374. .Distinct()
  375. .ToList();
  376. foreach (var p in paths) Logger.Info(p + " reports change.");
  377. // If the root folder changed, run the library task so the user can see it
  378. if (itemsToRefresh.Any(i => i is AggregateFolder))
  379. {
  380. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  381. return;
  382. }
  383. await Task.WhenAll(itemsToRefresh.Select(i => Task.Run(async () =>
  384. {
  385. Logger.Info(i.Name + " (" + i.Path + ") will be refreshed.");
  386. try
  387. {
  388. await i.ChangedExternally().ConfigureAwait(false);
  389. }
  390. catch (IOException ex)
  391. {
  392. // For now swallow and log.
  393. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  394. // Should we remove it from it's parent?
  395. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  396. }
  397. catch (Exception ex)
  398. {
  399. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  400. }
  401. }))).ConfigureAwait(false);
  402. }
  403. /// <summary>
  404. /// Gets the affected base item.
  405. /// </summary>
  406. /// <param name="path">The path.</param>
  407. /// <returns>BaseItem.</returns>
  408. private BaseItem GetAffectedBaseItem(string path)
  409. {
  410. BaseItem item = null;
  411. while (item == null && !string.IsNullOrEmpty(path))
  412. {
  413. item = LibraryManager.RootFolder.FindByPath(path);
  414. path = Path.GetDirectoryName(path);
  415. }
  416. if (item != null)
  417. {
  418. // If the item has been deleted find the first valid parent that still exists
  419. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  420. {
  421. item = item.Parent;
  422. if (item == null)
  423. {
  424. break;
  425. }
  426. }
  427. }
  428. return item;
  429. }
  430. /// <summary>
  431. /// Stops this instance.
  432. /// </summary>
  433. public void Stop()
  434. {
  435. LibraryManager.LibraryChanged -= Instance_LibraryChanged;
  436. FileSystemWatcher watcher;
  437. while (_fileSystemWatchers.TryTake(out watcher))
  438. {
  439. watcher.Changed -= watcher_Changed;
  440. watcher.EnableRaisingEvents = false;
  441. watcher.Dispose();
  442. }
  443. lock (_timerLock)
  444. {
  445. if (_updateTimer != null)
  446. {
  447. _updateTimer.Dispose();
  448. _updateTimer = null;
  449. }
  450. }
  451. _affectedPaths.Clear();
  452. }
  453. /// <summary>
  454. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  455. /// </summary>
  456. public void Dispose()
  457. {
  458. Dispose(true);
  459. GC.SuppressFinalize(this);
  460. }
  461. /// <summary>
  462. /// Releases unmanaged and - optionally - managed resources.
  463. /// </summary>
  464. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  465. protected virtual void Dispose(bool dispose)
  466. {
  467. if (dispose)
  468. {
  469. Stop();
  470. }
  471. }
  472. }
  473. }