| | | 1 | | using System; |
| | | 2 | | using System.Collections.Concurrent; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Linq; |
| | | 6 | | using System.Threading; |
| | | 7 | | using System.Threading.Channels; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | using MediaBrowser.Controller.Configuration; |
| | | 10 | | using Microsoft.Extensions.Hosting; |
| | | 11 | | using Microsoft.Extensions.Logging; |
| | | 12 | | |
| | | 13 | | namespace MediaBrowser.Controller.LibraryTaskScheduler; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Provides Parallel action interface to process tasks with a set concurrency level. |
| | | 17 | | /// </summary> |
| | | 18 | | public sealed class LimitedConcurrencyLibraryScheduler : ILimitedConcurrencyLibraryScheduler, IAsyncDisposable |
| | | 19 | | { |
| | 2 | 20 | | private static readonly TimeSpan _cleanupGracePeriod = TimeSpan.FromSeconds(60); |
| | | 21 | | |
| | | 22 | | private readonly IHostApplicationLifetime _hostApplicationLifetime; |
| | | 23 | | private readonly ILogger<LimitedConcurrencyLibraryScheduler> _logger; |
| | | 24 | | private readonly IServerConfigurationManager _serverConfigurationManager; |
| | 35 | 25 | | private readonly Dictionary<CancellationTokenSource, Task> _taskRunners = new(); |
| | | 26 | | |
| | 2 | 27 | | private static readonly AsyncLocal<CancellationTokenSource> _deadlockDetector = new(); |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Gets used to lock all operations on the Tasks queue and creating workers. |
| | | 31 | | /// </summary> |
| | 35 | 32 | | private readonly Lock _taskLock = new(); |
| | | 33 | | |
| | 35 | 34 | | private readonly Channel<TaskQueueItem> _tasks = Channel.CreateUnbounded<TaskQueueItem>(); |
| | 35 | 35 | | private readonly CancellationTokenSource _disposeTokenSource = new(); |
| | | 36 | | private readonly TimeSpan _gracePeriod; |
| | | 37 | | |
| | | 38 | | private volatile int _workCounter; |
| | | 39 | | private Task? _cleanupTask; |
| | | 40 | | private bool _disposed; |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Initializes a new instance of the <see cref="LimitedConcurrencyLibraryScheduler"/> class. |
| | | 44 | | /// </summary> |
| | | 45 | | /// <param name="hostApplicationLifetime">The hosting lifetime.</param> |
| | | 46 | | /// <param name="logger">The logger.</param> |
| | | 47 | | /// <param name="serverConfigurationManager">The server configuration manager.</param> |
| | | 48 | | public LimitedConcurrencyLibraryScheduler( |
| | | 49 | | IHostApplicationLifetime hostApplicationLifetime, |
| | | 50 | | ILogger<LimitedConcurrencyLibraryScheduler> logger, |
| | | 51 | | IServerConfigurationManager serverConfigurationManager) |
| | 27 | 52 | | : this(hostApplicationLifetime, logger, serverConfigurationManager, _cleanupGracePeriod) |
| | | 53 | | { |
| | 27 | 54 | | } |
| | | 55 | | |
| | | 56 | | internal LimitedConcurrencyLibraryScheduler( |
| | | 57 | | IHostApplicationLifetime hostApplicationLifetime, |
| | | 58 | | ILogger<LimitedConcurrencyLibraryScheduler> logger, |
| | | 59 | | IServerConfigurationManager serverConfigurationManager, |
| | | 60 | | TimeSpan gracePeriod) |
| | | 61 | | { |
| | 35 | 62 | | _hostApplicationLifetime = hostApplicationLifetime; |
| | 35 | 63 | | _logger = logger; |
| | 35 | 64 | | _serverConfigurationManager = serverConfigurationManager; |
| | 35 | 65 | | _gracePeriod = gracePeriod; |
| | 35 | 66 | | } |
| | | 67 | | |
| | | 68 | | /// <summary> |
| | | 69 | | /// Gets the number of runners the scheduler currently keeps alive. |
| | | 70 | | /// </summary> |
| | | 71 | | internal int ActiveRunnerCount |
| | | 72 | | { |
| | | 73 | | get |
| | 17 | 74 | | { |
| | | 75 | | lock (_taskLock) |
| | | 76 | | { |
| | 17 | 77 | | return _taskRunners.Count; |
| | | 78 | | } |
| | 17 | 79 | | } |
| | | 80 | | } |
| | | 81 | | |
| | | 82 | | private void ScheduleTaskCleanup() |
| | 8 | 83 | | { |
| | | 84 | | lock (_taskLock) |
| | | 85 | | { |
| | 8 | 86 | | if (_cleanupTask is not null) |
| | | 87 | | { |
| | 0 | 88 | | _logger.LogDebug("Cleanup task already scheduled."); |
| | | 89 | | // cleanup task is already running. |
| | 0 | 90 | | return; |
| | | 91 | | } |
| | | 92 | | |
| | 8 | 93 | | _cleanupTask = RunCleanupTask(); |
| | 8 | 94 | | } |
| | | 95 | | |
| | | 96 | | async Task RunCleanupTask() |
| | | 97 | | { |
| | | 98 | | while (true) |
| | | 99 | | { |
| | | 100 | | _logger.LogDebug("Schedule cleanup task in {CleanupGracePeriod}.", _gracePeriod); |
| | | 101 | | try |
| | | 102 | | { |
| | | 103 | | await Task.Delay(_gracePeriod, _disposeTokenSource.Token).ConfigureAwait(false); |
| | | 104 | | } |
| | | 105 | | catch (OperationCanceledException) |
| | | 106 | | { |
| | | 107 | | _logger.LogDebug("Abort cleaning up, already disposed."); |
| | | 108 | | return; |
| | | 109 | | } |
| | | 110 | | |
| | | 111 | | if (_disposed) |
| | | 112 | | { |
| | | 113 | | _logger.LogDebug("Abort cleaning up, already disposed."); |
| | | 114 | | return; |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | CancellationTokenSource[] runners; |
| | | 118 | | lock (_taskLock) |
| | | 119 | | { |
| | | 120 | | if (_tasks.Reader.Count > 0 || _workCounter > 0) |
| | | 121 | | { |
| | | 122 | | _logger.LogDebug("Delay cleanup task, operations still running."); |
| | | 123 | | // tasks are still there so its still in use. Wait another grace period. |
| | | 124 | | // we cannot just exit here and rely on the other invoker because there is a considerable timefr |
| | | 125 | | continue; |
| | | 126 | | } |
| | | 127 | | |
| | | 128 | | runners = [.. _taskRunners.Keys]; |
| | | 129 | | |
| | | 130 | | // Retire the runners before they are told to stop: an operation starting while |
| | | 131 | | // they wind down must spawn its own instead of counting these towards the fanout. |
| | | 132 | | _taskRunners.Clear(); |
| | | 133 | | |
| | | 134 | | // Hand the next operation the ability to schedule a cleanup again. Without this |
| | | 135 | | // the very first cleanup would be the only one that ever runs. |
| | | 136 | | _cleanupTask = null; |
| | | 137 | | } |
| | | 138 | | |
| | | 139 | | _logger.LogDebug("Cleanup runners."); |
| | | 140 | | await StopRunners(runners).ConfigureAwait(false); |
| | | 141 | | return; |
| | | 142 | | } |
| | | 143 | | } |
| | 8 | 144 | | } |
| | | 145 | | |
| | | 146 | | private static async Task StopRunners(CancellationTokenSource[] runners) |
| | | 147 | | { |
| | 132 | 148 | | foreach (var runner in runners) |
| | | 149 | | { |
| | | 150 | | try |
| | | 151 | | { |
| | 28 | 152 | | await runner.CancelAsync().ConfigureAwait(false); |
| | 24 | 153 | | } |
| | 4 | 154 | | catch (ObjectDisposedException) |
| | | 155 | | { |
| | | 156 | | // The runner already stopped on its own and disposed its stop source. |
| | 4 | 157 | | } |
| | | 158 | | } |
| | 38 | 159 | | } |
| | | 160 | | |
| | | 161 | | private bool ShouldForceSequentialOperation() |
| | | 162 | | { |
| | | 163 | | // if the user either set the setting to 1 or it's unset and we have fewer than 4 cores it's better to run seque |
| | 37 | 164 | | var fanoutSetting = _serverConfigurationManager.Configuration.LibraryScanFanoutConcurrency; |
| | 37 | 165 | | return fanoutSetting == 1 || (fanoutSetting <= 0 && Environment.ProcessorCount <= 3); |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | private int CalculateScanConcurrencyLimit() |
| | | 169 | | { |
| | | 170 | | // when this is invoked, we already checked ShouldForceSequentialOperation for the sequential check. |
| | 8 | 171 | | var fanoutConcurrency = _serverConfigurationManager.Configuration.LibraryScanFanoutConcurrency; |
| | 8 | 172 | | if (fanoutConcurrency <= 0) |
| | | 173 | | { |
| | | 174 | | // in case the user did not set a limit manually, we can assume he has 3 or more cores as already checked by |
| | 0 | 175 | | return Environment.ProcessorCount - 3; |
| | | 176 | | } |
| | | 177 | | |
| | 8 | 178 | | return fanoutConcurrency; |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | private void Worker() |
| | 8 | 182 | | { |
| | | 183 | | lock (_taskLock) |
| | | 184 | | { |
| | 8 | 185 | | var operationFanout = Math.Max(0, CalculateScanConcurrencyLimit() - _taskRunners.Count); |
| | 8 | 186 | | _logger.LogDebug("Spawn {NumberRunners} new runners.", operationFanout); |
| | 80 | 187 | | for (int i = 0; i < operationFanout; i++) |
| | | 188 | | { |
| | 32 | 189 | | var stopToken = new CancellationTokenSource(); |
| | 32 | 190 | | var combinedSource = CancellationTokenSource.CreateLinkedTokenSource(stopToken.Token, _hostApplicationLi |
| | | 191 | | |
| | | 192 | | // Keyed on its own stop source, because cancelling that is what reaches the linked |
| | | 193 | | // source the runner waits on. Cancellation does not travel the other way. |
| | | 194 | | // Started without the runner's own token: a task cancelled before it is scheduled |
| | | 195 | | // never runs its body, so it would never take itself out of _taskRunners again. |
| | 32 | 196 | | _taskRunners.Add( |
| | 32 | 197 | | stopToken, |
| | 32 | 198 | | Task.Factory.StartNew( |
| | 32 | 199 | | ItemWorker, |
| | 32 | 200 | | (stopToken, combinedSource), |
| | 32 | 201 | | CancellationToken.None, |
| | 32 | 202 | | TaskCreationOptions.PreferFairness, |
| | 32 | 203 | | TaskScheduler.Default)); |
| | | 204 | | } |
| | 8 | 205 | | } |
| | 8 | 206 | | } |
| | | 207 | | |
| | | 208 | | private async Task ItemWorker(object? obj) |
| | | 209 | | { |
| | 32 | 210 | | var stopToken = ((CancellationTokenSource TaskStop, CancellationTokenSource GlobalStop))obj!; |
| | 32 | 211 | | _deadlockDetector.Value = stopToken.TaskStop; |
| | | 212 | | try |
| | | 213 | | { |
| | 200 | 214 | | while (!stopToken.GlobalStop.IsCancellationRequested) |
| | | 215 | | { |
| | 197 | 216 | | var item = await _tasks.Reader.ReadAsync(stopToken.GlobalStop.Token).ConfigureAwait(false); |
| | | 217 | | try |
| | | 218 | | { |
| | 168 | 219 | | var newWorkerLimit = Interlocked.Increment(ref _workCounter) > 0; |
| | | 220 | | Debug.Assert(newWorkerLimit, "_workCounter > 0"); |
| | 168 | 221 | | _logger.LogDebug("Process new item '{Data}'.", item.Data); |
| | 168 | 222 | | await ProcessItem(item).ConfigureAwait(false); |
| | 168 | 223 | | } |
| | | 224 | | finally |
| | | 225 | | { |
| | 168 | 226 | | var newWorkerLimit = Interlocked.Decrement(ref _workCounter) >= 0; |
| | | 227 | | Debug.Assert(newWorkerLimit, "_workCounter > 0"); |
| | | 228 | | } |
| | | 229 | | } |
| | 3 | 230 | | } |
| | 16 | 231 | | catch (OperationCanceledException) when (stopToken.GlobalStop.IsCancellationRequested) |
| | | 232 | | { |
| | | 233 | | // thats how you do it, interupt the waiter thread. There is nothing to do here when it was on purpose. |
| | 16 | 234 | | } |
| | 13 | 235 | | catch (ChannelClosedException) |
| | | 236 | | { |
| | | 237 | | // the scheduler was disposed and will not hand out any more work. |
| | 13 | 238 | | } |
| | | 239 | | finally |
| | | 240 | | { |
| | 32 | 241 | | _logger.LogDebug("Cleanup Runner'."); |
| | 32 | 242 | | _deadlockDetector.Value = default!; |
| | | 243 | | |
| | | 244 | | lock (_taskLock) |
| | | 245 | | { |
| | 32 | 246 | | _taskRunners.Remove(stopToken.TaskStop); |
| | 32 | 247 | | } |
| | | 248 | | |
| | 32 | 249 | | stopToken.GlobalStop.Dispose(); |
| | 32 | 250 | | stopToken.TaskStop.Dispose(); |
| | | 251 | | } |
| | 32 | 252 | | } |
| | | 253 | | |
| | | 254 | | private async Task ProcessItem(TaskQueueItem item) |
| | | 255 | | { |
| | | 256 | | try |
| | | 257 | | { |
| | 259 | 258 | | if (item.CancellationToken.IsCancellationRequested) |
| | | 259 | | { |
| | | 260 | | // if item is cancelled, just skip it |
| | 0 | 261 | | return; |
| | | 262 | | } |
| | | 263 | | |
| | 259 | 264 | | await item.Worker(item.Data).ConfigureAwait(true); |
| | 249 | 265 | | } |
| | 10 | 266 | | catch (Exception ex) |
| | | 267 | | { |
| | 10 | 268 | | _logger.LogError(ex, "Error while performing a library operation"); |
| | 10 | 269 | | } |
| | | 270 | | finally |
| | | 271 | | { |
| | 259 | 272 | | item.Progress.Report(100); |
| | 259 | 273 | | item.Done.TrySetResult(); |
| | | 274 | | } |
| | 259 | 275 | | } |
| | | 276 | | |
| | | 277 | | /// <inheritdoc/> |
| | | 278 | | public async Task Enqueue<T>(T[] data, Func<T, IProgress<double>, Task> worker, IProgress<double> progress, Cancella |
| | | 279 | | { |
| | 123 | 280 | | if (_disposed) |
| | | 281 | | { |
| | 1 | 282 | | return; |
| | | 283 | | } |
| | | 284 | | |
| | 122 | 285 | | if (data.Length == 0 || cancellationToken.IsCancellationRequested) |
| | | 286 | | { |
| | 85 | 287 | | progress.Report(100); |
| | 85 | 288 | | return; |
| | | 289 | | } |
| | | 290 | | |
| | 37 | 291 | | _logger.LogDebug("Enqueue new Workset of {NoItems} items.", data.Length); |
| | | 292 | | |
| | 37 | 293 | | TaskQueueItem[] workItems = null!; |
| | | 294 | | |
| | | 295 | | void UpdateProgress() |
| | | 296 | | { |
| | | 297 | | progress.Report(workItems.Select(e => e.ProgressValue).Average()); |
| | | 298 | | } |
| | | 299 | | |
| | 37 | 300 | | workItems = data.Select(item => |
| | 37 | 301 | | { |
| | 37 | 302 | | TaskQueueItem queueItem = null!; |
| | 37 | 303 | | return queueItem = new TaskQueueItem() |
| | 37 | 304 | | { |
| | 37 | 305 | | Data = item!, |
| | 37 | 306 | | Progress = new Progress<double>(innerPercent => |
| | 37 | 307 | | { |
| | 37 | 308 | | // round the percent and only update progress if it changed to prevent excessive UpdateProgress |
| | 37 | 309 | | var innerPercentRounded = Math.Round(innerPercent); |
| | 37 | 310 | | if (queueItem.ProgressValue != innerPercentRounded) |
| | 37 | 311 | | { |
| | 37 | 312 | | queueItem.ProgressValue = innerPercentRounded; |
| | 37 | 313 | | UpdateProgress(); |
| | 37 | 314 | | } |
| | 37 | 315 | | }), |
| | 37 | 316 | | Worker = (val) => worker((T)val, queueItem.Progress), |
| | 37 | 317 | | CancellationToken = cancellationToken |
| | 37 | 318 | | }; |
| | 37 | 319 | | }).ToArray(); |
| | | 320 | | |
| | 37 | 321 | | if (ShouldForceSequentialOperation() || _deadlockDetector.Value is not null) |
| | | 322 | | { |
| | 29 | 323 | | _logger.LogDebug("Process sequentially."); |
| | | 324 | | try |
| | | 325 | | { |
| | 240 | 326 | | foreach (var item in workItems) |
| | | 327 | | { |
| | 91 | 328 | | await ProcessItem(item).ConfigureAwait(false); |
| | | 329 | | } |
| | 29 | 330 | | } |
| | 0 | 331 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 332 | | { |
| | | 333 | | // operation is cancelled. Do nothing. |
| | 0 | 334 | | } |
| | | 335 | | |
| | 29 | 336 | | _logger.LogDebug("Process sequentially done."); |
| | 29 | 337 | | return; |
| | | 338 | | } |
| | | 339 | | |
| | 352 | 340 | | for (var i = 0; i < workItems.Length; i++) |
| | | 341 | | { |
| | 168 | 342 | | var item = workItems[i]!; |
| | 168 | 343 | | await _tasks.Writer.WriteAsync(item, CancellationToken.None).ConfigureAwait(false); |
| | | 344 | | } |
| | | 345 | | |
| | 8 | 346 | | Worker(); |
| | 8 | 347 | | _logger.LogDebug("Wait for {NoWorkers} to complete.", workItems.Length); |
| | 8 | 348 | | await Task.WhenAll([.. workItems.Select(f => f.Done.Task)]).ConfigureAwait(false); |
| | 8 | 349 | | _logger.LogDebug("{NoWorkers} completed.", workItems.Length); |
| | 8 | 350 | | ScheduleTaskCleanup(); |
| | 123 | 351 | | } |
| | | 352 | | |
| | | 353 | | /// <inheritdoc/> |
| | | 354 | | public async ValueTask DisposeAsync() |
| | | 355 | | { |
| | 35 | 356 | | if (_disposed) |
| | | 357 | | { |
| | 0 | 358 | | return; |
| | | 359 | | } |
| | | 360 | | |
| | 35 | 361 | | _disposed = true; |
| | 35 | 362 | | _tasks.Writer.Complete(); |
| | | 363 | | |
| | | 364 | | // Nobody is left to run these, so release whoever is waiting on them. |
| | 35 | 365 | | while (_tasks.Reader.TryRead(out var item)) |
| | | 366 | | { |
| | 0 | 367 | | item.Done.TrySetResult(); |
| | 0 | 368 | | } |
| | | 369 | | |
| | | 370 | | CancellationTokenSource[] runners; |
| | | 371 | | Task? cleanupTask; |
| | | 372 | | lock (_taskLock) |
| | | 373 | | { |
| | 35 | 374 | | runners = [.. _taskRunners.Keys]; |
| | 35 | 375 | | _taskRunners.Clear(); |
| | 35 | 376 | | cleanupTask = _cleanupTask; |
| | 35 | 377 | | } |
| | | 378 | | |
| | 35 | 379 | | await StopRunners(runners).ConfigureAwait(false); |
| | | 380 | | |
| | | 381 | | // Cuts the grace period short instead of holding up shutdown for the rest of it. |
| | 35 | 382 | | await _disposeTokenSource.CancelAsync().ConfigureAwait(false); |
| | | 383 | | |
| | 35 | 384 | | if (cleanupTask is not null) |
| | | 385 | | { |
| | 5 | 386 | | await cleanupTask.ConfigureAwait(false); |
| | | 387 | | } |
| | | 388 | | |
| | 35 | 389 | | _disposeTokenSource.Dispose(); |
| | 35 | 390 | | } |
| | | 391 | | |
| | | 392 | | private class TaskQueueItem |
| | | 393 | | { |
| | | 394 | | public required object Data { get; init; } |
| | | 395 | | |
| | | 396 | | public double ProgressValue { get; set; } |
| | | 397 | | |
| | | 398 | | public required Func<object, Task> Worker { get; init; } |
| | | 399 | | |
| | | 400 | | public required IProgress<double> Progress { get; init; } |
| | | 401 | | |
| | | 402 | | public TaskCompletionSource Done { get; } = new(); |
| | | 403 | | |
| | | 404 | | public CancellationToken CancellationToken { get; init; } |
| | | 405 | | } |
| | | 406 | | } |