LibraryMonitor.cs 21 KB

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