ScheduledTaskWorker.cs 21 KB

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