BaseApplicationHost.cs 29 KB

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