BaseKernel.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Logging;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Net.Handlers;
  5. using MediaBrowser.Common.Plugins;
  6. using MediaBrowser.Common.Serialization;
  7. using MediaBrowser.Model.Configuration;
  8. using MediaBrowser.Model.Progress;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.ComponentModel.Composition;
  12. using System.ComponentModel.Composition.Hosting;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Reflection;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Common.Kernel
  18. {
  19. /// <summary>
  20. /// Represents a shared base kernel for both the Ui and server apps
  21. /// </summary>
  22. public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable, IKernel
  23. where TConfigurationType : BaseApplicationConfiguration, new()
  24. where TApplicationPathsType : BaseApplicationPaths, new()
  25. {
  26. #region ReloadBeginning Event
  27. /// <summary>
  28. /// Fires whenever the kernel begins reloading
  29. /// </summary>
  30. public event EventHandler<GenericEventArgs<IProgress<TaskProgress>>> ReloadBeginning;
  31. private void OnReloadBeginning(IProgress<TaskProgress> progress)
  32. {
  33. if (ReloadBeginning != null)
  34. {
  35. ReloadBeginning(this, new GenericEventArgs<IProgress<TaskProgress>> { Argument = progress });
  36. }
  37. }
  38. #endregion
  39. #region ReloadCompleted Event
  40. /// <summary>
  41. /// Fires whenever the kernel completes reloading
  42. /// </summary>
  43. public event EventHandler<GenericEventArgs<IProgress<TaskProgress>>> ReloadCompleted;
  44. private void OnReloadCompleted(IProgress<TaskProgress> progress)
  45. {
  46. if (ReloadCompleted != null)
  47. {
  48. ReloadCompleted(this, new GenericEventArgs<IProgress<TaskProgress>> { Argument = progress });
  49. }
  50. }
  51. #endregion
  52. /// <summary>
  53. /// Gets the current configuration
  54. /// </summary>
  55. public TConfigurationType Configuration { get; private set; }
  56. public TApplicationPathsType ApplicationPaths { get; private set; }
  57. /// <summary>
  58. /// Gets the list of currently loaded plugins
  59. /// </summary>
  60. [ImportMany(typeof(BasePlugin))]
  61. public IEnumerable<BasePlugin> Plugins { get; private set; }
  62. /// <summary>
  63. /// Gets the list of currently registered http handlers
  64. /// </summary>
  65. [ImportMany(typeof(BaseHandler))]
  66. private IEnumerable<BaseHandler> HttpHandlers { get; set; }
  67. /// <summary>
  68. /// Gets the list of currently registered Loggers
  69. /// </summary>
  70. [ImportMany(typeof(BaseLogger))]
  71. public IEnumerable<BaseLogger> Loggers { get; set; }
  72. /// <summary>
  73. /// Both the Ui and server will have a built-in HttpServer.
  74. /// People will inevitably want remote control apps so it's needed in the Ui too.
  75. /// </summary>
  76. public HttpServer HttpServer { get; private set; }
  77. /// <summary>
  78. /// This subscribes to HttpListener requests and finds the appropate BaseHandler to process it
  79. /// </summary>
  80. private IDisposable HttpListener { get; set; }
  81. private CompositionContainer CompositionContainer { get; set; }
  82. protected virtual string HttpServerUrlPrefix
  83. {
  84. get
  85. {
  86. return "http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/";
  87. }
  88. }
  89. /// <summary>
  90. /// Gets the kernel context. Subclasses will have to override.
  91. /// </summary>
  92. public abstract KernelContext KernelContext { get; }
  93. /// <summary>
  94. /// Initializes the Kernel
  95. /// </summary>
  96. public async Task Init(IProgress<TaskProgress> progress)
  97. {
  98. Logger.Kernel = this;
  99. // Performs initializations that only occur once
  100. InitializeInternal(progress);
  101. // Performs initializations that can be reloaded at anytime
  102. await Reload(progress).ConfigureAwait(false);
  103. }
  104. /// <summary>
  105. /// Performs initializations that only occur once
  106. /// </summary>
  107. protected virtual void InitializeInternal(IProgress<TaskProgress> progress)
  108. {
  109. ApplicationPaths = new TApplicationPathsType();
  110. ReportProgress(progress, "Loading Configuration");
  111. ReloadConfiguration();
  112. ReportProgress(progress, "Loading Http Server");
  113. ReloadHttpServer();
  114. }
  115. /// <summary>
  116. /// Performs initializations that can be reloaded at anytime
  117. /// </summary>
  118. public async Task Reload(IProgress<TaskProgress> progress)
  119. {
  120. OnReloadBeginning(progress);
  121. await ReloadInternal(progress).ConfigureAwait(false);
  122. OnReloadCompleted(progress);
  123. ReportProgress(progress, "Kernel.Reload Complete");
  124. }
  125. /// <summary>
  126. /// Performs initializations that can be reloaded at anytime
  127. /// </summary>
  128. protected virtual async Task ReloadInternal(IProgress<TaskProgress> progress)
  129. {
  130. await Task.Run(() =>
  131. {
  132. ReportProgress(progress, "Loading Plugins");
  133. ReloadComposableParts();
  134. }).ConfigureAwait(false);
  135. }
  136. /// <summary>
  137. /// Uses MEF to locate plugins
  138. /// Subclasses can use this to locate types within plugins
  139. /// </summary>
  140. private void ReloadComposableParts()
  141. {
  142. DisposeComposableParts();
  143. CompositionContainer = GetCompositionContainer(includeCurrentAssembly: true);
  144. CompositionContainer.ComposeParts(this);
  145. OnComposablePartsLoaded();
  146. CompositionContainer.Catalog.Dispose();
  147. }
  148. /// <summary>
  149. /// Constructs an MEF CompositionContainer based on the current running assembly and all plugin assemblies
  150. /// </summary>
  151. public CompositionContainer GetCompositionContainer(bool includeCurrentAssembly = false)
  152. {
  153. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  154. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  155. IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly).Select(f => Assembly.Load(File.ReadAllBytes((f))));
  156. var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
  157. // Include composable parts in the Common assembly
  158. catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
  159. if (includeCurrentAssembly)
  160. {
  161. // Include composable parts in the subclass assembly
  162. catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
  163. }
  164. return new CompositionContainer(catalog);
  165. }
  166. /// <summary>
  167. /// Fires after MEF finishes finding composable parts within plugin assemblies
  168. /// </summary>
  169. protected virtual void OnComposablePartsLoaded()
  170. {
  171. foreach (var logger in Loggers)
  172. {
  173. logger.Initialize(this);
  174. }
  175. // Start-up each plugin
  176. foreach (var plugin in Plugins)
  177. {
  178. plugin.Initialize(this);
  179. }
  180. }
  181. /// <summary>
  182. /// Reloads application configuration from the config file
  183. /// </summary>
  184. private void ReloadConfiguration()
  185. {
  186. //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
  187. // Deserialize config
  188. // Use try/catch to avoid the extra file system lookup using File.Exists
  189. try
  190. {
  191. Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
  192. }
  193. catch (FileNotFoundException)
  194. {
  195. Configuration = new TConfigurationType();
  196. XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
  197. }
  198. }
  199. /// <summary>
  200. /// Restarts the Http Server, or starts it if not currently running
  201. /// </summary>
  202. private void ReloadHttpServer()
  203. {
  204. DisposeHttpServer();
  205. HttpServer = new HttpServer(HttpServerUrlPrefix);
  206. HttpListener = HttpServer.Subscribe(ctx =>
  207. {
  208. BaseHandler handler = HttpHandlers.FirstOrDefault(h => h.HandlesRequest(ctx.Request));
  209. // Find the appropiate http handler
  210. if (handler != null)
  211. {
  212. // Need to create a new instance because handlers are currently stateful
  213. handler = Activator.CreateInstance(handler.GetType()) as BaseHandler;
  214. // No need to await this, despite the compiler warning
  215. handler.ProcessRequest(ctx);
  216. }
  217. });
  218. }
  219. /// <summary>
  220. /// Disposes all resources currently in use.
  221. /// </summary>
  222. public virtual void Dispose()
  223. {
  224. Logger.LogInfo("Beginning Kernel.Dispose");
  225. DisposeHttpServer();
  226. DisposeComposableParts();
  227. }
  228. /// <summary>
  229. /// Disposes all objects gathered through MEF composable parts
  230. /// </summary>
  231. protected virtual void DisposeComposableParts()
  232. {
  233. if (CompositionContainer != null)
  234. {
  235. CompositionContainer.Dispose();
  236. }
  237. }
  238. /// <summary>
  239. /// Disposes the current HttpServer
  240. /// </summary>
  241. private void DisposeHttpServer()
  242. {
  243. if (HttpServer != null)
  244. {
  245. Logger.LogInfo("Disposing Http Server");
  246. HttpServer.Dispose();
  247. }
  248. if (HttpListener != null)
  249. {
  250. HttpListener.Dispose();
  251. }
  252. }
  253. /// <summary>
  254. /// Gets the current application version
  255. /// </summary>
  256. public Version ApplicationVersion
  257. {
  258. get
  259. {
  260. return GetType().Assembly.GetName().Version;
  261. }
  262. }
  263. protected void ReportProgress(IProgress<TaskProgress> progress, string message)
  264. {
  265. progress.Report(new TaskProgress { Description = message });
  266. Logger.LogInfo(message);
  267. }
  268. BaseApplicationPaths IKernel.ApplicationPaths
  269. {
  270. get { return ApplicationPaths; }
  271. }
  272. }
  273. public interface IKernel
  274. {
  275. BaseApplicationPaths ApplicationPaths { get; }
  276. KernelContext KernelContext { get; }
  277. Task Init(IProgress<TaskProgress> progress);
  278. Task Reload(IProgress<TaskProgress> progress);
  279. IEnumerable<BaseLogger> Loggers { get; }
  280. void Dispose();
  281. }
  282. }