ScheduledTaskWorker.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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. namespace MediaBrowser.Common.Implementations.ScheduledTasks
  16. {
  17. /// <summary>
  18. /// Class ScheduledTaskWorker
  19. /// </summary>
  20. public class ScheduledTaskWorker : IScheduledTaskWorker
  21. {
  22. public event EventHandler<GenericEventArgs<double>> TaskProgress;
  23. /// <summary>
  24. /// Gets or sets the scheduled task.
  25. /// </summary>
  26. /// <value>The scheduled task.</value>
  27. public IScheduledTask ScheduledTask { get; private set; }
  28. /// <summary>
  29. /// Gets or sets the json serializer.
  30. /// </summary>
  31. /// <value>The json serializer.</value>
  32. private IJsonSerializer JsonSerializer { get; set; }
  33. /// <summary>
  34. /// Gets or sets the application paths.
  35. /// </summary>
  36. /// <value>The application paths.</value>
  37. private IApplicationPaths ApplicationPaths { get; set; }
  38. /// <summary>
  39. /// Gets the logger.
  40. /// </summary>
  41. /// <value>The logger.</value>
  42. private ILogger Logger { get; set; }
  43. /// <summary>
  44. /// Gets the task manager.
  45. /// </summary>
  46. /// <value>The task manager.</value>
  47. private ITaskManager TaskManager { get; set; }
  48. /// <summary>
  49. /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
  50. /// </summary>
  51. /// <param name="scheduledTask">The scheduled task.</param>
  52. /// <param name="applicationPaths">The application paths.</param>
  53. /// <param name="taskManager">The task manager.</param>
  54. /// <param name="jsonSerializer">The json serializer.</param>
  55. /// <param name="logger">The logger.</param>
  56. /// <exception cref="System.ArgumentNullException">
  57. /// scheduledTask
  58. /// or
  59. /// applicationPaths
  60. /// or
  61. /// taskManager
  62. /// or
  63. /// jsonSerializer
  64. /// or
  65. /// logger
  66. /// </exception>
  67. public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger)
  68. {
  69. if (scheduledTask == null)
  70. {
  71. throw new ArgumentNullException("scheduledTask");
  72. }
  73. if (applicationPaths == null)
  74. {
  75. throw new ArgumentNullException("applicationPaths");
  76. }
  77. if (taskManager == null)
  78. {
  79. throw new ArgumentNullException("taskManager");
  80. }
  81. if (jsonSerializer == null)
  82. {
  83. throw new ArgumentNullException("jsonSerializer");
  84. }
  85. if (logger == null)
  86. {
  87. throw new ArgumentNullException("logger");
  88. }
  89. ScheduledTask = scheduledTask;
  90. ApplicationPaths = applicationPaths;
  91. TaskManager = taskManager;
  92. JsonSerializer = jsonSerializer;
  93. Logger = logger;
  94. ReloadTriggerEvents(true);
  95. }
  96. /// <summary>
  97. /// The _last execution result
  98. /// </summary>
  99. private TaskResult _lastExecutionResult;
  100. /// <summary>
  101. /// The _last execution result sync lock
  102. /// </summary>
  103. private readonly object _lastExecutionResultSyncLock = new object();
  104. /// <summary>
  105. /// Gets the last execution result.
  106. /// </summary>
  107. /// <value>The last execution result.</value>
  108. public TaskResult LastExecutionResult
  109. {
  110. get
  111. {
  112. if (_lastExecutionResult == null)
  113. {
  114. lock (_lastExecutionResultSyncLock)
  115. {
  116. if (_lastExecutionResult == null)
  117. {
  118. var path = GetHistoryFilePath();
  119. try
  120. {
  121. return JsonSerializer.DeserializeFromFile<TaskResult>(path);
  122. }
  123. catch (DirectoryNotFoundException)
  124. {
  125. // File doesn't exist. No biggie
  126. }
  127. catch (FileNotFoundException)
  128. {
  129. // File doesn't exist. No biggie
  130. }
  131. catch (Exception ex)
  132. {
  133. Logger.ErrorException("Error deserializing {0}", ex, path);
  134. }
  135. }
  136. }
  137. }
  138. return _lastExecutionResult;
  139. }
  140. private set
  141. {
  142. _lastExecutionResult = value;
  143. }
  144. }
  145. /// <summary>
  146. /// Gets the name.
  147. /// </summary>
  148. /// <value>The name.</value>
  149. public string Name
  150. {
  151. get { return ScheduledTask.Name; }
  152. }
  153. /// <summary>
  154. /// Gets the description.
  155. /// </summary>
  156. /// <value>The description.</value>
  157. public string Description
  158. {
  159. get { return ScheduledTask.Description; }
  160. }
  161. /// <summary>
  162. /// Gets the category.
  163. /// </summary>
  164. /// <value>The category.</value>
  165. public string Category
  166. {
  167. get { return ScheduledTask.Category; }
  168. }
  169. /// <summary>
  170. /// Gets the current cancellation token
  171. /// </summary>
  172. /// <value>The current cancellation token source.</value>
  173. private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
  174. /// <summary>
  175. /// Gets or sets the current execution start time.
  176. /// </summary>
  177. /// <value>The current execution start time.</value>
  178. private DateTime CurrentExecutionStartTime { get; set; }
  179. /// <summary>
  180. /// Gets the state.
  181. /// </summary>
  182. /// <value>The state.</value>
  183. public TaskState State
  184. {
  185. get
  186. {
  187. if (CurrentCancellationTokenSource != null)
  188. {
  189. return CurrentCancellationTokenSource.IsCancellationRequested
  190. ? TaskState.Cancelling
  191. : TaskState.Running;
  192. }
  193. return TaskState.Idle;
  194. }
  195. }
  196. /// <summary>
  197. /// Gets the current progress.
  198. /// </summary>
  199. /// <value>The current progress.</value>
  200. public double? CurrentProgress { get; private set; }
  201. /// <summary>
  202. /// The _triggers
  203. /// </summary>
  204. private IEnumerable<ITaskTrigger> _triggers;
  205. /// <summary>
  206. /// The _triggers sync lock
  207. /// </summary>
  208. private readonly object _triggersSyncLock = new object();
  209. /// <summary>
  210. /// Gets the triggers that define when the task will run
  211. /// </summary>
  212. /// <value>The triggers.</value>
  213. /// <exception cref="System.ArgumentNullException">value</exception>
  214. public IEnumerable<ITaskTrigger> Triggers
  215. {
  216. get
  217. {
  218. if (_triggers == null)
  219. {
  220. lock (_triggersSyncLock)
  221. {
  222. if (_triggers == null)
  223. {
  224. _triggers = LoadTriggers();
  225. }
  226. }
  227. }
  228. return _triggers;
  229. }
  230. set
  231. {
  232. if (value == null)
  233. {
  234. throw new ArgumentNullException("value");
  235. }
  236. // Cleanup current triggers
  237. if (_triggers != null)
  238. {
  239. DisposeTriggers();
  240. }
  241. _triggers = value.ToList();
  242. ReloadTriggerEvents(false);
  243. SaveTriggers(_triggers);
  244. }
  245. }
  246. /// <summary>
  247. /// The _id
  248. /// </summary>
  249. private string _id;
  250. /// <summary>
  251. /// Gets the unique id.
  252. /// </summary>
  253. /// <value>The unique id.</value>
  254. public string Id
  255. {
  256. get
  257. {
  258. if (_id == null)
  259. {
  260. _id = ScheduledTask.GetType().FullName.GetMD5().ToString("N");
  261. }
  262. return _id;
  263. }
  264. }
  265. /// <summary>
  266. /// Reloads the trigger events.
  267. /// </summary>
  268. /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
  269. private void ReloadTriggerEvents(bool isApplicationStartup)
  270. {
  271. foreach (var trigger in Triggers)
  272. {
  273. trigger.Stop();
  274. trigger.Triggered -= trigger_Triggered;
  275. trigger.Triggered += trigger_Triggered;
  276. trigger.Start(isApplicationStartup);
  277. }
  278. }
  279. /// <summary>
  280. /// Handles the Triggered event of the trigger control.
  281. /// </summary>
  282. /// <param name="sender">The source of the event.</param>
  283. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  284. async void trigger_Triggered(object sender, EventArgs e)
  285. {
  286. var trigger = (ITaskTrigger)sender;
  287. var configurableTask = ScheduledTask as IConfigurableScheduledTask;
  288. if (configurableTask != null && !configurableTask.IsEnabled)
  289. {
  290. return;
  291. }
  292. Logger.Info("{0} fired for task: {1}", trigger.GetType().Name, Name);
  293. trigger.Stop();
  294. TaskManager.QueueScheduledTask(ScheduledTask);
  295. await Task.Delay(1000).ConfigureAwait(false);
  296. trigger.Start(false);
  297. }
  298. /// <summary>
  299. /// Executes the task
  300. /// </summary>
  301. /// <returns>Task.</returns>
  302. /// <exception cref="System.InvalidOperationException">Cannot execute a Task that is already running</exception>
  303. public async Task Execute()
  304. {
  305. // Cancel the current execution, if any
  306. if (CurrentCancellationTokenSource != null)
  307. {
  308. throw new InvalidOperationException("Cannot execute a Task that is already running");
  309. }
  310. var progress = new Progress<double>();
  311. CurrentCancellationTokenSource = new CancellationTokenSource();
  312. Logger.Info("Executing {0}", Name);
  313. ((TaskManager)TaskManager).OnTaskExecuting(this);
  314. progress.ProgressChanged += progress_ProgressChanged;
  315. TaskCompletionStatus status;
  316. CurrentExecutionStartTime = DateTime.UtcNow;
  317. Exception failureException = null;
  318. try
  319. {
  320. await ExecuteTask(CurrentCancellationTokenSource.Token, progress).ConfigureAwait(false);
  321. status = TaskCompletionStatus.Completed;
  322. }
  323. catch (OperationCanceledException)
  324. {
  325. status = TaskCompletionStatus.Cancelled;
  326. }
  327. catch (Exception ex)
  328. {
  329. Logger.ErrorException("Error", ex);
  330. failureException = ex;
  331. status = TaskCompletionStatus.Failed;
  332. }
  333. var startTime = CurrentExecutionStartTime;
  334. var endTime = DateTime.UtcNow;
  335. progress.ProgressChanged -= progress_ProgressChanged;
  336. CurrentCancellationTokenSource.Dispose();
  337. CurrentCancellationTokenSource = null;
  338. CurrentProgress = null;
  339. OnTaskCompleted(startTime, endTime, status, failureException);
  340. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  341. GC.Collect(2, GCCollectionMode.Forced, true);
  342. GC.Collect(2, GCCollectionMode.Forced, true);
  343. }
  344. /// <summary>
  345. /// Executes the task.
  346. /// </summary>
  347. /// <param name="cancellationToken">The cancellation token.</param>
  348. /// <param name="progress">The progress.</param>
  349. /// <returns>Task.</returns>
  350. private Task ExecuteTask(CancellationToken cancellationToken, IProgress<double> progress)
  351. {
  352. return Task.Run(async () => await ScheduledTask.Execute(cancellationToken, progress).ConfigureAwait(false), cancellationToken);
  353. }
  354. /// <summary>
  355. /// Progress_s the progress changed.
  356. /// </summary>
  357. /// <param name="sender">The sender.</param>
  358. /// <param name="e">The e.</param>
  359. void progress_ProgressChanged(object sender, double e)
  360. {
  361. CurrentProgress = e;
  362. EventHelper.FireEventIfNotNull(TaskProgress, this, new GenericEventArgs<double>
  363. {
  364. Argument = e
  365. }, Logger);
  366. }
  367. /// <summary>
  368. /// Stops the task if it is currently executing
  369. /// </summary>
  370. /// <exception cref="System.InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
  371. public void Cancel()
  372. {
  373. if (State != TaskState.Running)
  374. {
  375. throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
  376. }
  377. CancelIfRunning();
  378. }
  379. /// <summary>
  380. /// Cancels if running.
  381. /// </summary>
  382. public void CancelIfRunning()
  383. {
  384. if (State == TaskState.Running)
  385. {
  386. Logger.Info("Attempting to cancel Scheduled Task {0}", Name);
  387. CurrentCancellationTokenSource.Cancel();
  388. }
  389. }
  390. /// <summary>
  391. /// Gets the scheduled tasks configuration directory.
  392. /// </summary>
  393. /// <returns>System.String.</returns>
  394. private string GetScheduledTasksConfigurationDirectory()
  395. {
  396. return Path.Combine(ApplicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
  397. }
  398. /// <summary>
  399. /// Gets the scheduled tasks data directory.
  400. /// </summary>
  401. /// <returns>System.String.</returns>
  402. private string GetScheduledTasksDataDirectory()
  403. {
  404. return Path.Combine(ApplicationPaths.DataPath, "ScheduledTasks");
  405. }
  406. /// <summary>
  407. /// Gets the history file path.
  408. /// </summary>
  409. /// <value>The history file path.</value>
  410. private string GetHistoryFilePath()
  411. {
  412. return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
  413. }
  414. /// <summary>
  415. /// Gets the configuration file path.
  416. /// </summary>
  417. /// <returns>System.String.</returns>
  418. private string GetConfigurationFilePath()
  419. {
  420. return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
  421. }
  422. /// <summary>
  423. /// Loads the triggers.
  424. /// </summary>
  425. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  426. private IEnumerable<ITaskTrigger> LoadTriggers()
  427. {
  428. try
  429. {
  430. return JsonSerializer.DeserializeFromFile<IEnumerable<TaskTriggerInfo>>(GetConfigurationFilePath())
  431. .Select(ScheduledTaskHelpers.GetTrigger)
  432. .ToList();
  433. }
  434. catch (FileNotFoundException)
  435. {
  436. // File doesn't exist. No biggie. Return defaults.
  437. return ScheduledTask.GetDefaultTriggers();
  438. }
  439. catch (DirectoryNotFoundException)
  440. {
  441. // File doesn't exist. No biggie. Return defaults.
  442. return ScheduledTask.GetDefaultTriggers();
  443. }
  444. }
  445. /// <summary>
  446. /// Saves the triggers.
  447. /// </summary>
  448. /// <param name="triggers">The triggers.</param>
  449. private void SaveTriggers(IEnumerable<ITaskTrigger> triggers)
  450. {
  451. var path = GetConfigurationFilePath();
  452. Directory.CreateDirectory(Path.GetDirectoryName(path));
  453. JsonSerializer.SerializeToFile(triggers.Select(ScheduledTaskHelpers.GetTriggerInfo), path);
  454. }
  455. /// <summary>
  456. /// Called when [task completed].
  457. /// </summary>
  458. /// <param name="startTime">The start time.</param>
  459. /// <param name="endTime">The end time.</param>
  460. /// <param name="status">The status.</param>
  461. private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
  462. {
  463. var elapsedTime = endTime - startTime;
  464. Logger.Info("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
  465. var result = new TaskResult
  466. {
  467. StartTimeUtc = startTime,
  468. EndTimeUtc = endTime,
  469. Status = status,
  470. Name = Name,
  471. Id = Id
  472. };
  473. var hasKey = ScheduledTask as IHasKey;
  474. if (hasKey != null)
  475. {
  476. result.Key = hasKey.Key;
  477. }
  478. if (ex != null)
  479. {
  480. result.ErrorMessage = ex.Message;
  481. result.LongErrorMessage = ex.StackTrace;
  482. }
  483. var path = GetHistoryFilePath();
  484. Directory.CreateDirectory(Path.GetDirectoryName(path));
  485. JsonSerializer.SerializeToFile(result, path);
  486. LastExecutionResult = result;
  487. ((TaskManager)TaskManager).OnTaskCompleted(this, result);
  488. }
  489. /// <summary>
  490. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  491. /// </summary>
  492. public void Dispose()
  493. {
  494. Dispose(true);
  495. GC.SuppressFinalize(this);
  496. }
  497. /// <summary>
  498. /// Releases unmanaged and - optionally - managed resources.
  499. /// </summary>
  500. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  501. protected virtual void Dispose(bool dispose)
  502. {
  503. if (dispose)
  504. {
  505. DisposeTriggers();
  506. if (State == TaskState.Running)
  507. {
  508. OnTaskCompleted(CurrentExecutionStartTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
  509. }
  510. if (CurrentCancellationTokenSource != null)
  511. {
  512. CurrentCancellationTokenSource.Dispose();
  513. }
  514. }
  515. }
  516. /// <summary>
  517. /// Disposes each trigger
  518. /// </summary>
  519. private void DisposeTriggers()
  520. {
  521. foreach (var trigger in Triggers)
  522. {
  523. trigger.Triggered -= trigger_Triggered;
  524. trigger.Stop();
  525. }
  526. }
  527. }
  528. }