BaseKernel.cs 16 KB

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