2
0

LibraryMonitor.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. using MediaBrowser.Common.ScheduledTasks;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Plugins;
  6. using MediaBrowser.Model.Configuration;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Server.Implementations.ScheduledTasks;
  9. using Microsoft.Win32;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using CommonIO;
  18. using MediaBrowser.Controller;
  19. namespace MediaBrowser.Server.Implementations.IO
  20. {
  21. public class LibraryMonitor : ILibraryMonitor
  22. {
  23. /// <summary>
  24. /// The file system watchers
  25. /// </summary>
  26. private readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new ConcurrentDictionary<string, FileSystemWatcher>(StringComparer.OrdinalIgnoreCase);
  27. /// <summary>
  28. /// The affected paths
  29. /// </summary>
  30. private readonly List<FileRefresher> _activeRefreshers = new List<FileRefresher>();
  31. /// <summary>
  32. /// A dynamic list of paths that should be ignored. Added to during our own file sytem modifications.
  33. /// </summary>
  34. private readonly ConcurrentDictionary<string, string> _tempIgnoredPaths = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  35. /// <summary>
  36. /// Any file name ending in any of these will be ignored by the watchers
  37. /// </summary>
  38. private readonly IReadOnlyList<string> _alwaysIgnoreFiles = new List<string>
  39. {
  40. "thumbs.db",
  41. "small.jpg",
  42. "albumart.jpg",
  43. // WMC temp recording directories that will constantly be written to
  44. "TempRec",
  45. "TempSBE"
  46. };
  47. /// <summary>
  48. /// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
  49. /// </summary>
  50. /// <param name="path">The path.</param>
  51. private void TemporarilyIgnore(string path)
  52. {
  53. _tempIgnoredPaths[path] = path;
  54. }
  55. public void ReportFileSystemChangeBeginning(string path)
  56. {
  57. if (string.IsNullOrEmpty(path))
  58. {
  59. throw new ArgumentNullException("path");
  60. }
  61. TemporarilyIgnore(path);
  62. }
  63. public bool IsPathLocked(string path)
  64. {
  65. var lockedPaths = _tempIgnoredPaths.Keys.ToList();
  66. return lockedPaths.Any(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase) || _fileSystem.ContainsSubPath(i, path));
  67. }
  68. public async void ReportFileSystemChangeComplete(string path, bool refreshPath)
  69. {
  70. if (string.IsNullOrEmpty(path))
  71. {
  72. throw new ArgumentNullException("path");
  73. }
  74. // This is an arbitraty amount of time, but delay it because file system writes often trigger events long after the file was actually written to.
  75. // Seeing long delays in some situations, especially over the network, sometimes up to 45 seconds
  76. // But if we make this delay too high, we risk missing legitimate changes, such as user adding a new file, or hand-editing metadata
  77. await Task.Delay(45000).ConfigureAwait(false);
  78. string val;
  79. _tempIgnoredPaths.TryRemove(path, out val);
  80. if (refreshPath)
  81. {
  82. ReportFileSystemChanged(path);
  83. }
  84. }
  85. /// <summary>
  86. /// Gets or sets the logger.
  87. /// </summary>
  88. /// <value>The logger.</value>
  89. private ILogger Logger { get; set; }
  90. /// <summary>
  91. /// Gets or sets the task manager.
  92. /// </summary>
  93. /// <value>The task manager.</value>
  94. private ITaskManager TaskManager { get; set; }
  95. private ILibraryManager LibraryManager { get; set; }
  96. private IServerConfigurationManager ConfigurationManager { get; set; }
  97. private readonly IFileSystem _fileSystem;
  98. private readonly IServerApplicationHost _appHost;
  99. /// <summary>
  100. /// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
  101. /// </summary>
  102. public LibraryMonitor(ILogManager logManager, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager, IFileSystem fileSystem, IServerApplicationHost appHost)
  103. {
  104. if (taskManager == null)
  105. {
  106. throw new ArgumentNullException("taskManager");
  107. }
  108. LibraryManager = libraryManager;
  109. TaskManager = taskManager;
  110. Logger = logManager.GetLogger(GetType().Name);
  111. ConfigurationManager = configurationManager;
  112. _fileSystem = fileSystem;
  113. _appHost = appHost;
  114. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  115. }
  116. /// <summary>
  117. /// Handles the PowerModeChanged event of the SystemEvents control.
  118. /// </summary>
  119. /// <param name="sender">The source of the event.</param>
  120. /// <param name="e">The <see cref="PowerModeChangedEventArgs"/> instance containing the event data.</param>
  121. void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  122. {
  123. Restart();
  124. }
  125. private void Restart()
  126. {
  127. Stop();
  128. Start();
  129. }
  130. private bool EnableLibraryMonitor
  131. {
  132. get
  133. {
  134. switch (ConfigurationManager.Configuration.EnableLibraryMonitor)
  135. {
  136. case AutoOnOff.Auto:
  137. return Environment.OSVersion.Platform == PlatformID.Win32NT;
  138. case AutoOnOff.Enabled:
  139. return true;
  140. default:
  141. return false;
  142. }
  143. }
  144. }
  145. public void Start()
  146. {
  147. if (EnableLibraryMonitor)
  148. {
  149. StartInternal();
  150. }
  151. }
  152. /// <summary>
  153. /// Starts this instance.
  154. /// </summary>
  155. private void StartInternal()
  156. {
  157. LibraryManager.ItemAdded += LibraryManager_ItemAdded;
  158. LibraryManager.ItemRemoved += LibraryManager_ItemRemoved;
  159. var pathsToWatch = new List<string> { LibraryManager.RootFolder.Path };
  160. var paths = LibraryManager
  161. .RootFolder
  162. .Children
  163. .OfType<Folder>()
  164. .SelectMany(f => f.PhysicalLocations)
  165. .Distinct(StringComparer.OrdinalIgnoreCase)
  166. .OrderBy(i => i)
  167. .ToList();
  168. foreach (var path in paths)
  169. {
  170. if (!ContainsParentFolder(pathsToWatch, path))
  171. {
  172. pathsToWatch.Add(path);
  173. }
  174. }
  175. foreach (var path in pathsToWatch)
  176. {
  177. StartWatchingPath(path);
  178. }
  179. }
  180. /// <summary>
  181. /// Handles the ItemRemoved event of the LibraryManager control.
  182. /// </summary>
  183. /// <param name="sender">The source of the event.</param>
  184. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  185. void LibraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
  186. {
  187. if (e.Item.GetParent() is AggregateFolder)
  188. {
  189. StopWatchingPath(e.Item.Path);
  190. }
  191. }
  192. /// <summary>
  193. /// Handles the ItemAdded event of the LibraryManager control.
  194. /// </summary>
  195. /// <param name="sender">The source of the event.</param>
  196. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  197. void LibraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  198. {
  199. if (e.Item.GetParent() is AggregateFolder)
  200. {
  201. StartWatchingPath(e.Item.Path);
  202. }
  203. }
  204. /// <summary>
  205. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  206. /// the provided path.
  207. /// </summary>
  208. /// <param name="lst">The LST.</param>
  209. /// <param name="path">The path.</param>
  210. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  211. /// <exception cref="System.ArgumentNullException">path</exception>
  212. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  213. {
  214. if (string.IsNullOrWhiteSpace(path))
  215. {
  216. throw new ArgumentNullException("path");
  217. }
  218. path = path.TrimEnd(Path.DirectorySeparatorChar);
  219. return lst.Any(str =>
  220. {
  221. //this should be a little quicker than examining each actual parent folder...
  222. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  223. return path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar);
  224. });
  225. }
  226. /// <summary>
  227. /// Starts the watching path.
  228. /// </summary>
  229. /// <param name="path">The path.</param>
  230. private void StartWatchingPath(string path)
  231. {
  232. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  233. Task.Run(() =>
  234. {
  235. try
  236. {
  237. var newWatcher = new FileSystemWatcher(path, "*")
  238. {
  239. IncludeSubdirectories = true
  240. };
  241. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  242. {
  243. newWatcher.InternalBufferSize = 32767;
  244. }
  245. newWatcher.NotifyFilter = NotifyFilters.CreationTime |
  246. NotifyFilters.DirectoryName |
  247. NotifyFilters.FileName |
  248. NotifyFilters.LastWrite |
  249. NotifyFilters.Size |
  250. NotifyFilters.Attributes;
  251. newWatcher.Created += watcher_Changed;
  252. newWatcher.Deleted += watcher_Changed;
  253. newWatcher.Renamed += watcher_Changed;
  254. newWatcher.Changed += watcher_Changed;
  255. newWatcher.Error += watcher_Error;
  256. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  257. {
  258. newWatcher.EnableRaisingEvents = true;
  259. Logger.Info("Watching directory " + path);
  260. }
  261. else
  262. {
  263. Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary.", path);
  264. newWatcher.Dispose();
  265. }
  266. }
  267. catch (Exception ex)
  268. {
  269. Logger.ErrorException("Error watching path: {0}", ex, path);
  270. }
  271. });
  272. }
  273. /// <summary>
  274. /// Stops the watching path.
  275. /// </summary>
  276. /// <param name="path">The path.</param>
  277. private void StopWatchingPath(string path)
  278. {
  279. FileSystemWatcher watcher;
  280. if (_fileSystemWatchers.TryGetValue(path, out watcher))
  281. {
  282. DisposeWatcher(watcher);
  283. }
  284. }
  285. /// <summary>
  286. /// Disposes the watcher.
  287. /// </summary>
  288. /// <param name="watcher">The watcher.</param>
  289. private void DisposeWatcher(FileSystemWatcher watcher)
  290. {
  291. try
  292. {
  293. using (watcher)
  294. {
  295. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  296. watcher.EnableRaisingEvents = false;
  297. }
  298. }
  299. catch
  300. {
  301. }
  302. finally
  303. {
  304. RemoveWatcherFromList(watcher);
  305. }
  306. }
  307. /// <summary>
  308. /// Removes the watcher from list.
  309. /// </summary>
  310. /// <param name="watcher">The watcher.</param>
  311. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  312. {
  313. FileSystemWatcher removed;
  314. _fileSystemWatchers.TryRemove(watcher.Path, out removed);
  315. }
  316. /// <summary>
  317. /// Handles the Error event of the watcher control.
  318. /// </summary>
  319. /// <param name="sender">The source of the event.</param>
  320. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  321. void watcher_Error(object sender, ErrorEventArgs e)
  322. {
  323. var ex = e.GetException();
  324. var dw = (FileSystemWatcher)sender;
  325. Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
  326. DisposeWatcher(dw);
  327. if (ConfigurationManager.Configuration.EnableLibraryMonitor == AutoOnOff.Auto)
  328. {
  329. Logger.Info("Disabling realtime monitor to prevent future instability");
  330. ConfigurationManager.Configuration.EnableLibraryMonitor = AutoOnOff.Disabled;
  331. Stop();
  332. }
  333. }
  334. /// <summary>
  335. /// Handles the Changed event of the watcher control.
  336. /// </summary>
  337. /// <param name="sender">The source of the event.</param>
  338. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  339. void watcher_Changed(object sender, FileSystemEventArgs e)
  340. {
  341. try
  342. {
  343. Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
  344. ReportFileSystemChanged(e.FullPath);
  345. }
  346. catch (Exception ex)
  347. {
  348. Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath);
  349. }
  350. }
  351. public void ReportFileSystemChanged(string path)
  352. {
  353. if (string.IsNullOrEmpty(path))
  354. {
  355. throw new ArgumentNullException("path");
  356. }
  357. var filename = Path.GetFileName(path);
  358. var monitorPath = !(!string.IsNullOrEmpty(filename) && _alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase));
  359. // Ignore certain files
  360. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  361. // If the parent of an ignored path has a change event, ignore that too
  362. if (tempIgnorePaths.Any(i =>
  363. {
  364. if (string.Equals(i, path, StringComparison.OrdinalIgnoreCase))
  365. {
  366. Logger.Debug("Ignoring change to {0}", path);
  367. return true;
  368. }
  369. if (_fileSystem.ContainsSubPath(i, path))
  370. {
  371. Logger.Debug("Ignoring change to {0}", path);
  372. return true;
  373. }
  374. // Go up a level
  375. var parent = Path.GetDirectoryName(i);
  376. if (!string.IsNullOrEmpty(parent))
  377. {
  378. if (string.Equals(parent, path, StringComparison.OrdinalIgnoreCase))
  379. {
  380. Logger.Debug("Ignoring change to {0}", path);
  381. return true;
  382. }
  383. }
  384. return false;
  385. }))
  386. {
  387. monitorPath = false;
  388. }
  389. if (monitorPath)
  390. {
  391. // Avoid implicitly captured closure
  392. CreateRefresher(path);
  393. }
  394. }
  395. private void CreateRefresher(string path)
  396. {
  397. var parentPath = Path.GetDirectoryName(path);
  398. lock (_activeRefreshers)
  399. {
  400. var refreshers = _activeRefreshers.ToList();
  401. foreach (var refresher in refreshers)
  402. {
  403. // Path is already being refreshed
  404. if (string.Equals(path, refresher.Path, StringComparison.Ordinal))
  405. {
  406. refresher.RestartTimer();
  407. return;
  408. }
  409. // Parent folder is already being refreshed
  410. if (_fileSystem.ContainsSubPath(refresher.Path, path))
  411. {
  412. refresher.AddPath(path);
  413. return;
  414. }
  415. // New path is a parent
  416. if (_fileSystem.ContainsSubPath(path, refresher.Path))
  417. {
  418. refresher.ResetPath(path, null);
  419. return;
  420. }
  421. // They are siblings. Rebase the refresher to the parent folder.
  422. if (string.Equals(parentPath, Path.GetDirectoryName(refresher.Path), StringComparison.Ordinal))
  423. {
  424. refresher.ResetPath(parentPath, path);
  425. return;
  426. }
  427. }
  428. var newRefresher = new FileRefresher(path, _fileSystem, ConfigurationManager, LibraryManager, TaskManager, Logger);
  429. newRefresher.Completed += NewRefresher_Completed;
  430. _activeRefreshers.Add(newRefresher);
  431. }
  432. }
  433. private void NewRefresher_Completed(object sender, EventArgs e)
  434. {
  435. var refresher = (FileRefresher)sender;
  436. DisposeRefresher(refresher);
  437. }
  438. /// <summary>
  439. /// Stops this instance.
  440. /// </summary>
  441. public void Stop()
  442. {
  443. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  444. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  445. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  446. {
  447. watcher.Created -= watcher_Changed;
  448. watcher.Deleted -= watcher_Changed;
  449. watcher.Renamed -= watcher_Changed;
  450. watcher.Changed -= watcher_Changed;
  451. try
  452. {
  453. watcher.EnableRaisingEvents = false;
  454. }
  455. catch (InvalidOperationException)
  456. {
  457. // Seeing this under mono on linux sometimes
  458. // Collection was modified; enumeration operation may not execute.
  459. }
  460. watcher.Dispose();
  461. }
  462. _fileSystemWatchers.Clear();
  463. DisposeRefreshers();
  464. }
  465. private void DisposeRefresher(FileRefresher refresher)
  466. {
  467. lock (_activeRefreshers)
  468. {
  469. refresher.Dispose();
  470. _activeRefreshers.Remove(refresher);
  471. }
  472. }
  473. private void DisposeRefreshers()
  474. {
  475. lock (_activeRefreshers)
  476. {
  477. foreach (var refresher in _activeRefreshers.ToList())
  478. {
  479. refresher.Dispose();
  480. }
  481. _activeRefreshers.Clear();
  482. }
  483. }
  484. /// <summary>
  485. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  486. /// </summary>
  487. public void Dispose()
  488. {
  489. Dispose(true);
  490. GC.SuppressFinalize(this);
  491. }
  492. /// <summary>
  493. /// Releases unmanaged and - optionally - managed resources.
  494. /// </summary>
  495. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  496. protected virtual void Dispose(bool dispose)
  497. {
  498. if (dispose)
  499. {
  500. Stop();
  501. }
  502. }
  503. }
  504. public class LibraryMonitorStartup : IServerEntryPoint
  505. {
  506. private readonly ILibraryMonitor _monitor;
  507. public LibraryMonitorStartup(ILibraryMonitor monitor)
  508. {
  509. _monitor = monitor;
  510. }
  511. public void Run()
  512. {
  513. _monitor.Start();
  514. }
  515. public void Dispose()
  516. {
  517. }
  518. }
  519. }