BaseKernel.cs 26 KB

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