ScheduledTaskWorker.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. #nullable disable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text.Json;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Emby.Server.Implementations.ScheduledTasks.Triggers;
  11. using Jellyfin.Data.Events;
  12. using Jellyfin.Extensions.Json;
  13. using MediaBrowser.Common.Configuration;
  14. using MediaBrowser.Common.Extensions;
  15. using MediaBrowser.Model.Tasks;
  16. using Microsoft.Extensions.Logging;
  17. namespace Emby.Server.Implementations.ScheduledTasks
  18. {
  19. /// <summary>
  20. /// Class ScheduledTaskWorker.
  21. /// </summary>
  22. public class ScheduledTaskWorker : IScheduledTaskWorker
  23. {
  24. private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  25. private readonly IApplicationPaths _applicationPaths;
  26. private readonly ILogger _logger;
  27. private readonly ITaskManager _taskManager;
  28. private readonly Lock _lastExecutionResultSyncLock = new();
  29. private bool _readFromFile;
  30. private TaskResult _lastExecutionResult;
  31. private Task _currentTask;
  32. private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
  33. private string _id;
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
  36. /// </summary>
  37. /// <param name="scheduledTask">The scheduled task.</param>
  38. /// <param name="applicationPaths">The application paths.</param>
  39. /// <param name="taskManager">The task manager.</param>
  40. /// <param name="logger">The logger.</param>
  41. /// <exception cref="ArgumentNullException">
  42. /// scheduledTask
  43. /// or
  44. /// applicationPaths
  45. /// or
  46. /// taskManager
  47. /// or
  48. /// jsonSerializer
  49. /// or
  50. /// logger.
  51. /// </exception>
  52. public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, ILogger logger)
  53. {
  54. ArgumentNullException.ThrowIfNull(scheduledTask);
  55. ArgumentNullException.ThrowIfNull(applicationPaths);
  56. ArgumentNullException.ThrowIfNull(taskManager);
  57. ArgumentNullException.ThrowIfNull(logger);
  58. ScheduledTask = scheduledTask;
  59. _applicationPaths = applicationPaths;
  60. _taskManager = taskManager;
  61. _logger = logger;
  62. InitTriggerEvents();
  63. }
  64. /// <inheritdoc />
  65. public event EventHandler<GenericEventArgs<double>> TaskProgress;
  66. /// <inheritdoc />
  67. public IScheduledTask ScheduledTask { get; private set; }
  68. /// <inheritdoc />
  69. public TaskResult LastExecutionResult
  70. {
  71. get
  72. {
  73. var path = GetHistoryFilePath();
  74. lock (_lastExecutionResultSyncLock)
  75. {
  76. if (_lastExecutionResult is null && !_readFromFile)
  77. {
  78. if (File.Exists(path))
  79. {
  80. var bytes = File.ReadAllBytes(path);
  81. if (bytes.Length > 0)
  82. {
  83. try
  84. {
  85. _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(bytes, _jsonOptions);
  86. }
  87. catch (JsonException ex)
  88. {
  89. _logger.LogError(ex, "Error deserializing {File}", path);
  90. }
  91. }
  92. else
  93. {
  94. _logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path);
  95. }
  96. }
  97. _readFromFile = true;
  98. }
  99. }
  100. return _lastExecutionResult;
  101. }
  102. private set
  103. {
  104. _lastExecutionResult = value;
  105. var path = GetHistoryFilePath();
  106. Directory.CreateDirectory(Path.GetDirectoryName(path));
  107. lock (_lastExecutionResultSyncLock)
  108. {
  109. using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
  110. using Utf8JsonWriter jsonStream = new Utf8JsonWriter(createStream);
  111. JsonSerializer.Serialize(jsonStream, value, _jsonOptions);
  112. }
  113. }
  114. }
  115. /// <inheritdoc />
  116. public string Name => ScheduledTask.Name;
  117. /// <inheritdoc />
  118. public string Description => ScheduledTask.Description;
  119. /// <inheritdoc />
  120. public string Category => ScheduledTask.Category;
  121. /// <summary>
  122. /// Gets or sets the current cancellation token.
  123. /// </summary>
  124. /// <value>The current cancellation token source.</value>
  125. private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
  126. /// <summary>
  127. /// Gets or sets the current execution start time.
  128. /// </summary>
  129. /// <value>The current execution start time.</value>
  130. private DateTime CurrentExecutionStartTime { get; set; }
  131. /// <inheritdoc />
  132. public TaskState State
  133. {
  134. get
  135. {
  136. if (CurrentCancellationTokenSource is not null)
  137. {
  138. return CurrentCancellationTokenSource.IsCancellationRequested
  139. ? TaskState.Cancelling
  140. : TaskState.Running;
  141. }
  142. return TaskState.Idle;
  143. }
  144. }
  145. /// <inheritdoc />
  146. public double? CurrentProgress { get; private set; }
  147. /// <summary>
  148. /// Gets or sets the triggers that define when the task will run.
  149. /// </summary>
  150. /// <value>The triggers.</value>
  151. private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
  152. {
  153. get => _triggers;
  154. set
  155. {
  156. ArgumentNullException.ThrowIfNull(value);
  157. // Cleanup current triggers
  158. if (_triggers is not null)
  159. {
  160. DisposeTriggers();
  161. }
  162. _triggers = value.ToArray();
  163. ReloadTriggerEvents(false);
  164. }
  165. }
  166. /// <inheritdoc />
  167. public IReadOnlyList<TaskTriggerInfo> Triggers
  168. {
  169. get
  170. {
  171. return Array.ConvertAll(InternalTriggers, i => i.Item1);
  172. }
  173. set
  174. {
  175. ArgumentNullException.ThrowIfNull(value);
  176. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  177. var triggerList = value.Where(i => i is not null).ToArray();
  178. SaveTriggers(triggerList);
  179. InternalTriggers = Array.ConvertAll(triggerList, i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i)));
  180. }
  181. }
  182. /// <inheritdoc />
  183. public string Id
  184. {
  185. get
  186. {
  187. return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  188. }
  189. }
  190. private void InitTriggerEvents()
  191. {
  192. _triggers = LoadTriggers();
  193. ReloadTriggerEvents(true);
  194. }
  195. /// <inheritdoc />
  196. public void ReloadTriggerEvents()
  197. {
  198. ReloadTriggerEvents(false);
  199. }
  200. /// <summary>
  201. /// Reloads the trigger events.
  202. /// </summary>
  203. /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
  204. private void ReloadTriggerEvents(bool isApplicationStartup)
  205. {
  206. foreach (var triggerInfo in InternalTriggers)
  207. {
  208. var trigger = triggerInfo.Item2;
  209. trigger.Stop();
  210. trigger.Triggered -= OnTriggerTriggered;
  211. trigger.Triggered += OnTriggerTriggered;
  212. trigger.Start(LastExecutionResult, _logger, Name, isApplicationStartup);
  213. }
  214. }
  215. /// <summary>
  216. /// Handles the Triggered event of the trigger control.
  217. /// </summary>
  218. /// <param name="sender">The source of the event.</param>
  219. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  220. private async void OnTriggerTriggered(object sender, EventArgs e)
  221. {
  222. var trigger = (ITaskTrigger)sender;
  223. if (ScheduledTask is IConfigurableScheduledTask configurableTask && !configurableTask.IsEnabled)
  224. {
  225. return;
  226. }
  227. _logger.LogDebug("{0} fired for task: {1}", trigger.GetType().Name, Name);
  228. trigger.Stop();
  229. _taskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
  230. await Task.Delay(1000).ConfigureAwait(false);
  231. trigger.Start(LastExecutionResult, _logger, Name, false);
  232. }
  233. /// <summary>
  234. /// Executes the task.
  235. /// </summary>
  236. /// <param name="options">Task options.</param>
  237. /// <returns>Task.</returns>
  238. /// <exception cref="InvalidOperationException">Cannot execute a Task that is already running.</exception>
  239. public async Task Execute(TaskOptions options)
  240. {
  241. var task = Task.Run(async () => await ExecuteInternal(options).ConfigureAwait(false));
  242. _currentTask = task;
  243. try
  244. {
  245. await task.ConfigureAwait(false);
  246. }
  247. finally
  248. {
  249. _currentTask = null;
  250. GC.Collect();
  251. }
  252. }
  253. private async Task ExecuteInternal(TaskOptions options)
  254. {
  255. // Cancel the current execution, if any
  256. if (CurrentCancellationTokenSource is not null)
  257. {
  258. throw new InvalidOperationException("Cannot execute a Task that is already running");
  259. }
  260. var progress = new Progress<double>();
  261. CurrentCancellationTokenSource = new CancellationTokenSource();
  262. _logger.LogDebug("Executing {0}", Name);
  263. ((TaskManager)_taskManager).OnTaskExecuting(this);
  264. progress.ProgressChanged += OnProgressChanged;
  265. TaskCompletionStatus status;
  266. CurrentExecutionStartTime = DateTime.UtcNow;
  267. Exception failureException = null;
  268. try
  269. {
  270. if (options is not null && options.MaxRuntimeTicks.HasValue)
  271. {
  272. CurrentCancellationTokenSource.CancelAfter(TimeSpan.FromTicks(options.MaxRuntimeTicks.Value));
  273. }
  274. await ScheduledTask.ExecuteAsync(progress, CurrentCancellationTokenSource.Token).ConfigureAwait(false);
  275. status = TaskCompletionStatus.Completed;
  276. }
  277. catch (OperationCanceledException)
  278. {
  279. status = TaskCompletionStatus.Cancelled;
  280. }
  281. catch (Exception ex)
  282. {
  283. _logger.LogError(ex, "Error executing Scheduled Task");
  284. failureException = ex;
  285. status = TaskCompletionStatus.Failed;
  286. }
  287. var startTime = CurrentExecutionStartTime;
  288. var endTime = DateTime.UtcNow;
  289. progress.ProgressChanged -= OnProgressChanged;
  290. CurrentCancellationTokenSource.Dispose();
  291. CurrentCancellationTokenSource = null;
  292. CurrentProgress = null;
  293. OnTaskCompleted(startTime, endTime, status, failureException);
  294. }
  295. /// <summary>
  296. /// Progress_s the progress changed.
  297. /// </summary>
  298. /// <param name="sender">The sender.</param>
  299. /// <param name="e">The e.</param>
  300. private void OnProgressChanged(object sender, double e)
  301. {
  302. e = Math.Min(e, 100);
  303. CurrentProgress = e;
  304. TaskProgress?.Invoke(this, new GenericEventArgs<double>(e));
  305. }
  306. /// <summary>
  307. /// Stops the task if it is currently executing.
  308. /// </summary>
  309. /// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
  310. public void Cancel()
  311. {
  312. if (State != TaskState.Running)
  313. {
  314. throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
  315. }
  316. CancelIfRunning();
  317. }
  318. /// <summary>
  319. /// Cancels if running.
  320. /// </summary>
  321. public void CancelIfRunning()
  322. {
  323. if (State == TaskState.Running)
  324. {
  325. _logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
  326. CurrentCancellationTokenSource.Cancel();
  327. }
  328. }
  329. /// <summary>
  330. /// Gets the scheduled tasks configuration directory.
  331. /// </summary>
  332. /// <returns>System.String.</returns>
  333. private string GetScheduledTasksConfigurationDirectory()
  334. {
  335. return Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
  336. }
  337. /// <summary>
  338. /// Gets the scheduled tasks data directory.
  339. /// </summary>
  340. /// <returns>System.String.</returns>
  341. private string GetScheduledTasksDataDirectory()
  342. {
  343. return Path.Combine(_applicationPaths.DataPath, "ScheduledTasks");
  344. }
  345. /// <summary>
  346. /// Gets the history file path.
  347. /// </summary>
  348. /// <value>The history file path.</value>
  349. private string GetHistoryFilePath()
  350. {
  351. return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
  352. }
  353. /// <summary>
  354. /// Gets the configuration file path.
  355. /// </summary>
  356. /// <returns>System.String.</returns>
  357. private string GetConfigurationFilePath()
  358. {
  359. return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
  360. }
  361. /// <summary>
  362. /// Loads the triggers.
  363. /// </summary>
  364. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  365. private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
  366. {
  367. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  368. var settings = LoadTriggerSettings().Where(i => i is not null);
  369. return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  370. }
  371. private TaskTriggerInfo[] LoadTriggerSettings()
  372. {
  373. string path = GetConfigurationFilePath();
  374. TaskTriggerInfo[] list = null;
  375. if (File.Exists(path))
  376. {
  377. var bytes = File.ReadAllBytes(path);
  378. list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(bytes, _jsonOptions);
  379. }
  380. // Return defaults if file doesn't exist.
  381. return list ?? GetDefaultTriggers();
  382. }
  383. private TaskTriggerInfo[] GetDefaultTriggers()
  384. {
  385. try
  386. {
  387. return ScheduledTask.GetDefaultTriggers().ToArray();
  388. }
  389. catch
  390. {
  391. return
  392. [
  393. new()
  394. {
  395. IntervalTicks = TimeSpan.FromDays(1).Ticks,
  396. Type = TaskTriggerInfoType.IntervalTrigger
  397. }
  398. ];
  399. }
  400. }
  401. /// <summary>
  402. /// Saves the triggers.
  403. /// </summary>
  404. /// <param name="triggers">The triggers.</param>
  405. private void SaveTriggers(TaskTriggerInfo[] triggers)
  406. {
  407. var path = GetConfigurationFilePath();
  408. Directory.CreateDirectory(Path.GetDirectoryName(path));
  409. using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
  410. using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream);
  411. JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions);
  412. }
  413. /// <summary>
  414. /// Called when [task completed].
  415. /// </summary>
  416. /// <param name="startTime">The start time.</param>
  417. /// <param name="endTime">The end time.</param>
  418. /// <param name="status">The status.</param>
  419. /// <param name="ex">The exception.</param>
  420. private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
  421. {
  422. var elapsedTime = endTime - startTime;
  423. _logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
  424. var result = new TaskResult
  425. {
  426. StartTimeUtc = startTime,
  427. EndTimeUtc = endTime,
  428. Status = status,
  429. Name = Name,
  430. Id = Id
  431. };
  432. result.Key = ScheduledTask.Key;
  433. if (ex is not null)
  434. {
  435. result.ErrorMessage = ex.Message;
  436. result.LongErrorMessage = ex.StackTrace;
  437. }
  438. LastExecutionResult = result;
  439. ((TaskManager)_taskManager).OnTaskCompleted(this, result);
  440. }
  441. /// <inheritdoc />
  442. public void Dispose()
  443. {
  444. Dispose(true);
  445. GC.SuppressFinalize(this);
  446. }
  447. /// <summary>
  448. /// Releases unmanaged and - optionally - managed resources.
  449. /// </summary>
  450. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  451. protected virtual void Dispose(bool dispose)
  452. {
  453. if (dispose)
  454. {
  455. DisposeTriggers();
  456. var wassRunning = State == TaskState.Running;
  457. var startTime = CurrentExecutionStartTime;
  458. var token = CurrentCancellationTokenSource;
  459. if (token is not null)
  460. {
  461. try
  462. {
  463. _logger.LogInformation("{Name}: Cancelling", Name);
  464. token.Cancel();
  465. }
  466. catch (Exception ex)
  467. {
  468. _logger.LogError(ex, "Error calling CancellationToken.Cancel();");
  469. }
  470. }
  471. var task = _currentTask;
  472. if (task is not null)
  473. {
  474. try
  475. {
  476. _logger.LogInformation("{Name}: Waiting on Task", Name);
  477. var exited = task.Wait(2000);
  478. if (exited)
  479. {
  480. _logger.LogInformation("{Name}: Task exited", Name);
  481. }
  482. else
  483. {
  484. _logger.LogInformation("{Name}: Timed out waiting for task to stop", Name);
  485. }
  486. }
  487. catch (Exception ex)
  488. {
  489. _logger.LogError(ex, "Error calling Task.WaitAll();");
  490. }
  491. }
  492. if (token is not null)
  493. {
  494. try
  495. {
  496. _logger.LogDebug("{Name}: Disposing CancellationToken", Name);
  497. token.Dispose();
  498. }
  499. catch (Exception ex)
  500. {
  501. _logger.LogError(ex, "Error calling CancellationToken.Dispose();");
  502. }
  503. }
  504. if (wassRunning)
  505. {
  506. OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
  507. }
  508. }
  509. }
  510. /// <summary>
  511. /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger.
  512. /// </summary>
  513. /// <param name="info">The info.</param>
  514. /// <returns>BaseTaskTrigger.</returns>
  515. /// <exception cref="ArgumentException">Invalid trigger type: + info.Type.</exception>
  516. private ITaskTrigger GetTrigger(TaskTriggerInfo info)
  517. {
  518. var options = new TaskOptions
  519. {
  520. MaxRuntimeTicks = info.MaxRuntimeTicks
  521. };
  522. if (info.Type == TaskTriggerInfoType.DailyTrigger)
  523. {
  524. if (!info.TimeOfDayTicks.HasValue)
  525. {
  526. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  527. }
  528. return new DailyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), options);
  529. }
  530. if (info.Type == TaskTriggerInfoType.WeeklyTrigger)
  531. {
  532. if (!info.TimeOfDayTicks.HasValue)
  533. {
  534. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  535. }
  536. if (!info.DayOfWeek.HasValue)
  537. {
  538. throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
  539. }
  540. return new WeeklyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), info.DayOfWeek.Value, options);
  541. }
  542. if (info.Type == TaskTriggerInfoType.IntervalTrigger)
  543. {
  544. if (!info.IntervalTicks.HasValue)
  545. {
  546. throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
  547. }
  548. return new IntervalTrigger(TimeSpan.FromTicks(info.IntervalTicks.Value), options);
  549. }
  550. if (info.Type == TaskTriggerInfoType.StartupTrigger)
  551. {
  552. return new StartupTrigger(options);
  553. }
  554. throw new ArgumentException("Unrecognized trigger type: " + info.Type);
  555. }
  556. /// <summary>
  557. /// Disposes each trigger.
  558. /// </summary>
  559. private void DisposeTriggers()
  560. {
  561. foreach (var triggerInfo in InternalTriggers)
  562. {
  563. var trigger = triggerInfo.Item2;
  564. trigger.Triggered -= OnTriggerTriggered;
  565. trigger.Stop();
  566. if (trigger is IDisposable disposable)
  567. {
  568. disposable.Dispose();
  569. }
  570. }
  571. }
  572. }
  573. }