BaseKernel.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. // This event handler will allow any plugin to reference another
  124. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  125. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  126. StartPlugins();
  127. }
  128. /// <summary>
  129. /// Initializes all plugins
  130. /// </summary>
  131. private void StartPlugins()
  132. {
  133. foreach (BasePlugin plugin in Plugins)
  134. {
  135. plugin.Initialize(this);
  136. }
  137. }
  138. /// <summary>
  139. /// Reloads application configuration from the config file
  140. /// </summary>
  141. protected virtual void ReloadConfiguration()
  142. {
  143. //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
  144. // Deserialize config
  145. if (!File.Exists(ApplicationPaths.SystemConfigurationFilePath))
  146. {
  147. Configuration = new TConfigurationType();
  148. XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
  149. }
  150. else
  151. {
  152. Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
  153. }
  154. Logger.LoggerInstance.LogSeverity = Configuration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info;
  155. }
  156. /// <summary>
  157. /// Restarts the Http Server, or starts it if not currently running
  158. /// </summary>
  159. private void ReloadHttpServer()
  160. {
  161. DisposeHttpServer();
  162. HttpServer = new HttpServer(HttpServerUrlPrefix);
  163. HttpListener = HttpServer.Subscribe((ctx) =>
  164. {
  165. BaseHandler handler = HttpHandlers.FirstOrDefault(h => h.HandlesRequest(ctx.Request));
  166. // Find the appropiate http handler
  167. if (handler != null)
  168. {
  169. // Need to create a new instance because handlers are currently stateful
  170. handler = Activator.CreateInstance(handler.GetType()) as BaseHandler;
  171. // No need to await this, despite the compiler warning
  172. handler.ProcessRequest(ctx);
  173. }
  174. });
  175. }
  176. /// <summary>
  177. /// This snippet will allow any plugin to reference another
  178. /// </summary>
  179. Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  180. {
  181. AssemblyName assemblyName = new AssemblyName(args.Name);
  182. // Look for the .dll recursively within the plugins directory
  183. string dll = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories)
  184. .FirstOrDefault(f => Path.GetFileNameWithoutExtension(f) == assemblyName.Name);
  185. // If we found a matching assembly, load it now
  186. if (!string.IsNullOrEmpty(dll))
  187. {
  188. return Assembly.Load(File.ReadAllBytes(dll));
  189. }
  190. return null;
  191. }
  192. /// <summary>
  193. /// Disposes all resources currently in use.
  194. /// </summary>
  195. public virtual void Dispose()
  196. {
  197. DisposeComposableParts();
  198. DisposeHttpServer();
  199. DisposeLogger();
  200. }
  201. /// <summary>
  202. /// Disposes all objects gathered through MEF composable parts
  203. /// </summary>
  204. protected virtual void DisposeComposableParts()
  205. {
  206. DisposePlugins();
  207. }
  208. /// <summary>
  209. /// Disposes all plugins
  210. /// </summary>
  211. private void DisposePlugins()
  212. {
  213. if (Plugins != null)
  214. {
  215. foreach (BasePlugin plugin in Plugins)
  216. {
  217. plugin.Dispose();
  218. }
  219. }
  220. }
  221. /// <summary>
  222. /// Disposes the current HttpServer
  223. /// </summary>
  224. private void DisposeHttpServer()
  225. {
  226. if (HttpServer != null)
  227. {
  228. HttpServer.Dispose();
  229. }
  230. if (HttpListener != null)
  231. {
  232. HttpListener.Dispose();
  233. }
  234. }
  235. /// <summary>
  236. /// Disposes the current Logger instance
  237. /// </summary>
  238. private void DisposeLogger()
  239. {
  240. if (Logger.LoggerInstance != null)
  241. {
  242. Logger.LoggerInstance.Dispose();
  243. }
  244. }
  245. /// <summary>
  246. /// Gets the current application version
  247. /// </summary>
  248. public Version ApplicationVersion
  249. {
  250. get
  251. {
  252. return GetType().Assembly.GetName().Version;
  253. }
  254. }
  255. BaseApplicationPaths IKernel.ApplicationPaths
  256. {
  257. get { return ApplicationPaths; }
  258. }
  259. }
  260. public interface IKernel
  261. {
  262. BaseApplicationPaths ApplicationPaths { get; }
  263. KernelContext KernelContext { get; }
  264. Task Init(IProgress<TaskProgress> progress);
  265. void Dispose();
  266. }
  267. }