BaseKernel.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. //catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
  84. //catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
  85. var container = new CompositionContainer(catalog);
  86. container.ComposeParts(this);
  87. OnComposablePartsLoaded();
  88. catalog.Dispose();
  89. container.Dispose();
  90. }
  91. /// <summary>
  92. /// Fires after MEF finishes finding composable parts within plugin assemblies
  93. /// </summary>
  94. protected virtual void OnComposablePartsLoaded()
  95. {
  96. // This event handler will allow any plugin to reference another
  97. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  98. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  99. StartPlugins();
  100. }
  101. /// <summary>
  102. /// Initializes all plugins
  103. /// </summary>
  104. private void StartPlugins()
  105. {
  106. foreach (BasePlugin plugin in Plugins)
  107. {
  108. Assembly assembly = plugin.GetType().Assembly;
  109. AssemblyName assemblyName = assembly.GetName();
  110. plugin.Version = assemblyName.Version;
  111. plugin.Path = Path.Combine(ApplicationPaths.PluginsPath, assemblyName.Name);
  112. plugin.Context = KernelContext;
  113. plugin.ReloadConfiguration();
  114. if (plugin.Enabled)
  115. {
  116. plugin.Init();
  117. }
  118. }
  119. }
  120. /// <summary>
  121. /// Reloads application configuration from the config file
  122. /// </summary>
  123. protected virtual void ReloadConfiguration()
  124. {
  125. //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
  126. // Deserialize config
  127. if (!File.Exists(ApplicationPaths.SystemConfigurationFilePath))
  128. {
  129. Configuration = new TConfigurationType();
  130. }
  131. else
  132. {
  133. Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
  134. }
  135. Logger.LoggerInstance.LogSeverity = Configuration.LogSeverity;
  136. }
  137. /// <summary>
  138. /// Restarts the Http Server, or starts it if not currently running
  139. /// </summary>
  140. private void ReloadHttpServer()
  141. {
  142. DisposeHttpServer();
  143. HttpServer = new HttpServer("http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/");
  144. }
  145. /// <summary>
  146. /// This snippet will allow any plugin to reference another
  147. /// </summary>
  148. Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  149. {
  150. AssemblyName assemblyName = new AssemblyName(args.Name);
  151. // Look for the .dll recursively within the plugins directory
  152. string dll = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories)
  153. .FirstOrDefault(f => Path.GetFileNameWithoutExtension(f) == assemblyName.Name);
  154. // If we found a matching assembly, load it now
  155. if (!string.IsNullOrEmpty(dll))
  156. {
  157. return Assembly.Load(File.ReadAllBytes(dll));
  158. }
  159. return null;
  160. }
  161. /// <summary>
  162. /// Disposes all resources currently in use.
  163. /// </summary>
  164. public virtual void Dispose()
  165. {
  166. DisposeComposableParts();
  167. DisposeHttpServer();
  168. DisposeLogger();
  169. }
  170. /// <summary>
  171. /// Disposes all objects gathered through MEF composable parts
  172. /// </summary>
  173. protected virtual void DisposeComposableParts()
  174. {
  175. DisposePlugins();
  176. }
  177. /// <summary>
  178. /// Disposes all plugins
  179. /// </summary>
  180. private void DisposePlugins()
  181. {
  182. if (Plugins != null)
  183. {
  184. foreach (BasePlugin plugin in Plugins)
  185. {
  186. plugin.Dispose();
  187. }
  188. }
  189. }
  190. /// <summary>
  191. /// Disposes the current HttpServer
  192. /// </summary>
  193. private void DisposeHttpServer()
  194. {
  195. if (HttpServer != null)
  196. {
  197. HttpServer.Dispose();
  198. }
  199. }
  200. /// <summary>
  201. /// Disposes the current Logger instance
  202. /// </summary>
  203. private void DisposeLogger()
  204. {
  205. if (Logger.LoggerInstance != null)
  206. {
  207. Logger.LoggerInstance.Dispose();
  208. }
  209. }
  210. /// <summary>
  211. /// Gets the current application version
  212. /// </summary>
  213. public Version ApplicationVersion
  214. {
  215. get
  216. {
  217. return GetType().Assembly.GetName().Version;
  218. }
  219. }
  220. }
  221. public interface IKernel
  222. {
  223. Task Init(IProgress<TaskProgress> progress);
  224. void Dispose();
  225. }
  226. }