2021-05-20 19:28:18 +00:00
|
|
|
#nullable disable
|
|
|
|
|
2020-05-29 09:28:19 +00:00
|
|
|
#pragma warning disable CS1591
|
|
|
|
|
2019-01-12 20:41:08 +00:00
|
|
|
using System;
|
2019-02-28 22:22:57 +00:00
|
|
|
using System.Globalization;
|
2016-10-29 05:40:15 +00:00
|
|
|
using System.IO;
|
|
|
|
using System.Linq;
|
2020-12-23 12:12:40 +00:00
|
|
|
using System.Text.Json;
|
2016-10-29 05:40:15 +00:00
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
2021-12-15 17:25:36 +00:00
|
|
|
using Emby.Server.Implementations.ScheduledTasks.Triggers;
|
2020-08-14 00:48:28 +00:00
|
|
|
using Jellyfin.Data.Events;
|
2021-10-02 16:53:51 +00:00
|
|
|
using Jellyfin.Extensions.Json;
|
2016-10-29 05:40:15 +00:00
|
|
|
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.Tasks;
|
2019-01-13 19:22:24 +00:00
|
|
|
using Microsoft.Extensions.Logging;
|
2016-10-29 05:40:15 +00:00
|
|
|
|
2017-08-16 06:43:41 +00:00
|
|
|
namespace Emby.Server.Implementations.ScheduledTasks
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
/// <summary>
|
2020-06-15 22:37:52 +00:00
|
|
|
/// Class ScheduledTaskWorker.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
|
|
|
public class ScheduledTaskWorker : IScheduledTaskWorker
|
|
|
|
{
|
2021-10-02 16:53:51 +00:00
|
|
|
/// <summary>
|
|
|
|
/// The options for the json Serializer.
|
|
|
|
/// </summary>
|
|
|
|
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
|
|
|
|
|
2016-10-29 05:40:15 +00:00
|
|
|
/// <summary>
|
|
|
|
/// Gets or sets the application paths.
|
|
|
|
/// </summary>
|
|
|
|
/// <value>The application paths.</value>
|
2020-08-20 10:16:24 +00:00
|
|
|
private readonly IApplicationPaths _applicationPaths;
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
/// <summary>
|
2020-08-20 10:16:24 +00:00
|
|
|
/// Gets or sets the logger.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
|
|
|
/// <value>The logger.</value>
|
2020-08-20 10:16:24 +00:00
|
|
|
private readonly ILogger _logger;
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
/// <summary>
|
2020-08-20 10:16:24 +00:00
|
|
|
/// Gets or sets the task manager.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
|
|
|
/// <value>The task manager.</value>
|
2020-08-20 10:16:24 +00:00
|
|
|
private readonly ITaskManager _taskManager;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// The _last execution result sync lock.
|
|
|
|
/// </summary>
|
|
|
|
private readonly object _lastExecutionResultSyncLock = new object();
|
|
|
|
|
|
|
|
private bool _readFromFile = false;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// The _last execution result.
|
|
|
|
/// </summary>
|
|
|
|
private TaskResult _lastExecutionResult;
|
|
|
|
|
|
|
|
private Task _currentTask;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// The _triggers.
|
|
|
|
/// </summary>
|
|
|
|
private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// The _id.
|
|
|
|
/// </summary>
|
|
|
|
private string _id;
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
/// <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="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
|
2020-08-20 10:16:24 +00:00
|
|
|
/// logger.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </exception>
|
2020-12-23 12:12:40 +00:00
|
|
|
public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, ILogger logger)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
2022-10-06 18:21:23 +00:00
|
|
|
ArgumentNullException.ThrowIfNull(scheduledTask);
|
|
|
|
ArgumentNullException.ThrowIfNull(applicationPaths);
|
|
|
|
ArgumentNullException.ThrowIfNull(taskManager);
|
|
|
|
ArgumentNullException.ThrowIfNull(logger);
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
ScheduledTask = scheduledTask;
|
2020-08-20 10:16:24 +00:00
|
|
|
_applicationPaths = applicationPaths;
|
|
|
|
_taskManager = taskManager;
|
|
|
|
_logger = logger;
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
InitTriggerEvents();
|
|
|
|
}
|
|
|
|
|
2020-08-20 10:16:24 +00:00
|
|
|
public event EventHandler<GenericEventArgs<double>> TaskProgress;
|
|
|
|
|
2016-10-29 05:40:15 +00:00
|
|
|
/// <summary>
|
2020-08-20 10:16:24 +00:00
|
|
|
/// Gets the scheduled task.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
2020-08-20 10:16:24 +00:00
|
|
|
/// <value>The scheduled task.</value>
|
|
|
|
public IScheduledTask ScheduledTask { get; private set; }
|
|
|
|
|
2016-10-29 05:40:15 +00:00
|
|
|
/// <summary>
|
|
|
|
/// Gets the last execution result.
|
|
|
|
/// </summary>
|
|
|
|
/// <value>The last execution result.</value>
|
|
|
|
public TaskResult LastExecutionResult
|
|
|
|
{
|
|
|
|
get
|
|
|
|
{
|
|
|
|
var path = GetHistoryFilePath();
|
|
|
|
|
|
|
|
lock (_lastExecutionResultSyncLock)
|
|
|
|
{
|
2022-12-05 14:00:20 +00:00
|
|
|
if (_lastExecutionResult is null && !_readFromFile)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
2019-01-27 16:00:17 +00:00
|
|
|
if (File.Exists(path))
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
2021-01-12 14:28:02 +00:00
|
|
|
var bytes = File.ReadAllBytes(path);
|
|
|
|
if (bytes.Length > 0)
|
2019-01-27 16:00:17 +00:00
|
|
|
{
|
2021-01-12 14:28:02 +00:00
|
|
|
try
|
2020-12-24 09:31:51 +00:00
|
|
|
{
|
2021-01-12 14:28:02 +00:00
|
|
|
_lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(bytes, _jsonOptions);
|
2020-12-24 09:31:51 +00:00
|
|
|
}
|
2021-01-12 14:28:02 +00:00
|
|
|
catch (JsonException ex)
|
2020-12-24 09:31:51 +00:00
|
|
|
{
|
2021-01-12 14:28:02 +00:00
|
|
|
_logger.LogError(ex, "Error deserializing {File}", path);
|
2020-12-24 09:31:51 +00:00
|
|
|
}
|
2019-01-27 16:00:17 +00:00
|
|
|
}
|
2021-01-12 14:28:02 +00:00
|
|
|
else
|
2019-01-27 16:00:17 +00:00
|
|
|
{
|
2021-01-12 14:28:02 +00:00
|
|
|
_logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path);
|
2019-01-27 16:00:17 +00:00
|
|
|
}
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
2020-06-15 21:43:52 +00:00
|
|
|
|
2016-10-29 05:40:15 +00:00
|
|
|
_readFromFile = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return _lastExecutionResult;
|
|
|
|
}
|
2020-06-15 21:43:52 +00:00
|
|
|
|
2016-10-29 05:40:15 +00:00
|
|
|
private set
|
|
|
|
{
|
|
|
|
_lastExecutionResult = value;
|
|
|
|
|
|
|
|
var path = GetHistoryFilePath();
|
2019-01-26 21:08:04 +00:00
|
|
|
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
lock (_lastExecutionResultSyncLock)
|
|
|
|
{
|
2021-01-12 14:51:32 +00:00
|
|
|
using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
|
2021-04-10 21:54:35 +00:00
|
|
|
using Utf8JsonWriter jsonStream = new Utf8JsonWriter(createStream);
|
|
|
|
JsonSerializer.Serialize(jsonStream, value, _jsonOptions);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Gets the name.
|
|
|
|
/// </summary>
|
|
|
|
/// <value>The name.</value>
|
2019-01-06 20:50:43 +00:00
|
|
|
public string Name => ScheduledTask.Name;
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Gets the description.
|
|
|
|
/// </summary>
|
|
|
|
/// <value>The description.</value>
|
2019-01-06 20:50:43 +00:00
|
|
|
public string Description => ScheduledTask.Description;
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Gets the category.
|
|
|
|
/// </summary>
|
|
|
|
/// <value>The category.</value>
|
2019-01-06 20:50:43 +00:00
|
|
|
public string Category => ScheduledTask.Category;
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
/// <summary>
|
2020-08-20 10:16:24 +00:00
|
|
|
/// Gets or sets the current cancellation token.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </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
|
|
|
|
{
|
2022-12-05 14:01:13 +00:00
|
|
|
if (CurrentCancellationTokenSource is not null)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
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>
|
2020-08-20 10:16:24 +00:00
|
|
|
/// Gets or sets the triggers that define when the task will run.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
|
|
|
/// <value>The triggers.</value>
|
|
|
|
private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
|
|
|
|
{
|
2019-01-06 20:50:43 +00:00
|
|
|
get => _triggers;
|
2016-10-29 05:40:15 +00:00
|
|
|
set
|
|
|
|
{
|
2022-10-06 18:21:23 +00:00
|
|
|
ArgumentNullException.ThrowIfNull(value);
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
// Cleanup current triggers
|
2022-12-05 14:01:13 +00:00
|
|
|
if (_triggers is not null)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
DisposeTriggers();
|
|
|
|
}
|
|
|
|
|
|
|
|
_triggers = value.ToArray();
|
|
|
|
|
|
|
|
ReloadTriggerEvents(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2021-08-28 22:32:50 +00:00
|
|
|
/// Gets or sets the triggers that define when the task will run.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
|
|
|
/// <value>The triggers.</value>
|
2020-08-20 10:16:24 +00:00
|
|
|
/// <exception cref="ArgumentNullException"><c>value</c> is <c>null</c>.</exception>
|
2016-10-29 05:40:15 +00:00
|
|
|
public TaskTriggerInfo[] Triggers
|
|
|
|
{
|
|
|
|
get
|
|
|
|
{
|
2017-08-09 19:56:38 +00:00
|
|
|
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
|
|
|
}
|
2020-06-15 21:43:52 +00:00
|
|
|
|
2016-10-29 05:40:15 +00:00
|
|
|
set
|
|
|
|
{
|
2022-10-06 18:21:23 +00:00
|
|
|
ArgumentNullException.ThrowIfNull(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
|
2022-12-05 14:01:13 +00:00
|
|
|
var triggerList = value.Where(i => i is not 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>
|
|
|
|
/// Gets the unique id.
|
|
|
|
/// </summary>
|
|
|
|
/// <value>The unique id.</value>
|
|
|
|
public string Id
|
|
|
|
{
|
|
|
|
get
|
|
|
|
{
|
2021-05-05 11:51:14 +00:00
|
|
|
return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
2020-08-20 10:16:24 +00:00
|
|
|
trigger.Triggered -= OnTriggerTriggered;
|
|
|
|
trigger.Triggered += OnTriggerTriggered;
|
|
|
|
trigger.Start(LastExecutionResult, _logger, Name, isApplicationStartup);
|
2016-10-29 05:40:15 +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>
|
2020-08-20 10:16:24 +00:00
|
|
|
private async void OnTriggerTriggered(object sender, EventArgs e)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
var trigger = (ITaskTrigger)sender;
|
|
|
|
|
2021-05-05 11:37:36 +00:00
|
|
|
if (ScheduledTask is IConfigurableScheduledTask configurableTask && !configurableTask.IsEnabled)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-03-01 15:43:55 +00:00
|
|
|
_logger.LogDebug("{0} fired for task: {1}", trigger.GetType().Name, Name);
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
trigger.Stop();
|
|
|
|
|
2020-08-20 10:16:24 +00:00
|
|
|
_taskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
await Task.Delay(1000).ConfigureAwait(false);
|
|
|
|
|
2020-08-20 10:16:24 +00:00
|
|
|
trigger.Start(LastExecutionResult, _logger, Name, false);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2020-06-15 22:37:52 +00:00
|
|
|
/// Executes the task.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
|
|
|
/// <param name="options">Task options.</param>
|
|
|
|
/// <returns>Task.</returns>
|
2021-10-02 16:53:51 +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
|
|
|
{
|
2017-02-19 03:46:09 +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
|
2022-12-05 14:01:13 +00:00
|
|
|
if (CurrentCancellationTokenSource is not null)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
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();
|
|
|
|
|
2023-03-01 15:43:55 +00:00
|
|
|
_logger.LogDebug("Executing {0}", Name);
|
2016-10-29 05:40:15 +00:00
|
|
|
|
2020-08-20 10:16:24 +00:00
|
|
|
((TaskManager)_taskManager).OnTaskExecuting(this);
|
2016-10-29 05:40:15 +00:00
|
|
|
|
2020-04-05 16:10:56 +00:00
|
|
|
progress.ProgressChanged += OnProgressChanged;
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
TaskCompletionStatus status;
|
|
|
|
CurrentExecutionStartTime = DateTime.UtcNow;
|
|
|
|
|
|
|
|
Exception failureException = null;
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
2022-12-05 14:01:13 +00:00
|
|
|
if (options is not 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
|
|
|
}
|
|
|
|
|
2022-02-15 17:59:46 +00:00
|
|
|
await ScheduledTask.ExecuteAsync(progress, CurrentCancellationTokenSource.Token).ConfigureAwait(false);
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
status = TaskCompletionStatus.Completed;
|
|
|
|
}
|
|
|
|
catch (OperationCanceledException)
|
|
|
|
{
|
|
|
|
status = TaskCompletionStatus.Cancelled;
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
2023-03-01 15:43:55 +00:00
|
|
|
_logger.LogError(ex, "Error executing Scheduled Task");
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
failureException = ex;
|
|
|
|
|
|
|
|
status = TaskCompletionStatus.Failed;
|
|
|
|
}
|
|
|
|
|
|
|
|
var startTime = CurrentExecutionStartTime;
|
|
|
|
var endTime = DateTime.UtcNow;
|
|
|
|
|
2020-04-05 16:10:56 +00:00
|
|
|
progress.ProgressChanged -= OnProgressChanged;
|
2016-10-29 05:40:15 +00:00
|
|
|
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>
|
2020-04-05 16:10:56 +00:00
|
|
|
private void OnProgressChanged(object sender, double e)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
2017-11-03 18:11:04 +00:00
|
|
|
e = Math.Min(e, 100);
|
|
|
|
|
2016-10-29 05:40:15 +00:00
|
|
|
CurrentProgress = e;
|
|
|
|
|
2020-04-05 16:10:56 +00:00
|
|
|
TaskProgress?.Invoke(this, new GenericEventArgs<double>(e));
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2020-06-15 22:37:52 +00:00
|
|
|
/// Stops the task if it is currently executing.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </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)
|
|
|
|
{
|
2020-08-20 10:16:24 +00:00
|
|
|
_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()
|
|
|
|
{
|
2020-08-20 10:16:24 +00:00
|
|
|
return Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Gets the scheduled tasks data directory.
|
|
|
|
/// </summary>
|
|
|
|
/// <returns>System.String.</returns>
|
|
|
|
private string GetScheduledTasksDataDirectory()
|
|
|
|
{
|
2020-08-20 10:16:24 +00:00
|
|
|
return Path.Combine(_applicationPaths.DataPath, "ScheduledTasks");
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <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
|
2022-12-05 14:01:13 +00:00
|
|
|
var settings = LoadTriggerSettings().Where(i => i is not 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()
|
|
|
|
{
|
2019-01-27 16:00:17 +00:00
|
|
|
string path = GetConfigurationFilePath();
|
2019-01-27 19:18:51 +00:00
|
|
|
TaskTriggerInfo[] list = null;
|
|
|
|
if (File.Exists(path))
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
2021-01-12 14:28:02 +00:00
|
|
|
var bytes = File.ReadAllBytes(path);
|
|
|
|
list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(bytes, _jsonOptions);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
2018-09-12 17:26:21 +00:00
|
|
|
|
2019-01-27 19:18:51 +00:00
|
|
|
// Return defaults if file doesn't exist.
|
2019-01-27 16:00:17 +00:00
|
|
|
return list ?? GetDefaultTriggers();
|
2018-09-12 17:26:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
2019-01-26 21:08:04 +00:00
|
|
|
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
2021-01-12 14:51:32 +00:00
|
|
|
using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
|
2021-04-10 21:54:35 +00:00
|
|
|
using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream);
|
|
|
|
JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <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>
|
2020-05-29 09:28:19 +00:00
|
|
|
/// <param name="ex">The exception.</param>
|
2016-10-29 05:40:15 +00:00
|
|
|
private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
|
|
|
|
{
|
|
|
|
var elapsedTime = endTime - startTime;
|
|
|
|
|
2020-08-20 10:16:24 +00:00
|
|
|
_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;
|
|
|
|
|
2022-12-05 14:01:13 +00:00
|
|
|
if (ex is not null)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
result.ErrorMessage = ex.Message;
|
|
|
|
result.LongErrorMessage = ex.StackTrace;
|
|
|
|
}
|
|
|
|
|
|
|
|
LastExecutionResult = result;
|
|
|
|
|
2020-08-20 10:16:24 +00:00
|
|
|
((TaskManager)_taskManager).OnTaskCompleted(this, result);
|
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);
|
2020-08-20 10:16:24 +00:00
|
|
|
GC.SuppressFinalize(this);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <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;
|
2022-12-05 14:01:13 +00:00
|
|
|
if (token is not null)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
2021-11-09 21:29:33 +00:00
|
|
|
_logger.LogInformation("{Name}: Cancelling", Name);
|
2016-10-29 05:40:15 +00:00
|
|
|
token.Cancel();
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
2020-08-20 10:16:24 +00:00
|
|
|
_logger.LogError(ex, "Error calling CancellationToken.Cancel();");
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
}
|
2020-06-15 21:43:52 +00:00
|
|
|
|
2016-10-29 05:40:15 +00:00
|
|
|
var task = _currentTask;
|
2022-12-05 14:01:13 +00:00
|
|
|
if (task is not null)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
2021-11-09 21:29:33 +00:00
|
|
|
_logger.LogInformation("{Name}: Waiting on Task", Name);
|
2020-11-14 19:30:08 +00:00
|
|
|
var exited = task.Wait(2000);
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
if (exited)
|
|
|
|
{
|
2021-11-09 21:29:33 +00:00
|
|
|
_logger.LogInformation("{Name}: Task exited", Name);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2021-11-09 21:29:33 +00:00
|
|
|
_logger.LogInformation("{Name}: Timed out waiting for task to stop", Name);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
2020-08-20 10:16:24 +00:00
|
|
|
_logger.LogError(ex, "Error calling Task.WaitAll();");
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-05 14:01:13 +00:00
|
|
|
if (token is not null)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
2021-11-09 21:29:33 +00:00
|
|
|
_logger.LogDebug("{Name}: Disposing CancellationToken", Name);
|
2016-10-29 05:40:15 +00:00
|
|
|
token.Dispose();
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
2020-08-20 10:16:24 +00:00
|
|
|
_logger.LogError(ex, "Error calling CancellationToken.Dispose();");
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
}
|
2020-06-15 21:43:52 +00:00
|
|
|
|
2016-10-29 05:40:15 +00:00
|
|
|
if (wassRunning)
|
|
|
|
{
|
|
|
|
OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2020-06-15 22:37:52 +00:00
|
|
|
/// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
|
|
|
/// <param name="info">The info.</param>
|
|
|
|
/// <returns>BaseTaskTrigger.</returns>
|
2020-08-20 10:16:24 +00:00
|
|
|
/// <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
|
|
|
};
|
|
|
|
|
2020-10-17 14:19:57 +00:00
|
|
|
if (info.Type.Equals(nameof(DailyTrigger), StringComparison.OrdinalIgnoreCase))
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
if (!info.TimeOfDayTicks.HasValue)
|
|
|
|
{
|
2019-01-13 19:22:24 +00:00
|
|
|
throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
2021-05-28 12:33:54 +00:00
|
|
|
return new DailyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), options);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
2020-10-17 14:19:57 +00:00
|
|
|
if (info.Type.Equals(nameof(WeeklyTrigger), StringComparison.OrdinalIgnoreCase))
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
if (!info.TimeOfDayTicks.HasValue)
|
|
|
|
{
|
2019-01-06 20:50:43 +00:00
|
|
|
throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!info.DayOfWeek.HasValue)
|
|
|
|
{
|
2019-01-06 20:50:43 +00:00
|
|
|
throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
2021-05-28 12:33:54 +00:00
|
|
|
return new WeeklyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), info.DayOfWeek.Value, options);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
2020-10-17 14:19:57 +00:00
|
|
|
if (info.Type.Equals(nameof(IntervalTrigger), StringComparison.OrdinalIgnoreCase))
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
if (!info.IntervalTicks.HasValue)
|
|
|
|
{
|
2019-01-06 20:50:43 +00:00
|
|
|
throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
2021-05-28 12:33:54 +00:00
|
|
|
return new IntervalTrigger(TimeSpan.FromTicks(info.IntervalTicks.Value), options);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
2020-10-17 14:19:57 +00:00
|
|
|
if (info.Type.Equals(nameof(StartupTrigger), StringComparison.OrdinalIgnoreCase))
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
2021-05-28 12:33:54 +00:00
|
|
|
return new StartupTrigger(options);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new ArgumentException("Unrecognized trigger type: " + info.Type);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2020-06-15 22:37:52 +00:00
|
|
|
/// Disposes each trigger.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
|
|
|
private void DisposeTriggers()
|
|
|
|
{
|
|
|
|
foreach (var triggerInfo in InternalTriggers)
|
|
|
|
{
|
|
|
|
var trigger = triggerInfo.Item2;
|
2020-08-20 10:16:24 +00:00
|
|
|
trigger.Triggered -= OnTriggerTriggered;
|
2016-10-29 05:40:15 +00:00
|
|
|
trigger.Stop();
|
2022-02-15 17:59:46 +00:00
|
|
|
if (trigger is IDisposable disposable)
|
|
|
|
{
|
|
|
|
disposable.Dispose();
|
|
|
|
}
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|