TaskManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Model.Events;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.Serialization;
  11. using MediaBrowser.Model.System;
  12. using MediaBrowser.Model.Tasks;
  13. using Microsoft.Extensions.Logging;
  14. namespace Emby.Server.Implementations.ScheduledTasks
  15. {
  16. /// <summary>
  17. /// Class TaskManager
  18. /// </summary>
  19. public class TaskManager : ITaskManager
  20. {
  21. public event EventHandler<GenericEventArgs<IScheduledTaskWorker>> TaskExecuting;
  22. public event EventHandler<TaskCompletionEventArgs> TaskCompleted;
  23. /// <summary>
  24. /// Gets the list of Scheduled Tasks
  25. /// </summary>
  26. /// <value>The scheduled tasks.</value>
  27. public IScheduledTaskWorker[] ScheduledTasks { get; private set; }
  28. /// <summary>
  29. /// The _task queue
  30. /// </summary>
  31. private readonly ConcurrentQueue<Tuple<Type, TaskOptions>> _taskQueue =
  32. new ConcurrentQueue<Tuple<Type, TaskOptions>>();
  33. /// <summary>
  34. /// Gets or sets the json serializer.
  35. /// </summary>
  36. /// <value>The json serializer.</value>
  37. private IJsonSerializer JsonSerializer { get; set; }
  38. /// <summary>
  39. /// Gets or sets the application paths.
  40. /// </summary>
  41. /// <value>The application paths.</value>
  42. private IApplicationPaths ApplicationPaths { get; set; }
  43. private readonly ISystemEvents _systemEvents;
  44. /// <summary>
  45. /// Gets the logger.
  46. /// </summary>
  47. /// <value>The logger.</value>
  48. private ILogger Logger { get; set; }
  49. private readonly IFileSystem _fileSystem;
  50. /// <summary>
  51. /// Initializes a new instance of the <see cref="TaskManager" /> class.
  52. /// </summary>
  53. /// <param name="applicationPaths">The application paths.</param>
  54. /// <param name="jsonSerializer">The json serializer.</param>
  55. /// <param name="logger">The logger.</param>
  56. /// <exception cref="System.ArgumentException">kernel</exception>
  57. public TaskManager(
  58. IApplicationPaths applicationPaths,
  59. IJsonSerializer jsonSerializer,
  60. ILoggerFactory loggerFactory,
  61. IFileSystem fileSystem,
  62. ISystemEvents systemEvents)
  63. {
  64. ApplicationPaths = applicationPaths;
  65. JsonSerializer = jsonSerializer;
  66. Logger = loggerFactory.CreateLogger(nameof(TaskManager));
  67. _fileSystem = fileSystem;
  68. _systemEvents = systemEvents;
  69. ScheduledTasks = new IScheduledTaskWorker[] { };
  70. }
  71. private void BindToSystemEvent()
  72. {
  73. _systemEvents.Resume += _systemEvents_Resume;
  74. }
  75. private void _systemEvents_Resume(object sender, EventArgs e)
  76. {
  77. foreach (var task in ScheduledTasks)
  78. {
  79. task.ReloadTriggerEvents();
  80. }
  81. }
  82. public void RunTaskOnNextStartup(string key)
  83. {
  84. var path = Path.Combine(ApplicationPaths.CachePath, "startuptasks.txt");
  85. List<string> lines;
  86. try
  87. {
  88. lines = _fileSystem.ReadAllLines(path).ToList();
  89. }
  90. catch
  91. {
  92. lines = new List<string>();
  93. }
  94. if (!lines.Contains(key, StringComparer.OrdinalIgnoreCase))
  95. {
  96. lines.Add(key);
  97. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  98. _fileSystem.WriteAllLines(path, lines);
  99. }
  100. }
  101. private void RunStartupTasks()
  102. {
  103. var path = Path.Combine(ApplicationPaths.CachePath, "startuptasks.txt");
  104. // ToDo: Fix this shit
  105. if (!File.Exists(path))
  106. return;
  107. List<string> lines;
  108. try
  109. {
  110. lines = _fileSystem.ReadAllLines(path).Where(i => !string.IsNullOrWhiteSpace(i)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  111. foreach (var key in lines)
  112. {
  113. var task = ScheduledTasks.FirstOrDefault(i => string.Equals(i.ScheduledTask.Key, key, StringComparison.OrdinalIgnoreCase));
  114. if (task != null)
  115. {
  116. QueueScheduledTask(task, new TaskOptions());
  117. }
  118. }
  119. _fileSystem.DeleteFile(path);
  120. }
  121. catch
  122. {
  123. return;
  124. }
  125. }
  126. /// <summary>
  127. /// Cancels if running and queue.
  128. /// </summary>
  129. /// <typeparam name="T"></typeparam>
  130. /// <param name="options">Task options.</param>
  131. public void CancelIfRunningAndQueue<T>(TaskOptions options)
  132. where T : IScheduledTask
  133. {
  134. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  135. ((ScheduledTaskWorker)task).CancelIfRunning();
  136. QueueScheduledTask<T>(options);
  137. }
  138. public void CancelIfRunningAndQueue<T>()
  139. where T : IScheduledTask
  140. {
  141. CancelIfRunningAndQueue<T>(new TaskOptions());
  142. }
  143. /// <summary>
  144. /// Cancels if running
  145. /// </summary>
  146. /// <typeparam name="T"></typeparam>
  147. public void CancelIfRunning<T>()
  148. where T : IScheduledTask
  149. {
  150. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  151. ((ScheduledTaskWorker)task).CancelIfRunning();
  152. }
  153. /// <summary>
  154. /// Queues the scheduled task.
  155. /// </summary>
  156. /// <typeparam name="T"></typeparam>
  157. /// <param name="options">Task options</param>
  158. public void QueueScheduledTask<T>(TaskOptions options)
  159. where T : IScheduledTask
  160. {
  161. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  162. if (scheduledTask == null)
  163. {
  164. Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
  165. }
  166. else
  167. {
  168. QueueScheduledTask(scheduledTask, options);
  169. }
  170. }
  171. public void QueueScheduledTask<T>()
  172. where T : IScheduledTask
  173. {
  174. QueueScheduledTask<T>(new TaskOptions());
  175. }
  176. public void QueueIfNotRunning<T>()
  177. where T : IScheduledTask
  178. {
  179. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  180. if (task.State != TaskState.Running)
  181. {
  182. QueueScheduledTask<T>(new TaskOptions());
  183. }
  184. }
  185. public void Execute<T>()
  186. where T : IScheduledTask
  187. {
  188. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  189. if (scheduledTask == null)
  190. {
  191. Logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
  192. }
  193. else
  194. {
  195. var type = scheduledTask.ScheduledTask.GetType();
  196. Logger.LogInformation("Queueing task {0}", type.Name);
  197. lock (_taskQueue)
  198. {
  199. if (scheduledTask.State == TaskState.Idle)
  200. {
  201. Execute(scheduledTask, new TaskOptions());
  202. }
  203. }
  204. }
  205. }
  206. /// <summary>
  207. /// Queues the scheduled task.
  208. /// </summary>
  209. /// <param name="task">The task.</param>
  210. /// <param name="options">The task options.</param>
  211. public void QueueScheduledTask(IScheduledTask task, TaskOptions options)
  212. {
  213. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());
  214. if (scheduledTask == null)
  215. {
  216. Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
  217. }
  218. else
  219. {
  220. QueueScheduledTask(scheduledTask, options);
  221. }
  222. }
  223. /// <summary>
  224. /// Queues the scheduled task.
  225. /// </summary>
  226. /// <param name="task">The task.</param>
  227. /// <param name="options">The task options.</param>
  228. private void QueueScheduledTask(IScheduledTaskWorker task, TaskOptions options)
  229. {
  230. var type = task.ScheduledTask.GetType();
  231. Logger.LogInformation("Queueing task {0}", type.Name);
  232. lock (_taskQueue)
  233. {
  234. if (task.State == TaskState.Idle)
  235. {
  236. Execute(task, options);
  237. return;
  238. }
  239. _taskQueue.Enqueue(new Tuple<Type, TaskOptions>(type, options));
  240. }
  241. }
  242. /// <summary>
  243. /// Adds the tasks.
  244. /// </summary>
  245. /// <param name="tasks">The tasks.</param>
  246. public void AddTasks(IEnumerable<IScheduledTask> tasks)
  247. {
  248. var myTasks = ScheduledTasks.ToList();
  249. var list = tasks.ToList();
  250. myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger, _fileSystem, _systemEvents)));
  251. ScheduledTasks = myTasks.ToArray();
  252. BindToSystemEvent();
  253. RunStartupTasks();
  254. }
  255. /// <summary>
  256. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  257. /// </summary>
  258. public void Dispose()
  259. {
  260. Dispose(true);
  261. }
  262. /// <summary>
  263. /// Releases unmanaged and - optionally - managed resources.
  264. /// </summary>
  265. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  266. protected virtual void Dispose(bool dispose)
  267. {
  268. foreach (var task in ScheduledTasks)
  269. {
  270. task.Dispose();
  271. }
  272. }
  273. public void Cancel(IScheduledTaskWorker task)
  274. {
  275. ((ScheduledTaskWorker)task).Cancel();
  276. }
  277. public Task Execute(IScheduledTaskWorker task, TaskOptions options)
  278. {
  279. return ((ScheduledTaskWorker)task).Execute(options);
  280. }
  281. /// <summary>
  282. /// Called when [task executing].
  283. /// </summary>
  284. /// <param name="task">The task.</param>
  285. internal void OnTaskExecuting(IScheduledTaskWorker task)
  286. {
  287. TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>
  288. {
  289. Argument = task
  290. });
  291. }
  292. /// <summary>
  293. /// Called when [task completed].
  294. /// </summary>
  295. /// <param name="task">The task.</param>
  296. /// <param name="result">The result.</param>
  297. internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
  298. {
  299. TaskCompleted?.Invoke(task, new TaskCompletionEventArgs
  300. {
  301. Result = result,
  302. Task = task
  303. });
  304. ExecuteQueuedTasks();
  305. }
  306. /// <summary>
  307. /// Executes the queued tasks.
  308. /// </summary>
  309. private void ExecuteQueuedTasks()
  310. {
  311. Logger.LogInformation("ExecuteQueuedTasks");
  312. // Execute queued tasks
  313. lock (_taskQueue)
  314. {
  315. var list = new List<Tuple<Type, TaskOptions>>();
  316. while (_taskQueue.TryDequeue(out var item))
  317. {
  318. if (list.All(i => i.Item1 != item.Item1))
  319. {
  320. list.Add(item);
  321. }
  322. }
  323. foreach (var enqueuedType in list)
  324. {
  325. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Item1);
  326. if (scheduledTask.State == TaskState.Idle)
  327. {
  328. Execute(scheduledTask, enqueuedType.Item2);
  329. }
  330. }
  331. }
  332. }
  333. }
  334. }