ScheduledTaskWorker.cs 19 KB

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