BaseKernel.cs 19 KB

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