ScheduledTaskWorker.cs 22 KB

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