BaseKernel.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. using MediaBrowser.Common.Logging;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Common.Net.Handlers;
  4. using MediaBrowser.Common.Plugins;
  5. using MediaBrowser.Common.Serialization;
  6. using MediaBrowser.Model.Configuration;
  7. using MediaBrowser.Model.Progress;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.ComponentModel.Composition;
  11. using System.ComponentModel.Composition.Hosting;
  12. using System.Diagnostics;
  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. /// <summary>
  27. /// Gets the current configuration
  28. /// </summary>
  29. public TConfigurationType Configuration { get; private set; }
  30. public TApplicationPathsType ApplicationPaths { get; private set; }
  31. /// <summary>
  32. /// Gets the list of currently loaded plugins
  33. /// </summary>
  34. [ImportMany(typeof(BasePlugin))]
  35. public IEnumerable<BasePlugin> Plugins { get; private set; }
  36. /// <summary>
  37. /// Gets the list of currently registered http handlers
  38. /// </summary>
  39. [ImportMany(typeof(BaseHandler))]
  40. private IEnumerable<BaseHandler> HttpHandlers { get; set; }
  41. /// <summary>
  42. /// Both the Ui and server will have a built-in HttpServer.
  43. /// People will inevitably want remote control apps so it's needed in the Ui too.
  44. /// </summary>
  45. public HttpServer HttpServer { get; private set; }
  46. /// <summary>
  47. /// This subscribes to HttpListener requests and finds the appropate BaseHandler to process it
  48. /// </summary>
  49. private IDisposable HttpListener { get; set; }
  50. protected virtual string HttpServerUrlPrefix
  51. {
  52. get
  53. {
  54. return "http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/";
  55. }
  56. }
  57. /// <summary>
  58. /// Gets the kernel context. Subclasses will have to override.
  59. /// </summary>
  60. public abstract KernelContext KernelContext { get; }
  61. protected BaseKernel()
  62. {
  63. ApplicationPaths = new TApplicationPathsType();
  64. }
  65. public virtual async Task Init(IProgress<TaskProgress> progress)
  66. {
  67. ReloadLogger();
  68. progress.Report(new TaskProgress { Description = "Loading configuration", PercentComplete = 0 });
  69. ReloadConfiguration();
  70. progress.Report(new TaskProgress { Description = "Starting Http server", PercentComplete = 5 });
  71. ReloadHttpServer();
  72. progress.Report(new TaskProgress { Description = "Loading Plugins", PercentComplete = 10 });
  73. await ReloadComposableParts().ConfigureAwait(false);
  74. }
  75. private void ReloadLogger()
  76. {
  77. DisposeLogger();
  78. DateTime now = DateTime.Now;
  79. string logFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, "log-" + now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
  80. Trace.Listeners.Add(new TextWriterTraceListener(logFilePath));
  81. Trace.AutoFlush = true;
  82. Logger.LoggerInstance = new TraceLogger();
  83. }
  84. /// <summary>
  85. /// Uses MEF to locate plugins
  86. /// Subclasses can use this to locate types within plugins
  87. /// </summary>
  88. protected virtual Task ReloadComposableParts()
  89. {
  90. return Task.Run(() =>
  91. {
  92. DisposeComposableParts();
  93. var container = GetCompositionContainer(includeCurrentAssembly: true);
  94. container.ComposeParts(this);
  95. OnComposablePartsLoaded();
  96. container.Catalog.Dispose();
  97. container.Dispose();
  98. });
  99. }
  100. public CompositionContainer GetCompositionContainer(bool includeCurrentAssembly = false)
  101. {
  102. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  103. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  104. IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly).Select(f => Assembly.Load(File.ReadAllBytes((f))));
  105. var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
  106. // Include composable parts in the Common assembly
  107. // Uncomment this if it's ever needed
  108. //catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
  109. if (includeCurrentAssembly)
  110. {
  111. // Include composable parts in the subclass assembly
  112. catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
  113. }
  114. return new CompositionContainer(catalog);
  115. }
  116. /// <summary>
  117. /// Fires after MEF finishes finding composable parts within plugin assemblies
  118. /// </summary>
  119. protected virtual void OnComposablePartsLoaded()
  120. {
  121. StartPlugins();
  122. }
  123. /// <summary>
  124. /// Initializes all plugins
  125. /// </summary>
  126. private void StartPlugins()
  127. {
  128. foreach (BasePlugin plugin in Plugins)
  129. {
  130. plugin.Initialize(this);
  131. }
  132. }
  133. /// <summary>
  134. /// Reloads application configuration from the config file
  135. /// </summary>
  136. protected virtual void ReloadConfiguration()
  137. {
  138. //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
  139. // Deserialize config
  140. if (!File.Exists(ApplicationPaths.SystemConfigurationFilePath))
  141. {
  142. Configuration = new TConfigurationType();
  143. XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
  144. }
  145. else
  146. {
  147. Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
  148. }
  149. Logger.LoggerInstance.LogSeverity = Configuration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info;
  150. }
  151. /// <summary>
  152. /// Restarts the Http Server, or starts it if not currently running
  153. /// </summary>
  154. private void ReloadHttpServer()
  155. {
  156. DisposeHttpServer();
  157. HttpServer = new HttpServer(HttpServerUrlPrefix);
  158. HttpListener = HttpServer.Subscribe(ctx =>
  159. {
  160. BaseHandler handler = HttpHandlers.FirstOrDefault(h => h.HandlesRequest(ctx.Request));
  161. // Find the appropiate http handler
  162. if (handler != null)
  163. {
  164. // Need to create a new instance because handlers are currently stateful
  165. handler = Activator.CreateInstance(handler.GetType()) as BaseHandler;
  166. // No need to await this, despite the compiler warning
  167. handler.ProcessRequest(ctx);
  168. }
  169. });
  170. }
  171. /// <summary>
  172. /// Disposes all resources currently in use.
  173. /// </summary>
  174. public virtual void Dispose()
  175. {
  176. DisposeComposableParts();
  177. DisposeHttpServer();
  178. DisposeLogger();
  179. }
  180. /// <summary>
  181. /// Disposes all objects gathered through MEF composable parts
  182. /// </summary>
  183. protected virtual void DisposeComposableParts()
  184. {
  185. DisposePlugins();
  186. }
  187. /// <summary>
  188. /// Disposes all plugins
  189. /// </summary>
  190. private void DisposePlugins()
  191. {
  192. if (Plugins != null)
  193. {
  194. foreach (BasePlugin plugin in Plugins)
  195. {
  196. plugin.Dispose();
  197. }
  198. }
  199. }
  200. /// <summary>
  201. /// Disposes the current HttpServer
  202. /// </summary>
  203. private void DisposeHttpServer()
  204. {
  205. if (HttpServer != null)
  206. {
  207. HttpServer.Dispose();
  208. }
  209. if (HttpListener != null)
  210. {
  211. HttpListener.Dispose();
  212. }
  213. }
  214. /// <summary>
  215. /// Disposes the current Logger instance
  216. /// </summary>
  217. private void DisposeLogger()
  218. {
  219. Trace.Listeners.Clear();
  220. if (Logger.LoggerInstance != null)
  221. {
  222. Logger.LoggerInstance.Dispose();
  223. }
  224. }
  225. /// <summary>
  226. /// Gets the current application version
  227. /// </summary>
  228. public Version ApplicationVersion
  229. {
  230. get
  231. {
  232. return GetType().Assembly.GetName().Version;
  233. }
  234. }
  235. BaseApplicationPaths IKernel.ApplicationPaths
  236. {
  237. get { return ApplicationPaths; }
  238. }
  239. }
  240. public interface IKernel
  241. {
  242. BaseApplicationPaths ApplicationPaths { get; }
  243. KernelContext KernelContext { get; }
  244. Task Init(IProgress<TaskProgress> progress);
  245. void Dispose();
  246. }
  247. }