BaseApplicationHost.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Implementations.Devices;
  4. using MediaBrowser.Common.Implementations.IO;
  5. using MediaBrowser.Common.Implementations.ScheduledTasks;
  6. using MediaBrowser.Common.Implementations.Serialization;
  7. using MediaBrowser.Common.Implementations.Updates;
  8. using MediaBrowser.Common.Net;
  9. using MediaBrowser.Common.Plugins;
  10. using MediaBrowser.Common.Progress;
  11. using MediaBrowser.Common.ScheduledTasks;
  12. using MediaBrowser.Common.Security;
  13. using MediaBrowser.Common.Updates;
  14. using MediaBrowser.Model.Events;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.Logging;
  17. using MediaBrowser.Model.Serialization;
  18. using MediaBrowser.Model.Updates;
  19. using System;
  20. using System.Collections.Generic;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Net;
  24. using System.Reflection;
  25. using System.Runtime.InteropServices;
  26. using System.Text;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using MediaBrowser.Common.Extensions;
  30. using MediaBrowser.Common.Implementations.Cryptography;
  31. using MediaBrowser.Common.IO;
  32. using MediaBrowser.Model.Cryptography;
  33. using MediaBrowser.Model.System;
  34. using MediaBrowser.Model.Tasks;
  35. namespace MediaBrowser.Common.Implementations
  36. {
  37. /// <summary>
  38. /// Class BaseApplicationHost
  39. /// </summary>
  40. /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
  41. public abstract class BaseApplicationHost<TApplicationPathsType> : IApplicationHost
  42. where TApplicationPathsType : class, IApplicationPaths
  43. {
  44. /// <summary>
  45. /// Occurs when [has pending restart changed].
  46. /// </summary>
  47. public event EventHandler HasPendingRestartChanged;
  48. /// <summary>
  49. /// Occurs when [application updated].
  50. /// </summary>
  51. public event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
  52. /// <summary>
  53. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  54. /// </summary>
  55. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  56. public bool HasPendingRestart { get; private set; }
  57. /// <summary>
  58. /// Gets or sets the logger.
  59. /// </summary>
  60. /// <value>The logger.</value>
  61. protected ILogger Logger { get; private set; }
  62. /// <summary>
  63. /// Gets or sets the plugins.
  64. /// </summary>
  65. /// <value>The plugins.</value>
  66. public IPlugin[] Plugins { get; protected set; }
  67. /// <summary>
  68. /// Gets or sets the log manager.
  69. /// </summary>
  70. /// <value>The log manager.</value>
  71. public ILogManager LogManager { get; protected set; }
  72. /// <summary>
  73. /// Gets the application paths.
  74. /// </summary>
  75. /// <value>The application paths.</value>
  76. protected TApplicationPathsType ApplicationPaths { get; private set; }
  77. /// <summary>
  78. /// The json serializer
  79. /// </summary>
  80. public IJsonSerializer JsonSerializer { get; private set; }
  81. /// <summary>
  82. /// The _XML serializer
  83. /// </summary>
  84. protected readonly IXmlSerializer XmlSerializer;
  85. /// <summary>
  86. /// Gets assemblies that failed to load
  87. /// </summary>
  88. /// <value>The failed assemblies.</value>
  89. public List<string> FailedAssemblies { get; protected set; }
  90. /// <summary>
  91. /// Gets all concrete types.
  92. /// </summary>
  93. /// <value>All concrete types.</value>
  94. public Type[] AllConcreteTypes { get; protected set; }
  95. /// <summary>
  96. /// The disposable parts
  97. /// </summary>
  98. protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
  99. /// <summary>
  100. /// Gets a value indicating whether this instance is first run.
  101. /// </summary>
  102. /// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
  103. public bool IsFirstRun { get; private set; }
  104. /// <summary>
  105. /// Gets the kernel.
  106. /// </summary>
  107. /// <value>The kernel.</value>
  108. protected ITaskManager TaskManager { get; private set; }
  109. /// <summary>
  110. /// Gets the HTTP client.
  111. /// </summary>
  112. /// <value>The HTTP client.</value>
  113. public IHttpClient HttpClient { get; private set; }
  114. /// <summary>
  115. /// Gets the network manager.
  116. /// </summary>
  117. /// <value>The network manager.</value>
  118. protected INetworkManager NetworkManager { get; private set; }
  119. /// <summary>
  120. /// Gets the configuration manager.
  121. /// </summary>
  122. /// <value>The configuration manager.</value>
  123. protected IConfigurationManager ConfigurationManager { get; private set; }
  124. protected IFileSystem FileSystemManager { get; private set; }
  125. protected IIsoManager IsoManager { get; private set; }
  126. protected ISystemEvents SystemEvents { get; private set; }
  127. /// <summary>
  128. /// Gets the name.
  129. /// </summary>
  130. /// <value>The name.</value>
  131. public abstract string Name { get; }
  132. /// <summary>
  133. /// Gets a value indicating whether this instance is running as service.
  134. /// </summary>
  135. /// <value><c>true</c> if this instance is running as service; otherwise, <c>false</c>.</value>
  136. public abstract bool IsRunningAsService { get; }
  137. protected ICryptographyProvider CryptographyProvider = new CryptographyProvider();
  138. private DeviceId _deviceId;
  139. public string SystemId
  140. {
  141. get
  142. {
  143. if (_deviceId == null)
  144. {
  145. _deviceId = new DeviceId(ApplicationPaths, LogManager.GetLogger("SystemId"), FileSystemManager);
  146. }
  147. return _deviceId.Value;
  148. }
  149. }
  150. public virtual string OperatingSystemDisplayName
  151. {
  152. get { return Environment.OSVersion.VersionString; }
  153. }
  154. public IMemoryStreamProvider MemoryStreamProvider { get; set; }
  155. /// <summary>
  156. /// Initializes a new instance of the <see cref="BaseApplicationHost{TApplicationPathsType}"/> class.
  157. /// </summary>
  158. protected BaseApplicationHost(TApplicationPathsType applicationPaths,
  159. ILogManager logManager,
  160. IFileSystem fileSystem)
  161. {
  162. // hack alert, until common can target .net core
  163. BaseExtensions.CryptographyProvider = CryptographyProvider;
  164. XmlSerializer = new XmlSerializer(fileSystem, logManager.GetLogger("XmlSerializer"));
  165. FailedAssemblies = new List<string>();
  166. ApplicationPaths = applicationPaths;
  167. LogManager = logManager;
  168. FileSystemManager = fileSystem;
  169. ConfigurationManager = GetConfigurationManager();
  170. // Initialize this early in case the -v command line option is used
  171. Logger = LogManager.GetLogger("App");
  172. }
  173. /// <summary>
  174. /// Inits this instance.
  175. /// </summary>
  176. /// <returns>Task.</returns>
  177. public virtual async Task Init(IProgress<double> progress)
  178. {
  179. progress.Report(1);
  180. JsonSerializer = CreateJsonSerializer();
  181. MemoryStreamProvider = CreateMemoryStreamProvider();
  182. SystemEvents = CreateSystemEvents();
  183. OnLoggerLoaded(true);
  184. LogManager.LoggerLoaded += (s, e) => OnLoggerLoaded(false);
  185. IsFirstRun = !ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted;
  186. progress.Report(2);
  187. LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
  188. ? LogSeverity.Debug
  189. : LogSeverity.Info;
  190. progress.Report(3);
  191. DiscoverTypes();
  192. progress.Report(14);
  193. SetHttpLimit();
  194. progress.Report(15);
  195. var innerProgress = new ActionableProgress<double>();
  196. innerProgress.RegisterAction(p => progress.Report(.8 * p + 15));
  197. await RegisterResources(innerProgress).ConfigureAwait(false);
  198. FindParts();
  199. progress.Report(95);
  200. await InstallIsoMounters(CancellationToken.None).ConfigureAwait(false);
  201. progress.Report(100);
  202. }
  203. protected abstract IMemoryStreamProvider CreateMemoryStreamProvider();
  204. protected abstract ISystemEvents CreateSystemEvents();
  205. protected virtual void OnLoggerLoaded(bool isFirstLoad)
  206. {
  207. Logger.Info("Application version: {0}", ApplicationVersion);
  208. if (!isFirstLoad)
  209. {
  210. LogEnvironmentInfo(Logger, ApplicationPaths, false);
  211. }
  212. // Put the app config in the log for troubleshooting purposes
  213. Logger.LogMultiline("Application configuration:", LogSeverity.Info, new StringBuilder(JsonSerializer.SerializeToString(ConfigurationManager.CommonConfiguration)));
  214. if (Plugins != null)
  215. {
  216. var pluginBuilder = new StringBuilder();
  217. foreach (var plugin in Plugins)
  218. {
  219. pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
  220. }
  221. Logger.LogMultiline("Plugins:", LogSeverity.Info, pluginBuilder);
  222. }
  223. }
  224. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, bool isStartup)
  225. {
  226. logger.LogMultiline("Emby", LogSeverity.Info, GetBaseExceptionMessage(appPaths));
  227. }
  228. protected static StringBuilder GetBaseExceptionMessage(IApplicationPaths appPaths)
  229. {
  230. var builder = new StringBuilder();
  231. builder.AppendLine(string.Format("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs())));
  232. builder.AppendLine(string.Format("Operating system: {0}", Environment.OSVersion));
  233. builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount));
  234. builder.AppendLine(string.Format("64-Bit OS: {0}", Environment.Is64BitOperatingSystem));
  235. builder.AppendLine(string.Format("64-Bit Process: {0}", Environment.Is64BitProcess));
  236. builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath));
  237. Type type = Type.GetType("Mono.Runtime");
  238. if (type != null)
  239. {
  240. MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
  241. if (displayName != null)
  242. {
  243. builder.AppendLine("Mono: " + displayName.Invoke(null, null));
  244. }
  245. }
  246. builder.AppendLine(string.Format("Application Path: {0}", appPaths.ApplicationPath));
  247. return builder;
  248. }
  249. protected abstract IJsonSerializer CreateJsonSerializer();
  250. private void SetHttpLimit()
  251. {
  252. try
  253. {
  254. // Increase the max http request limit
  255. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  256. }
  257. catch (Exception ex)
  258. {
  259. Logger.ErrorException("Error setting http limit", ex);
  260. }
  261. }
  262. /// <summary>
  263. /// Installs the iso mounters.
  264. /// </summary>
  265. /// <param name="cancellationToken">The cancellation token.</param>
  266. /// <returns>Task.</returns>
  267. private async Task InstallIsoMounters(CancellationToken cancellationToken)
  268. {
  269. var list = new List<IIsoMounter>();
  270. foreach (var isoMounter in GetExports<IIsoMounter>())
  271. {
  272. try
  273. {
  274. if (isoMounter.RequiresInstallation && !isoMounter.IsInstalled)
  275. {
  276. Logger.Info("Installing {0}", isoMounter.Name);
  277. await isoMounter.Install(cancellationToken).ConfigureAwait(false);
  278. }
  279. list.Add(isoMounter);
  280. }
  281. catch (Exception ex)
  282. {
  283. Logger.ErrorException("{0} failed to load.", ex, isoMounter.Name);
  284. }
  285. }
  286. IsoManager.AddParts(list);
  287. }
  288. /// <summary>
  289. /// Runs the startup tasks.
  290. /// </summary>
  291. /// <returns>Task.</returns>
  292. public virtual Task RunStartupTasks()
  293. {
  294. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  295. ConfigureAutorun();
  296. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  297. return Task.FromResult(true);
  298. }
  299. /// <summary>
  300. /// Configures the autorun.
  301. /// </summary>
  302. private void ConfigureAutorun()
  303. {
  304. try
  305. {
  306. ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
  307. }
  308. catch (Exception ex)
  309. {
  310. Logger.ErrorException("Error configuring autorun", ex);
  311. }
  312. }
  313. /// <summary>
  314. /// Gets the composable part assemblies.
  315. /// </summary>
  316. /// <returns>IEnumerable{Assembly}.</returns>
  317. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  318. /// <summary>
  319. /// Gets the configuration manager.
  320. /// </summary>
  321. /// <returns>IConfigurationManager.</returns>
  322. protected abstract IConfigurationManager GetConfigurationManager();
  323. /// <summary>
  324. /// Finds the parts.
  325. /// </summary>
  326. protected virtual void FindParts()
  327. {
  328. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  329. Plugins = GetExports<IPlugin>().Select(LoadPlugin).Where(i => i != null).ToArray();
  330. }
  331. private IPlugin LoadPlugin(IPlugin plugin)
  332. {
  333. try
  334. {
  335. var assemblyPlugin = plugin as IPluginAssembly;
  336. if (assemblyPlugin != null)
  337. {
  338. var assembly = plugin.GetType().Assembly;
  339. var assemblyName = assembly.GetName();
  340. var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
  341. var assemblyId = new Guid(attribute.Value);
  342. var assemblyFileName = assemblyName.Name + ".dll";
  343. var assemblyFilePath = Path.Combine(ApplicationPaths.PluginsPath, assemblyFileName);
  344. assemblyPlugin.SetAttributes(assemblyFilePath, assemblyFileName, assemblyName.Version, assemblyId);
  345. }
  346. var isFirstRun = !File.Exists(plugin.ConfigurationFilePath);
  347. plugin.SetStartupInfo(isFirstRun, File.GetLastWriteTimeUtc, s => Directory.CreateDirectory(s));
  348. }
  349. catch (Exception ex)
  350. {
  351. Logger.ErrorException("Error loading plugin {0}", ex, plugin.GetType().FullName);
  352. return null;
  353. }
  354. return plugin;
  355. }
  356. /// <summary>
  357. /// Discovers the types.
  358. /// </summary>
  359. protected void DiscoverTypes()
  360. {
  361. FailedAssemblies.Clear();
  362. var assemblies = GetComposablePartAssemblies().ToList();
  363. foreach (var assembly in assemblies)
  364. {
  365. Logger.Info("Loading {0}", assembly.FullName);
  366. }
  367. AllConcreteTypes = assemblies
  368. .SelectMany(GetTypes)
  369. .Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType)
  370. .ToArray();
  371. }
  372. /// <summary>
  373. /// Registers resources that classes will depend on
  374. /// </summary>
  375. /// <returns>Task.</returns>
  376. protected virtual Task RegisterResources(IProgress<double> progress)
  377. {
  378. RegisterSingleInstance(ConfigurationManager);
  379. RegisterSingleInstance<IApplicationHost>(this);
  380. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  381. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager, SystemEvents);
  382. RegisterSingleInstance(JsonSerializer);
  383. RegisterSingleInstance(XmlSerializer);
  384. RegisterSingleInstance(MemoryStreamProvider);
  385. RegisterSingleInstance(SystemEvents);
  386. RegisterSingleInstance(LogManager);
  387. RegisterSingleInstance(Logger);
  388. RegisterSingleInstance(TaskManager);
  389. RegisterSingleInstance(FileSystemManager);
  390. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, MemoryStreamProvider);
  391. RegisterSingleInstance(HttpClient);
  392. NetworkManager = CreateNetworkManager(LogManager.GetLogger("NetworkManager"));
  393. RegisterSingleInstance(NetworkManager);
  394. IsoManager = new IsoManager();
  395. RegisterSingleInstance(IsoManager);
  396. return Task.FromResult(true);
  397. }
  398. /// <summary>
  399. /// Gets a list of types within an assembly
  400. /// 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
  401. /// </summary>
  402. /// <param name="assembly">The assembly.</param>
  403. /// <returns>IEnumerable{Type}.</returns>
  404. /// <exception cref="System.ArgumentNullException">assembly</exception>
  405. protected IEnumerable<Type> GetTypes(Assembly assembly)
  406. {
  407. if (assembly == null)
  408. {
  409. throw new ArgumentNullException("assembly");
  410. }
  411. try
  412. {
  413. return assembly.GetTypes();
  414. }
  415. catch (ReflectionTypeLoadException ex)
  416. {
  417. if (ex.LoaderExceptions != null)
  418. {
  419. foreach (var loaderException in ex.LoaderExceptions)
  420. {
  421. Logger.Error("LoaderException: " + loaderException.Message);
  422. }
  423. }
  424. // If it fails we can still get a list of the Types it was able to resolve
  425. return ex.Types.Where(t => t != null);
  426. }
  427. }
  428. protected abstract INetworkManager CreateNetworkManager(ILogger logger);
  429. /// <summary>
  430. /// Creates an instance of type and resolves all constructor dependancies
  431. /// </summary>
  432. /// <param name="type">The type.</param>
  433. /// <returns>System.Object.</returns>
  434. public abstract object CreateInstance(Type type);
  435. /// <summary>
  436. /// Creates the instance safe.
  437. /// </summary>
  438. /// <param name="type">The type.</param>
  439. /// <returns>System.Object.</returns>
  440. protected abstract object CreateInstanceSafe(Type type);
  441. /// <summary>
  442. /// Registers the specified obj.
  443. /// </summary>
  444. /// <typeparam name="T"></typeparam>
  445. /// <param name="obj">The obj.</param>
  446. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  447. protected abstract void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  448. where T : class;
  449. /// <summary>
  450. /// Registers the single instance.
  451. /// </summary>
  452. /// <typeparam name="T"></typeparam>
  453. /// <param name="func">The func.</param>
  454. protected abstract void RegisterSingleInstance<T>(Func<T> func)
  455. where T : class;
  456. /// <summary>
  457. /// Resolves this instance.
  458. /// </summary>
  459. /// <typeparam name="T"></typeparam>
  460. /// <returns>``0.</returns>
  461. public abstract T Resolve<T>();
  462. /// <summary>
  463. /// Resolves this instance.
  464. /// </summary>
  465. /// <typeparam name="T"></typeparam>
  466. /// <returns>``0.</returns>
  467. public abstract T TryResolve<T>();
  468. /// <summary>
  469. /// Loads the assembly.
  470. /// </summary>
  471. /// <param name="file">The file.</param>
  472. /// <returns>Assembly.</returns>
  473. protected Assembly LoadAssembly(string file)
  474. {
  475. try
  476. {
  477. return Assembly.Load(File.ReadAllBytes(file));
  478. }
  479. catch (Exception ex)
  480. {
  481. FailedAssemblies.Add(file);
  482. Logger.ErrorException("Error loading assembly {0}", ex, file);
  483. return null;
  484. }
  485. }
  486. /// <summary>
  487. /// Gets the export types.
  488. /// </summary>
  489. /// <typeparam name="T"></typeparam>
  490. /// <returns>IEnumerable{Type}.</returns>
  491. public IEnumerable<Type> GetExportTypes<T>()
  492. {
  493. var currentType = typeof(T);
  494. return AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom);
  495. }
  496. /// <summary>
  497. /// Gets the exports.
  498. /// </summary>
  499. /// <typeparam name="T"></typeparam>
  500. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  501. /// <returns>IEnumerable{``0}.</returns>
  502. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  503. {
  504. var parts = GetExportTypes<T>()
  505. .Select(CreateInstanceSafe)
  506. .Where(i => i != null)
  507. .Cast<T>()
  508. .ToList();
  509. if (manageLiftime)
  510. {
  511. lock (DisposableParts)
  512. {
  513. DisposableParts.AddRange(parts.OfType<IDisposable>());
  514. }
  515. }
  516. return parts;
  517. }
  518. /// <summary>
  519. /// Gets the application version.
  520. /// </summary>
  521. /// <value>The application version.</value>
  522. public abstract Version ApplicationVersion { get; }
  523. /// <summary>
  524. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  525. /// </summary>
  526. /// <param name="sender">The source of the event.</param>
  527. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  528. /// <exception cref="System.NotImplementedException"></exception>
  529. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  530. {
  531. ConfigureAutorun();
  532. }
  533. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  534. /// <summary>
  535. /// Removes the plugin.
  536. /// </summary>
  537. /// <param name="plugin">The plugin.</param>
  538. public void RemovePlugin(IPlugin plugin)
  539. {
  540. var list = Plugins.ToList();
  541. list.Remove(plugin);
  542. Plugins = list.ToArray();
  543. }
  544. /// <summary>
  545. /// Gets a value indicating whether this instance can self restart.
  546. /// </summary>
  547. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  548. public abstract bool CanSelfRestart { get; }
  549. /// <summary>
  550. /// Notifies that the kernel that a change has been made that requires a restart
  551. /// </summary>
  552. public void NotifyPendingRestart()
  553. {
  554. var changed = !HasPendingRestart;
  555. HasPendingRestart = true;
  556. if (changed)
  557. {
  558. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  559. }
  560. }
  561. /// <summary>
  562. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  563. /// </summary>
  564. public void Dispose()
  565. {
  566. Dispose(true);
  567. }
  568. /// <summary>
  569. /// Releases unmanaged and - optionally - managed resources.
  570. /// </summary>
  571. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  572. protected virtual void Dispose(bool dispose)
  573. {
  574. if (dispose)
  575. {
  576. var type = GetType();
  577. Logger.Info("Disposing " + type.Name);
  578. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  579. DisposableParts.Clear();
  580. foreach (var part in parts)
  581. {
  582. Logger.Info("Disposing " + part.GetType().Name);
  583. try
  584. {
  585. part.Dispose();
  586. }
  587. catch (Exception ex)
  588. {
  589. Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
  590. }
  591. }
  592. }
  593. }
  594. /// <summary>
  595. /// Restarts this instance.
  596. /// </summary>
  597. public abstract Task Restart();
  598. /// <summary>
  599. /// Gets or sets a value indicating whether this instance can self update.
  600. /// </summary>
  601. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  602. public abstract bool CanSelfUpdate { get; }
  603. /// <summary>
  604. /// Checks for update.
  605. /// </summary>
  606. /// <param name="cancellationToken">The cancellation token.</param>
  607. /// <param name="progress">The progress.</param>
  608. /// <returns>Task{CheckForUpdateResult}.</returns>
  609. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  610. IProgress<double> progress);
  611. /// <summary>
  612. /// Updates the application.
  613. /// </summary>
  614. /// <param name="package">The package that contains the update</param>
  615. /// <param name="cancellationToken">The cancellation token.</param>
  616. /// <param name="progress">The progress.</param>
  617. /// <returns>Task.</returns>
  618. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  619. IProgress<double> progress);
  620. /// <summary>
  621. /// Shuts down.
  622. /// </summary>
  623. public abstract Task Shutdown();
  624. /// <summary>
  625. /// Called when [application updated].
  626. /// </summary>
  627. /// <param name="package">The package.</param>
  628. protected void OnApplicationUpdated(PackageVersionInfo package)
  629. {
  630. Logger.Info("Application has been updated to version {0}", package.versionStr);
  631. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  632. {
  633. Argument = package
  634. }, Logger);
  635. NotifyPendingRestart();
  636. }
  637. }
  638. }