BaseKernel.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. /// <summary>
  62. /// Initializes the Kernel
  63. /// </summary>
  64. public async Task Init(IProgress<TaskProgress> progress)
  65. {
  66. // Performs initializations that only occur once
  67. InitializeInternal(progress);
  68. // Performs initializations that can be reloaded at anytime
  69. await Reload(progress).ConfigureAwait(false);
  70. progress.Report(new TaskProgress { Description = "Loading Complete", PercentComplete = 100 });
  71. }
  72. /// <summary>
  73. /// Performs initializations that only occur once
  74. /// </summary>
  75. protected virtual void InitializeInternal(IProgress<TaskProgress> progress)
  76. {
  77. ApplicationPaths = new TApplicationPathsType();
  78. ReloadLogger();
  79. progress.Report(new TaskProgress { Description = "Loading configuration", PercentComplete = 0 });
  80. ReloadConfiguration();
  81. progress.Report(new TaskProgress { Description = "Starting Http server", PercentComplete = 5 });
  82. ReloadHttpServer();
  83. }
  84. /// <summary>
  85. /// Performs initializations that can be reloaded at anytime
  86. /// </summary>
  87. public virtual async Task Reload(IProgress<TaskProgress> progress)
  88. {
  89. await Task.Run(() =>
  90. {
  91. progress.Report(new TaskProgress { Description = "Loading Plugins", PercentComplete = 10 });
  92. ReloadComposableParts();
  93. }).ConfigureAwait(false);
  94. }
  95. /// <summary>
  96. /// Disposes the current logger and creates a new one
  97. /// </summary>
  98. private void ReloadLogger()
  99. {
  100. DisposeLogger();
  101. DateTime now = DateTime.Now;
  102. string logFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, "log-" + now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
  103. Trace.Listeners.Add(new TextWriterTraceListener(logFilePath));
  104. Trace.AutoFlush = true;
  105. Logger.LoggerInstance = new TraceLogger();
  106. }
  107. /// <summary>
  108. /// Uses MEF to locate plugins
  109. /// Subclasses can use this to locate types within plugins
  110. /// </summary>
  111. private void ReloadComposableParts()
  112. {
  113. DisposeComposableParts();
  114. var container = GetCompositionContainer(includeCurrentAssembly: true);
  115. container.ComposeParts(this);
  116. OnComposablePartsLoaded();
  117. container.Catalog.Dispose();
  118. container.Dispose();
  119. }
  120. /// <summary>
  121. /// Constructs an MEF CompositionContainer based on the current running assembly and all plugin assemblies
  122. /// </summary>
  123. public CompositionContainer GetCompositionContainer(bool includeCurrentAssembly = false)
  124. {
  125. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  126. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  127. IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly).Select(f => Assembly.Load(File.ReadAllBytes((f))));
  128. var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
  129. // Include composable parts in the Common assembly
  130. // Uncomment this if it's ever needed
  131. //catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
  132. if (includeCurrentAssembly)
  133. {
  134. // Include composable parts in the subclass assembly
  135. catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
  136. }
  137. return new CompositionContainer(catalog);
  138. }
  139. /// <summary>
  140. /// Fires after MEF finishes finding composable parts within plugin assemblies
  141. /// </summary>
  142. protected virtual void OnComposablePartsLoaded()
  143. {
  144. // Start-up each plugin
  145. foreach (BasePlugin plugin in Plugins)
  146. {
  147. plugin.Initialize(this);
  148. }
  149. }
  150. /// <summary>
  151. /// Reloads application configuration from the config file
  152. /// </summary>
  153. private void ReloadConfiguration()
  154. {
  155. //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
  156. // Deserialize config
  157. if (!File.Exists(ApplicationPaths.SystemConfigurationFilePath))
  158. {
  159. Configuration = new TConfigurationType();
  160. XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
  161. }
  162. else
  163. {
  164. Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
  165. }
  166. Logger.LoggerInstance.LogSeverity = Configuration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info;
  167. }
  168. /// <summary>
  169. /// Restarts the Http Server, or starts it if not currently running
  170. /// </summary>
  171. private void ReloadHttpServer()
  172. {
  173. DisposeHttpServer();
  174. HttpServer = new HttpServer(HttpServerUrlPrefix);
  175. HttpListener = HttpServer.Subscribe(ctx =>
  176. {
  177. BaseHandler handler = HttpHandlers.FirstOrDefault(h => h.HandlesRequest(ctx.Request));
  178. // Find the appropiate http handler
  179. if (handler != null)
  180. {
  181. // Need to create a new instance because handlers are currently stateful
  182. handler = Activator.CreateInstance(handler.GetType()) as BaseHandler;
  183. // No need to await this, despite the compiler warning
  184. handler.ProcessRequest(ctx);
  185. }
  186. });
  187. }
  188. /// <summary>
  189. /// Disposes all resources currently in use.
  190. /// </summary>
  191. public virtual void Dispose()
  192. {
  193. Logger.LogInfo("Beginning Kernel.Dispose");
  194. DisposeComposableParts();
  195. DisposeHttpServer();
  196. DisposeLogger();
  197. }
  198. /// <summary>
  199. /// Disposes all objects gathered through MEF composable parts
  200. /// </summary>
  201. protected virtual void DisposeComposableParts()
  202. {
  203. DisposePlugins();
  204. }
  205. /// <summary>
  206. /// Disposes all plugins
  207. /// </summary>
  208. private void DisposePlugins()
  209. {
  210. if (Plugins != null)
  211. {
  212. Logger.LogInfo("Disposing Plugins");
  213. foreach (BasePlugin plugin in Plugins)
  214. {
  215. plugin.Dispose();
  216. }
  217. }
  218. }
  219. /// <summary>
  220. /// Disposes the current HttpServer
  221. /// </summary>
  222. private void DisposeHttpServer()
  223. {
  224. if (HttpServer != null)
  225. {
  226. Logger.LogInfo("Disposing Http Server");
  227. HttpServer.Dispose();
  228. }
  229. if (HttpListener != null)
  230. {
  231. HttpListener.Dispose();
  232. }
  233. }
  234. /// <summary>
  235. /// Disposes the current Logger instance
  236. /// </summary>
  237. private void DisposeLogger()
  238. {
  239. Trace.Listeners.Clear();
  240. if (Logger.LoggerInstance != null)
  241. {
  242. Logger.LogInfo("Disposing Logger");
  243. Logger.LoggerInstance.Dispose();
  244. }
  245. }
  246. /// <summary>
  247. /// Gets the current application version
  248. /// </summary>
  249. public Version ApplicationVersion
  250. {
  251. get
  252. {
  253. return GetType().Assembly.GetName().Version;
  254. }
  255. }
  256. BaseApplicationPaths IKernel.ApplicationPaths
  257. {
  258. get { return ApplicationPaths; }
  259. }
  260. }
  261. public interface IKernel
  262. {
  263. BaseApplicationPaths ApplicationPaths { get; }
  264. KernelContext KernelContext { get; }
  265. Task Init(IProgress<TaskProgress> progress);
  266. Task Reload(IProgress<TaskProgress> progress);
  267. void Dispose();
  268. }
  269. }