TaskManager.cs 12 KB

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