Address various issues in FileSystemWatcher

- On Linux, FileSystemWatcher is built on top of inotify, which has various limits configured in the system for how many instances and watches can be created.  When these limits are hit, exceptions are generated, but the Linux-provided error messages are cryptic about what the problem is.  This change adds better error messages for those cases.  It also ensures that errors regarding watch limits always come out of OnError rather than sometimes being thrown synchronously from EnableRaisingEvents and other times coming out asynchronously.
- As part of fixing that, I noticed that we had some reliability issues around marking the instance as enabled.  I fixed this up to ensure that we only mark the instance as enabled when we've created everything we need to successfully launch it.
- While doing that, I noticed that on OS X, if we restart an FSW, we were unnecessarily re-creating a delegate.  I changed it to avoid the unnecessary allocation.
- And while doing that, I also noticed that we we had a bad exception message when constructing an FSW with something other than a directory.  I fixed the error message.
- I added tests for all these things.


Commit migrated from https://github.com/dotnet/corefx/commit/57cf111281a22feafb83854789680680da3cab50
This commit is contained in:
stephentoub committed 2015-09-02 16:51:12 -04:00
1 parent 873d3bb24a
commit 2dd748811e
6 files changed
+211 -26

No files matched your search

@@ -174,4 +174,19 @@
<data name="Argument_InvalidPathChars" xml:space="preserve">
<value>Illegal characters in path.</value>
</data>
<data name="IOException_INotifyInstanceSystemLimitExceeded" xml:space="preserve">
<value>The system limit on the number of inotify instances has been reached.</value>
</data>
<data name="IOException_INotifyInstanceUserLimitExceeded_Value" xml:space="preserve">
<value>The configured user limit ({0}) on the number of inotify instances has been reached.</value>
</data>
<data name="IOException_INotifyWatchesUserLimitExceeded_Value" xml:space="preserve">
<value>The configured user limit ({0}) on the number of inotify watches has been reached.</value>
</data>
<data name="IOException_INotifyInstanceUserLimitExceeded" xml:space="preserve">
<value>The configured user limit on the number of inotify instances has been reached.</value>
</data>
<data name="IOException_INotifyWatchesUserLimitExceeded" xml:space="preserve">
<value>The configured user limit on the number of inotify watches has been reached.</value>
</data>
</root>
@@ -31,8 +31,24 @@ namespace System.IO
SafeFileHandle handle;
try { } finally
{
int fd;
Interop.CheckIo(fd = Interop.libc.inotify_init());
int fd = Interop.libc.inotify_init();
if (fd == -1)
{
Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
switch (error.Error)
{
case Interop.Error.EMFILE:
string maxValue = ReadMaxUserLimit(MaxUserInstancesPath);
string message = !string.IsNullOrEmpty(maxValue) ?
SR.Format(SR.IOException_INotifyInstanceUserLimitExceeded_Value, maxValue) :
SR.IOException_INotifyInstanceUserLimitExceeded;
throw new IOException(message, error.RawErrno);
case Interop.Error.ENFILE:
throw new IOException(SR.IOException_INotifyInstanceSystemLimitExceeded, error.RawErrno);
default:
throw Interop.GetExceptionForIoErrno(error);
}
}
handle = new SafeFileHandle((IntPtr)fd, ownsHandle: true);
}
@@ -44,15 +60,18 @@ namespace System.IO
// Start running. All state associated with the watch operation is stored in a separate object; this is done
// to avoid race conditions that could result if the users quickly starts/stops/starts/stops/etc. causing multiple
// active operations to all be outstanding at the same time.
new RunningInstance(
var runner = new RunningInstance(
this, handle, _directory,
IncludeSubdirectories, TranslateFilters(NotifyFilter), cancellation.Token);
// Now that we've started running successfully, store the cancellation object and mark the instance
// as running. We wait to store the cancellation token so that if there was a failure, StartRaisingEvents
// Now that we've created the runner, store the cancellation object and mark the instance
// as running. We wait to do this so that if there was a failure, StartRaisingEvents
// may be called to try again without first having to call StopRaisingEvents.
_cancellation = cancellation;
_enabled = true;
// Start the runner
runner.Start();
}
catch
{
@@ -67,13 +86,14 @@ namespace System.IO
/// <summary>Cancels the currently running watch operation if there is one.</summary>
private void StopRaisingEvents()
{
_enabled = false;
// If there's an active cancellation token, cancel and release it.
// The cancellation token and the processing task respond to cancellation
// to handle all other cleanup.
var cts = _cancellation;
if (cts != null)
{
_enabled = false;
_cancellation = null;
cts.Cancel();
}
@@ -92,12 +112,27 @@ namespace System.IO
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Path to the procfs file that contains the maximum number of inotify instances an individual user may create.</summary>
private const string MaxUserInstancesPath = "/proc/sys/fs/inotify/max_user_instances";
/// <summary>Path to the procfs file that contains the maximum number of inotify watches an individual user may create.</summary>
private const string MaxUserWatchesPath = "/proc/sys/fs/inotify/max_user_watches";
/// <summary>
/// Cancellation for the currently running watch operation.
/// This is non-null if an operation has been started and null if stopped.
/// </summary>
private CancellationTokenSource _cancellation;
/// <summary>Reads the value of a max user limit path from procfs.</summary>
/// <param name="path">The path to read.</param>
/// <returns>The value read, or "0" if a failure occurred.</returns>
private static string ReadMaxUserLimit(string path)
{
try { return File.ReadAllText(path).Trim(); }
catch { return null; }
}
/// <summary>
/// Maps the FileSystemWatcher's NotifyFilters enumeration to the
/// corresponding Interop.libc.NotifyEvents values.
@@ -257,7 +292,10 @@ namespace System.IO
// mapping in a dictionary; this is needed in order to be able to determine the containing directory
// for all notifications so that we can reconstruct the full path.
AddDirectoryWatchUnlocked(null, directoryPath);
}
internal void Start()
{
// Schedule a task to read from the inotify queue and process the events.
Task.Factory.StartNew(obj => ((RunningInstance)obj).ProcessEvents(),
this, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
@@ -295,7 +333,7 @@ namespace System.IO
/// <summary>Adds a watch on a directory to the existing inotify handle.</summary>
/// <param name="parent">The parent directory entry.</param>
/// <param name="directoryName">The new directory path to monitor, relative to the root.</param>
private WatchedDirectory AddDirectoryWatchUnlocked(WatchedDirectory parent, string directoryName)
private void AddDirectoryWatchUnlocked(WatchedDirectory parent, string directoryName)
{
string fullPath = parent != null ? parent.GetPath(false, directoryName) : directoryName;
@@ -304,7 +342,7 @@ namespace System.IO
if ((Interop.Sys.LStat(fullPath, out status) == 0) &&
((status.Mode & (uint)Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFLNK))
{
return null;
return;
}
// Add a watch for the full path. If the path is already being watched, this will return
@@ -314,7 +352,36 @@ namespace System.IO
int wd = (int)SysCall(
(fd, path, thisRef) => Interop.libc.inotify_add_watch(fd, path, (uint)(thisRef._notifyFilters | Interop.libc.NotifyEvents.IN_DONT_FOLLOW | Interop.libc.NotifyEvents.IN_EXCL_UNLINK)),
fullPath,
this);
this,
checkErrors: false);
if (wd == -1)
{
// If we get an error when trying to add the watch, don't let that tear down processing. Instead,
// raise the Error event with the exception and let the user decide how to handle it.
Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
Exception exc;
if (error.Error == Interop.Error.ENOSPC)
{
string maxValue = ReadMaxUserLimit(MaxUserWatchesPath);
string message = !string.IsNullOrEmpty(maxValue) ?
SR.Format(SR.IOException_INotifyWatchesUserLimitExceeded_Value, maxValue) :
SR.IOException_INotifyWatchesUserLimitExceeded;
exc = new IOException(message, error.RawErrno);
}
else
{
exc = Interop.GetExceptionForIoErrno(error, fullPath);
}
FileSystemWatcher watcher;
if (_weakWatcher.TryGetTarget(out watcher))
{
watcher.OnError(new ErrorEventArgs(exc));
}
return;
}
// Then store the path information into our map.
WatchedDirectory directoryEntry;
@@ -375,8 +442,6 @@ namespace System.IO
// this.Children, so we don't have to / shouldn't also do it here.
}
}
return directoryEntry;
}
/// <summary>Removes the watched directory from our state, and optionally removes the inotify watch itself.</summary>
@@ -782,12 +847,13 @@ namespace System.IO
/// <param name="sysCall">A delegate that invokes the system call. It's passed the associated file descriptor and should return the result.</param>
/// <param name="arg1">The first argument to be passed to the system call, after the file descriptor.</param>
/// <param name="arg2">The second argument to be passed to the system call.</param>
/// <param name="checkErrors">true to validate the result of the <paramref name="sysCall"/>; false to leave that responsibility to the caller.</param>
/// <returns>The return value of the system call.</returns>
/// <remarks>
/// Arguments are expected to be passed via <paramref name="arg1"/> and <paramref name="arg2"/>
/// so as to avoid delegate and closure allocations at the call sites.
/// </remarks>
private long SysCall<TArg1, TArg2>(Func<int, TArg1, TArg2, long> sysCall, TArg1 arg1, TArg2 arg2)
private long SysCall<TArg1, TArg2>(Func<int, TArg1, TArg2, long> sysCall, TArg1 arg1, TArg2 arg2, bool checkErrors = true)
{
bool gotRefOnHandle = false;
try
@@ -799,9 +865,16 @@ namespace System.IO
int fd = (int)_inotifyHandle.DangerousGetHandle();
Debug.Assert(fd >= 0);
long result;
while (Interop.CheckIo(result = sysCall(fd, arg1, arg2), isDirectory: true));
return result;
if (checkErrors)
{
long result;
while (Interop.CheckIo(result = sysCall(fd, arg1, arg2), isDirectory: true)) ;
return result;
}
else
{
return sysCall(fd, arg1, arg2);
}
}
finally
{
@@ -66,6 +66,8 @@ namespace System.IO
private void StopRaisingEvents()
{
_enabled = false;
// Make sure the Start and Stop can be called from different threads and don't
// stomp on the other's operation. We use the _syncLock instead of the
// RunLoop or StreamRef because IntPtrs are value types and can't be locked
@@ -156,8 +158,11 @@ namespace System.IO
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true);
}
// Create the callback for the EventStream
_callback = new Interop.EventStream.FSEventStreamCallback(FileSystemEventCallback);
// Create the callback for the EventStream if it wasn't previously created for this instance.
if (_callback == null)
{
_callback = new Interop.EventStream.FSEventStreamCallback(FileSystemEventCallback);
}
// Make sure the OS file buffer(s) are fully flushed so we don't get events from cached I/O
Interop.libc.sync();
@@ -176,6 +181,8 @@ namespace System.IO
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true);
}
_enabled = true;
// Create and start our watcher thread then wait for the thread to initialize and start
// the RunLoop. We wait for that to prevent this function from returning before the RunLoop
// has a chance to start so that any callers won't race with the background thread's initialization
@@ -64,6 +64,8 @@ namespace System.IO
/// <summary>Stop monitoring the current directory.</summary>
private void StopRaisingEvents()
{
_enabled = false;
// If we're not running, do nothing.
if (IsHandleInvalid(_directoryHandle))
return;
@@ -82,9 +84,6 @@ namespace System.IO
// check will see a valid handle, unless we also null it out.
_directoryHandle.Dispose();
_directoryHandle = null;
// Set enabled to false
_enabled = false;
}
private void FinalizeDispose()
@@ -106,7 +106,7 @@ namespace System.IO
// Early check for directory parameter so that an exception can be thrown as early as possible.
if (path.Length == 0 || !Directory.Exists(path))
throw new ArgumentException(SR.InvalidDirName, path);
throw new ArgumentException(SR.Format(SR.InvalidDirName, path), "path");
_directory = path;
_filter = filter;
@@ -152,15 +152,13 @@ namespace System.IO
return;
}
_enabled = value;
if (_enabled)
if (value)
{
StartRaisingEventsIfNotDisposed();
StartRaisingEventsIfNotDisposed(); // will set _enabled to true once successfully started
}
else
{
StopRaisingEvents();
StopRaisingEvents(); // will set _enabled to false
}
}
}
@@ -2,8 +2,10 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Xunit;
public class FileSystemWatcherTests
@@ -45,6 +47,25 @@ public class FileSystemWatcherTests
ValidateDefaults(watcher, path, pattern);
}
[Fact]
public static void FileSystemWatcher_ctor_InvalidStrings()
{
// Null filter
Assert.Throws<ArgumentNullException>("filter", () => new FileSystemWatcher(".", null));
// Null path
Assert.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null));
Assert.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null, "*"));
// Empty path
Assert.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty));
Assert.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty, "*"));
// Invalid directory
Assert.Throws<ArgumentException>("path", () => new FileSystemWatcher(Guid.NewGuid().ToString()));
Assert.Throws<ArgumentException>("path", () => new FileSystemWatcher(Guid.NewGuid().ToString(), "*"));
}
[Fact]
public static void FileSystemWatcher_Changed()
{
@@ -417,4 +438,76 @@ public class FileSystemWatcherTests
watcher.Renamed -= handler;
}
}
[PlatformSpecific(PlatformID.Linux)]
[Fact]
public static void FileSystemWatcher_CreateManyConcurrentInstances()
{
int maxUserInstances = int.Parse(File.ReadAllText("/proc/sys/fs/inotify/max_user_instances"));
var watchers = new List<FileSystemWatcher>();
using (var dir = Utility.CreateTestDirectory())
{
try
{
Assert.Throws<IOException>(() =>
{
// Create enough inotify instances to exceed the number of allowed watches
for (int i = 0; i <= maxUserInstances; i++)
{
watchers.Add(new FileSystemWatcher(dir.Path) { EnableRaisingEvents = true });
}
});
}
finally
{
foreach (FileSystemWatcher watcher in watchers)
{
watcher.Dispose();
}
}
}
}
[PlatformSpecific(PlatformID.Linux)]
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void FileSystemWatcher_CreateManyConcurrentWatches(bool enableBeforeCreatingWatches)
{
int maxUserWatches = int.Parse(File.ReadAllText("/proc/sys/fs/inotify/max_user_watches"));
using (var dir = Utility.CreateTestDirectory())
using (var watcher = new FileSystemWatcher(dir.Path) { IncludeSubdirectories = true, NotifyFilter = NotifyFilters.FileName })
{
Exception exc = null;
ManualResetEventSlim mres = new ManualResetEventSlim();
watcher.Error += (s, e) =>
{
exc = e.GetException();
mres.Set();
};
if (enableBeforeCreatingWatches)
watcher.EnableRaisingEvents = true;
// Create enough directories to exceed the number of allowed watches
for (int i = 0; i <= maxUserWatches; i++)
{
Directory.CreateDirectory(Path.Combine(dir.Path, i.ToString()));
}
if (!enableBeforeCreatingWatches)
watcher.EnableRaisingEvents = true;
Assert.True(mres.Wait(Utility.WaitForExpectedEventTimeout));
Assert.IsType<IOException>(exc);
// Make sure existing watches still work even after we've had one or more failures
AutoResetEvent are = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
Utility.CreateTestFile(Path.Combine(dir.Path, Path.GetRandomFileName())).Dispose();
Utility.ExpectEvent(are, "file created");
}
}
}