BaseKernel.cs 17 KB

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