From f5ce131f50e74e9c7e5c124de52b48dadbda0b54 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Sep 2022 17:17:29 -0500 Subject: use a Channel to fan out directory scanning --- src/slskd/Shares/SharedFileCache.cs | 146 +++++++++++++++++++++++------------- 1 file changed, 93 insertions(+), 53 deletions(-) (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index fc9052bb..fbd47a5d 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -27,6 +27,7 @@ namespace slskd.Shares using System.Linq; using System.Text.RegularExpressions; using System.Threading; + using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.Data.Sqlite; using Serilog; @@ -42,9 +43,10 @@ namespace slskd.Shares /// /// /// - public SharedFileCache(StorageMode storageMode, ISoulseekFileFactory soulseekFileFactory = null) + public SharedFileCache(StorageMode storageMode, int workerCount, ISoulseekFileFactory soulseekFileFactory = null) { StorageMode = storageMode; + WorkerCount = workerCount; SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); } @@ -54,11 +56,13 @@ namespace slskd.Shares public IStateMonitor StateMonitor => State; private StorageMode StorageMode { get; } + private int WorkerCount { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + private Channel DirectoryChannel { get; set; } /// /// Returns the contents of the cache. @@ -137,7 +141,7 @@ namespace slskd.Shares /// The list of shares from which to fill the cache. /// The list of regular expressions used to exclude files or paths from scanning. /// The operation context. - public async Task FillAsync(IEnumerable shares, IEnumerable filters) + public async Task FillAsync(IEnumerable shares, IEnumerable filters, CancellationToken cancellationToken = default) { // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) @@ -227,72 +231,108 @@ namespace slskd.Shares var cached = 0; var filtered = 0; - foreach (var directory in unmaskedDirectories) + // set up a channel to fan out for directory scanning + DirectoryChannel = Channel.CreateBounded(new BoundedChannelOptions(1000) { - Log.Debug("Starting scan of {Directory} ({Current}/{Total})", directory, current + 1, unmaskedDirectories.Count); - - var addedFiles = 0; - var filteredFiles = 0; - - var share = Shares.First(share => directory.StartsWith(share.LocalPath)); + AllowSynchronousContinuations = false, + FullMode = BoundedChannelFullMode.Wait, + SingleReader = false, + SingleWriter = true, + }); - maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); - InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + // create workers to perform the fan out + var workers = new List(); - // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized - // filename and with a value of a Soulseek.File object - try - { - // enumerate files in this directory only (no subdirectories) exclude hidden and system files and anything - // that can't be accessed due to security restrictions - var newFiles = System.IO.Directory.GetFiles(directory, "*", new EnumerationOptions() + foreach (var id in Enumerable.Range(0, WorkerCount)) + { + workers.Add(new SharedFileCacheWorker( + id: id, + directoryChannel: DirectoryChannel, + cancellationToken: cancellationToken, + handler: (directory) => { - AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, - IgnoreInaccessible = true, - RecurseSubdirectories = false, - }); + Log.Debug("Starting scan of {Directory} ({Current}/{Total})", directory, current + 1, unmaskedDirectories.Count); - addedFiles = newFiles.Count(); + var addedFiles = 0; + var filteredFiles = 0; - // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully - // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. - foreach (var originalFilename in newFiles) - { - var info = new FileInfo(originalFilename); - var file = SoulseekFileFactory.Create(originalFilename, maskedFilename: originalFilename.ReplaceFirst(share.LocalPath, share.RemotePath)); + var share = Shares.First(share => directory.StartsWith(share.LocalPath)); - if (filters.Any(filter => filter.IsMatch(originalFilename))) + maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + + // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized + // filename and with a value of a Soulseek.File object + try + { + // enumerate files in this directory only (no subdirectories) exclude hidden and system files and anything + // that can't be accessed due to security restrictions + var newFiles = System.IO.Directory.GetFiles(directory, "*", new EnumerationOptions() + { + AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, + IgnoreInaccessible = true, + RecurseSubdirectories = false, + }); + + addedFiles = newFiles.Count(); + + // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully + // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. + foreach (var originalFilename in newFiles) + { + var info = new FileInfo(originalFilename); + var file = SoulseekFileFactory.Create(originalFilename, maskedFilename: originalFilename.ReplaceFirst(share.LocalPath, share.RemotePath)); + + if (filters.Any(filter => filter.IsMatch(originalFilename))) + { + filteredFiles++; + continue; + } + + InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file); + } + } + catch (Exception ex) { - filteredFiles++; - continue; + Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); + Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); } - InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file); - } - } - catch (Exception ex) - { - Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); - Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); - } + current++; + filtered += filteredFiles; + cached += addedFiles; - current++; - filtered += filteredFiles; - cached += addedFiles; + Log.Debug("Finished scanning {Directory}: {Added} files added and {Filtered} filtered", directory, addedFiles, filteredFiles); - Log.Debug("Finished scanning {Directory}: {Added} files added and {Filtered} filtered", directory, addedFiles, filteredFiles); + try + { + State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = cached }); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to set cache state following scan of {Directory}: {Message}", directory, ex.Message); + throw; + } + })); + } - try - { - State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = cached }); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to set cache state following scan of {Directory}: {Message}", directory, ex.Message); - throw; - } + Log.Debug("Starting workers..."); + workers.ForEach(w => w.Start()); + Log.Debug("All workers started"); + + Log.Debug("Filling DirectoryChannel..."); + foreach (var directory in unmaskedDirectories) + { + await DirectoryChannel.Writer.WriteAsync(directory); } + DirectoryChannel.Writer.Complete(); + Log.Debug("DirectoryChannel filled"); + + Log.Debug("Waiting for workers to finish working..."); + await Task.WhenAll(workers.Select(w => w.Completed)); + Log.Debug("All workers finished"); + Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; -- cgit v1.2.3 From 3279e498bc9da1231e26dd636465a8c2983baa73 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Sep 2022 17:26:07 -0500 Subject: minor optimization --- src/slskd/Shares/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index fbd47a5d..1c2b61aa 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -274,7 +274,7 @@ namespace slskd.Shares RecurseSubdirectories = false, }); - addedFiles = newFiles.Count(); + addedFiles = newFiles.Length; // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. -- cgit v1.2.3 From 938e610419bbadd0e194c4b789409453399e85ba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Sep 2022 13:03:33 -0500 Subject: refactor SharedFileCacheWorker into ChannelReader --- src/slskd/Common/ChannelReader.cs | 139 +++++++++++++++++++++++++++++ src/slskd/Shares/ISharedFileCacheWorker.cs | 42 --------- src/slskd/Shares/SharedFileCache.cs | 8 +- src/slskd/Shares/SharedFileCacheWorker.cs | 96 -------------------- 4 files changed, 143 insertions(+), 142 deletions(-) create mode 100644 src/slskd/Common/ChannelReader.cs delete mode 100644 src/slskd/Shares/ISharedFileCacheWorker.cs delete mode 100644 src/slskd/Shares/SharedFileCacheWorker.cs (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Common/ChannelReader.cs b/src/slskd/Common/ChannelReader.cs new file mode 100644 index 00000000..f358fb07 --- /dev/null +++ b/src/slskd/Common/ChannelReader.cs @@ -0,0 +1,139 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + using System; + using System.Threading; + using System.Threading.Channels; + using System.Threading.Tasks; + + /// + /// Reads and handles items from a channel. + /// + public interface IChannelReader + { + /// + /// Gets the that completes when the reader has read all available items from the channel. + /// + Task Completed { get; } + + /// + /// Gets a value indicating whether the reader has started reading. + /// + bool Started { get; } + + /// + /// Starts the reader. + /// + void Start(); + } + + /// + /// Shared file cache worker. + /// + /// The type of the underlying channel. + public class ChannelReader : IChannelReader + { + /// + /// Initializes a new instance of the class. + /// + /// The channel from which the reader will read. + /// An to be invoked for each item read from the channel. + /// An optional to be invoked if the reader encounters an . + /// An optional value indicating whether to automatically start the reader. + /// An optional to monitor for cancellation. + public ChannelReader( + Channel channel, + Action handler, + Action exceptionHandler = null, + bool automaticallyStart = true, + CancellationToken cancellationToken = default) + { + Channel = channel; + Handler = handler; + ExceptionHandler = exceptionHandler; + + CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + CancellationToken = CancellationTokenSource.Token; + + if (automaticallyStart) + { + Start(); + } + } + + /// + /// Gets the that completes when the worker has completed all of its work. + /// + public Task Completed => TaskCompletionSource.Task; + + /// + /// Gets a value indicating whether the reader has started reading. + /// + public bool Started { get; private set; } + + private Channel Channel { get; } + private Action Handler { get; } + private Action ExceptionHandler { get; } + private TaskCompletionSource TaskCompletionSource { get; } = new TaskCompletionSource(); + private CancellationTokenSource CancellationTokenSource { get; } + private CancellationToken CancellationToken { get; } + private object SyncRoot { get; } = new object(); + + /// + /// Starts the reader. + /// + public void Start() + { + lock (SyncRoot) + { + if (!Started) + { + _ = Read(); + Started = true; + } + } + } + + private async Task Read() + { + try + { + while (Started && !CancellationTokenSource.Token.IsCancellationRequested && !Channel.Reader.Completion.IsCompleted) + { + var item = await Channel.Reader.ReadAsync(CancellationToken); + Handler(item); + } + } + catch (ChannelClosedException) + { + // noop. the channel might close between the time we check and when we go to read; this just means there is no more data. + } + catch (Exception ex) + { + ExceptionHandler?.Invoke(ex); + TaskCompletionSource.SetException(ex); + throw; + } + finally + { + TaskCompletionSource.SetResult(); + } + } + } +} diff --git a/src/slskd/Shares/ISharedFileCacheWorker.cs b/src/slskd/Shares/ISharedFileCacheWorker.cs deleted file mode 100644 index b6b85c5d..00000000 --- a/src/slskd/Shares/ISharedFileCacheWorker.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Shares -{ - using System.Threading.Tasks; - - /// - /// Shared file cache worker. - /// - public interface ISharedFileCacheWorker - { - /// - /// Gets the that completes when the worker has completed all of its work. - /// - Task Completed { get; } - - /// - /// Gets the Id of the worker. - /// - int Id { get; } - - /// - /// Starts the worker. - /// - void Start(); - } -} diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 1c2b61aa..6a0cf87c 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -42,6 +42,7 @@ namespace slskd.Shares /// Initializes a new instance of the class. /// /// + /// /// public SharedFileCache(StorageMode storageMode, int workerCount, ISoulseekFileFactory soulseekFileFactory = null) { @@ -241,13 +242,12 @@ namespace slskd.Shares }); // create workers to perform the fan out - var workers = new List(); + var workers = new List>(); foreach (var id in Enumerable.Range(0, WorkerCount)) { - workers.Add(new SharedFileCacheWorker( - id: id, - directoryChannel: DirectoryChannel, + workers.Add(new ChannelReader( + channel: DirectoryChannel, cancellationToken: cancellationToken, handler: (directory) => { diff --git a/src/slskd/Shares/SharedFileCacheWorker.cs b/src/slskd/Shares/SharedFileCacheWorker.cs deleted file mode 100644 index 6ac5452b..00000000 --- a/src/slskd/Shares/SharedFileCacheWorker.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Shares -{ - using System; - using System.Threading; - using System.Threading.Channels; - using System.Threading.Tasks; - using Serilog; - - /// - /// Shared file cache worker. - /// - public class SharedFileCacheWorker : ISharedFileCacheWorker - { - /// - /// Initializes a new instance of the class. - /// - /// The worker's unique Id. - /// The channel from which the worker will receive directories to scan. - /// A to monitor for cancellation requests. - /// An to be performed on each item read from the channel. - public SharedFileCacheWorker( - int id, - Channel directoryChannel, - CancellationToken cancellationToken, - Action handler) - { - Id = id; - DirectoryChannel = directoryChannel; - CancellationToken = cancellationToken; - Handler = handler; - } - - /// - /// Gets the that completes when the worker has completed all of its work. - /// - public Task Completed => TaskCompletionSource.Task; - - /// - /// Gets the Id of the worker. - /// - public int Id { get; } - - private Channel DirectoryChannel { get; } - private Action Handler { get; } - private TaskCompletionSource TaskCompletionSource { get; } = new TaskCompletionSource(); - private CancellationToken CancellationToken { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Starts the worker. - /// - public void Start() - { - _ = Read(); - Log.Debug("Shared file cache worker {Id} started", Id); - } - - private async Task Read() - { - try - { - while (!CancellationToken.IsCancellationRequested && !DirectoryChannel.Reader.Completion.IsCompleted) - { - var directory = await DirectoryChannel.Reader.ReadAsync(CancellationToken); - Handler(directory); - } - } - catch (ChannelClosedException) - { - // noop. the channel might close between the time we check and when we go to read; this just means there is no more data. - } - finally - { - Log.Debug($"Shared file cache worker {Id}'s work is complete.", Id); - TaskCompletionSource.SetResult(); - } - } - } -} -- cgit v1.2.3