diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-09-18 13:42:50 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-09-18 13:42:50 -0500 |
| commit | 6a307269ab99956fb2c5ea2149ae76c3ef24c8b2 (patch) | |
| tree | 490d0b393c33c533a1c7c0344ebb1ce346b28166 /src/slskd | |
| parent | 2700743d8b7b049a8c5fe20f398354e28ce1a94b (diff) | |
| parent | ab95c9841b2967f86b9217fddef2d70b99a57b7a (diff) | |
| download | slskd-6a307269ab99956fb2c5ea2149ae76c3ef24c8b2.tar.gz | |
Merge pull request #649 from slskd/faster-scan
Increase the speed of share scanning by 4-5x
Diffstat (limited to 'src/slskd')
| -rw-r--r-- | src/slskd/Common/ChannelReader.cs | 139 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 10 | ||||
| -rw-r--r-- | src/slskd/Shares/ISharedFileCache.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareService.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Shares/SharedFileCache.cs | 146 |
5 files changed, 249 insertions, 55 deletions
diff --git a/src/slskd/Common/ChannelReader.cs b/src/slskd/Common/ChannelReader.cs new file mode 100644 index 00000000..a6a8b9a3 --- /dev/null +++ b/src/slskd/Common/ChannelReader.cs @@ -0,0 +1,139 @@ +// <copyright file="ChannelReader.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Shares +{ + using System; + using System.Threading; + using System.Threading.Channels; + using System.Threading.Tasks; + + /// <summary> + /// Reads and handles items from a channel. + /// </summary> + public interface IChannelReader + { + /// <summary> + /// Gets the <see cref="Task"/> that completes when the reader has read all available items from the channel. + /// </summary> + Task Completed { get; } + + /// <summary> + /// Gets a value indicating whether the reader has started reading. + /// </summary> + bool Started { get; } + + /// <summary> + /// Starts the reader. + /// </summary> + void Start(); + } + + /// <summary> + /// Shared file cache worker. + /// </summary> + /// <typeparam name="T">The type of the underlying channel.</typeparam> + public class ChannelReader<T> : IChannelReader + { + /// <summary> + /// Initializes a new instance of the <see cref="ChannelReader"/> class. + /// </summary> + /// <param name="channel">The channel from which the reader will read.</param> + /// <param name="handler">An <see cref="Action"/> to be invoked for each item read from the channel.</param> + /// <param name="exceptionHandler">An optional <see cref="Action"/> to be invoked if the reader encounters an <see cref="Exception"/>.</param> + /// <param name="automaticallyStart">An optional value indicating whether to automatically start the reader.</param> + /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to monitor for cancellation.</param> + public ChannelReader( + Channel<T> channel, + Action<T> handler, + Action<Exception> exceptionHandler = null, + bool automaticallyStart = true, + CancellationToken cancellationToken = default) + { + Channel = channel; + Handler = handler; + ExceptionHandler = exceptionHandler; + + CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + CancellationToken = CancellationTokenSource.Token; + + if (automaticallyStart) + { + Start(); + } + } + + /// <summary> + /// Gets the <see cref="Task"/> that completes when the worker has completed all of its work. + /// </summary> + public Task Completed => TaskCompletionSource.Task; + + /// <summary> + /// Gets a value indicating whether the reader has started reading. + /// </summary> + public bool Started { get; private set; } + + private Channel<T> Channel { get; } + private Action<T> Handler { get; } + private Action<Exception> ExceptionHandler { get; } + private TaskCompletionSource TaskCompletionSource { get; } = new TaskCompletionSource(); + private CancellationTokenSource CancellationTokenSource { get; } + private CancellationToken CancellationToken { get; } + private object SyncRoot { get; } = new object(); + + /// <summary> + /// Starts the reader. + /// </summary> + public void Start() + { + lock (SyncRoot) + { + if (!Started) + { + _ = Read(); + Started = true; + } + } + } + + private async Task Read() + { + try + { + while (!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/Core/Options.cs b/src/slskd/Core/Options.cs index 2d561e29..070476d1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -394,6 +394,16 @@ namespace slskd [Enum(typeof(StorageMode))] [RequiresRestart] public string StorageMode { get; init; } = slskd.StorageMode.Memory.ToString().ToLowerInvariant(); + + /// <summary> + /// Gets the number of workers to use while scanning shares. + /// </summary> + [Argument(default, "share-cache-workers")] + [EnvironmentVariable("SHARE_CACHE_WORKERS")] + [Description("the number of workers to use while scanning shares")] + [Range(1, 128)] + [RequiresRestart] + public int Workers { get; init; } = 16; } /// <summary> diff --git a/src/slskd/Shares/ISharedFileCache.cs b/src/slskd/Shares/ISharedFileCache.cs index 7043b030..52c7783c 100644 --- a/src/slskd/Shares/ISharedFileCache.cs +++ b/src/slskd/Shares/ISharedFileCache.cs @@ -19,6 +19,7 @@ namespace slskd.Shares { using System.Collections.Generic; using System.Text.RegularExpressions; + using System.Threading; using System.Threading.Tasks; using Soulseek; @@ -44,8 +45,9 @@ namespace slskd.Shares /// <remarks>Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete.</remarks> /// <param name="shares">The list of shares from which to fill the cache.</param> /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param> + /// <param name="cancellationToken">The optional cancellation token to monitor.</param> /// <returns>The operation context.</returns> - Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters); + Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters, CancellationToken cancellationToken = default); /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index dd808360..96ac4c1c 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -41,7 +41,10 @@ namespace slskd.Shares IOptionsMonitor<Options> optionsMonitor, ISharedFileCache sharedFileCache = null) { - Cache = sharedFileCache ?? new SharedFileCache(storageMode: optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum<StorageMode>()); + Cache = sharedFileCache ?? new SharedFileCache( + storageMode: optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum<StorageMode>(), + workerCount: optionsMonitor.CurrentValue.Shares.Cache.Workers); + Cache.StateMonitor.OnChange(cacheState => { var (previous, current) = cacheState; diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 59abc789..4afbfed8 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; @@ -41,10 +42,12 @@ namespace slskd.Shares /// Initializes a new instance of the <see cref="SharedFileCache"/> class. /// </summary> /// <param name="storageMode"></param> + /// <param name="workerCount"></param> /// <param name="soulseekFileFactory"></param> - 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 +57,13 @@ namespace slskd.Shares public IStateMonitor<SharedFileCacheState> StateMonitor => State; private StorageMode StorageMode { get; } + private int WorkerCount { get; } private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>(); private List<Share> Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + private Channel<string> DirectoryChannel { get; set; } /// <summary> /// Returns the contents of the cache. @@ -137,7 +142,7 @@ namespace slskd.Shares /// <param name="shares">The list of shares from which to fill the cache.</param> /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param> /// <returns>The operation context.</returns> - public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters) + public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> 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 +232,107 @@ 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<string>(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<ChannelReader<string>>(); - // 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 ChannelReader<string>( + channel: 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.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. + 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", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; |
