ScheduledTaskWorker.cs 19 KB

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