BaseKernel.cs 9.8 KB

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