TaskManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. /// <summary>
  44. /// Gets the logger.
  45. /// </summary>
  46. /// <value>The logger.</value>
  47. private ILogger Logger { get; set; }
  48. private readonly IFileSystem _fileSystem;
  49. /// <summary>
  50. /// Initializes a new instance of the <see cref="TaskManager" /> class.
  51. /// </summary>
  52. /// <param name="applicationPaths">The application paths.</param>
  53. /// <param name="jsonSerializer">The json serializer.</param>
  54. /// <param name="loggerFactory">The logger factory.</param>
  55. /// <exception cref="System.ArgumentException">kernel</exception>
  56. public TaskManager(
  57. IApplicationPaths applicationPaths,
  58. IJsonSerializer jsonSerializer,
  59. ILoggerFactory loggerFactory,
  60. IFileSystem fileSystem)
  61. {
  62. ApplicationPaths = applicationPaths;
  63. JsonSerializer = jsonSerializer;
  64. Logger = loggerFactory.CreateLogger(nameof(TaskManager));
  65. _fileSystem = fileSystem;
  66. ScheduledTasks = new IScheduledTaskWorker[] { };
  67. }
  68. private void RunStartupTasks()
  69. {
  70. var path = Path.Combine(ApplicationPaths.CachePath, "startuptasks.txt");
  71. // ToDo: Fix this shit
  72. if (!File.Exists(path))
  73. return;
  74. List<string> lines;
  75. try
  76. {
  77. lines = File.ReadAllLines(path).Where(i => !string.IsNullOrWhiteSpace(i)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  78. foreach (var key in lines)
  79. {
  80. var task = ScheduledTasks.FirstOrDefault(i => string.Equals(i.ScheduledTask.Key, key, StringComparison.OrdinalIgnoreCase));
  81. if (task != null)
  82. {
  83. QueueScheduledTask(task, new TaskOptions());
  84. }
  85. }
  86. _fileSystem.DeleteFile(path);
  87. }
  88. catch
  89. {
  90. return;
  91. }
  92. }
  93. /// <summary>
  94. /// Cancels if running and queue.
  95. /// </summary>
  96. /// <typeparam name="T"></typeparam>
  97. /// <param name="options">Task options.</param>
  98. public void CancelIfRunningAndQueue<T>(TaskOptions options)
  99. where T : IScheduledTask
  100. {
  101. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  102. ((ScheduledTaskWorker)task).CancelIfRunning();
  103. QueueScheduledTask<T>(options);
  104. }
  105. public void CancelIfRunningAndQueue<T>()
  106. where T : IScheduledTask
  107. {
  108. CancelIfRunningAndQueue<T>(new TaskOptions());
  109. }
  110. /// <summary>
  111. /// Cancels if running
  112. /// </summary>
  113. /// <typeparam name="T"></typeparam>
  114. public void CancelIfRunning<T>()
  115. where T : IScheduledTask
  116. {
  117. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  118. ((ScheduledTaskWorker)task).CancelIfRunning();
  119. }
  120. /// <summary>
  121. /// Queues the scheduled task.
  122. /// </summary>
  123. /// <typeparam name="T"></typeparam>
  124. /// <param name="options">Task options</param>
  125. public void QueueScheduledTask<T>(TaskOptions options)
  126. where T : IScheduledTask
  127. {
  128. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  129. if (scheduledTask == null)
  130. {
  131. Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
  132. }
  133. else
  134. {
  135. QueueScheduledTask(scheduledTask, options);
  136. }
  137. }
  138. public void QueueScheduledTask<T>()
  139. where T : IScheduledTask
  140. {
  141. QueueScheduledTask<T>(new TaskOptions());
  142. }
  143. public void QueueIfNotRunning<T>()
  144. where T : IScheduledTask
  145. {
  146. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  147. if (task.State != TaskState.Running)
  148. {
  149. QueueScheduledTask<T>(new TaskOptions());
  150. }
  151. }
  152. public void Execute<T>()
  153. where T : IScheduledTask
  154. {
  155. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  156. if (scheduledTask == null)
  157. {
  158. Logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
  159. }
  160. else
  161. {
  162. var type = scheduledTask.ScheduledTask.GetType();
  163. Logger.LogInformation("Queueing task {0}", type.Name);
  164. lock (_taskQueue)
  165. {
  166. if (scheduledTask.State == TaskState.Idle)
  167. {
  168. Execute(scheduledTask, new TaskOptions());
  169. }
  170. }
  171. }
  172. }
  173. /// <summary>
  174. /// Queues the scheduled task.
  175. /// </summary>
  176. /// <param name="task">The task.</param>
  177. /// <param name="options">The task options.</param>
  178. public void QueueScheduledTask(IScheduledTask task, TaskOptions options)
  179. {
  180. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());
  181. if (scheduledTask == null)
  182. {
  183. Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
  184. }
  185. else
  186. {
  187. QueueScheduledTask(scheduledTask, options);
  188. }
  189. }
  190. /// <summary>
  191. /// Queues the scheduled task.
  192. /// </summary>
  193. /// <param name="task">The task.</param>
  194. /// <param name="options">The task options.</param>
  195. private void QueueScheduledTask(IScheduledTaskWorker task, TaskOptions options)
  196. {
  197. var type = task.ScheduledTask.GetType();
  198. Logger.LogInformation("Queueing task {0}", type.Name);
  199. lock (_taskQueue)
  200. {
  201. if (task.State == TaskState.Idle)
  202. {
  203. Execute(task, options);
  204. return;
  205. }
  206. _taskQueue.Enqueue(new Tuple<Type, TaskOptions>(type, options));
  207. }
  208. }
  209. /// <summary>
  210. /// Adds the tasks.
  211. /// </summary>
  212. /// <param name="tasks">The tasks.</param>
  213. public void AddTasks(IEnumerable<IScheduledTask> tasks)
  214. {
  215. var myTasks = ScheduledTasks.ToList();
  216. var list = tasks.ToList();
  217. myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger, _fileSystem)));
  218. ScheduledTasks = myTasks.ToArray();
  219. RunStartupTasks();
  220. }
  221. /// <summary>
  222. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  223. /// </summary>
  224. public void Dispose()
  225. {
  226. Dispose(true);
  227. }
  228. /// <summary>
  229. /// Releases unmanaged and - optionally - managed resources.
  230. /// </summary>
  231. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  232. protected virtual void Dispose(bool dispose)
  233. {
  234. foreach (var task in ScheduledTasks)
  235. {
  236. task.Dispose();
  237. }
  238. }
  239. public void Cancel(IScheduledTaskWorker task)
  240. {
  241. ((ScheduledTaskWorker)task).Cancel();
  242. }
  243. public Task Execute(IScheduledTaskWorker task, TaskOptions options)
  244. {
  245. return ((ScheduledTaskWorker)task).Execute(options);
  246. }
  247. /// <summary>
  248. /// Called when [task executing].
  249. /// </summary>
  250. /// <param name="task">The task.</param>
  251. internal void OnTaskExecuting(IScheduledTaskWorker task)
  252. {
  253. TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>
  254. {
  255. Argument = task
  256. });
  257. }
  258. /// <summary>
  259. /// Called when [task completed].
  260. /// </summary>
  261. /// <param name="task">The task.</param>
  262. /// <param name="result">The result.</param>
  263. internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
  264. {
  265. TaskCompleted?.Invoke(task, new TaskCompletionEventArgs
  266. {
  267. Result = result,
  268. Task = task
  269. });
  270. ExecuteQueuedTasks();
  271. }
  272. /// <summary>
  273. /// Executes the queued tasks.
  274. /// </summary>
  275. private void ExecuteQueuedTasks()
  276. {
  277. Logger.LogInformation("ExecuteQueuedTasks");
  278. // Execute queued tasks
  279. lock (_taskQueue)
  280. {
  281. var list = new List<Tuple<Type, TaskOptions>>();
  282. while (_taskQueue.TryDequeue(out var item))
  283. {
  284. if (list.All(i => i.Item1 != item.Item1))
  285. {
  286. list.Add(item);
  287. }
  288. }
  289. foreach (var enqueuedType in list)
  290. {
  291. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Item1);
  292. if (scheduledTask.State == TaskState.Idle)
  293. {
  294. Execute(scheduledTask, enqueuedType.Item2);
  295. }
  296. }
  297. }
  298. }
  299. }
  300. }