BaseKernel.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Localization;
  4. using MediaBrowser.Common.Mef;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Common.Plugins;
  7. using MediaBrowser.Common.ScheduledTasks;
  8. using MediaBrowser.Common.Serialization;
  9. using MediaBrowser.Model.Configuration;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.System;
  12. using NLog;
  13. using NLog.Config;
  14. using NLog.Targets;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.ComponentModel.Composition;
  18. using System.ComponentModel.Composition.Hosting;
  19. using System.Deployment.Application;
  20. using System.Diagnostics;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Reflection;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. namespace MediaBrowser.Common.Kernel
  27. {
  28. /// <summary>
  29. /// Represents a shared base kernel for both the Ui and server apps
  30. /// </summary>
  31. /// <typeparam name="TConfigurationType">The type of the T configuration type.</typeparam>
  32. /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
  33. public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable, IKernel
  34. where TConfigurationType : BaseApplicationConfiguration, new()
  35. where TApplicationPathsType : BaseApplicationPaths, new()
  36. {
  37. /// <summary>
  38. /// Occurs when [has pending restart changed].
  39. /// </summary>
  40. public event EventHandler HasPendingRestartChanged;
  41. /// <summary>
  42. /// Notifiies the containing application that a restart has been requested
  43. /// </summary>
  44. public event EventHandler ApplicationRestartRequested;
  45. #region ConfigurationUpdated Event
  46. /// <summary>
  47. /// Occurs when [configuration updated].
  48. /// </summary>
  49. public event EventHandler<EventArgs> ConfigurationUpdated;
  50. /// <summary>
  51. /// Called when [configuration updated].
  52. /// </summary>
  53. internal void OnConfigurationUpdated()
  54. {
  55. EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty);
  56. // Notify connected clients
  57. TcpManager.SendWebSocketMessage("ConfigurationUpdated", Configuration);
  58. }
  59. #endregion
  60. #region LoggerLoaded Event
  61. /// <summary>
  62. /// Fires whenever the logger is loaded
  63. /// </summary>
  64. public event EventHandler LoggerLoaded;
  65. /// <summary>
  66. /// Called when [logger loaded].
  67. /// </summary>
  68. private void OnLoggerLoaded()
  69. {
  70. EventHelper.QueueEventIfNotNull(LoggerLoaded, this, EventArgs.Empty);
  71. }
  72. #endregion
  73. #region ReloadBeginning Event
  74. /// <summary>
  75. /// Fires whenever the kernel begins reloading
  76. /// </summary>
  77. public event EventHandler<EventArgs> ReloadBeginning;
  78. /// <summary>
  79. /// Called when [reload beginning].
  80. /// </summary>
  81. private void OnReloadBeginning()
  82. {
  83. EventHelper.QueueEventIfNotNull(ReloadBeginning, this, EventArgs.Empty);
  84. }
  85. #endregion
  86. #region ReloadCompleted Event
  87. /// <summary>
  88. /// Fires whenever the kernel completes reloading
  89. /// </summary>
  90. public event EventHandler<EventArgs> ReloadCompleted;
  91. /// <summary>
  92. /// Called when [reload completed].
  93. /// </summary>
  94. private void OnReloadCompleted()
  95. {
  96. EventHelper.QueueEventIfNotNull(ReloadCompleted, this, EventArgs.Empty);
  97. }
  98. #endregion
  99. #region ApplicationUpdated Event
  100. /// <summary>
  101. /// Occurs when [application updated].
  102. /// </summary>
  103. public event EventHandler<GenericEventArgs<Version>> ApplicationUpdated;
  104. /// <summary>
  105. /// Called when [application updated].
  106. /// </summary>
  107. /// <param name="newVersion">The new version.</param>
  108. public void OnApplicationUpdated(Version newVersion)
  109. {
  110. EventHelper.QueueEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<Version> { Argument = newVersion });
  111. NotifyPendingRestart();
  112. }
  113. #endregion
  114. /// <summary>
  115. /// The _configuration loaded
  116. /// </summary>
  117. private bool _configurationLoaded;
  118. /// <summary>
  119. /// The _configuration sync lock
  120. /// </summary>
  121. private object _configurationSyncLock = new object();
  122. /// <summary>
  123. /// The _configuration
  124. /// </summary>
  125. private TConfigurationType _configuration;
  126. /// <summary>
  127. /// Gets the system configuration
  128. /// </summary>
  129. /// <value>The configuration.</value>
  130. public TConfigurationType Configuration
  131. {
  132. get
  133. {
  134. // Lazy load
  135. LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationLoaded, ref _configurationSyncLock, () => XmlSerializer.GetXmlConfiguration<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath));
  136. return _configuration;
  137. }
  138. protected set
  139. {
  140. _configuration = value;
  141. if (value == null)
  142. {
  143. _configurationLoaded = false;
  144. }
  145. }
  146. }
  147. /// <summary>
  148. /// Gets a value indicating whether this instance is first run.
  149. /// </summary>
  150. /// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
  151. public bool IsFirstRun { get; private set; }
  152. /// <summary>
  153. /// The version of the application to display
  154. /// </summary>
  155. /// <value>The display version.</value>
  156. public string DisplayVersion { get { return ApplicationVersion.ToString(); } }
  157. /// <summary>
  158. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  159. /// </summary>
  160. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  161. public bool HasPendingRestart { get; private set; }
  162. /// <summary>
  163. /// Gets the application paths.
  164. /// </summary>
  165. /// <value>The application paths.</value>
  166. public TApplicationPathsType ApplicationPaths { get; private set; }
  167. /// <summary>
  168. /// The _failed assembly loads
  169. /// </summary>
  170. private readonly List<string> _failedPluginAssemblies = new List<string>();
  171. /// <summary>
  172. /// Gets the plugin assemblies that failed to load.
  173. /// </summary>
  174. /// <value>The failed assembly loads.</value>
  175. public IEnumerable<string> FailedPluginAssemblies
  176. {
  177. get { return _failedPluginAssemblies; }
  178. }
  179. /// <summary>
  180. /// Gets the list of currently loaded plugins
  181. /// </summary>
  182. /// <value>The plugins.</value>
  183. [ImportMany(typeof(IPlugin))]
  184. public IEnumerable<IPlugin> Plugins { get; protected set; }
  185. /// <summary>
  186. /// Gets the list of Scheduled Tasks
  187. /// </summary>
  188. /// <value>The scheduled tasks.</value>
  189. [ImportMany(typeof(IScheduledTask))]
  190. public IEnumerable<IScheduledTask> ScheduledTasks { get; private set; }
  191. /// <summary>
  192. /// Gets the web socket listeners.
  193. /// </summary>
  194. /// <value>The web socket listeners.</value>
  195. [ImportMany(typeof(IWebSocketListener))]
  196. public IEnumerable<IWebSocketListener> WebSocketListeners { get; private set; }
  197. /// <summary>
  198. /// Gets the list of Localized string files
  199. /// </summary>
  200. /// <value>The string files.</value>
  201. [ImportMany(typeof(LocalizedStringData))]
  202. public IEnumerable<LocalizedStringData> StringFiles { get; private set; }
  203. /// <summary>
  204. /// Gets the MEF CompositionContainer
  205. /// </summary>
  206. /// <value>The composition container.</value>
  207. private CompositionContainer CompositionContainer { get; set; }
  208. /// <summary>
  209. /// The _HTTP manager
  210. /// </summary>
  211. /// <value>The HTTP manager.</value>
  212. public HttpManager HttpManager { get; private set; }
  213. /// <summary>
  214. /// Gets or sets the TCP manager.
  215. /// </summary>
  216. /// <value>The TCP manager.</value>
  217. public TcpManager TcpManager { get; private set; }
  218. /// <summary>
  219. /// Gets the task manager.
  220. /// </summary>
  221. /// <value>The task manager.</value>
  222. public TaskManager TaskManager { get; private set; }
  223. /// <summary>
  224. /// Gets the iso manager.
  225. /// </summary>
  226. /// <value>The iso manager.</value>
  227. public IIsoManager IsoManager { get; private set; }
  228. /// <summary>
  229. /// Gets the rest services.
  230. /// </summary>
  231. /// <value>The rest services.</value>
  232. [ImportMany(typeof(IRestfulService))]
  233. public IEnumerable<IRestfulService> RestServices { get; private set; }
  234. /// <summary>
  235. /// The _protobuf serializer initialized
  236. /// </summary>
  237. private bool _protobufSerializerInitialized;
  238. /// <summary>
  239. /// The _protobuf serializer sync lock
  240. /// </summary>
  241. private object _protobufSerializerSyncLock = new object();
  242. /// <summary>
  243. /// Gets a dynamically compiled generated serializer that can serialize protocontracts without reflection
  244. /// </summary>
  245. private DynamicProtobufSerializer _protobufSerializer;
  246. /// <summary>
  247. /// Gets the protobuf serializer.
  248. /// </summary>
  249. /// <value>The protobuf serializer.</value>
  250. public DynamicProtobufSerializer ProtobufSerializer
  251. {
  252. get
  253. {
  254. // Lazy load
  255. LazyInitializer.EnsureInitialized(ref _protobufSerializer, ref _protobufSerializerInitialized, ref _protobufSerializerSyncLock, () => DynamicProtobufSerializer.Create(Assemblies));
  256. return _protobufSerializer;
  257. }
  258. private set
  259. {
  260. _protobufSerializer = value;
  261. if (value == null)
  262. {
  263. _protobufSerializerInitialized = false;
  264. }
  265. }
  266. }
  267. /// <summary>
  268. /// Gets the UDP server port number.
  269. /// This can't be configurable because then the user would have to configure their client to discover the server.
  270. /// </summary>
  271. /// <value>The UDP server port number.</value>
  272. public abstract int UdpServerPortNumber { get; }
  273. /// <summary>
  274. /// Gets the name of the web application that can be used for url building.
  275. /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
  276. /// </summary>
  277. /// <value>The name of the web application.</value>
  278. public string WebApplicationName
  279. {
  280. get { return "mediabrowser"; }
  281. }
  282. /// <summary>
  283. /// Gets the HTTP server URL prefix.
  284. /// </summary>
  285. /// <value>The HTTP server URL prefix.</value>
  286. public virtual string HttpServerUrlPrefix
  287. {
  288. get
  289. {
  290. return "http://+:" + Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/";
  291. }
  292. }
  293. /// <summary>
  294. /// Gets the kernel context. Subclasses will have to override.
  295. /// </summary>
  296. /// <value>The kernel context.</value>
  297. public abstract KernelContext KernelContext { get; }
  298. /// <summary>
  299. /// Gets the log file path.
  300. /// </summary>
  301. /// <value>The log file path.</value>
  302. public string LogFilePath { get; private set; }
  303. /// <summary>
  304. /// Gets the logger.
  305. /// </summary>
  306. /// <value>The logger.</value>
  307. protected ILogger Logger { get; private set; }
  308. /// <summary>
  309. /// Gets the assemblies.
  310. /// </summary>
  311. /// <value>The assemblies.</value>
  312. public Assembly[] Assemblies { get; private set; }
  313. /// <summary>
  314. /// Initializes a new instance of the <see cref="BaseKernel{TApplicationPathsType}" /> class.
  315. /// </summary>
  316. /// <param name="isoManager">The iso manager.</param>
  317. protected BaseKernel(IIsoManager isoManager)
  318. {
  319. IsoManager = isoManager;
  320. }
  321. /// <summary>
  322. /// Initializes the Kernel
  323. /// </summary>
  324. /// <returns>Task.</returns>
  325. public async Task Init()
  326. {
  327. Logger = Logging.LogManager.GetLogger(GetType().Name);
  328. ApplicationPaths = new TApplicationPathsType();
  329. IsFirstRun = !File.Exists(ApplicationPaths.SystemConfigurationFilePath);
  330. // Performs initializations that can be reloaded at anytime
  331. await Reload().ConfigureAwait(false);
  332. }
  333. /// <summary>
  334. /// Performs initializations that can be reloaded at anytime
  335. /// </summary>
  336. /// <returns>Task.</returns>
  337. public async Task Reload()
  338. {
  339. OnReloadBeginning();
  340. await ReloadInternal().ConfigureAwait(false);
  341. OnReloadCompleted();
  342. Logger.Info("Kernel.Reload Complete");
  343. }
  344. /// <summary>
  345. /// Performs initializations that can be reloaded at anytime
  346. /// </summary>
  347. /// <returns>Task.</returns>
  348. protected virtual async Task ReloadInternal()
  349. {
  350. // Set these to null so that they can be lazy loaded again
  351. Configuration = null;
  352. ProtobufSerializer = null;
  353. ReloadLogger();
  354. Logger.Info("Version {0} initializing", ApplicationVersion);
  355. DisposeHttpManager();
  356. HttpManager = new HttpManager(this);
  357. await OnConfigurationLoaded().ConfigureAwait(false);
  358. DisposeTaskManager();
  359. TaskManager = new TaskManager(this);
  360. Logger.Info("Loading Plugins");
  361. await ReloadComposableParts().ConfigureAwait(false);
  362. DisposeTcpManager();
  363. TcpManager = new TcpManager(this);
  364. }
  365. /// <summary>
  366. /// Called when [configuration loaded].
  367. /// </summary>
  368. /// <returns>Task.</returns>
  369. protected virtual Task OnConfigurationLoaded()
  370. {
  371. return Task.FromResult<object>(null);
  372. }
  373. /// <summary>
  374. /// Disposes and reloads all loggers
  375. /// </summary>
  376. public void ReloadLogger()
  377. {
  378. DisposeLogger();
  379. LogFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, KernelContext + "-" + DateTime.Now.Ticks + ".log");
  380. var logFile = new FileTarget();
  381. logFile.FileName = LogFilePath;
  382. logFile.Layout = "${longdate}, ${level}, ${logger}, ${message}";
  383. AddLogTarget(logFile, "ApplicationLogFile");
  384. Logging.Logger.LoggerInstance = Logging.LogManager.GetLogger("App");
  385. OnLoggerLoaded();
  386. }
  387. /// <summary>
  388. /// Adds the log target.
  389. /// </summary>
  390. /// <param name="target">The target.</param>
  391. /// <param name="name">The name.</param>
  392. private void AddLogTarget(Target target, string name)
  393. {
  394. var config = LogManager.Configuration;
  395. config.RemoveTarget(name);
  396. target.Name = name;
  397. config.AddTarget(name, target);
  398. var level = Configuration.EnableDebugLevelLogging ? LogLevel.Debug : LogLevel.Info;
  399. var rule = new LoggingRule("*", level, target);
  400. config.LoggingRules.Add(rule);
  401. LogManager.Configuration = config;
  402. }
  403. /// <summary>
  404. /// Uses MEF to locate plugins
  405. /// Subclasses can use this to locate types within plugins
  406. /// </summary>
  407. /// <returns>Task.</returns>
  408. private async Task ReloadComposableParts()
  409. {
  410. _failedPluginAssemblies.Clear();
  411. DisposeComposableParts();
  412. Assemblies = GetComposablePartAssemblies().ToArray();
  413. CompositionContainer = MefUtils.GetSafeCompositionContainer(Assemblies.Select(i => new AssemblyCatalog(i)));
  414. CompositionContainer.ComposeExportedValue("kernel", this);
  415. CompositionContainer.ComposeExportedValue("logger", Logging.LogManager.GetLogger("App"));
  416. CompositionContainer.ComposeParts(this);
  417. await OnComposablePartsLoaded().ConfigureAwait(false);
  418. CompositionContainer.Catalog.Dispose();
  419. }
  420. /// <summary>
  421. /// Gets the composable part assemblies.
  422. /// </summary>
  423. /// <returns>IEnumerable{Assembly}.</returns>
  424. protected virtual IEnumerable<Assembly> GetComposablePartAssemblies()
  425. {
  426. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  427. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  428. var pluginAssemblies = Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  429. .Select(file =>
  430. {
  431. try
  432. {
  433. return Assembly.Load(File.ReadAllBytes((file)));
  434. }
  435. catch (Exception ex)
  436. {
  437. _failedPluginAssemblies.Add(file);
  438. Logger.ErrorException("Error loading {0}", ex, file);
  439. return null;
  440. }
  441. }).Where(a => a != null);
  442. foreach (var pluginAssembly in pluginAssemblies)
  443. {
  444. yield return pluginAssembly;
  445. }
  446. var runningDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
  447. var corePluginDirectory = Path.Combine(runningDirectory, "CorePlugins");
  448. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  449. pluginAssemblies = Directory.EnumerateFiles(corePluginDirectory, "*.dll", SearchOption.TopDirectoryOnly)
  450. .Select(file =>
  451. {
  452. try
  453. {
  454. return Assembly.Load(File.ReadAllBytes((file)));
  455. }
  456. catch (Exception ex)
  457. {
  458. _failedPluginAssemblies.Add(file);
  459. Logger.ErrorException("Error loading {0}", ex, file);
  460. return null;
  461. }
  462. }).Where(a => a != null);
  463. foreach (var pluginAssembly in pluginAssemblies)
  464. {
  465. yield return pluginAssembly;
  466. }
  467. // Include composable parts in the Model assembly
  468. yield return typeof(SystemInfo).Assembly;
  469. // Include composable parts in the Common assembly
  470. yield return Assembly.GetExecutingAssembly();
  471. // Include composable parts in the subclass assembly
  472. yield return GetType().Assembly;
  473. }
  474. /// <summary>
  475. /// Fires after MEF finishes finding composable parts within plugin assemblies
  476. /// </summary>
  477. /// <returns>Task.</returns>
  478. protected virtual Task OnComposablePartsLoaded()
  479. {
  480. return Task.Run(() =>
  481. {
  482. foreach (var listener in WebSocketListeners)
  483. {
  484. listener.Initialize(this);
  485. }
  486. foreach (var task in ScheduledTasks)
  487. {
  488. task.Initialize(this);
  489. }
  490. // Start-up each plugin
  491. Parallel.ForEach(Plugins, plugin =>
  492. {
  493. Logger.Info("Initializing {0} {1}", plugin.Name, plugin.Version);
  494. try
  495. {
  496. plugin.Initialize(this);
  497. Logger.Info("{0} {1} initialized.", plugin.Name, plugin.Version);
  498. }
  499. catch (Exception ex)
  500. {
  501. Logger.ErrorException("Error initializing {0}", ex, plugin.Name);
  502. }
  503. });
  504. });
  505. }
  506. /// <summary>
  507. /// Notifies that the kernel that a change has been made that requires a restart
  508. /// </summary>
  509. public void NotifyPendingRestart()
  510. {
  511. HasPendingRestart = true;
  512. TcpManager.SendWebSocketMessage("HasPendingRestartChanged", GetSystemInfo());
  513. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty);
  514. }
  515. /// <summary>
  516. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  517. /// </summary>
  518. public void Dispose()
  519. {
  520. Dispose(true);
  521. GC.SuppressFinalize(this);
  522. }
  523. /// <summary>
  524. /// Releases unmanaged and - optionally - managed resources.
  525. /// </summary>
  526. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  527. protected virtual void Dispose(bool dispose)
  528. {
  529. if (dispose)
  530. {
  531. DisposeTcpManager();
  532. DisposeTaskManager();
  533. DisposeIsoManager();
  534. DisposeHttpManager();
  535. DisposeComposableParts();
  536. }
  537. }
  538. /// <summary>
  539. /// Disposes the iso manager.
  540. /// </summary>
  541. private void DisposeIsoManager()
  542. {
  543. if (IsoManager != null)
  544. {
  545. IsoManager.Dispose();
  546. IsoManager = null;
  547. }
  548. }
  549. /// <summary>
  550. /// Disposes the TCP manager.
  551. /// </summary>
  552. private void DisposeTcpManager()
  553. {
  554. if (TcpManager != null)
  555. {
  556. TcpManager.Dispose();
  557. TcpManager = null;
  558. }
  559. }
  560. /// <summary>
  561. /// Disposes the task manager.
  562. /// </summary>
  563. private void DisposeTaskManager()
  564. {
  565. if (TaskManager != null)
  566. {
  567. TaskManager.Dispose();
  568. TaskManager = null;
  569. }
  570. }
  571. /// <summary>
  572. /// Disposes the HTTP manager.
  573. /// </summary>
  574. private void DisposeHttpManager()
  575. {
  576. if (HttpManager != null)
  577. {
  578. HttpManager.Dispose();
  579. HttpManager = null;
  580. }
  581. }
  582. /// <summary>
  583. /// Disposes all objects gathered through MEF composable parts
  584. /// </summary>
  585. protected virtual void DisposeComposableParts()
  586. {
  587. if (CompositionContainer != null)
  588. {
  589. CompositionContainer.Dispose();
  590. }
  591. }
  592. /// <summary>
  593. /// Disposes all logger resources
  594. /// </summary>
  595. private void DisposeLogger()
  596. {
  597. // Dispose all current loggers
  598. var listeners = Trace.Listeners.OfType<TraceListener>().ToList();
  599. Trace.Listeners.Clear();
  600. foreach (var listener in listeners)
  601. {
  602. listener.Dispose();
  603. }
  604. }
  605. /// <summary>
  606. /// Gets the current application version
  607. /// </summary>
  608. /// <value>The application version.</value>
  609. public Version ApplicationVersion
  610. {
  611. get
  612. {
  613. return GetType().Assembly.GetName().Version;
  614. }
  615. }
  616. /// <summary>
  617. /// Performs the pending restart.
  618. /// </summary>
  619. /// <returns>Task.</returns>
  620. public void PerformPendingRestart()
  621. {
  622. if (HasPendingRestart)
  623. {
  624. RestartApplication();
  625. }
  626. else
  627. {
  628. Logger.Info("PerformPendingRestart - not needed");
  629. }
  630. }
  631. /// <summary>
  632. /// Restarts the application.
  633. /// </summary>
  634. protected void RestartApplication()
  635. {
  636. Logger.Info("Restarting the application");
  637. EventHelper.QueueEventIfNotNull(ApplicationRestartRequested, this, EventArgs.Empty);
  638. }
  639. /// <summary>
  640. /// Gets the system status.
  641. /// </summary>
  642. /// <returns>SystemInfo.</returns>
  643. public virtual SystemInfo GetSystemInfo()
  644. {
  645. return new SystemInfo
  646. {
  647. HasPendingRestart = HasPendingRestart,
  648. Version = DisplayVersion,
  649. IsNetworkDeployed = ApplicationDeployment.IsNetworkDeployed,
  650. WebSocketPortNumber = TcpManager.WebSocketPortNumber,
  651. SupportsNativeWebSocket = TcpManager.SupportsNativeWebSocket,
  652. FailedPluginAssemblies = FailedPluginAssemblies.ToArray()
  653. };
  654. }
  655. /// <summary>
  656. /// The _save lock
  657. /// </summary>
  658. private readonly object _configurationSaveLock = new object();
  659. /// <summary>
  660. /// Saves the current configuration
  661. /// </summary>
  662. public void SaveConfiguration()
  663. {
  664. lock (_configurationSaveLock)
  665. {
  666. XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
  667. }
  668. OnConfigurationUpdated();
  669. }
  670. /// <summary>
  671. /// Gets the application paths.
  672. /// </summary>
  673. /// <value>The application paths.</value>
  674. BaseApplicationPaths IKernel.ApplicationPaths
  675. {
  676. get { return ApplicationPaths; }
  677. }
  678. /// <summary>
  679. /// Gets the configuration.
  680. /// </summary>
  681. /// <value>The configuration.</value>
  682. BaseApplicationConfiguration IKernel.Configuration
  683. {
  684. get { return Configuration; }
  685. }
  686. }
  687. }