jellyfin/MediaBrowser.Server.Implementations/IO/DirectoryWatchers.cs

605 lines
21 KiB
C#
Raw Normal View History

2013-03-04 06:43:06 +01:00
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Controller.Configuration;
2013-02-21 02:33:05 +01:00
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.IO;
2013-02-21 02:33:05 +01:00
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Logging;
using MediaBrowser.Server.Implementations.ScheduledTasks;
2013-02-21 02:33:05 +01:00
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.IO
2013-02-21 02:33:05 +01:00
{
/// <summary>
/// Class DirectoryWatchers
/// </summary>
public class DirectoryWatchers : IDirectoryWatchers
2013-02-21 02:33:05 +01:00
{
/// <summary>
/// The file system watchers
/// </summary>
2013-05-08 20:12:55 +02:00
private readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new ConcurrentDictionary<string,FileSystemWatcher>(StringComparer.OrdinalIgnoreCase);
2013-02-21 02:33:05 +01:00
/// <summary>
/// The update timer
/// </summary>
private Timer _updateTimer;
2013-02-21 02:33:05 +01:00
/// <summary>
/// The affected paths
/// </summary>
private readonly ConcurrentDictionary<string, string> _affectedPaths = new ConcurrentDictionary<string, string>();
2013-02-21 02:33:05 +01:00
/// <summary>
/// A dynamic list of paths that should be ignored. Added to during our own file sytem modifications.
/// </summary>
2013-04-28 15:24:20 +02:00
private readonly ConcurrentDictionary<string, string> _tempIgnoredPaths = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
2013-02-21 02:33:05 +01:00
/// <summary>
/// Any file name ending in any of these will be ignored by the watchers
/// </summary>
private readonly IReadOnlyList<string> _alwaysIgnoreFiles = new List<string> { "thumbs.db", "small.jpg", "albumart.jpg" };
2013-02-21 02:33:05 +01:00
/// <summary>
/// The timer lock
/// </summary>
private readonly object _timerLock = new object();
2013-02-21 02:33:05 +01:00
/// <summary>
/// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
/// </summary>
/// <param name="path">The path.</param>
public void TemporarilyIgnore(string path)
{
_tempIgnoredPaths[path] = path;
2013-02-21 02:33:05 +01:00
}
/// <summary>
/// Removes the temp ignore.
/// </summary>
/// <param name="path">The path.</param>
public async void RemoveTempIgnore(string path)
2013-02-21 02:33:05 +01:00
{
// This is an arbitraty amount of time, but delay it because file system writes often trigger events after RemoveTempIgnore has been called.
2013-07-12 21:56:40 +02:00
await Task.Delay(1000).ConfigureAwait(false);
2013-02-21 02:33:05 +01:00
string val;
_tempIgnoredPaths.TryRemove(path, out val);
2013-02-21 02:33:05 +01:00
}
/// <summary>
/// Gets or sets the logger.
/// </summary>
/// <value>The logger.</value>
private ILogger Logger { get; set; }
2013-02-23 08:57:11 +01:00
/// <summary>
/// Gets or sets the task manager.
/// </summary>
/// <value>The task manager.</value>
private ITaskManager TaskManager { get; set; }
private ILibraryManager LibraryManager { get; set; }
2013-03-04 06:43:06 +01:00
private IServerConfigurationManager ConfigurationManager { get; set; }
2013-02-21 02:33:05 +01:00
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryWatchers" /> class.
/// </summary>
2013-03-04 06:43:06 +01:00
public DirectoryWatchers(ILogManager logManager, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager)
2013-02-21 02:33:05 +01:00
{
2013-02-23 08:57:11 +01:00
if (taskManager == null)
{
throw new ArgumentNullException("taskManager");
}
2013-02-21 21:26:35 +01:00
LibraryManager = libraryManager;
2013-02-23 08:57:11 +01:00
TaskManager = taskManager;
2013-03-04 06:43:06 +01:00
Logger = logManager.GetLogger("DirectoryWatchers");
ConfigurationManager = configurationManager;
2013-02-21 02:33:05 +01:00
}
2013-04-28 15:24:20 +02:00
2013-02-21 02:33:05 +01:00
/// <summary>
/// Starts this instance.
/// </summary>
public void Start()
2013-02-21 02:33:05 +01:00
{
LibraryManager.ItemAdded += LibraryManager_ItemAdded;
LibraryManager.ItemRemoved += LibraryManager_ItemRemoved;
var pathsToWatch = new List<string> { LibraryManager.RootFolder.Path };
2013-02-21 02:33:05 +01:00
var paths = LibraryManager.RootFolder.Children.OfType<Folder>()
2013-02-21 02:33:05 +01:00
.SelectMany(f =>
{
try
{
// Accessing ResolveArgs could involve file system access
return f.ResolveArgs.PhysicalLocations;
}
catch (IOException)
{
2013-04-28 15:24:20 +02:00
return new string[] { };
2013-02-21 02:33:05 +01:00
}
})
.Where(Path.IsPathRooted);
foreach (var path in paths)
{
if (!ContainsParentFolder(pathsToWatch, path))
{
pathsToWatch.Add(path);
}
}
foreach (var path in pathsToWatch)
{
StartWatchingPath(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>
void LibraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
{
if (e.Item.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>
void LibraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
{
if (e.Item.Parent is AggregateFolder)
{
StartWatchingPath(e.Item.Path);
}
}
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>
/// <exception cref="System.ArgumentNullException">path</exception>
private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
path = path.TrimEnd(Path.DirectorySeparatorChar);
return lst.Any(str =>
{
//this should be a little quicker than examining each actual parent folder...
var compare = str.TrimEnd(Path.DirectorySeparatorChar);
return (path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar));
});
}
/// <summary>
/// Starts the watching path.
/// </summary>
/// <param name="path">The path.</param>
private void StartWatchingPath(string path)
{
// 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(() =>
{
var newWatcher = new FileSystemWatcher(path, "*") { IncludeSubdirectories = true, InternalBufferSize = 32767 };
newWatcher.Created += watcher_Changed;
newWatcher.Deleted += watcher_Changed;
newWatcher.Renamed += watcher_Changed;
newWatcher.Changed += watcher_Changed;
newWatcher.Error += watcher_Error;
try
{
2013-05-05 15:40:44 +02:00
if (_fileSystemWatchers.TryAdd(path, newWatcher))
{
newWatcher.EnableRaisingEvents = true;
Logger.Info("Watching directory " + path);
}
else
{
Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary." + path);
newWatcher.Dispose();
}
2013-02-21 02:33:05 +01:00
}
catch (IOException ex)
{
Logger.ErrorException("Error watching path: {0}", ex, path);
}
catch (PlatformNotSupportedException ex)
{
Logger.ErrorException("Error watching path: {0}", ex, path);
}
});
}
/// <summary>
/// Stops the watching path.
/// </summary>
/// <param name="path">The path.</param>
private void StopWatchingPath(string path)
{
2013-05-05 15:40:44 +02:00
FileSystemWatcher watcher;
2013-02-21 02:33:05 +01:00
2013-05-05 15:40:44 +02:00
if (_fileSystemWatchers.TryGetValue(path, out watcher))
2013-02-21 02:33:05 +01:00
{
DisposeWatcher(watcher);
}
}
/// <summary>
/// Disposes the watcher.
/// </summary>
/// <param name="watcher">The watcher.</param>
private void DisposeWatcher(FileSystemWatcher watcher)
{
Logger.Info("Stopping directory watching for path {0}", watcher.Path);
watcher.EnableRaisingEvents = false;
watcher.Dispose();
2013-05-05 15:40:44 +02:00
RemoveWatcherFromList(watcher);
}
2013-02-21 02:33:05 +01:00
2013-05-05 15:40:44 +02:00
/// <summary>
/// Removes the watcher from list.
/// </summary>
/// <param name="watcher">The watcher.</param>
private void RemoveWatcherFromList(FileSystemWatcher watcher)
{
FileSystemWatcher removed;
2013-02-21 02:33:05 +01:00
2013-05-05 15:40:44 +02:00
_fileSystemWatchers.TryRemove(watcher.Path, out removed);
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>
async void watcher_Error(object sender, ErrorEventArgs e)
{
var ex = e.GetException();
2013-04-28 15:24:20 +02:00
var dw = (FileSystemWatcher)sender;
2013-02-21 02:33:05 +01:00
2013-04-28 15:24:20 +02:00
Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
2013-02-21 02:33:05 +01:00
2013-04-28 15:24:20 +02:00
//Network either dropped or, we are coming out of sleep and it hasn't reconnected yet - wait and retry
var retries = 0;
var success = false;
while (!success && retries < 10)
2013-02-21 02:33:05 +01:00
{
2013-04-28 15:24:20 +02:00
await Task.Delay(500).ConfigureAwait(false);
2013-02-21 02:33:05 +01:00
2013-04-28 15:24:20 +02:00
try
{
dw.EnableRaisingEvents = false;
dw.EnableRaisingEvents = true;
success = true;
2013-02-21 02:33:05 +01:00
}
2013-05-05 15:40:44 +02:00
catch (ObjectDisposedException)
{
RemoveWatcherFromList(dw);
return;
}
2013-04-28 15:24:20 +02:00
catch (IOException)
2013-02-21 02:33:05 +01:00
{
2013-04-28 15:24:20 +02:00
Logger.Warn("Network still unavailable...");
retries++;
2013-02-21 02:33:05 +01:00
}
catch (ApplicationException)
{
Logger.Warn("Network still unavailable...");
retries++;
}
2013-02-21 02:33:05 +01:00
}
2013-04-28 15:24:20 +02:00
if (!success)
2013-02-21 02:33:05 +01:00
{
2013-04-28 15:24:20 +02:00
Logger.Warn("Unable to access network. Giving up.");
DisposeWatcher(dw);
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>
void watcher_Changed(object sender, FileSystemEventArgs e)
{
var name = e.Name;
// Ignore certain files
if (_alwaysIgnoreFiles.Contains(name, StringComparer.OrdinalIgnoreCase))
{
return;
}
var nameFromFullPath = Path.GetFileName(e.FullPath);
// Ignore certain files
if (!string.IsNullOrEmpty(nameFromFullPath) && _alwaysIgnoreFiles.Contains(nameFromFullPath, StringComparer.OrdinalIgnoreCase))
{
return;
}
// Ignore when someone manually creates a new folder
if (e.ChangeType == WatcherChangeTypes.Created && name == "New folder")
2013-02-21 02:33:05 +01:00
{
return;
}
2013-05-20 01:44:05 +02:00
var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
if (e.ChangeType == WatcherChangeTypes.Changed)
{
// If the parent of an ignored path has a change event, ignore that too
2013-06-10 03:47:12 +02:00
if (tempIgnorePaths.Any(i => string.Equals(Path.GetDirectoryName(i), e.FullPath, StringComparison.OrdinalIgnoreCase) || string.Equals(i, e.FullPath, StringComparison.OrdinalIgnoreCase)))
2013-05-20 01:44:05 +02:00
{
return;
}
}
if (tempIgnorePaths.Contains(e.FullPath, StringComparer.OrdinalIgnoreCase))
2013-02-21 02:33:05 +01:00
{
2013-05-20 01:44:05 +02:00
Logger.Debug("Watcher requested to ignore change to " + e.FullPath);
2013-02-21 02:33:05 +01:00
return;
}
Logger.Info("Watcher sees change of type " + e.ChangeType + " to " + e.FullPath);
2013-02-21 02:33:05 +01:00
//Since we're watching created, deleted and renamed we always want the parent of the item to be the affected path
var affectedPath = e.FullPath;
_affectedPaths.AddOrUpdate(affectedPath, affectedPath, (key, oldValue) => affectedPath);
2013-02-21 02:33:05 +01:00
lock (_timerLock)
2013-02-21 02:33:05 +01:00
{
if (_updateTimer == null)
2013-02-21 02:33:05 +01:00
{
_updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
2013-02-21 02:33:05 +01:00
}
else
{
_updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
2013-02-21 02:33:05 +01:00
}
}
}
/// <summary>
/// Timers the stopped.
/// </summary>
/// <param name="stateInfo">The state info.</param>
private async void TimerStopped(object stateInfo)
{
lock (_timerLock)
2013-02-21 02:33:05 +01:00
{
// Extend the timer as long as any of the paths are still being written to.
2013-05-14 15:49:40 +02:00
if (_affectedPaths.Any(p => IsFileLocked(p.Key)))
2013-02-21 02:33:05 +01:00
{
Logger.Info("Timer extended.");
_updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
2013-02-21 02:33:05 +01:00
return;
}
Logger.Info("Timer stopped.");
if (_updateTimer != null)
{
_updateTimer.Dispose();
_updateTimer = null;
}
2013-02-21 02:33:05 +01:00
}
var paths = _affectedPaths.Keys.ToList();
_affectedPaths.Clear();
2013-02-21 02:33:05 +01:00
await ProcessPathChanges(paths).ConfigureAwait(false);
}
/// <summary>
/// Try and determine if a file is locked
/// This is not perfect, and is subject to race conditions, so I'd rather not make this a re-usable library method.
/// </summary>
/// <param name="path">The path.</param>
/// <returns><c>true</c> if [is file locked] [the specified path]; otherwise, <c>false</c>.</returns>
private bool IsFileLocked(string path)
{
try
{
var data = FileSystem.GetFileSystemInfo(path);
2013-02-21 02:33:05 +01:00
2013-05-14 15:49:40 +02:00
if (!data.Exists
|| data.Attributes.HasFlag(FileAttributes.Directory)
|| data.Attributes.HasFlag(FileAttributes.ReadOnly))
2013-02-21 02:33:05 +01:00
{
return false;
}
}
catch (IOException)
{
return false;
}
try
{
2013-05-07 20:57:27 +02:00
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
//file is not locked
return false;
}
2013-02-21 02:33:05 +01:00
}
catch (DirectoryNotFoundException)
{
return false;
}
catch (FileNotFoundException)
{
return false;
}
catch (IOException)
2013-02-21 02:33:05 +01:00
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
2013-05-08 20:12:55 +02:00
Logger.Debug("{0} is locked.", path);
2013-02-21 02:33:05 +01:00
return true;
}
catch
{
return false;
}
2013-02-21 02:33:05 +01:00
}
/// <summary>
/// Processes the path changes.
/// </summary>
/// <param name="paths">The paths.</param>
/// <returns>Task.</returns>
private async Task ProcessPathChanges(List<string> paths)
{
var itemsToRefresh = paths.Select(Path.GetDirectoryName)
.Select(GetAffectedBaseItem)
.Where(item => item != null)
.Distinct()
.ToList();
foreach (var p in paths) Logger.Info(p + " reports change.");
// If the root folder changed, run the library task so the user can see it
if (itemsToRefresh.Any(i => i is AggregateFolder))
{
2013-02-23 08:57:11 +01:00
TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
2013-02-21 02:33:05 +01:00
return;
}
await Task.WhenAll(itemsToRefresh.Select(i => Task.Run(async () =>
{
Logger.Info(i.Name + " (" + i.Path + ") will be refreshed.");
2013-04-28 15:24:20 +02:00
2013-02-21 02:33:05 +01:00
try
{
await i.ChangedExternally().ConfigureAwait(false);
}
catch (IOException ex)
{
// For now swallow and log.
// Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
// Should we remove it from it's parent?
Logger.ErrorException("Error refreshing {0}", ex, i.Name);
}
2013-03-27 23:13:46 +01:00
catch (Exception ex)
{
Logger.ErrorException("Error refreshing {0}", ex, i.Name);
}
2013-02-21 02:33:05 +01:00
}))).ConfigureAwait(false);
}
/// <summary>
/// Gets the affected base item.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>BaseItem.</returns>
private BaseItem GetAffectedBaseItem(string path)
{
BaseItem item = null;
while (item == null && !string.IsNullOrEmpty(path))
{
item = LibraryManager.RootFolder.FindByPath(path);
2013-02-21 02:33:05 +01:00
path = Path.GetDirectoryName(path);
}
if (item != null)
{
// If the item has been deleted find the first valid parent that still exists
while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
{
item = item.Parent;
if (item == null)
{
break;
}
}
}
return item;
}
/// <summary>
/// Stops this instance.
/// </summary>
public void Stop()
2013-02-21 02:33:05 +01:00
{
LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
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
{
watcher.Changed -= watcher_Changed;
watcher.EnableRaisingEvents = false;
watcher.Dispose();
}
lock (_timerLock)
2013-02-21 02:33:05 +01:00
{
if (_updateTimer != null)
2013-02-21 02:33:05 +01:00
{
_updateTimer.Dispose();
_updateTimer = null;
2013-02-21 02:33:05 +01:00
}
2013-04-28 15:24:20 +02:00
}
2013-02-21 02:33:05 +01:00
2013-08-13 16:41:45 +02:00
_fileSystemWatchers.Clear();
_affectedPaths.Clear();
2013-02-21 02:33:05 +01:00
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
Stop();
}
}
}
}