ScheduledTaskWorker.cs 22 KB

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