BaseKernel.cs 9.4 KB

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