BaseKernel.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.Composition;
  4. using System.ComponentModel.Composition.Hosting;
  5. using System.Configuration;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  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> : IDisposable
  21. where TConfigurationType : BaseApplicationConfiguration, new()
  22. {
  23. /// <summary>
  24. /// Gets the current configuration
  25. /// </summary>
  26. public TConfigurationType Configuration { get; private set; }
  27. /// <summary>
  28. /// Gets the list of currently loaded plugins
  29. /// </summary>
  30. [ImportMany(typeof(BasePlugin))]
  31. public IEnumerable<BasePlugin> Plugins { get; private set; }
  32. /// <summary>
  33. /// Both the UI and server will have a built-in HttpServer.
  34. /// People will inevitably want remote control apps so it's needed in the UI too.
  35. /// </summary>
  36. public HttpServer HttpServer { get; private set; }
  37. /// <summary>
  38. /// Gets the kernel context. The UI kernel will have to override this.
  39. /// </summary>
  40. protected KernelContext KernelContext { get { return KernelContext.Server; } }
  41. public BaseKernel()
  42. {
  43. }
  44. public virtual void Init(IProgress<TaskProgress> progress)
  45. {
  46. ReloadLogger();
  47. progress.Report(new TaskProgress() { Description = "Loading configuration", PercentComplete = 0 });
  48. ReloadConfiguration();
  49. progress.Report(new TaskProgress() { Description = "Starting Http server", PercentComplete = 5 });
  50. ReloadHttpServer();
  51. progress.Report(new TaskProgress() { Description = "Loading Plugins", PercentComplete = 10 });
  52. ReloadComposableParts();
  53. }
  54. /// <summary>
  55. /// Gets or sets the path to the current log file
  56. /// </summary>
  57. public static string LogFilePath { get; set; }
  58. private void ReloadLogger()
  59. {
  60. DisposeLogger();
  61. DateTime now = DateTime.Now;
  62. LogFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, Assembly.GetExecutingAssembly().GetType().Name + "-" + now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
  63. FileStream fs = new FileStream(LogFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
  64. Logger.LoggerInstance = new StreamLogger(fs);
  65. }
  66. /// <summary>
  67. /// Uses MEF to locate plugins
  68. /// Subclasses can use this to locate types within plugins
  69. /// </summary>
  70. protected void ReloadComposableParts()
  71. {
  72. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  73. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  74. IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories).Select(f => Assembly.Load(File.ReadAllBytes((f))));
  75. var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
  76. //catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
  77. //catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
  78. var container = new CompositionContainer(catalog);
  79. container.ComposeParts(this);
  80. OnComposablePartsLoaded();
  81. catalog.Dispose();
  82. container.Dispose();
  83. }
  84. /// <summary>
  85. /// Fires after MEF finishes finding composable parts within plugin assemblies
  86. /// </summary>
  87. protected virtual void OnComposablePartsLoaded()
  88. {
  89. // This event handler will allow any plugin to reference another
  90. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  91. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  92. StartPlugins();
  93. }
  94. /// <summary>
  95. /// Initializes all plugins
  96. /// </summary>
  97. private void StartPlugins()
  98. {
  99. foreach (BasePlugin plugin in Plugins)
  100. {
  101. Assembly assembly = plugin.GetType().Assembly;
  102. AssemblyName assemblyName = assembly.GetName();
  103. plugin.Version = assemblyName.Version;
  104. plugin.Path = Path.Combine(ApplicationPaths.PluginsPath, assemblyName.Name);
  105. plugin.Context = KernelContext;
  106. plugin.ReloadConfiguration();
  107. if (plugin.Enabled)
  108. {
  109. plugin.Init();
  110. }
  111. }
  112. }
  113. /// <summary>
  114. /// Reloads application configuration from the config file
  115. /// </summary>
  116. protected virtual void ReloadConfiguration()
  117. {
  118. //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
  119. // Deserialize config
  120. if (!File.Exists(ApplicationPaths.ConfigurationPath))
  121. {
  122. Configuration = new TConfigurationType();
  123. }
  124. else
  125. {
  126. Configuration = JsonSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.ConfigurationPath);
  127. }
  128. Logger.LoggerInstance.LogSeverity = Configuration.LogSeverity;
  129. }
  130. /// <summary>
  131. /// Restarts the Http Server, or starts it if not currently running
  132. /// </summary>
  133. private void ReloadHttpServer()
  134. {
  135. DisposeHttpServer();
  136. HttpServer = new HttpServer("http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/");
  137. }
  138. /// <summary>
  139. /// This snippet will allow any plugin to reference another
  140. /// </summary>
  141. Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  142. {
  143. AssemblyName assemblyName = new AssemblyName(args.Name);
  144. // Look for the .dll recursively within the plugins directory
  145. string dll = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories)
  146. .FirstOrDefault(f => Path.GetFileNameWithoutExtension(f) == assemblyName.Name);
  147. // If we found a matching assembly, load it now
  148. if (!string.IsNullOrEmpty(dll))
  149. {
  150. return Assembly.Load(File.ReadAllBytes(dll));
  151. }
  152. return null;
  153. }
  154. /// <summary>
  155. /// Disposes all resources currently in use.
  156. /// </summary>
  157. public virtual void Dispose()
  158. {
  159. DisposeHttpServer();
  160. DisposeLogger();
  161. }
  162. /// <summary>
  163. /// Disposes the current HttpServer
  164. /// </summary>
  165. private void DisposeHttpServer()
  166. {
  167. if (HttpServer != null)
  168. {
  169. HttpServer.Dispose();
  170. }
  171. }
  172. /// <summary>
  173. /// Disposes the current Logger instance
  174. /// </summary>
  175. private void DisposeLogger()
  176. {
  177. if (Logger.LoggerInstance != null)
  178. {
  179. Logger.LoggerInstance.Dispose();
  180. }
  181. }
  182. }
  183. }