jellyfin-server/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs

388 lines
12 KiB
C#
Raw Normal View History

using System;
2016-10-29 05:40:15 +00:00
using System.Collections.Concurrent;
using System.Collections.Generic;
2018-12-28 14:30:53 +00:00
using System.IO;
2016-10-29 05:40:15 +00:00
using System.Linq;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Events;
2016-10-29 05:40:15 +00:00
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
2016-10-29 05:40:15 +00:00
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
2016-10-29 05:40:15 +00:00
namespace Emby.Server.Implementations.ScheduledTasks
2016-10-29 05:40:15 +00:00
{
/// <summary>
/// Class TaskManager
/// </summary>
public class TaskManager : ITaskManager
{
public event EventHandler<GenericEventArgs<IScheduledTaskWorker>> TaskExecuting;
public event EventHandler<TaskCompletionEventArgs> TaskCompleted;
/// <summary>
/// Gets the list of Scheduled Tasks
/// </summary>
/// <value>The scheduled tasks.</value>
public IScheduledTaskWorker[] ScheduledTasks { get; private set; }
/// <summary>
/// The _task queue
/// </summary>
2018-09-12 17:26:21 +00:00
private readonly ConcurrentQueue<Tuple<Type, TaskOptions>> _taskQueue =
new ConcurrentQueue<Tuple<Type, TaskOptions>>();
2016-10-29 05:40:15 +00:00
/// <summary>
/// Gets or sets the json serializer.
/// </summary>
/// <value>The json serializer.</value>
private IJsonSerializer JsonSerializer { get; set; }
/// <summary>
/// Gets or sets the application paths.
/// </summary>
/// <value>The application paths.</value>
private IApplicationPaths ApplicationPaths { get; set; }
private readonly ISystemEvents _systemEvents;
/// <summary>
/// Gets the logger.
/// </summary>
/// <value>The logger.</value>
private ILogger Logger { get; set; }
private readonly IFileSystem _fileSystem;
/// <summary>
/// Initializes a new instance of the <see cref="TaskManager" /> class.
/// </summary>
/// <param name="applicationPaths">The application paths.</param>
/// <param name="jsonSerializer">The json serializer.</param>
/// <param name="logger">The logger.</param>
2019-01-13 20:37:13 +00:00
/// <exception cref="ArgumentException">kernel</exception>
2016-10-29 05:40:15 +00:00
public TaskManager(IApplicationPaths applicationPaths, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem, ISystemEvents systemEvents)
{
ApplicationPaths = applicationPaths;
JsonSerializer = jsonSerializer;
Logger = logger;
_fileSystem = fileSystem;
_systemEvents = systemEvents;
ScheduledTasks = new IScheduledTaskWorker[] { };
}
private void BindToSystemEvent()
{
_systemEvents.Resume += _systemEvents_Resume;
}
private void _systemEvents_Resume(object sender, EventArgs e)
{
foreach (var task in ScheduledTasks)
{
task.ReloadTriggerEvents();
}
}
2017-10-16 06:10:55 +00:00
public void RunTaskOnNextStartup(string key)
{
var path = Path.Combine(ApplicationPaths.CachePath, "startuptasks.txt");
List<string> lines;
try
{
lines = _fileSystem.ReadAllLines(path).ToList();
2017-10-16 06:10:55 +00:00
}
catch
{
lines = new List<string>();
}
if (!lines.Contains(key, StringComparer.OrdinalIgnoreCase))
{
lines.Add(key);
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
_fileSystem.WriteAllLines(path, lines);
}
}
private void RunStartupTasks()
{
var path = Path.Combine(ApplicationPaths.CachePath, "startuptasks.txt");
2018-09-12 17:26:21 +00:00
// ToDo: Fix this shit
if (!File.Exists(path))
return;
2017-10-16 06:10:55 +00:00
List<string> lines;
try
{
lines = _fileSystem.ReadAllLines(path).Where(i => !string.IsNullOrWhiteSpace(i)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
foreach (var key in lines)
{
var task = ScheduledTasks.FirstOrDefault(i => string.Equals(i.ScheduledTask.Key, key, StringComparison.OrdinalIgnoreCase));
if (task != null)
{
2018-09-12 17:26:21 +00:00
QueueScheduledTask(task, new TaskOptions());
2017-10-16 06:10:55 +00:00
}
}
_fileSystem.DeleteFile(path);
}
catch
{
return;
}
}
2016-10-29 05:40:15 +00:00
/// <summary>
/// Cancels if running and queue.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="options">Task options.</param>
2018-09-12 17:26:21 +00:00
public void CancelIfRunningAndQueue<T>(TaskOptions options)
2016-10-29 05:40:15 +00:00
where T : IScheduledTask
{
var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
((ScheduledTaskWorker)task).CancelIfRunning();
QueueScheduledTask<T>(options);
}
public void CancelIfRunningAndQueue<T>()
where T : IScheduledTask
{
2018-09-12 17:26:21 +00:00
CancelIfRunningAndQueue<T>(new TaskOptions());
2016-10-29 05:40:15 +00:00
}
/// <summary>
/// Cancels if running
/// </summary>
/// <typeparam name="T"></typeparam>
public void CancelIfRunning<T>()
where T : IScheduledTask
{
var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
((ScheduledTaskWorker)task).CancelIfRunning();
}
/// <summary>
/// Queues the scheduled task.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="options">Task options</param>
2018-09-12 17:26:21 +00:00
public void QueueScheduledTask<T>(TaskOptions options)
2016-10-29 05:40:15 +00:00
where T : IScheduledTask
{
var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
if (scheduledTask == null)
{
Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
2016-10-29 05:40:15 +00:00
}
else
{
QueueScheduledTask(scheduledTask, options);
}
}
public void QueueScheduledTask<T>()
where T : IScheduledTask
{
2018-09-12 17:26:21 +00:00
QueueScheduledTask<T>(new TaskOptions());
2016-10-29 05:40:15 +00:00
}
public void QueueIfNotRunning<T>()
where T : IScheduledTask
{
var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
if (task.State != TaskState.Running)
{
2018-09-12 17:26:21 +00:00
QueueScheduledTask<T>(new TaskOptions());
2016-10-29 05:40:15 +00:00
}
}
public void Execute<T>()
where T : IScheduledTask
{
var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
if (scheduledTask == null)
{
Logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
2016-10-29 05:40:15 +00:00
}
else
{
var type = scheduledTask.ScheduledTask.GetType();
Logger.LogInformation("Queueing task {0}", type.Name);
2016-10-29 05:40:15 +00:00
lock (_taskQueue)
{
if (scheduledTask.State == TaskState.Idle)
{
2018-09-12 17:26:21 +00:00
Execute(scheduledTask, new TaskOptions());
2016-10-29 05:40:15 +00:00
}
}
}
}
/// <summary>
/// Queues the scheduled task.
/// </summary>
/// <param name="task">The task.</param>
/// <param name="options">The task options.</param>
2018-09-12 17:26:21 +00:00
public void QueueScheduledTask(IScheduledTask task, TaskOptions options)
2016-10-29 05:40:15 +00:00
{
var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());
if (scheduledTask == null)
{
Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
2016-10-29 05:40:15 +00:00
}
else
{
QueueScheduledTask(scheduledTask, options);
}
}
/// <summary>
/// Queues the scheduled task.
/// </summary>
/// <param name="task">The task.</param>
/// <param name="options">The task options.</param>
2018-09-12 17:26:21 +00:00
private void QueueScheduledTask(IScheduledTaskWorker task, TaskOptions options)
2016-10-29 05:40:15 +00:00
{
var type = task.ScheduledTask.GetType();
Logger.LogInformation("Queueing task {0}", type.Name);
2016-10-29 05:40:15 +00:00
lock (_taskQueue)
{
if (task.State == TaskState.Idle)
2016-10-29 05:40:15 +00:00
{
Execute(task, options);
return;
}
2018-09-12 17:26:21 +00:00
_taskQueue.Enqueue(new Tuple<Type, TaskOptions>(type, options));
2016-10-29 05:40:15 +00:00
}
}
/// <summary>
/// Adds the tasks.
/// </summary>
/// <param name="tasks">The tasks.</param>
public void AddTasks(IEnumerable<IScheduledTask> tasks)
{
var myTasks = ScheduledTasks.ToList();
var list = tasks.ToList();
2016-10-29 18:46:14 +00:00
myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger, _fileSystem, _systemEvents)));
2016-10-29 05:40:15 +00:00
ScheduledTasks = myTasks.ToArray();
BindToSystemEvent();
2017-10-16 06:10:55 +00:00
RunStartupTasks();
2016-10-29 05:40:15 +00:00
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
foreach (var task in ScheduledTasks)
{
task.Dispose();
}
}
public void Cancel(IScheduledTaskWorker task)
{
((ScheduledTaskWorker)task).Cancel();
}
2018-09-12 17:26:21 +00:00
public Task Execute(IScheduledTaskWorker task, TaskOptions options)
2016-10-29 05:40:15 +00:00
{
return ((ScheduledTaskWorker)task).Execute(options);
}
/// <summary>
/// Called when [task executing].
/// </summary>
/// <param name="task">The task.</param>
internal void OnTaskExecuting(IScheduledTaskWorker task)
{
TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>
2016-10-29 05:40:15 +00:00
{
Argument = task
});
2016-10-29 05:40:15 +00:00
}
/// <summary>
/// Called when [task completed].
/// </summary>
/// <param name="task">The task.</param>
/// <param name="result">The result.</param>
internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
{
TaskCompleted?.Invoke(task, new TaskCompletionEventArgs
2016-10-29 05:40:15 +00:00
{
Result = result,
Task = task
});
2016-10-29 05:40:15 +00:00
ExecuteQueuedTasks();
}
/// <summary>
/// Executes the queued tasks.
/// </summary>
private void ExecuteQueuedTasks()
{
Logger.LogInformation("ExecuteQueuedTasks");
2016-10-29 05:40:15 +00:00
// Execute queued tasks
lock (_taskQueue)
{
2018-09-12 17:26:21 +00:00
var list = new List<Tuple<Type, TaskOptions>>();
2016-10-29 05:40:15 +00:00
while (_taskQueue.TryDequeue(out var item))
2016-10-29 05:40:15 +00:00
{
if (list.All(i => i.Item1 != item.Item1))
{
list.Add(item);
}
}
foreach (var enqueuedType in list)
{
var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Item1);
if (scheduledTask.State == TaskState.Idle)
{
Execute(scheduledTask, enqueuedType.Item2);
}
}
}
}
}
}