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

801 lines
26 KiB
C#
Raw Normal View History

2019-01-12 20:41:08 +00:00
using System;
2016-10-29 05:40:15 +00:00
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
2017-06-23 16:04:45 +00:00
using MediaBrowser.Common.Progress;
2016-10-29 05:40:15 +00:00
using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
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 ScheduledTaskWorker
/// </summary>
public class ScheduledTaskWorker : IScheduledTaskWorker
{
public event EventHandler<GenericEventArgs<double>> TaskProgress;
/// <summary>
/// Gets or sets the scheduled task.
/// </summary>
/// <value>The scheduled task.</value>
public IScheduledTask ScheduledTask { get; private set; }
2019-01-12 21:54:47 +00:00
/// <summary>
2016-10-29 05:40:15 +00:00
/// 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; }
/// <summary>
/// Gets the logger.
/// </summary>
/// <value>The logger.</value>
private ILogger Logger { get; set; }
/// <summary>
/// Gets the task manager.
/// </summary>
/// <value>The task manager.</value>
private ITaskManager TaskManager { get; set; }
private readonly IFileSystem _fileSystem;
private readonly ISystemEvents _systemEvents;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
/// </summary>
/// <param name="scheduledTask">The scheduled task.</param>
/// <param name="applicationPaths">The application paths.</param>
/// <param name="taskManager">The task manager.</param>
/// <param name="jsonSerializer">The json serializer.</param>
/// <param name="logger">The logger.</param>
2019-01-13 20:37:13 +00:00
/// <exception cref="ArgumentNullException">
2016-10-29 05:40:15 +00:00
/// scheduledTask
/// or
/// applicationPaths
/// or
/// taskManager
/// or
/// jsonSerializer
/// or
/// logger
/// </exception>
public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem, ISystemEvents systemEvents)
{
if (scheduledTask == null)
{
throw new ArgumentNullException(nameof(scheduledTask));
2016-10-29 05:40:15 +00:00
}
if (applicationPaths == null)
{
throw new ArgumentNullException(nameof(applicationPaths));
2016-10-29 05:40:15 +00:00
}
if (taskManager == null)
{
throw new ArgumentNullException(nameof(taskManager));
2016-10-29 05:40:15 +00:00
}
if (jsonSerializer == null)
{
throw new ArgumentNullException(nameof(jsonSerializer));
2016-10-29 05:40:15 +00:00
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
2016-10-29 05:40:15 +00:00
}
ScheduledTask = scheduledTask;
ApplicationPaths = applicationPaths;
TaskManager = taskManager;
JsonSerializer = jsonSerializer;
Logger = logger;
_fileSystem = fileSystem;
_systemEvents = systemEvents;
InitTriggerEvents();
}
private bool _readFromFile = false;
/// <summary>
/// The _last execution result
/// </summary>
private TaskResult _lastExecutionResult;
/// <summary>
/// The _last execution result sync lock
/// </summary>
private readonly object _lastExecutionResultSyncLock = new object();
/// <summary>
/// Gets the last execution result.
/// </summary>
/// <value>The last execution result.</value>
public TaskResult LastExecutionResult
{
get
{
var path = GetHistoryFilePath();
lock (_lastExecutionResultSyncLock)
{
if (_lastExecutionResult == null && !_readFromFile)
{
try
{
_lastExecutionResult = JsonSerializer.DeserializeFromFile<TaskResult>(path);
}
catch (DirectoryNotFoundException)
{
// File doesn't exist. No biggie
}
catch (FileNotFoundException)
{
// File doesn't exist. No biggie
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
Logger.LogError(ex, "Error deserializing {path}", path);
2016-10-29 05:40:15 +00:00
}
_readFromFile = true;
}
}
return _lastExecutionResult;
}
private set
{
_lastExecutionResult = value;
var path = GetHistoryFilePath();
2018-09-12 17:26:21 +00:00
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
2016-10-29 05:40:15 +00:00
lock (_lastExecutionResultSyncLock)
{
JsonSerializer.SerializeToFile(value, path);
}
}
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ScheduledTask.Name;
2016-10-29 05:40:15 +00:00
/// <summary>
/// Gets the description.
/// </summary>
/// <value>The description.</value>
public string Description => ScheduledTask.Description;
2016-10-29 05:40:15 +00:00
/// <summary>
/// Gets the category.
/// </summary>
/// <value>The category.</value>
public string Category => ScheduledTask.Category;
2016-10-29 05:40:15 +00:00
/// <summary>
/// Gets the current cancellation token
/// </summary>
/// <value>The current cancellation token source.</value>
private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
/// <summary>
/// Gets or sets the current execution start time.
/// </summary>
/// <value>The current execution start time.</value>
private DateTime CurrentExecutionStartTime { get; set; }
/// <summary>
/// Gets the state.
/// </summary>
/// <value>The state.</value>
public TaskState State
{
get
{
if (CurrentCancellationTokenSource != null)
{
return CurrentCancellationTokenSource.IsCancellationRequested
? TaskState.Cancelling
: TaskState.Running;
}
return TaskState.Idle;
}
}
/// <summary>
/// Gets the current progress.
/// </summary>
/// <value>The current progress.</value>
public double? CurrentProgress { get; private set; }
/// <summary>
/// The _triggers
/// </summary>
2018-09-12 17:26:21 +00:00
private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
2016-10-29 05:40:15 +00:00
/// <summary>
/// Gets the triggers that define when the task will run
/// </summary>
/// <value>The triggers.</value>
private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
{
get => _triggers;
2016-10-29 05:40:15 +00:00
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
2016-10-29 05:40:15 +00:00
}
// Cleanup current triggers
if (_triggers != null)
{
DisposeTriggers();
}
_triggers = value.ToArray();
ReloadTriggerEvents(false);
}
}
/// <summary>
/// Gets the triggers that define when the task will run
/// </summary>
/// <value>The triggers.</value>
2019-01-13 20:37:13 +00:00
/// <exception cref="ArgumentNullException">value</exception>
2016-10-29 05:40:15 +00:00
public TaskTriggerInfo[] Triggers
{
get
{
var triggers = InternalTriggers;
2018-12-28 15:48:26 +00:00
return triggers.Select(i => i.Item1).ToArray();
2016-10-29 05:40:15 +00:00
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
2016-10-29 05:40:15 +00:00
}
2016-12-22 15:57:45 +00:00
// This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
var triggerList = value.Where(i => i != null).ToArray();
2016-10-29 05:40:15 +00:00
2016-12-22 15:57:45 +00:00
SaveTriggers(triggerList);
2018-12-28 15:48:26 +00:00
InternalTriggers = triggerList.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
2016-10-29 05:40:15 +00:00
}
}
/// <summary>
/// The _id
/// </summary>
private string _id;
/// <summary>
/// Gets the unique id.
/// </summary>
/// <value>The unique id.</value>
public string Id
{
get
{
if (_id == null)
{
_id = ScheduledTask.GetType().FullName.GetMD5().ToString("N");
}
return _id;
}
}
private void InitTriggerEvents()
{
_triggers = LoadTriggers();
ReloadTriggerEvents(true);
}
public void ReloadTriggerEvents()
{
ReloadTriggerEvents(false);
}
/// <summary>
/// Reloads the trigger events.
/// </summary>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
private void ReloadTriggerEvents(bool isApplicationStartup)
{
foreach (var triggerInfo in InternalTriggers)
{
var trigger = triggerInfo.Item2;
trigger.Stop();
trigger.Triggered -= trigger_Triggered;
trigger.Triggered += trigger_Triggered;
trigger.Start(LastExecutionResult, Logger, Name, isApplicationStartup);
}
}
/// <summary>
/// Handles the Triggered event of the trigger control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
2018-09-12 17:26:21 +00:00
async void trigger_Triggered(object sender, EventArgs e)
2016-10-29 05:40:15 +00:00
{
var trigger = (ITaskTrigger)sender;
var configurableTask = ScheduledTask as IConfigurableScheduledTask;
if (configurableTask != null && !configurableTask.IsEnabled)
{
return;
}
Logger.LogInformation("{0} fired for task: {1}", trigger.GetType().Name, Name);
2016-10-29 05:40:15 +00:00
trigger.Stop();
2018-09-12 17:26:21 +00:00
TaskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
2016-10-29 05:40:15 +00:00
await Task.Delay(1000).ConfigureAwait(false);
trigger.Start(LastExecutionResult, Logger, Name, false);
}
private Task _currentTask;
/// <summary>
/// Executes the task
/// </summary>
/// <param name="options">Task options.</param>
/// <returns>Task.</returns>
2019-01-13 20:37:13 +00:00
/// <exception cref="InvalidOperationException">Cannot execute a Task that is already running</exception>
2018-09-12 17:26:21 +00:00
public async Task Execute(TaskOptions options)
2016-10-29 05:40:15 +00:00
{
var task = Task.Run(async () => await ExecuteInternal(options).ConfigureAwait(false));
2016-10-29 05:40:15 +00:00
_currentTask = task;
try
{
await task.ConfigureAwait(false);
}
finally
{
_currentTask = null;
2016-12-13 15:44:34 +00:00
GC.Collect();
2016-10-29 05:40:15 +00:00
}
}
2018-09-12 17:26:21 +00:00
private async Task ExecuteInternal(TaskOptions options)
2016-10-29 05:40:15 +00:00
{
// Cancel the current execution, if any
if (CurrentCancellationTokenSource != null)
{
throw new InvalidOperationException("Cannot execute a Task that is already running");
}
2017-06-23 16:04:45 +00:00
var progress = new SimpleProgress<double>();
2016-10-29 05:40:15 +00:00
CurrentCancellationTokenSource = new CancellationTokenSource();
Logger.LogInformation("Executing {0}", Name);
2016-10-29 05:40:15 +00:00
((TaskManager)TaskManager).OnTaskExecuting(this);
progress.ProgressChanged += progress_ProgressChanged;
TaskCompletionStatus status;
CurrentExecutionStartTime = DateTime.UtcNow;
Exception failureException = null;
try
{
2018-09-12 17:26:21 +00:00
if (options != null && options.MaxRuntimeTicks.HasValue)
2016-10-29 05:40:15 +00:00
{
2018-09-12 17:26:21 +00:00
CurrentCancellationTokenSource.CancelAfter(TimeSpan.FromTicks(options.MaxRuntimeTicks.Value));
2016-10-29 05:40:15 +00:00
}
2018-09-12 17:26:21 +00:00
await ScheduledTask.Execute(CurrentCancellationTokenSource.Token, progress).ConfigureAwait(false);
2016-10-29 05:40:15 +00:00
status = TaskCompletionStatus.Completed;
}
catch (OperationCanceledException)
{
status = TaskCompletionStatus.Cancelled;
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
Logger.LogError(ex, "Error");
2016-10-29 05:40:15 +00:00
failureException = ex;
status = TaskCompletionStatus.Failed;
}
var startTime = CurrentExecutionStartTime;
var endTime = DateTime.UtcNow;
progress.ProgressChanged -= progress_ProgressChanged;
CurrentCancellationTokenSource.Dispose();
CurrentCancellationTokenSource = null;
CurrentProgress = null;
OnTaskCompleted(startTime, endTime, status, failureException);
}
/// <summary>
/// Progress_s the progress changed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
void progress_ProgressChanged(object sender, double e)
{
2017-11-03 18:11:04 +00:00
e = Math.Min(e, 100);
2016-10-29 05:40:15 +00:00
CurrentProgress = e;
TaskProgress?.Invoke(this, new GenericEventArgs<double>
2016-10-29 05:40:15 +00:00
{
Argument = e
});
2016-10-29 05:40:15 +00:00
}
/// <summary>
/// Stops the task if it is currently executing
/// </summary>
2019-01-13 20:37:13 +00:00
/// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
2016-10-29 05:40:15 +00:00
public void Cancel()
{
if (State != TaskState.Running)
{
throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
}
CancelIfRunning();
}
/// <summary>
/// Cancels if running.
/// </summary>
public void CancelIfRunning()
{
if (State == TaskState.Running)
{
Logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
2016-10-29 05:40:15 +00:00
CurrentCancellationTokenSource.Cancel();
}
}
/// <summary>
/// Gets the scheduled tasks configuration directory.
/// </summary>
/// <returns>System.String.</returns>
private string GetScheduledTasksConfigurationDirectory()
{
return Path.Combine(ApplicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
}
/// <summary>
/// Gets the scheduled tasks data directory.
/// </summary>
/// <returns>System.String.</returns>
private string GetScheduledTasksDataDirectory()
{
return Path.Combine(ApplicationPaths.DataPath, "ScheduledTasks");
}
/// <summary>
/// Gets the history file path.
/// </summary>
/// <value>The history file path.</value>
private string GetHistoryFilePath()
{
return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
}
/// <summary>
/// Gets the configuration file path.
/// </summary>
/// <returns>System.String.</returns>
private string GetConfigurationFilePath()
{
return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
}
/// <summary>
/// Loads the triggers.
/// </summary>
/// <returns>IEnumerable{BaseTaskTrigger}.</returns>
private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
{
2016-12-22 15:57:45 +00:00
// This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
var settings = LoadTriggerSettings().Where(i => i != null).ToArray();
2016-10-29 05:40:15 +00:00
return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
}
private TaskTriggerInfo[] LoadTriggerSettings()
{
try
{
2016-12-22 15:57:45 +00:00
var list = JsonSerializer.DeserializeFromFile<IEnumerable<TaskTriggerInfo>>(GetConfigurationFilePath());
if (list != null)
{
return list.ToArray();
}
2016-10-29 05:40:15 +00:00
}
catch (FileNotFoundException)
{
// File doesn't exist. No biggie. Return defaults.
}
catch (DirectoryNotFoundException)
{
// File doesn't exist. No biggie. Return defaults.
}
2018-09-12 17:26:21 +00:00
catch
{
}
return GetDefaultTriggers();
}
private TaskTriggerInfo[] GetDefaultTriggers()
{
try
{
return ScheduledTask.GetDefaultTriggers().ToArray();
}
catch
{
return new TaskTriggerInfo[]
{
new TaskTriggerInfo
{
IntervalTicks = TimeSpan.FromDays(1).Ticks,
Type = TaskTriggerInfo.TriggerInterval
}
};
}
2016-10-29 05:40:15 +00:00
}
/// <summary>
/// Saves the triggers.
/// </summary>
/// <param name="triggers">The triggers.</param>
private void SaveTriggers(TaskTriggerInfo[] triggers)
{
var path = GetConfigurationFilePath();
2018-09-12 17:26:21 +00:00
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
2016-10-29 05:40:15 +00:00
JsonSerializer.SerializeToFile(triggers, path);
}
/// <summary>
/// Called when [task completed].
/// </summary>
/// <param name="startTime">The start time.</param>
/// <param name="endTime">The end time.</param>
/// <param name="status">The status.</param>
private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
{
var elapsedTime = endTime - startTime;
Logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
2016-10-29 05:40:15 +00:00
var result = new TaskResult
{
StartTimeUtc = startTime,
EndTimeUtc = endTime,
Status = status,
Name = Name,
Id = Id
};
result.Key = ScheduledTask.Key;
if (ex != null)
{
result.ErrorMessage = ex.Message;
result.LongErrorMessage = ex.StackTrace;
}
LastExecutionResult = result;
((TaskManager)TaskManager).OnTaskCompleted(this, result);
}
/// <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)
{
if (dispose)
{
DisposeTriggers();
var wassRunning = State == TaskState.Running;
var startTime = CurrentExecutionStartTime;
var token = CurrentCancellationTokenSource;
if (token != null)
{
try
{
Logger.LogInformation(Name + ": Cancelling");
2016-10-29 05:40:15 +00:00
token.Cancel();
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
Logger.LogError(ex, "Error calling CancellationToken.Cancel();");
2016-10-29 05:40:15 +00:00
}
}
var task = _currentTask;
if (task != null)
{
try
{
Logger.LogInformation(Name + ": Waiting on Task");
2016-10-29 05:40:15 +00:00
var exited = Task.WaitAll(new[] { task }, 2000);
if (exited)
{
Logger.LogInformation(Name + ": Task exited");
2016-10-29 05:40:15 +00:00
}
else
{
Logger.LogInformation(Name + ": Timed out waiting for task to stop");
2016-10-29 05:40:15 +00:00
}
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
Logger.LogError(ex, "Error calling Task.WaitAll();");
2016-10-29 05:40:15 +00:00
}
}
if (token != null)
{
try
{
Logger.LogDebug(Name + ": Disposing CancellationToken");
2016-10-29 05:40:15 +00:00
token.Dispose();
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
Logger.LogError(ex, "Error calling CancellationToken.Dispose();");
2016-10-29 05:40:15 +00:00
}
}
if (wassRunning)
{
OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
}
}
}
/// <summary>
/// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger
/// </summary>
/// <param name="info">The info.</param>
/// <returns>BaseTaskTrigger.</returns>
2019-01-13 20:37:13 +00:00
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException">Invalid trigger type: + info.Type</exception>
2016-10-29 05:40:15 +00:00
private ITaskTrigger GetTrigger(TaskTriggerInfo info)
{
2018-09-12 17:26:21 +00:00
var options = new TaskOptions
2016-10-29 05:40:15 +00:00
{
2018-09-12 17:26:21 +00:00
MaxRuntimeTicks = info.MaxRuntimeTicks
2016-10-29 05:40:15 +00:00
};
if (info.Type.Equals(typeof(DailyTrigger).Name, StringComparison.OrdinalIgnoreCase))
{
if (!info.TimeOfDayTicks.HasValue)
{
throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
2016-10-29 05:40:15 +00:00
}
return new DailyTrigger
{
TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
TaskOptions = options
};
}
if (info.Type.Equals(typeof(WeeklyTrigger).Name, StringComparison.OrdinalIgnoreCase))
{
if (!info.TimeOfDayTicks.HasValue)
{
throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
2016-10-29 05:40:15 +00:00
}
if (!info.DayOfWeek.HasValue)
{
throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
2016-10-29 05:40:15 +00:00
}
return new WeeklyTrigger
{
TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
DayOfWeek = info.DayOfWeek.Value,
TaskOptions = options
};
}
if (info.Type.Equals(typeof(IntervalTrigger).Name, StringComparison.OrdinalIgnoreCase))
{
if (!info.IntervalTicks.HasValue)
{
throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
2016-10-29 05:40:15 +00:00
}
return new IntervalTrigger
{
Interval = TimeSpan.FromTicks(info.IntervalTicks.Value),
TaskOptions = options
};
}
if (info.Type.Equals(typeof(SystemEventTrigger).Name, StringComparison.OrdinalIgnoreCase))
{
if (!info.SystemEvent.HasValue)
{
throw new ArgumentException("Info did not contain a SystemEvent.", nameof(info));
2016-10-29 05:40:15 +00:00
}
return new SystemEventTrigger(_systemEvents)
{
SystemEvent = info.SystemEvent.Value,
TaskOptions = options
};
}
if (info.Type.Equals(typeof(StartupTrigger).Name, StringComparison.OrdinalIgnoreCase))
{
return new StartupTrigger();
}
throw new ArgumentException("Unrecognized trigger type: " + info.Type);
}
/// <summary>
/// Disposes each trigger
/// </summary>
private void DisposeTriggers()
{
foreach (var triggerInfo in InternalTriggers)
{
var trigger = triggerInfo.Item2;
trigger.Triggered -= trigger_Triggered;
trigger.Stop();
}
}
}
}