ScheduledTaskWorker.cs 18 KB

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