jellyfin/Emby.Server.Implementations/IO/LibraryMonitor.cs

480 lines
16 KiB
C#
Raw Normal View History

using System;
2013-02-21 02:33:05 +01:00
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Emby.Server.Implementations.Library;
2016-11-11 05:25:21 +01:00
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
2016-10-25 21:02:04 +02:00
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
2013-02-21 02:33:05 +01:00
namespace Emby.Server.Implementations.IO
2013-02-21 02:33:05 +01:00
{
/// <inheritdoc cref="ILibraryMonitor" />
public sealed class LibraryMonitor : ILibraryMonitor, IDisposable
2013-02-21 02:33:05 +01:00
{
2020-06-06 02:15:56 +02:00
private readonly ILogger<LibraryMonitor> _logger;
private readonly ILibraryManager _libraryManager;
private readonly IServerConfigurationManager _configurationManager;
private readonly IFileSystem _fileSystem;
2013-02-21 02:33:05 +01:00
/// <summary>
2019-11-01 18:38:54 +01:00
/// The file system watchers.
2013-02-21 02:33:05 +01:00
/// </summary>
private readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new(StringComparer.OrdinalIgnoreCase);
2013-02-21 02:33:05 +01:00
/// <summary>
2019-11-01 18:38:54 +01:00
/// The affected paths.
2013-02-21 02:33:05 +01:00
/// </summary>
private readonly List<FileRefresher> _activeRefreshers = [];
2013-02-21 02:33:05 +01:00
/// <summary>
2019-11-01 18:38:54 +01:00
/// A dynamic list of paths that should be ignored. Added to during our own file system modifications.
2013-02-21 02:33:05 +01:00
/// </summary>
private readonly ConcurrentDictionary<string, string> _tempIgnoredPaths = new(StringComparer.OrdinalIgnoreCase);
2013-02-21 02:33:05 +01:00
private bool _disposed;
2021-10-02 19:31:31 +02:00
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="libraryManager">The library manager.</param>
/// <param name="configurationManager">The configuration manager.</param>
/// <param name="fileSystem">The filesystem.</param>
/// <param name="appLifetime">The <see cref="IHostApplicationLifetime"/>.</param>
2021-10-02 19:31:31 +02:00
public LibraryMonitor(
ILogger<LibraryMonitor> logger,
ILibraryManager libraryManager,
IServerConfigurationManager configurationManager,
IFileSystem fileSystem,
IHostApplicationLifetime appLifetime)
2021-10-02 19:31:31 +02:00
{
_libraryManager = libraryManager;
_logger = logger;
_configurationManager = configurationManager;
_fileSystem = fileSystem;
appLifetime.ApplicationStarted.Register(Start);
2013-02-21 02:33:05 +01:00
}
/// <inheritdoc />
public void ReportFileSystemChangeBeginning(string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
_tempIgnoredPaths[path] = path;
}
/// <inheritdoc />
2014-01-29 06:17:58 +01:00
public async void ReportFileSystemChangeComplete(string path, bool refreshPath)
{
ArgumentException.ThrowIfNullOrEmpty(path);
// This is an arbitrary amount of time, but delay it because file system writes often trigger events long after the file was actually written to.
2015-05-24 20:33:28 +02:00
// Seeing long delays in some situations, especially over the network, sometimes up to 45 seconds
2015-06-03 07:30:14 +02:00
// But if we make this delay too high, we risk missing legitimate changes, such as user adding a new file, or hand-editing metadata
2016-07-22 07:17:09 +02:00
await Task.Delay(45000).ConfigureAwait(false);
2014-01-29 06:17:58 +01:00
2021-12-15 18:25:36 +01:00
_tempIgnoredPaths.TryRemove(path, out _);
if (refreshPath)
{
2016-09-15 22:30:46 +02:00
try
{
ReportFileSystemChanged(path);
}
catch (Exception ex)
{
2020-08-31 22:20:19 +02:00
_logger.LogError(ex, "Error in ReportFileSystemChanged for {Path}", path);
2016-09-15 22:30:46 +02:00
}
}
}
2019-01-25 22:41:43 +01:00
private bool IsLibraryMonitorEnabled(BaseItem item)
2014-01-29 21:30:26 +01:00
{
if (item is BasePluginFolder)
{
return false;
}
var options = _libraryManager.GetLibraryOptions(item);
2016-08-24 22:46:26 +02:00
return options is not null && options.EnableRealtimeMonitor;
2014-01-29 21:30:26 +01:00
}
/// <inheritdoc />
2016-08-24 22:46:26 +02:00
public void Start()
2013-02-21 02:33:05 +01:00
{
_libraryManager.ItemAdded += OnLibraryManagerItemAdded;
_libraryManager.ItemRemoved += OnLibraryManagerItemRemoved;
var pathsToWatch = new List<string>();
2013-02-21 02:33:05 +01:00
var paths = _libraryManager
.RootFolder
.Children
2019-01-25 22:41:43 +01:00
.Where(IsLibraryMonitorEnabled)
.OfType<Folder>()
.SelectMany(f => f.PhysicalLocations)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Order();
2013-02-21 02:33:05 +01:00
foreach (var path in paths)
{
if (!ContainsParentFolder(pathsToWatch, path))
{
pathsToWatch.Add(path);
}
}
foreach (var path in pathsToWatch)
{
StartWatchingPath(path);
}
}
2016-08-24 22:46:26 +02:00
private void StartWatching(BaseItem item)
{
2019-01-25 22:41:43 +01:00
if (IsLibraryMonitorEnabled(item))
2016-08-24 22:46:26 +02:00
{
StartWatchingPath(item.Path);
}
}
/// <summary>
/// Handles the ItemRemoved event of the LibraryManager control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
private void OnLibraryManagerItemRemoved(object? sender, ItemChangeEventArgs e)
{
2017-11-26 05:48:12 +01:00
if (e.Parent is AggregateFolder)
{
StopWatchingPath(e.Item.Path);
}
}
/// <summary>
/// Handles the ItemAdded event of the LibraryManager control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
private void OnLibraryManagerItemAdded(object? sender, ItemChangeEventArgs e)
{
2017-11-26 05:48:12 +01:00
if (e.Parent is AggregateFolder)
{
2016-08-24 22:46:26 +02:00
StartWatching(e.Item);
}
}
2013-02-21 02:33:05 +01:00
/// <summary>
/// Examine a list of strings assumed to be file paths to see if it contains a parent of
/// the provided path.
/// </summary>
/// <param name="lst">The LST.</param>
/// <param name="path">The path.</param>
/// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
2021-10-02 19:31:31 +02:00
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <c>null</c>.</exception>
private static bool ContainsParentFolder(IReadOnlyList<string> lst, ReadOnlySpan<char> path)
2013-02-21 02:33:05 +01:00
{
if (path.IsEmpty)
{
throw new ArgumentException("Path can't be empty", nameof(path));
}
2013-02-21 02:33:05 +01:00
path = path.TrimEnd(Path.DirectorySeparatorChar);
foreach (var str in lst)
2013-02-21 02:33:05 +01:00
{
// this should be a little quicker than examining each actual parent folder...
var compare = str.AsSpan().TrimEnd(Path.DirectorySeparatorChar);
2013-02-21 02:33:05 +01:00
if (path.Equals(compare, StringComparison.OrdinalIgnoreCase)
|| (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar))
{
return true;
}
}
return false;
2013-02-21 02:33:05 +01:00
}
/// <summary>
/// Starts the watching path.
/// </summary>
/// <param name="path">The path.</param>
private void StartWatchingPath(string path)
{
if (!Directory.Exists(path))
2017-02-03 21:52:56 +01:00
{
// Seeing a crash in the mono runtime due to an exception being thrown on a different thread
_logger.LogInformation("Skipping realtime monitor for {Path} because the path does not exist", path);
2017-02-03 21:52:56 +01:00
return;
}
// Already being watched
if (_fileSystemWatchers.ContainsKey(path))
{
return;
}
2013-02-21 02:33:05 +01:00
// Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
Task.Run(() =>
{
2014-03-27 20:30:21 +01:00
try
{
var newWatcher = new FileSystemWatcher(path, "*")
{
IncludeSubdirectories = true,
InternalBufferSize = 65536,
NotifyFilter = NotifyFilters.CreationTime |
NotifyFilters.DirectoryName |
NotifyFilters.FileName |
NotifyFilters.LastWrite |
NotifyFilters.Size |
NotifyFilters.Attributes
2014-03-27 20:30:21 +01:00
};
2013-02-21 02:33:05 +01:00
newWatcher.Created += OnWatcherChanged;
newWatcher.Deleted += OnWatcherChanged;
newWatcher.Renamed += OnWatcherChanged;
newWatcher.Changed += OnWatcherChanged;
newWatcher.Error += OnWatcherError;
2013-02-21 02:33:05 +01:00
2013-05-05 15:40:44 +02:00
if (_fileSystemWatchers.TryAdd(path, newWatcher))
{
newWatcher.EnableRaisingEvents = true;
2021-11-09 22:29:33 +01:00
_logger.LogInformation("Watching directory {Path}", path);
2013-05-05 15:40:44 +02:00
}
else
{
2018-09-12 19:26:21 +02:00
DisposeWatcher(newWatcher, false);
2013-05-05 15:40:44 +02:00
}
2013-02-21 02:33:05 +01:00
}
2014-03-27 20:30:21 +01:00
catch (Exception ex)
2013-02-21 02:33:05 +01:00
{
2021-11-09 13:14:31 +01:00
_logger.LogError(ex, "Error watching path: {Path}", path);
2013-02-21 02:33:05 +01:00
}
});
}
/// <summary>
/// Stops the watching path.
/// </summary>
/// <param name="path">The path.</param>
private void StopWatchingPath(string path)
{
if (_fileSystemWatchers.TryGetValue(path, out var watcher))
2013-02-21 02:33:05 +01:00
{
2018-09-12 19:26:21 +02:00
DisposeWatcher(watcher, true);
2013-02-21 02:33:05 +01:00
}
}
/// <summary>
/// Disposes the watcher.
/// </summary>
2018-09-12 19:26:21 +02:00
private void DisposeWatcher(FileSystemWatcher watcher, bool removeFromList)
2013-02-21 02:33:05 +01:00
{
2014-10-13 22:14:53 +02:00
try
{
using (watcher)
{
_logger.LogInformation("Stopping directory watching for path {Path}", watcher.Path);
2013-02-21 02:33:05 +01:00
watcher.Created -= OnWatcherChanged;
watcher.Deleted -= OnWatcherChanged;
watcher.Renamed -= OnWatcherChanged;
watcher.Changed -= OnWatcherChanged;
watcher.Error -= OnWatcherError;
2018-09-12 19:26:21 +02:00
watcher.EnableRaisingEvents = false;
2014-10-13 22:14:53 +02:00
}
}
finally
{
2018-09-12 19:26:21 +02:00
if (removeFromList)
{
_fileSystemWatchers.TryRemove(watcher.Path, out _);
2018-09-12 19:26:21 +02:00
}
2014-10-13 22:14:53 +02:00
}
2013-05-05 15:40:44 +02:00
}
2013-02-21 02:33:05 +01:00
/// <summary>
/// Handles the Error event of the watcher control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
private void OnWatcherError(object sender, ErrorEventArgs e)
2013-02-21 02:33:05 +01:00
{
var ex = e.GetException();
2013-04-28 15:24:20 +02:00
var dw = (FileSystemWatcher)sender;
2013-02-21 02:33:05 +01:00
_logger.LogError(ex, "Error in Directory watcher for: {Path}", dw.Path);
2013-02-21 02:33:05 +01:00
2018-09-12 19:26:21 +02:00
DisposeWatcher(dw, true);
2013-02-21 02:33:05 +01:00
}
/// <summary>
/// Handles the Changed event of the watcher control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
private void OnWatcherChanged(object sender, FileSystemEventArgs e)
{
try
{
ReportFileSystemChanged(e.FullPath);
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception in ReportFileSystemChanged. Path: {FullPath}", e.FullPath);
}
}
/// <inheritdoc />
public void ReportFileSystemChanged(string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
2014-01-29 21:30:26 +01:00
if (IgnorePatterns.ShouldIgnore(path))
{
return;
}
2022-01-04 17:05:36 +01:00
// Ignore certain files, If the parent of an ignored path has a change event, ignore that too
foreach (var i in _tempIgnoredPaths.Keys)
2013-05-20 01:44:05 +02:00
{
if (_fileSystem.AreEqual(i, path)
|| _fileSystem.ContainsSubPath(i, path))
{
_logger.LogDebug("Ignoring change to {Path}", path);
return;
}
// Go up a level
var parent = Path.GetDirectoryName(i);
if (!string.IsNullOrEmpty(parent) && _fileSystem.AreEqual(parent, path))
{
_logger.LogDebug("Ignoring change to {Path}", path);
return;
}
2013-05-20 01:44:05 +02:00
}
CreateRefresher(path);
2013-02-21 02:33:05 +01:00
}
private void CreateRefresher(string path)
2014-04-02 23:55:19 +02:00
{
var parentPath = Path.GetDirectoryName(path);
lock (_activeRefreshers)
2014-04-02 23:55:19 +02:00
{
foreach (var refresher in _activeRefreshers)
2014-04-02 23:55:19 +02:00
{
// Path is already being refreshed
2017-05-04 09:00:52 +02:00
if (_fileSystem.AreEqual(path, refresher.Path))
{
refresher.RestartTimer();
return;
}
// Parent folder is already being refreshed
if (_fileSystem.ContainsSubPath(refresher.Path, path))
2014-04-02 23:55:19 +02:00
{
refresher.AddPath(path);
return;
2014-04-02 23:55:19 +02:00
}
// New path is a parent
if (_fileSystem.ContainsSubPath(path, refresher.Path))
{
refresher.ResetPath(path, null);
return;
}
2014-04-02 23:55:19 +02:00
2016-05-27 05:46:21 +02:00
// They are siblings. Rebase the refresher to the parent folder.
2023-09-18 20:50:05 +02:00
if (parentPath is not null
&& Path.GetDirectoryName(refresher.Path.AsSpan()).Equals(parentPath, StringComparison.Ordinal))
{
refresher.ResetPath(parentPath, path);
return;
}
2013-05-07 20:57:27 +02:00
}
2013-04-28 15:24:20 +02:00
var newRefresher = new FileRefresher(path, _configurationManager, _libraryManager, _logger);
2021-11-15 15:57:07 +01:00
newRefresher.Completed += OnNewRefresherCompleted;
_activeRefreshers.Add(newRefresher);
2013-12-30 03:41:22 +01:00
}
2013-02-21 02:33:05 +01:00
}
private void OnNewRefresherCompleted(object? sender, EventArgs e)
2013-02-21 02:33:05 +01:00
{
if (sender is null)
{
return;
}
var refresher = (FileRefresher)sender;
DisposeRefresher(refresher);
2013-02-21 02:33:05 +01:00
}
/// <summary>
/// Stops this instance.
/// </summary>
public void Stop()
2013-02-21 02:33:05 +01:00
{
_libraryManager.ItemAdded -= OnLibraryManagerItemAdded;
_libraryManager.ItemRemoved -= OnLibraryManagerItemRemoved;
2013-02-21 02:33:05 +01:00
2013-05-05 15:40:44 +02:00
foreach (var watcher in _fileSystemWatchers.Values.ToList())
2013-02-21 02:33:05 +01:00
{
2018-09-12 19:26:21 +02:00
DisposeWatcher(watcher, false);
2013-02-21 02:33:05 +01:00
}
2013-08-13 16:41:45 +02:00
_fileSystemWatchers.Clear();
DisposeRefreshers();
}
private void DisposeRefresher(FileRefresher refresher)
{
lock (_activeRefreshers)
{
2021-11-15 15:57:07 +01:00
refresher.Completed -= OnNewRefresherCompleted;
refresher.Dispose();
_activeRefreshers.Remove(refresher);
}
}
private void DisposeRefreshers()
{
lock (_activeRefreshers)
{
2022-01-04 17:05:36 +01:00
foreach (var refresher in _activeRefreshers)
{
2021-11-15 15:57:07 +01:00
refresher.Completed -= OnNewRefresherCompleted;
refresher.Dispose();
}
_activeRefreshers.Clear();
}
2013-02-21 02:33:05 +01:00
}
/// <inheritdoc />
2013-02-21 02:33:05 +01:00
public void Dispose()
{
2019-02-01 21:56:50 +01:00
if (_disposed)
{
return;
}
Stop();
2019-02-01 21:56:50 +01:00
_disposed = true;
2013-02-21 02:33:05 +01:00
}
}
}