TaskManager.cs 12 KB

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