ScheduledTaskWorker.cs 22 KB

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