ScheduledTaskWorker.cs 19 KB

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