LibraryMonitor.cs 21 KB

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