ScheduledTaskWorker.cs 22 KB

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