BaseKernel.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Plugins;
  3. using MediaBrowser.Common.Security;
  4. using MediaBrowser.Model.Configuration;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using MediaBrowser.Model.System;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Common.Kernel
  15. {
  16. /// <summary>
  17. /// Represents a shared base kernel for both the Ui and server apps
  18. /// </summary>
  19. /// <typeparam name="TConfigurationType">The type of the T configuration type.</typeparam>
  20. /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
  21. public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable, IKernel
  22. where TConfigurationType : BaseApplicationConfiguration, new()
  23. where TApplicationPathsType : IApplicationPaths
  24. {
  25. /// <summary>
  26. /// Occurs when [has pending restart changed].
  27. /// </summary>
  28. public event EventHandler HasPendingRestartChanged;
  29. #region ConfigurationUpdated Event
  30. /// <summary>
  31. /// Occurs when [configuration updated].
  32. /// </summary>
  33. public event EventHandler<EventArgs> ConfigurationUpdated;
  34. /// <summary>
  35. /// Called when [configuration updated].
  36. /// </summary>
  37. internal void OnConfigurationUpdated()
  38. {
  39. EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty, Logger);
  40. }
  41. #endregion
  42. #region ReloadCompleted Event
  43. /// <summary>
  44. /// Fires whenever the kernel completes reloading
  45. /// </summary>
  46. public event EventHandler<EventArgs> ReloadCompleted;
  47. /// <summary>
  48. /// Called when [reload completed].
  49. /// </summary>
  50. private void OnReloadCompleted()
  51. {
  52. EventHelper.QueueEventIfNotNull(ReloadCompleted, this, EventArgs.Empty, Logger);
  53. }
  54. #endregion
  55. #region ApplicationUpdated Event
  56. /// <summary>
  57. /// Occurs when [application updated].
  58. /// </summary>
  59. public event EventHandler<GenericEventArgs<Version>> ApplicationUpdated;
  60. /// <summary>
  61. /// Called when [application updated].
  62. /// </summary>
  63. /// <param name="newVersion">The new version.</param>
  64. public void OnApplicationUpdated(Version newVersion)
  65. {
  66. EventHelper.QueueEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<Version> { Argument = newVersion }, Logger);
  67. NotifyPendingRestart();
  68. }
  69. #endregion
  70. /// <summary>
  71. /// The _configuration loaded
  72. /// </summary>
  73. private bool _configurationLoaded;
  74. /// <summary>
  75. /// The _configuration sync lock
  76. /// </summary>
  77. private object _configurationSyncLock = new object();
  78. /// <summary>
  79. /// The _configuration
  80. /// </summary>
  81. private TConfigurationType _configuration;
  82. /// <summary>
  83. /// Gets the system configuration
  84. /// </summary>
  85. /// <value>The configuration.</value>
  86. public TConfigurationType Configuration
  87. {
  88. get
  89. {
  90. // Lazy load
  91. LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationLoaded, ref _configurationSyncLock, () => GetXmlConfiguration<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath));
  92. return _configuration;
  93. }
  94. protected set
  95. {
  96. _configuration = value;
  97. if (value == null)
  98. {
  99. _configurationLoaded = false;
  100. }
  101. }
  102. }
  103. /// <summary>
  104. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  105. /// </summary>
  106. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  107. public bool HasPendingRestart { get; private set; }
  108. /// <summary>
  109. /// Gets the application paths.
  110. /// </summary>
  111. /// <value>The application paths.</value>
  112. public TApplicationPathsType ApplicationPaths { get; private set; }
  113. /// <summary>
  114. /// Gets the list of currently loaded plugins
  115. /// </summary>
  116. /// <value>The plugins.</value>
  117. public IEnumerable<IPlugin> Plugins { get; protected set; }
  118. /// <summary>
  119. /// Gets or sets the TCP manager.
  120. /// </summary>
  121. /// <value>The TCP manager.</value>
  122. private IServerManager ServerManager { get; set; }
  123. /// <summary>
  124. /// Gets the plug-in security manager.
  125. /// </summary>
  126. /// <value>The plug-in security manager.</value>
  127. public ISecurityManager SecurityManager { get; set; }
  128. /// <summary>
  129. /// Gets the UDP server port number.
  130. /// This can't be configurable because then the user would have to configure their client to discover the server.
  131. /// </summary>
  132. /// <value>The UDP server port number.</value>
  133. public abstract int UdpServerPortNumber { get; }
  134. /// <summary>
  135. /// Gets the name of the web application that can be used for url building.
  136. /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
  137. /// </summary>
  138. /// <value>The name of the web application.</value>
  139. public string WebApplicationName
  140. {
  141. get { return "mediabrowser"; }
  142. }
  143. /// <summary>
  144. /// Gets the HTTP server URL prefix.
  145. /// </summary>
  146. /// <value>The HTTP server URL prefix.</value>
  147. public virtual string HttpServerUrlPrefix
  148. {
  149. get
  150. {
  151. return "http://+:" + Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/";
  152. }
  153. }
  154. /// <summary>
  155. /// Gets the kernel context. Subclasses will have to override.
  156. /// </summary>
  157. /// <value>The kernel context.</value>
  158. public abstract KernelContext KernelContext { get; }
  159. /// <summary>
  160. /// Gets the logger.
  161. /// </summary>
  162. /// <value>The logger.</value>
  163. protected ILogger Logger { get; private set; }
  164. /// <summary>
  165. /// Gets or sets the application host.
  166. /// </summary>
  167. /// <value>The application host.</value>
  168. protected IApplicationHost ApplicationHost { get; private set; }
  169. /// <summary>
  170. /// The _XML serializer
  171. /// </summary>
  172. private readonly IXmlSerializer _xmlSerializer;
  173. /// <summary>
  174. /// Initializes a new instance of the <see cref="BaseKernel{TApplicationPathsType}" /> class.
  175. /// </summary>
  176. /// <param name="appHost">The app host.</param>
  177. /// <param name="appPaths">The app paths.</param>
  178. /// <param name="xmlSerializer">The XML serializer.</param>
  179. /// <param name="logger">The logger.</param>
  180. /// <exception cref="System.ArgumentNullException">isoManager</exception>
  181. protected BaseKernel(IApplicationHost appHost, TApplicationPathsType appPaths, IXmlSerializer xmlSerializer, ILogger logger)
  182. {
  183. ApplicationPaths = appPaths;
  184. ApplicationHost = appHost;
  185. _xmlSerializer = xmlSerializer;
  186. Logger = logger;
  187. }
  188. /// <summary>
  189. /// Initializes the Kernel
  190. /// </summary>
  191. /// <returns>Task.</returns>
  192. public async Task Init()
  193. {
  194. await ReloadInternal().ConfigureAwait(false);
  195. OnReloadCompleted();
  196. Logger.Info("Kernel.Reload Complete");
  197. }
  198. /// <summary>
  199. /// Performs initializations that can be reloaded at anytime
  200. /// </summary>
  201. /// <returns>Task.</returns>
  202. protected virtual async Task ReloadInternal()
  203. {
  204. // Set these to null so that they can be lazy loaded again
  205. Configuration = null;
  206. await OnConfigurationLoaded().ConfigureAwait(false);
  207. FindParts();
  208. await OnComposablePartsLoaded().ConfigureAwait(false);
  209. ServerManager = ApplicationHost.Resolve<IServerManager>();
  210. }
  211. /// <summary>
  212. /// Called when [configuration loaded].
  213. /// </summary>
  214. /// <returns>Task.</returns>
  215. protected virtual Task OnConfigurationLoaded()
  216. {
  217. return Task.FromResult<object>(null);
  218. }
  219. /// <summary>
  220. /// Composes the parts with ioc container.
  221. /// </summary>
  222. protected virtual void FindParts()
  223. {
  224. Plugins = ApplicationHost.GetExports<IPlugin>();
  225. }
  226. /// <summary>
  227. /// Fires after MEF finishes finding composable parts within plugin assemblies
  228. /// </summary>
  229. /// <returns>Task.</returns>
  230. protected virtual Task OnComposablePartsLoaded()
  231. {
  232. return Task.Run(() =>
  233. {
  234. // Start-up each plugin
  235. Parallel.ForEach(Plugins, plugin =>
  236. {
  237. Logger.Info("Initializing {0} {1}", plugin.Name, plugin.Version);
  238. try
  239. {
  240. plugin.Initialize(this, _xmlSerializer, Logger);
  241. Logger.Info("{0} {1} initialized.", plugin.Name, plugin.Version);
  242. }
  243. catch (Exception ex)
  244. {
  245. Logger.ErrorException("Error initializing {0}", ex, plugin.Name);
  246. }
  247. });
  248. });
  249. }
  250. /// <summary>
  251. /// Notifies that the kernel that a change has been made that requires a restart
  252. /// </summary>
  253. public void NotifyPendingRestart()
  254. {
  255. HasPendingRestart = true;
  256. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  257. }
  258. /// <summary>
  259. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  260. /// </summary>
  261. public void Dispose()
  262. {
  263. Dispose(true);
  264. GC.SuppressFinalize(this);
  265. }
  266. /// <summary>
  267. /// Releases unmanaged and - optionally - managed resources.
  268. /// </summary>
  269. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  270. protected virtual void Dispose(bool dispose)
  271. {
  272. }
  273. /// <summary>
  274. /// Performs the pending restart.
  275. /// </summary>
  276. /// <returns>Task.</returns>
  277. public void PerformPendingRestart()
  278. {
  279. if (HasPendingRestart)
  280. {
  281. Logger.Info("Restarting the application");
  282. ApplicationHost.Restart();
  283. }
  284. else
  285. {
  286. Logger.Info("PerformPendingRestart - not needed");
  287. }
  288. }
  289. /// <summary>
  290. /// Gets the system status.
  291. /// </summary>
  292. /// <returns>SystemInfo.</returns>
  293. public virtual SystemInfo GetSystemInfo()
  294. {
  295. return new SystemInfo
  296. {
  297. HasPendingRestart = HasPendingRestart,
  298. Version = ApplicationHost.ApplicationVersion.ToString(),
  299. IsNetworkDeployed = ApplicationHost.CanSelfUpdate,
  300. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  301. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  302. FailedPluginAssemblies = ApplicationHost.FailedAssemblies.ToArray()
  303. };
  304. }
  305. /// <summary>
  306. /// The _save lock
  307. /// </summary>
  308. private readonly object _configurationSaveLock = new object();
  309. /// <summary>
  310. /// Saves the current configuration
  311. /// </summary>
  312. public void SaveConfiguration()
  313. {
  314. lock (_configurationSaveLock)
  315. {
  316. _xmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
  317. }
  318. OnConfigurationUpdated();
  319. }
  320. /// <summary>
  321. /// Gets the application paths.
  322. /// </summary>
  323. /// <value>The application paths.</value>
  324. IApplicationPaths IKernel.ApplicationPaths
  325. {
  326. get { return ApplicationPaths; }
  327. }
  328. /// <summary>
  329. /// Gets the configuration.
  330. /// </summary>
  331. /// <value>The configuration.</value>
  332. BaseApplicationConfiguration IKernel.Configuration
  333. {
  334. get { return Configuration; }
  335. }
  336. /// <summary>
  337. /// Reads an xml configuration file from the file system
  338. /// It will immediately re-serialize and save if new serialization data is available due to property changes
  339. /// </summary>
  340. /// <param name="type">The type.</param>
  341. /// <param name="path">The path.</param>
  342. /// <returns>System.Object.</returns>
  343. public object GetXmlConfiguration(Type type, string path)
  344. {
  345. Logger.Info("Loading {0} at {1}", type.Name, path);
  346. object configuration;
  347. byte[] buffer = null;
  348. // Use try/catch to avoid the extra file system lookup using File.Exists
  349. try
  350. {
  351. buffer = File.ReadAllBytes(path);
  352. configuration = _xmlSerializer.DeserializeFromBytes(type, buffer);
  353. }
  354. catch (FileNotFoundException)
  355. {
  356. configuration = Activator.CreateInstance(type);
  357. }
  358. // Take the object we just got and serialize it back to bytes
  359. var newBytes = _xmlSerializer.SerializeToBytes(configuration);
  360. // If the file didn't exist before, or if something has changed, re-save
  361. if (buffer == null || !buffer.SequenceEqual(newBytes))
  362. {
  363. Logger.Info("Saving {0} to {1}", type.Name, path);
  364. // Save it after load in case we got new items
  365. File.WriteAllBytes(path, newBytes);
  366. }
  367. return configuration;
  368. }
  369. /// <summary>
  370. /// Reads an xml configuration file from the file system
  371. /// It will immediately save the configuration after loading it, just
  372. /// in case there are new serializable properties
  373. /// </summary>
  374. /// <typeparam name="T"></typeparam>
  375. /// <param name="path">The path.</param>
  376. /// <returns>``0.</returns>
  377. private T GetXmlConfiguration<T>(string path)
  378. where T : class
  379. {
  380. return GetXmlConfiguration(typeof(T), path) as T;
  381. }
  382. /// <summary>
  383. /// Limits simultaneous access to various resources
  384. /// </summary>
  385. /// <value>The resource pools.</value>
  386. public ResourcePool ResourcePools { get; set; }
  387. /// <summary>
  388. /// Removes the plugin.
  389. /// </summary>
  390. /// <param name="plugin">The plugin.</param>
  391. public void RemovePlugin(IPlugin plugin)
  392. {
  393. var list = Plugins.ToList();
  394. list.Remove(plugin);
  395. Plugins = list;
  396. }
  397. }
  398. }