ScheduledTaskWorker.cs 22 KB

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