ScheduledTaskWorker.cs 17 KB

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