BaseKernel.cs 9.7 KB

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