BaseKernel.cs 16 KB

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