BaseKernel.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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, Logger));
  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. OnLoggerLoaded();
  385. }
  386. /// <summary>
  387. /// Adds the log target.
  388. /// </summary>
  389. /// <param name="target">The target.</param>
  390. /// <param name="name">The name.</param>
  391. private void AddLogTarget(Target target, string name)
  392. {
  393. var config = LogManager.Configuration;
  394. config.RemoveTarget(name);
  395. target.Name = name;
  396. config.AddTarget(name, target);
  397. var level = Configuration.EnableDebugLevelLogging ? LogLevel.Debug : LogLevel.Info;
  398. var rule = new LoggingRule("*", level, target);
  399. config.LoggingRules.Add(rule);
  400. LogManager.Configuration = config;
  401. }
  402. /// <summary>
  403. /// Uses MEF to locate plugins
  404. /// Subclasses can use this to locate types within plugins
  405. /// </summary>
  406. /// <returns>Task.</returns>
  407. private async Task ReloadComposableParts()
  408. {
  409. _failedPluginAssemblies.Clear();
  410. DisposeComposableParts();
  411. Assemblies = GetComposablePartAssemblies().ToArray();
  412. CompositionContainer = MefUtils.GetSafeCompositionContainer(Assemblies.Select(i => new AssemblyCatalog(i)));
  413. ComposeExportedValues(CompositionContainer);
  414. CompositionContainer.ComposeParts(this);
  415. await OnComposablePartsLoaded().ConfigureAwait(false);
  416. CompositionContainer.Catalog.Dispose();
  417. }
  418. /// <summary>
  419. /// Composes the exported values.
  420. /// </summary>
  421. /// <param name="container">The container.</param>
  422. protected virtual void ComposeExportedValues(CompositionContainer container)
  423. {
  424. container.ComposeExportedValue("logger", Logging.LogManager.GetLogger("App"));
  425. }
  426. /// <summary>
  427. /// Gets the composable part assemblies.
  428. /// </summary>
  429. /// <returns>IEnumerable{Assembly}.</returns>
  430. protected virtual IEnumerable<Assembly> GetComposablePartAssemblies()
  431. {
  432. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  433. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  434. var pluginAssemblies = Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  435. .Select(file =>
  436. {
  437. try
  438. {
  439. return Assembly.Load(File.ReadAllBytes((file)));
  440. }
  441. catch (Exception ex)
  442. {
  443. _failedPluginAssemblies.Add(file);
  444. Logger.ErrorException("Error loading {0}", ex, file);
  445. return null;
  446. }
  447. }).Where(a => a != null);
  448. foreach (var pluginAssembly in pluginAssemblies)
  449. {
  450. yield return pluginAssembly;
  451. }
  452. var runningDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
  453. var corePluginDirectory = Path.Combine(runningDirectory, "CorePlugins");
  454. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  455. pluginAssemblies = Directory.EnumerateFiles(corePluginDirectory, "*.dll", SearchOption.TopDirectoryOnly)
  456. .Select(file =>
  457. {
  458. try
  459. {
  460. return Assembly.Load(File.ReadAllBytes((file)));
  461. }
  462. catch (Exception ex)
  463. {
  464. _failedPluginAssemblies.Add(file);
  465. Logger.ErrorException("Error loading {0}", ex, file);
  466. return null;
  467. }
  468. }).Where(a => a != null);
  469. foreach (var pluginAssembly in pluginAssemblies)
  470. {
  471. yield return pluginAssembly;
  472. }
  473. // Include composable parts in the Model assembly
  474. yield return typeof(SystemInfo).Assembly;
  475. // Include composable parts in the Common assembly
  476. yield return Assembly.GetExecutingAssembly();
  477. // Include composable parts in the subclass assembly
  478. yield return GetType().Assembly;
  479. }
  480. /// <summary>
  481. /// Fires after MEF finishes finding composable parts within plugin assemblies
  482. /// </summary>
  483. /// <returns>Task.</returns>
  484. protected virtual Task OnComposablePartsLoaded()
  485. {
  486. return Task.Run(() =>
  487. {
  488. foreach (var listener in WebSocketListeners)
  489. {
  490. listener.Initialize(this);
  491. }
  492. foreach (var task in ScheduledTasks)
  493. {
  494. task.Initialize(this);
  495. }
  496. // Start-up each plugin
  497. Parallel.ForEach(Plugins, plugin =>
  498. {
  499. Logger.Info("Initializing {0} {1}", plugin.Name, plugin.Version);
  500. try
  501. {
  502. plugin.Initialize(this, Logging.LogManager.GetLogger(plugin.GetType().Name));
  503. Logger.Info("{0} {1} initialized.", plugin.Name, plugin.Version);
  504. }
  505. catch (Exception ex)
  506. {
  507. Logger.ErrorException("Error initializing {0}", ex, plugin.Name);
  508. }
  509. });
  510. });
  511. }
  512. /// <summary>
  513. /// Notifies that the kernel that a change has been made that requires a restart
  514. /// </summary>
  515. public void NotifyPendingRestart()
  516. {
  517. HasPendingRestart = true;
  518. TcpManager.SendWebSocketMessage("HasPendingRestartChanged", GetSystemInfo());
  519. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty);
  520. }
  521. /// <summary>
  522. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  523. /// </summary>
  524. public void Dispose()
  525. {
  526. Dispose(true);
  527. GC.SuppressFinalize(this);
  528. }
  529. /// <summary>
  530. /// Releases unmanaged and - optionally - managed resources.
  531. /// </summary>
  532. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  533. protected virtual void Dispose(bool dispose)
  534. {
  535. if (dispose)
  536. {
  537. DisposeTcpManager();
  538. DisposeTaskManager();
  539. DisposeIsoManager();
  540. DisposeHttpManager();
  541. DisposeComposableParts();
  542. }
  543. }
  544. /// <summary>
  545. /// Disposes the iso manager.
  546. /// </summary>
  547. private void DisposeIsoManager()
  548. {
  549. if (IsoManager != null)
  550. {
  551. IsoManager.Dispose();
  552. IsoManager = null;
  553. }
  554. }
  555. /// <summary>
  556. /// Disposes the TCP manager.
  557. /// </summary>
  558. private void DisposeTcpManager()
  559. {
  560. if (TcpManager != null)
  561. {
  562. TcpManager.Dispose();
  563. TcpManager = null;
  564. }
  565. }
  566. /// <summary>
  567. /// Disposes the task manager.
  568. /// </summary>
  569. private void DisposeTaskManager()
  570. {
  571. if (TaskManager != null)
  572. {
  573. TaskManager.Dispose();
  574. TaskManager = null;
  575. }
  576. }
  577. /// <summary>
  578. /// Disposes the HTTP manager.
  579. /// </summary>
  580. private void DisposeHttpManager()
  581. {
  582. if (HttpManager != null)
  583. {
  584. HttpManager.Dispose();
  585. HttpManager = null;
  586. }
  587. }
  588. /// <summary>
  589. /// Disposes all objects gathered through MEF composable parts
  590. /// </summary>
  591. protected virtual void DisposeComposableParts()
  592. {
  593. if (CompositionContainer != null)
  594. {
  595. CompositionContainer.Dispose();
  596. }
  597. }
  598. /// <summary>
  599. /// Disposes all logger resources
  600. /// </summary>
  601. private void DisposeLogger()
  602. {
  603. // Dispose all current loggers
  604. var listeners = Trace.Listeners.OfType<TraceListener>().ToList();
  605. Trace.Listeners.Clear();
  606. foreach (var listener in listeners)
  607. {
  608. listener.Dispose();
  609. }
  610. }
  611. /// <summary>
  612. /// Gets the current application version
  613. /// </summary>
  614. /// <value>The application version.</value>
  615. public Version ApplicationVersion
  616. {
  617. get
  618. {
  619. return GetType().Assembly.GetName().Version;
  620. }
  621. }
  622. /// <summary>
  623. /// Performs the pending restart.
  624. /// </summary>
  625. /// <returns>Task.</returns>
  626. public void PerformPendingRestart()
  627. {
  628. if (HasPendingRestart)
  629. {
  630. RestartApplication();
  631. }
  632. else
  633. {
  634. Logger.Info("PerformPendingRestart - not needed");
  635. }
  636. }
  637. /// <summary>
  638. /// Restarts the application.
  639. /// </summary>
  640. protected void RestartApplication()
  641. {
  642. Logger.Info("Restarting the application");
  643. EventHelper.QueueEventIfNotNull(ApplicationRestartRequested, this, EventArgs.Empty);
  644. }
  645. /// <summary>
  646. /// Gets the system status.
  647. /// </summary>
  648. /// <returns>SystemInfo.</returns>
  649. public virtual SystemInfo GetSystemInfo()
  650. {
  651. return new SystemInfo
  652. {
  653. HasPendingRestart = HasPendingRestart,
  654. Version = DisplayVersion,
  655. IsNetworkDeployed = ApplicationDeployment.IsNetworkDeployed,
  656. WebSocketPortNumber = TcpManager.WebSocketPortNumber,
  657. SupportsNativeWebSocket = TcpManager.SupportsNativeWebSocket,
  658. FailedPluginAssemblies = FailedPluginAssemblies.ToArray()
  659. };
  660. }
  661. /// <summary>
  662. /// The _save lock
  663. /// </summary>
  664. private readonly object _configurationSaveLock = new object();
  665. /// <summary>
  666. /// Saves the current configuration
  667. /// </summary>
  668. public void SaveConfiguration()
  669. {
  670. lock (_configurationSaveLock)
  671. {
  672. XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
  673. }
  674. OnConfigurationUpdated();
  675. }
  676. /// <summary>
  677. /// Gets the application paths.
  678. /// </summary>
  679. /// <value>The application paths.</value>
  680. BaseApplicationPaths IKernel.ApplicationPaths
  681. {
  682. get { return ApplicationPaths; }
  683. }
  684. /// <summary>
  685. /// Gets the configuration.
  686. /// </summary>
  687. /// <value>The configuration.</value>
  688. BaseApplicationConfiguration IKernel.Configuration
  689. {
  690. get { return Configuration; }
  691. }
  692. }
  693. }