BaseKernel.cs 12 KB

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