BaseKernel.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. Logger.Info("Version {0} initializing", ApplicationVersion);
  280. await OnConfigurationLoaded().ConfigureAwait(false);
  281. FindParts();
  282. await OnComposablePartsLoaded().ConfigureAwait(false);
  283. DisposeTcpManager();
  284. TcpManager = (TcpManager)ApplicationHost.CreateInstance(typeof(TcpManager));
  285. }
  286. /// <summary>
  287. /// Called when [configuration loaded].
  288. /// </summary>
  289. /// <returns>Task.</returns>
  290. protected virtual Task OnConfigurationLoaded()
  291. {
  292. return Task.FromResult<object>(null);
  293. }
  294. /// <summary>
  295. /// Disposes and reloads all loggers
  296. /// </summary>
  297. public void ReloadLogger()
  298. {
  299. ApplicationHost.ReloadLogger();
  300. OnLoggerLoaded();
  301. }
  302. /// <summary>
  303. /// Composes the parts with ioc container.
  304. /// </summary>
  305. protected virtual void FindParts()
  306. {
  307. RestServices = ApplicationHost.GetExports<IRestfulService>();
  308. WebSocketListeners = ApplicationHost.GetExports<IWebSocketListener>();
  309. Plugins = ApplicationHost.GetExports<IPlugin>();
  310. }
  311. /// <summary>
  312. /// Fires after MEF finishes finding composable parts within plugin assemblies
  313. /// </summary>
  314. /// <returns>Task.</returns>
  315. protected virtual Task OnComposablePartsLoaded()
  316. {
  317. return Task.Run(() =>
  318. {
  319. // Start-up each plugin
  320. Parallel.ForEach(Plugins, plugin =>
  321. {
  322. Logger.Info("Initializing {0} {1}", plugin.Name, plugin.Version);
  323. try
  324. {
  325. plugin.Initialize(this, _xmlSerializer, Logger);
  326. Logger.Info("{0} {1} initialized.", plugin.Name, plugin.Version);
  327. }
  328. catch (Exception ex)
  329. {
  330. Logger.ErrorException("Error initializing {0}", ex, plugin.Name);
  331. }
  332. });
  333. });
  334. }
  335. /// <summary>
  336. /// Notifies that the kernel that a change has been made that requires a restart
  337. /// </summary>
  338. public void NotifyPendingRestart()
  339. {
  340. HasPendingRestart = true;
  341. TcpManager.SendWebSocketMessage("HasPendingRestartChanged", GetSystemInfo());
  342. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  343. }
  344. /// <summary>
  345. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  346. /// </summary>
  347. public void Dispose()
  348. {
  349. Dispose(true);
  350. GC.SuppressFinalize(this);
  351. }
  352. /// <summary>
  353. /// Releases unmanaged and - optionally - managed resources.
  354. /// </summary>
  355. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  356. protected virtual void Dispose(bool dispose)
  357. {
  358. if (dispose)
  359. {
  360. DisposeTcpManager();
  361. }
  362. }
  363. /// <summary>
  364. /// Disposes the TCP manager.
  365. /// </summary>
  366. private void DisposeTcpManager()
  367. {
  368. if (TcpManager != null)
  369. {
  370. TcpManager.Dispose();
  371. TcpManager = null;
  372. }
  373. }
  374. /// <summary>
  375. /// Gets the current application version
  376. /// </summary>
  377. /// <value>The application version.</value>
  378. public Version ApplicationVersion
  379. {
  380. get
  381. {
  382. return GetType().Assembly.GetName().Version;
  383. }
  384. }
  385. /// <summary>
  386. /// Performs the pending restart.
  387. /// </summary>
  388. /// <returns>Task.</returns>
  389. public void PerformPendingRestart()
  390. {
  391. if (HasPendingRestart)
  392. {
  393. RestartApplication();
  394. }
  395. else
  396. {
  397. Logger.Info("PerformPendingRestart - not needed");
  398. }
  399. }
  400. /// <summary>
  401. /// Restarts the application.
  402. /// </summary>
  403. protected void RestartApplication()
  404. {
  405. Logger.Info("Restarting the application");
  406. ApplicationHost.Restart();
  407. }
  408. /// <summary>
  409. /// Gets the system status.
  410. /// </summary>
  411. /// <returns>SystemInfo.</returns>
  412. public virtual SystemInfo GetSystemInfo()
  413. {
  414. return new SystemInfo
  415. {
  416. HasPendingRestart = HasPendingRestart,
  417. Version = ApplicationVersion.ToString(),
  418. IsNetworkDeployed = ApplicationHost.CanSelfUpdate,
  419. WebSocketPortNumber = TcpManager.WebSocketPortNumber,
  420. SupportsNativeWebSocket = TcpManager.SupportsNativeWebSocket,
  421. FailedPluginAssemblies = ApplicationHost.FailedAssemblies.ToArray()
  422. };
  423. }
  424. /// <summary>
  425. /// The _save lock
  426. /// </summary>
  427. private readonly object _configurationSaveLock = new object();
  428. /// <summary>
  429. /// Saves the current configuration
  430. /// </summary>
  431. public void SaveConfiguration()
  432. {
  433. lock (_configurationSaveLock)
  434. {
  435. _xmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
  436. }
  437. OnConfigurationUpdated();
  438. }
  439. /// <summary>
  440. /// Gets the application paths.
  441. /// </summary>
  442. /// <value>The application paths.</value>
  443. IApplicationPaths IKernel.ApplicationPaths
  444. {
  445. get { return ApplicationPaths; }
  446. }
  447. /// <summary>
  448. /// Gets the configuration.
  449. /// </summary>
  450. /// <value>The configuration.</value>
  451. BaseApplicationConfiguration IKernel.Configuration
  452. {
  453. get { return Configuration; }
  454. }
  455. /// <summary>
  456. /// Reads an xml configuration file from the file system
  457. /// It will immediately re-serialize and save if new serialization data is available due to property changes
  458. /// </summary>
  459. /// <param name="type">The type.</param>
  460. /// <param name="path">The path.</param>
  461. /// <returns>System.Object.</returns>
  462. public object GetXmlConfiguration(Type type, string path)
  463. {
  464. Logger.Info("Loading {0} at {1}", type.Name, path);
  465. object configuration;
  466. byte[] buffer = null;
  467. // Use try/catch to avoid the extra file system lookup using File.Exists
  468. try
  469. {
  470. buffer = File.ReadAllBytes(path);
  471. configuration = _xmlSerializer.DeserializeFromBytes(type, buffer);
  472. }
  473. catch (FileNotFoundException)
  474. {
  475. configuration = ApplicationHost.CreateInstance(type);
  476. }
  477. // Take the object we just got and serialize it back to bytes
  478. var newBytes = _xmlSerializer.SerializeToBytes(configuration);
  479. // If the file didn't exist before, or if something has changed, re-save
  480. if (buffer == null || !buffer.SequenceEqual(newBytes))
  481. {
  482. Logger.Info("Saving {0} to {1}", type.Name, path);
  483. // Save it after load in case we got new items
  484. File.WriteAllBytes(path, newBytes);
  485. }
  486. return configuration;
  487. }
  488. /// <summary>
  489. /// Reads an xml configuration file from the file system
  490. /// It will immediately save the configuration after loading it, just
  491. /// in case there are new serializable properties
  492. /// </summary>
  493. /// <typeparam name="T"></typeparam>
  494. /// <param name="path">The path.</param>
  495. /// <returns>``0.</returns>
  496. private T GetXmlConfiguration<T>(string path)
  497. where T : class
  498. {
  499. return GetXmlConfiguration(typeof(T), path) as T;
  500. }
  501. }
  502. }