diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/Resources/Strings.resx b/src/libraries/System.IO.FileSystem.Watcher/src/Resources/Strings.resx index 45cefa22d93..abfa455fa46 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/Resources/Strings.resx +++ b/src/libraries/System.IO.FileSystem.Watcher/src/Resources/Strings.resx @@ -174,4 +174,19 @@ Illegal characters in path. + + The system limit on the number of inotify instances has been reached. + + + The configured user limit ({0}) on the number of inotify instances has been reached. + + + The configured user limit ({0}) on the number of inotify watches has been reached. + + + The configured user limit on the number of inotify instances has been reached. + + + The configured user limit on the number of inotify watches has been reached. + \ No newline at end of file diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs index b584148b8b0..c0844ecf3fb 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs @@ -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 /// Cancels the currently running watch operation if there is one. 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 ---- // ----------------------------- + /// Path to the procfs file that contains the maximum number of inotify instances an individual user may create. + private const string MaxUserInstancesPath = "/proc/sys/fs/inotify/max_user_instances"; + + /// Path to the procfs file that contains the maximum number of inotify watches an individual user may create. + private const string MaxUserWatchesPath = "/proc/sys/fs/inotify/max_user_watches"; + /// /// Cancellation for the currently running watch operation. /// This is non-null if an operation has been started and null if stopped. /// private CancellationTokenSource _cancellation; + /// Reads the value of a max user limit path from procfs. + /// The path to read. + /// The value read, or "0" if a failure occurred. + private static string ReadMaxUserLimit(string path) + { + try { return File.ReadAllText(path).Trim(); } + catch { return null; } + } + /// /// 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 /// Adds a watch on a directory to the existing inotify handle. /// The parent directory entry. /// The new directory path to monitor, relative to the root. - 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; } /// Removes the watched directory from our state, and optionally removes the inotify watch itself. @@ -782,12 +847,13 @@ namespace System.IO /// A delegate that invokes the system call. It's passed the associated file descriptor and should return the result. /// The first argument to be passed to the system call, after the file descriptor. /// The second argument to be passed to the system call. + /// true to validate the result of the ; false to leave that responsibility to the caller. /// The return value of the system call. /// /// Arguments are expected to be passed via and /// so as to avoid delegate and closure allocations at the call sites. /// - private long SysCall(Func sysCall, TArg1 arg1, TArg2 arg2) + private long SysCall(Func 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 { diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs index 86496df4168..18dcaa626bc 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs @@ -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 diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs index a043a7451e3..3139c604672 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs @@ -64,6 +64,8 @@ namespace System.IO /// Stop monitoring the current directory. 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() diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs index 25ce6b1b7ae..518dbc5aa88 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs @@ -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 } } } diff --git a/src/libraries/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs b/src/libraries/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs index 33edc0b307c..21ffc093a65 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs @@ -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("filter", () => new FileSystemWatcher(".", null)); + + // Null path + Assert.Throws("path", () => new FileSystemWatcher(null)); + Assert.Throws("path", () => new FileSystemWatcher(null, "*")); + + // Empty path + Assert.Throws("path", () => new FileSystemWatcher(string.Empty)); + Assert.Throws("path", () => new FileSystemWatcher(string.Empty, "*")); + + // Invalid directory + Assert.Throws("path", () => new FileSystemWatcher(Guid.NewGuid().ToString())); + Assert.Throws("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(); + + using (var dir = Utility.CreateTestDirectory()) + { + try + { + Assert.Throws(() => + { + // 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(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"); + } + } + }