2
0

ScheduledTaskWorker.cs 19 KB

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