ScheduledTaskWorker.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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. /// Progress_s the progress changed.
  369. /// </summary>
  370. /// <param name="sender">The sender.</param>
  371. /// <param name="e">The e.</param>
  372. void progress_ProgressChanged(object sender, double e)
  373. {
  374. CurrentProgress = e;
  375. EventHelper.FireEventIfNotNull(TaskProgress, this, new GenericEventArgs<double>
  376. {
  377. Argument = e
  378. }, Logger);
  379. }
  380. /// <summary>
  381. /// Stops the task if it is currently executing
  382. /// </summary>
  383. /// <exception cref="System.InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
  384. public void Cancel()
  385. {
  386. if (State != TaskState.Running)
  387. {
  388. throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
  389. }
  390. CancelIfRunning();
  391. }
  392. /// <summary>
  393. /// Cancels if running.
  394. /// </summary>
  395. public void CancelIfRunning()
  396. {
  397. if (State == TaskState.Running)
  398. {
  399. Logger.Info("Attempting to cancel Scheduled Task {0}", Name);
  400. CurrentCancellationTokenSource.Cancel();
  401. }
  402. }
  403. /// <summary>
  404. /// Gets the scheduled tasks configuration directory.
  405. /// </summary>
  406. /// <returns>System.String.</returns>
  407. private string GetScheduledTasksConfigurationDirectory()
  408. {
  409. return Path.Combine(ApplicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
  410. }
  411. /// <summary>
  412. /// Gets the scheduled tasks data directory.
  413. /// </summary>
  414. /// <returns>System.String.</returns>
  415. private string GetScheduledTasksDataDirectory()
  416. {
  417. return Path.Combine(ApplicationPaths.DataPath, "ScheduledTasks");
  418. }
  419. /// <summary>
  420. /// Gets the history file path.
  421. /// </summary>
  422. /// <value>The history file path.</value>
  423. private string GetHistoryFilePath()
  424. {
  425. return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
  426. }
  427. /// <summary>
  428. /// Gets the configuration file path.
  429. /// </summary>
  430. /// <returns>System.String.</returns>
  431. private string GetConfigurationFilePath()
  432. {
  433. return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
  434. }
  435. /// <summary>
  436. /// Loads the triggers.
  437. /// </summary>
  438. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  439. private List<ITaskTrigger> LoadTriggers()
  440. {
  441. try
  442. {
  443. return JsonSerializer.DeserializeFromFile<IEnumerable<TaskTriggerInfo>>(GetConfigurationFilePath())
  444. .Select(ScheduledTaskHelpers.GetTrigger)
  445. .ToList();
  446. }
  447. catch (FileNotFoundException)
  448. {
  449. // File doesn't exist. No biggie. Return defaults.
  450. return ScheduledTask.GetDefaultTriggers().ToList();
  451. }
  452. catch (DirectoryNotFoundException)
  453. {
  454. // File doesn't exist. No biggie. Return defaults.
  455. return ScheduledTask.GetDefaultTriggers().ToList();
  456. }
  457. }
  458. /// <summary>
  459. /// Saves the triggers.
  460. /// </summary>
  461. /// <param name="triggers">The triggers.</param>
  462. private void SaveTriggers(IEnumerable<ITaskTrigger> triggers)
  463. {
  464. var path = GetConfigurationFilePath();
  465. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  466. JsonSerializer.SerializeToFile(triggers.Select(ScheduledTaskHelpers.GetTriggerInfo), path);
  467. }
  468. /// <summary>
  469. /// Called when [task completed].
  470. /// </summary>
  471. /// <param name="startTime">The start time.</param>
  472. /// <param name="endTime">The end time.</param>
  473. /// <param name="status">The status.</param>
  474. private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
  475. {
  476. var elapsedTime = endTime - startTime;
  477. Logger.Info("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
  478. var result = new TaskResult
  479. {
  480. StartTimeUtc = startTime,
  481. EndTimeUtc = endTime,
  482. Status = status,
  483. Name = Name,
  484. Id = Id
  485. };
  486. var hasKey = ScheduledTask as IHasKey;
  487. if (hasKey != null)
  488. {
  489. result.Key = hasKey.Key;
  490. }
  491. if (ex != null)
  492. {
  493. result.ErrorMessage = ex.Message;
  494. result.LongErrorMessage = ex.StackTrace;
  495. }
  496. LastExecutionResult = result;
  497. ((TaskManager)TaskManager).OnTaskCompleted(this, result);
  498. }
  499. /// <summary>
  500. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  501. /// </summary>
  502. public void Dispose()
  503. {
  504. Dispose(true);
  505. GC.SuppressFinalize(this);
  506. }
  507. /// <summary>
  508. /// Releases unmanaged and - optionally - managed resources.
  509. /// </summary>
  510. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  511. protected virtual void Dispose(bool dispose)
  512. {
  513. if (dispose)
  514. {
  515. DisposeTriggers();
  516. var wassRunning = State == TaskState.Running;
  517. var startTime = CurrentExecutionStartTime;
  518. var token = CurrentCancellationTokenSource;
  519. if (token != null)
  520. {
  521. try
  522. {
  523. Logger.Info(Name + ": Cancelling");
  524. token.Cancel();
  525. }
  526. catch (Exception ex)
  527. {
  528. Logger.ErrorException("Error calling CancellationToken.Cancel();", ex);
  529. }
  530. }
  531. var task = _currentTask;
  532. if (task != null)
  533. {
  534. try
  535. {
  536. Logger.Info(Name + ": Waiting on Task");
  537. var exited = Task.WaitAll(new[] { task }, 2000);
  538. if (exited)
  539. {
  540. Logger.Info(Name + ": Task exited");
  541. }
  542. else
  543. {
  544. Logger.Info(Name + ": Timed out waiting for task to stop");
  545. }
  546. }
  547. catch (Exception ex)
  548. {
  549. Logger.ErrorException("Error calling Task.WaitAll();", ex);
  550. }
  551. }
  552. if (token != null)
  553. {
  554. try
  555. {
  556. Logger.Debug(Name + ": Disposing CancellationToken");
  557. token.Dispose();
  558. }
  559. catch (Exception ex)
  560. {
  561. Logger.ErrorException("Error calling CancellationToken.Dispose();", ex);
  562. }
  563. }
  564. if (wassRunning)
  565. {
  566. OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
  567. }
  568. }
  569. }
  570. /// <summary>
  571. /// Disposes each trigger
  572. /// </summary>
  573. private void DisposeTriggers()
  574. {
  575. foreach (var trigger in Triggers)
  576. {
  577. trigger.Triggered -= trigger_Triggered;
  578. trigger.Stop();
  579. }
  580. }
  581. }
  582. }