ScheduledTaskWorker.cs 22 KB

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