jellyfin-server/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs

671 lines
21 KiB
C#
Raw Normal View History

2013-03-04 05:43:06 +00:00
using MediaBrowser.Common.Configuration;
2014-05-10 17:28:03 +00:00
using MediaBrowser.Common.Events;
2013-03-04 05:43:06 +00:00
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.ScheduledTasks;
2014-05-10 17:28:03 +00:00
using MediaBrowser.Model.Events;
2013-02-21 01:33:05 +00:00
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
2013-02-21 01:33:05 +00:00
using MediaBrowser.Model.Tasks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2015-10-04 04:23:11 +00:00
using CommonIO;
2013-02-21 01:33:05 +00:00
namespace MediaBrowser.Common.Implementations.ScheduledTasks
2013-02-21 01:33:05 +00:00
{
/// <summary>
/// Class ScheduledTaskWorker
2013-02-21 01:33:05 +00:00
/// </summary>
public class ScheduledTaskWorker : IScheduledTaskWorker
2013-02-21 01:33:05 +00:00
{
2014-05-10 17:28:03 +00:00
public event EventHandler<GenericEventArgs<double>> TaskProgress;
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets or sets the scheduled task.
2013-02-21 01:33:05 +00:00
/// </summary>
/// <value>The scheduled task.</value>
public IScheduledTask ScheduledTask { get; private set; }
/// <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; }
2013-02-21 01:33:05 +00:00
2013-02-23 07:57:11 +00:00
/// <summary>
/// Gets the logger.
/// </summary>
/// <value>The logger.</value>
private ILogger Logger { get; set; }
2013-02-23 07:57:11 +00:00
/// <summary>
/// Gets the task manager.
/// </summary>
/// <value>The task manager.</value>
private ITaskManager TaskManager { get; set; }
2015-09-13 23:07:54 +00:00
private readonly IFileSystem _fileSystem;
2013-02-23 07:57:11 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
2013-02-23 07:57:11 +00:00
/// </summary>
/// <param name="scheduledTask">The scheduled task.</param>
/// <param name="applicationPaths">The application paths.</param>
2013-02-23 07:57:11 +00:00
/// <param name="taskManager">The task manager.</param>
/// <param name="jsonSerializer">The json serializer.</param>
2013-02-23 07:57:11 +00:00
/// <param name="logger">The logger.</param>
/// <exception cref="System.ArgumentNullException">
/// scheduledTask
/// or
/// applicationPaths
/// or
/// taskManager
/// or
/// jsonSerializer
/// or
/// logger
/// </exception>
2015-09-13 23:07:54 +00:00
public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem)
2013-02-23 07:57:11 +00:00
{
if (scheduledTask == null)
{
throw new ArgumentNullException("scheduledTask");
}
if (applicationPaths == null)
{
throw new ArgumentNullException("applicationPaths");
}
if (taskManager == null)
{
throw new ArgumentNullException("taskManager");
}
if (jsonSerializer == null)
{
throw new ArgumentNullException("jsonSerializer");
}
if (logger == null)
{
throw new ArgumentNullException("logger");
}
ScheduledTask = scheduledTask;
ApplicationPaths = applicationPaths;
2013-02-23 07:57:11 +00:00
TaskManager = taskManager;
JsonSerializer = jsonSerializer;
2013-02-23 07:57:11 +00:00
Logger = logger;
2015-09-13 23:07:54 +00:00
_fileSystem = fileSystem;
2013-02-27 04:19:05 +00:00
2016-02-24 05:36:58 +00:00
InitTriggerEvents();
2013-02-23 07:57:11 +00:00
}
2016-07-01 15:04:08 +00:00
private bool _readFromFile = false;
2013-02-21 01:33:05 +00:00
/// <summary>
/// The _last execution result
/// </summary>
private TaskResult _lastExecutionResult;
/// <summary>
/// The _last execution result sync lock
/// </summary>
private readonly object _lastExecutionResultSyncLock = new object();
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the last execution result.
/// </summary>
/// <value>The last execution result.</value>
public TaskResult LastExecutionResult
{
get
{
2016-06-29 18:48:26 +00:00
var path = GetHistoryFilePath();
2015-04-13 16:34:36 +00:00
2016-06-29 18:48:26 +00:00
lock (_lastExecutionResultSyncLock)
{
2016-07-01 15:04:08 +00:00
if (_lastExecutionResult == null && !_readFromFile)
2013-06-04 02:02:49 +00:00
{
2016-06-29 18:48:26 +00:00
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)
{
2016-06-29 18:48:26 +00:00
Logger.ErrorException("Error deserializing {0}", ex, path);
}
2016-07-01 15:04:08 +00:00
_readFromFile = true;
}
}
2013-02-21 01:33:05 +00:00
return _lastExecutionResult;
}
private set
{
_lastExecutionResult = value;
2015-04-13 16:34:36 +00:00
var path = GetHistoryFilePath();
2015-09-13 21:32:02 +00:00
_fileSystem.CreateDirectory(Path.GetDirectoryName(path));
2015-04-13 16:34:36 +00:00
lock (_lastExecutionResultSyncLock)
{
JsonSerializer.SerializeToFile(value, path);
}
2013-02-21 01:33:05 +00:00
}
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get { return ScheduledTask.Name; }
}
/// <summary>
/// Gets the description.
/// </summary>
/// <value>The description.</value>
public string Description
{
get { return ScheduledTask.Description; }
}
/// <summary>
/// Gets the category.
/// </summary>
/// <value>The category.</value>
public string Category
{
get { return ScheduledTask.Category; }
}
2013-02-21 01:33:05 +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>
2013-02-22 04:23:06 +00:00
public double? CurrentProgress { get; private set; }
2013-02-21 01:33:05 +00:00
/// <summary>
/// The _triggers
/// </summary>
2016-02-24 05:36:58 +00:00
private List<ITaskTrigger> _triggers;
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the triggers that define when the task will run
/// </summary>
/// <value>The triggers.</value>
/// <exception cref="System.ArgumentNullException">value</exception>
2013-02-24 21:53:54 +00:00
public IEnumerable<ITaskTrigger> Triggers
2013-02-21 01:33:05 +00:00
{
get
{
return _triggers;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
// Cleanup current triggers
if (_triggers != null)
{
DisposeTriggers();
}
_triggers = value.ToList();
2013-02-23 07:57:11 +00:00
ReloadTriggerEvents(false);
2013-02-21 01:33:05 +00:00
SaveTriggers(_triggers);
2013-02-21 01:33:05 +00:00
}
}
/// <summary>
/// The _id
/// </summary>
2014-05-09 19:43:06 +00:00
private string _id;
2013-02-24 21:53:54 +00:00
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the unique id.
/// </summary>
/// <value>The unique id.</value>
2014-05-09 19:43:06 +00:00
public string Id
2013-02-21 01:33:05 +00:00
{
get
{
2014-05-09 19:43:06 +00:00
if (_id == null)
2013-02-21 01:33:05 +00:00
{
2014-05-09 19:43:06 +00:00
_id = ScheduledTask.GetType().FullName.GetMD5().ToString("N");
2013-02-21 01:33:05 +00:00
}
2014-05-09 19:43:06 +00:00
return _id;
2013-02-21 01:33:05 +00:00
}
}
2016-02-24 05:36:58 +00:00
private void InitTriggerEvents()
{
_triggers = LoadTriggers();
ReloadTriggerEvents(true);
}
2015-10-25 15:48:44 +00:00
public void ReloadTriggerEvents()
{
ReloadTriggerEvents(false);
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Reloads the trigger events.
/// </summary>
2013-02-23 07:57:11 +00:00
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
private void ReloadTriggerEvents(bool isApplicationStartup)
2013-02-21 01:33:05 +00:00
{
foreach (var trigger in Triggers)
{
trigger.Stop();
trigger.Triggered -= trigger_Triggered;
trigger.Triggered += trigger_Triggered;
2016-05-12 19:21:43 +00:00
trigger.Start(LastExecutionResult, Logger, Name, isApplicationStartup);
2013-02-21 01:33:05 +00:00
}
}
/// <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>
async void trigger_Triggered(object sender, GenericEventArgs<TaskExecutionOptions> e)
2013-02-21 01:33:05 +00:00
{
2013-02-24 21:53:54 +00:00
var trigger = (ITaskTrigger)sender;
2013-02-21 01:33:05 +00:00
var configurableTask = ScheduledTask as IConfigurableScheduledTask;
if (configurableTask != null && !configurableTask.IsEnabled)
{
return;
}
2013-02-21 01:33:05 +00:00
Logger.Info("{0} fired for task: {1}", trigger.GetType().Name, Name);
2013-02-24 21:53:54 +00:00
trigger.Stop();
TaskManager.QueueScheduledTask(ScheduledTask, e.Argument);
await Task.Delay(1000).ConfigureAwait(false);
2013-02-24 21:53:54 +00:00
2016-05-12 19:21:43 +00:00
trigger.Start(LastExecutionResult, Logger, Name, false);
2013-02-21 01:33:05 +00:00
}
2015-02-08 18:21:24 +00:00
private Task _currentTask;
2013-02-21 01:33:05 +00:00
/// <summary>
/// Executes the task
/// </summary>
/// <param name="options">Task options.</param>
2013-02-21 01:33:05 +00:00
/// <returns>Task.</returns>
/// <exception cref="System.InvalidOperationException">Cannot execute a Task that is already running</exception>
public async Task Execute(TaskExecutionOptions options)
2015-02-08 18:21:24 +00:00
{
var task = ExecuteInternal(options);
2015-02-08 18:21:24 +00:00
_currentTask = task;
try
{
await task.ConfigureAwait(false);
}
finally
{
_currentTask = null;
}
}
private async Task ExecuteInternal(TaskExecutionOptions options)
2013-02-21 01:33:05 +00:00
{
// Cancel the current execution, if any
if (CurrentCancellationTokenSource != null)
{
throw new InvalidOperationException("Cannot execute a Task that is already running");
}
2014-05-10 17:28:03 +00:00
var progress = new Progress<double>();
2013-02-21 01:33:05 +00:00
CurrentCancellationTokenSource = new CancellationTokenSource();
Logger.Info("Executing {0}", Name);
2014-05-10 17:28:03 +00:00
((TaskManager)TaskManager).OnTaskExecuting(this);
2013-02-21 01:33:05 +00:00
progress.ProgressChanged += progress_ProgressChanged;
TaskCompletionStatus status;
CurrentExecutionStartTime = DateTime.UtcNow;
2013-07-06 21:23:32 +00:00
Exception failureException = null;
2013-02-21 01:33:05 +00:00
try
{
var localTask = ScheduledTask.Execute(CurrentCancellationTokenSource.Token, progress);
if (options != null && options.MaxRuntimeMs.HasValue)
{
CurrentCancellationTokenSource.CancelAfter(options.MaxRuntimeMs.Value);
}
await localTask.ConfigureAwait(false);
2013-02-21 01:33:05 +00:00
status = TaskCompletionStatus.Completed;
}
catch (OperationCanceledException)
{
status = TaskCompletionStatus.Cancelled;
}
catch (Exception ex)
{
Logger.ErrorException("Error", ex);
2013-07-06 21:23:32 +00:00
failureException = ex;
2013-02-21 01:33:05 +00:00
status = TaskCompletionStatus.Failed;
}
2013-02-24 21:53:54 +00:00
var startTime = CurrentExecutionStartTime;
2013-02-21 01:33:05 +00:00
var endTime = DateTime.UtcNow;
progress.ProgressChanged -= progress_ProgressChanged;
CurrentCancellationTokenSource.Dispose();
CurrentCancellationTokenSource = null;
CurrentProgress = null;
2013-07-06 21:23:32 +00:00
OnTaskCompleted(startTime, endTime, status, failureException);
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Progress_s the progress changed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
2013-02-22 04:23:06 +00:00
void progress_ProgressChanged(object sender, double e)
2013-02-21 01:33:05 +00:00
{
CurrentProgress = e;
2014-05-10 17:28:03 +00:00
EventHelper.FireEventIfNotNull(TaskProgress, this, new GenericEventArgs<double>
{
Argument = e
}, Logger);
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Stops the task if it is currently executing
/// </summary>
/// <exception cref="System.InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
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.Info("Attempting to cancel Scheduled Task {0}", Name);
CurrentCancellationTokenSource.Cancel();
}
}
/// <summary>
/// Gets the scheduled tasks configuration directory.
/// </summary>
2013-06-04 02:02:49 +00:00
/// <returns>System.String.</returns>
2013-12-29 17:07:29 +00:00
private string GetScheduledTasksConfigurationDirectory()
{
2013-12-29 17:07:29 +00:00
return Path.Combine(ApplicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
}
/// <summary>
/// Gets the scheduled tasks data directory.
/// </summary>
2013-06-04 02:02:49 +00:00
/// <returns>System.String.</returns>
2013-12-29 17:07:29 +00:00
private string GetScheduledTasksDataDirectory()
{
2013-12-29 17:07:29 +00:00
return Path.Combine(ApplicationPaths.DataPath, "ScheduledTasks");
}
/// <summary>
/// Gets the history file path.
/// </summary>
/// <value>The history file path.</value>
2013-12-29 17:07:29 +00:00
private string GetHistoryFilePath()
{
2014-05-09 19:43:06 +00:00
return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
}
/// <summary>
/// Gets the configuration file path.
/// </summary>
/// <returns>System.String.</returns>
private string GetConfigurationFilePath()
{
2014-05-09 19:43:06 +00:00
return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
}
/// <summary>
/// Loads the triggers.
/// </summary>
/// <returns>IEnumerable{BaseTaskTrigger}.</returns>
2016-02-01 00:57:40 +00:00
private List<ITaskTrigger> LoadTriggers()
{
try
{
return JsonSerializer.DeserializeFromFile<IEnumerable<TaskTriggerInfo>>(GetConfigurationFilePath())
.Select(ScheduledTaskHelpers.GetTrigger)
.ToList();
}
2013-06-04 02:02:49 +00:00
catch (FileNotFoundException)
{
// File doesn't exist. No biggie. Return defaults.
2016-02-01 00:57:40 +00:00
return ScheduledTask.GetDefaultTriggers().ToList();
2013-06-04 02:02:49 +00:00
}
catch (DirectoryNotFoundException)
{
// File doesn't exist. No biggie. Return defaults.
2016-02-01 00:57:40 +00:00
return ScheduledTask.GetDefaultTriggers().ToList();
}
}
/// <summary>
/// Saves the triggers.
/// </summary>
/// <param name="triggers">The triggers.</param>
private void SaveTriggers(IEnumerable<ITaskTrigger> triggers)
{
var path = GetConfigurationFilePath();
2015-09-13 21:32:02 +00:00
_fileSystem.CreateDirectory(Path.GetDirectoryName(path));
JsonSerializer.SerializeToFile(triggers.Select(ScheduledTaskHelpers.GetTriggerInfo), 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>
2013-07-06 21:23:32 +00:00
private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
{
var elapsedTime = endTime - startTime;
Logger.Info("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
var result = new TaskResult
{
StartTimeUtc = startTime,
EndTimeUtc = endTime,
Status = status,
Name = Name,
2014-05-09 19:43:06 +00:00
Id = Id
};
2015-01-24 19:03:55 +00:00
var hasKey = ScheduledTask as IHasKey;
if (hasKey != null)
{
result.Key = hasKey.Key;
}
2013-07-06 21:23:32 +00:00
if (ex != null)
{
result.ErrorMessage = ex.Message;
2014-08-10 22:13:17 +00:00
result.LongErrorMessage = ex.StackTrace;
2013-07-06 21:23:32 +00:00
}
LastExecutionResult = result;
2014-05-10 17:28:03 +00:00
((TaskManager)TaskManager).OnTaskCompleted(this, result);
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <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();
2015-02-08 18:21:24 +00:00
var wassRunning = State == TaskState.Running;
var startTime = CurrentExecutionStartTime;
var token = CurrentCancellationTokenSource;
if (token != null)
{
try
{
2015-10-04 22:04:56 +00:00
Logger.Info(Name + ": Cancelling");
2015-02-08 18:21:24 +00:00
token.Cancel();
}
catch (Exception ex)
{
Logger.ErrorException("Error calling CancellationToken.Cancel();", ex);
}
}
var task = _currentTask;
if (task != null)
2013-02-21 01:33:05 +00:00
{
2015-02-08 18:21:24 +00:00
try
{
2015-10-04 22:04:56 +00:00
Logger.Info(Name + ": Waiting on Task");
2015-02-08 18:21:24 +00:00
var exited = Task.WaitAll(new[] { task }, 2000);
if (exited)
{
2015-10-04 22:04:56 +00:00
Logger.Info(Name + ": Task exited");
2015-02-08 18:21:24 +00:00
}
else
{
2015-10-04 22:04:56 +00:00
Logger.Info(Name + ": Timed out waiting for task to stop");
2015-02-08 18:21:24 +00:00
}
}
catch (Exception ex)
{
Logger.ErrorException("Error calling Task.WaitAll();", ex);
}
2013-02-21 01:33:05 +00:00
}
2015-02-08 18:21:24 +00:00
if (token != null)
{
try
{
Logger.Debug(Name + ": Disposing CancellationToken");
token.Dispose();
}
catch (Exception ex)
{
Logger.ErrorException("Error calling CancellationToken.Dispose();", ex);
}
}
if (wassRunning)
2013-02-21 01:33:05 +00:00
{
2015-02-08 18:21:24 +00:00
OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
2013-02-21 01:33:05 +00:00
}
}
}
/// <summary>
/// Disposes each trigger
/// </summary>
private void DisposeTriggers()
{
foreach (var trigger in Triggers)
{
trigger.Triggered -= trigger_Triggered;
2013-02-24 21:53:54 +00:00
trigger.Stop();
2013-02-21 01:33:05 +00:00
}
}
}
}