ScheduledTaskWorker.cs 22 KB

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