BaseKernel.cs 16 KB

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