BaseKernel.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.Composition;
  4. using System.ComponentModel.Composition.Hosting;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Logging;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Common.Plugins;
  12. using MediaBrowser.Common.Serialization;
  13. using MediaBrowser.Model.Configuration;
  14. using MediaBrowser.Model.Progress;
  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. The UI kernel will have to override this.
  48. /// </summary>
  49. protected KernelContext KernelContext { get { return KernelContext.Server; } }
  50. public BaseKernel()
  51. {
  52. ApplicationPaths = new TApplicationPathsType();
  53. }
  54. public virtual Task Init(IProgress<TaskProgress> progress)
  55. {
  56. return Task.Run(() =>
  57. {
  58. ReloadLogger();
  59. progress.Report(new TaskProgress() { Description = "Loading configuration", PercentComplete = 0 });
  60. ReloadConfiguration();
  61. progress.Report(new TaskProgress() { Description = "Starting Http server", PercentComplete = 5 });
  62. ReloadHttpServer();
  63. progress.Report(new TaskProgress() { Description = "Loading Plugins", PercentComplete = 10 });
  64. ReloadComposableParts();
  65. });
  66. }
  67. /// <summary>
  68. /// Gets or sets the path to the current log file
  69. /// </summary>
  70. public static string LogFilePath { get; set; }
  71. private void ReloadLogger()
  72. {
  73. DisposeLogger();
  74. DateTime now = DateTime.Now;
  75. LogFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, "log-" + now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
  76. FileStream fs = new FileStream(LogFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
  77. Logger.LoggerInstance = new StreamLogger(fs);
  78. }
  79. /// <summary>
  80. /// Uses MEF to locate plugins
  81. /// Subclasses can use this to locate types within plugins
  82. /// </summary>
  83. protected void ReloadComposableParts()
  84. {
  85. DisposeComposableParts();
  86. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  87. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  88. IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories).Select(f => Assembly.Load(File.ReadAllBytes((f))));
  89. var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
  90. // Include composable parts in the Common assembly
  91. // Uncomment this if it's ever needed
  92. //catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
  93. // Include composable parts in the subclass assembly
  94. catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
  95. var container = new CompositionContainer(catalog);
  96. container.ComposeParts(this);
  97. OnComposablePartsLoaded();
  98. catalog.Dispose();
  99. container.Dispose();
  100. }
  101. /// <summary>
  102. /// Fires after MEF finishes finding composable parts within plugin assemblies
  103. /// </summary>
  104. protected virtual void OnComposablePartsLoaded()
  105. {
  106. // This event handler will allow any plugin to reference another
  107. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  108. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  109. StartPlugins();
  110. }
  111. /// <summary>
  112. /// Initializes all plugins
  113. /// </summary>
  114. private void StartPlugins()
  115. {
  116. foreach (BasePlugin plugin in Plugins)
  117. {
  118. Assembly assembly = plugin.GetType().Assembly;
  119. AssemblyName assemblyName = assembly.GetName();
  120. plugin.Version = assemblyName.Version;
  121. plugin.Path = Path.Combine(ApplicationPaths.PluginsPath, assemblyName.Name);
  122. plugin.Context = KernelContext;
  123. plugin.ReloadConfiguration();
  124. if (plugin.Enabled)
  125. {
  126. plugin.Init();
  127. }
  128. }
  129. }
  130. /// <summary>
  131. /// Reloads application configuration from the config file
  132. /// </summary>
  133. protected virtual void ReloadConfiguration()
  134. {
  135. //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
  136. // Deserialize config
  137. if (!File.Exists(ApplicationPaths.SystemConfigurationFilePath))
  138. {
  139. Configuration = new TConfigurationType();
  140. }
  141. else
  142. {
  143. Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
  144. }
  145. Logger.LoggerInstance.LogSeverity = Configuration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info;
  146. }
  147. /// <summary>
  148. /// Restarts the Http Server, or starts it if not currently running
  149. /// </summary>
  150. private void ReloadHttpServer()
  151. {
  152. DisposeHttpServer();
  153. HttpServer = new HttpServer(HttpServerUrlPrefix);
  154. }
  155. /// <summary>
  156. /// This snippet will allow any plugin to reference another
  157. /// </summary>
  158. Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  159. {
  160. AssemblyName assemblyName = new AssemblyName(args.Name);
  161. // Look for the .dll recursively within the plugins directory
  162. string dll = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories)
  163. .FirstOrDefault(f => Path.GetFileNameWithoutExtension(f) == assemblyName.Name);
  164. // If we found a matching assembly, load it now
  165. if (!string.IsNullOrEmpty(dll))
  166. {
  167. return Assembly.Load(File.ReadAllBytes(dll));
  168. }
  169. return null;
  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. }
  210. /// <summary>
  211. /// Disposes the current Logger instance
  212. /// </summary>
  213. private void DisposeLogger()
  214. {
  215. if (Logger.LoggerInstance != null)
  216. {
  217. Logger.LoggerInstance.Dispose();
  218. }
  219. }
  220. /// <summary>
  221. /// Gets the current application version
  222. /// </summary>
  223. public Version ApplicationVersion
  224. {
  225. get
  226. {
  227. return GetType().Assembly.GetName().Version;
  228. }
  229. }
  230. }
  231. public interface IKernel
  232. {
  233. Task Init(IProgress<TaskProgress> progress);
  234. void Dispose();
  235. }
  236. }