BaseApplicationHost.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. using System.Net;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Events;
  4. using MediaBrowser.Common.Implementations.Archiving;
  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.Net;
  11. using MediaBrowser.Common.Plugins;
  12. using MediaBrowser.Common.ScheduledTasks;
  13. using MediaBrowser.Common.Security;
  14. using MediaBrowser.Common.Updates;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.Logging;
  17. using MediaBrowser.Model.Serialization;
  18. using MediaBrowser.Model.Updates;
  19. using SimpleInjector;
  20. using System;
  21. using System.Collections.Generic;
  22. using System.IO;
  23. using System.Linq;
  24. using System.Net.Http;
  25. using System.Reflection;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. namespace MediaBrowser.Common.Implementations
  29. {
  30. /// <summary>
  31. /// Class BaseApplicationHost
  32. /// </summary>
  33. /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
  34. public abstract class BaseApplicationHost<TApplicationPathsType> : IApplicationHost
  35. where TApplicationPathsType : class, IApplicationPaths, new()
  36. {
  37. /// <summary>
  38. /// Occurs when [has pending restart changed].
  39. /// </summary>
  40. public event EventHandler HasPendingRestartChanged;
  41. /// <summary>
  42. /// Occurs when [application updated].
  43. /// </summary>
  44. public event EventHandler<GenericEventArgs<Version>> ApplicationUpdated;
  45. /// <summary>
  46. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  47. /// </summary>
  48. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  49. public bool HasPendingRestart { get; private set; }
  50. /// <summary>
  51. /// Gets or sets the logger.
  52. /// </summary>
  53. /// <value>The logger.</value>
  54. protected ILogger Logger { get; private set; }
  55. /// <summary>
  56. /// Gets or sets the plugins.
  57. /// </summary>
  58. /// <value>The plugins.</value>
  59. public IEnumerable<IPlugin> Plugins { get; protected set; }
  60. /// <summary>
  61. /// Gets or sets the log manager.
  62. /// </summary>
  63. /// <value>The log manager.</value>
  64. public ILogManager LogManager { get; protected set; }
  65. /// <summary>
  66. /// Gets the application paths.
  67. /// </summary>
  68. /// <value>The application paths.</value>
  69. protected TApplicationPathsType ApplicationPaths { get; private set; }
  70. /// <summary>
  71. /// The container
  72. /// </summary>
  73. protected readonly Container Container = new Container();
  74. /// <summary>
  75. /// The json serializer
  76. /// </summary>
  77. public readonly IJsonSerializer JsonSerializer = new JsonSerializer();
  78. /// <summary>
  79. /// The _XML serializer
  80. /// </summary>
  81. protected readonly IXmlSerializer XmlSerializer = new XmlSerializer();
  82. /// <summary>
  83. /// Gets assemblies that failed to load
  84. /// </summary>
  85. /// <value>The failed assemblies.</value>
  86. public List<string> FailedAssemblies { get; protected set; }
  87. /// <summary>
  88. /// Gets all types within all running assemblies
  89. /// </summary>
  90. /// <value>All types.</value>
  91. public Type[] AllTypes { get; protected set; }
  92. /// <summary>
  93. /// Gets all concrete types.
  94. /// </summary>
  95. /// <value>All concrete types.</value>
  96. public Type[] AllConcreteTypes { get; protected set; }
  97. /// <summary>
  98. /// The disposable parts
  99. /// </summary>
  100. protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
  101. /// <summary>
  102. /// Gets a value indicating whether this instance is first run.
  103. /// </summary>
  104. /// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
  105. public bool IsFirstRun { get; private set; }
  106. /// <summary>
  107. /// Gets the kernel.
  108. /// </summary>
  109. /// <value>The kernel.</value>
  110. protected ITaskManager TaskManager { get; private set; }
  111. /// <summary>
  112. /// Gets the security manager.
  113. /// </summary>
  114. /// <value>The security manager.</value>
  115. protected ISecurityManager SecurityManager { get; private set; }
  116. /// <summary>
  117. /// Gets the HTTP client.
  118. /// </summary>
  119. /// <value>The HTTP client.</value>
  120. protected IHttpClient HttpClient { get; private set; }
  121. /// <summary>
  122. /// Gets the network manager.
  123. /// </summary>
  124. /// <value>The network manager.</value>
  125. protected INetworkManager NetworkManager { get; private set; }
  126. /// <summary>
  127. /// Gets the configuration manager.
  128. /// </summary>
  129. /// <value>The configuration manager.</value>
  130. protected IConfigurationManager ConfigurationManager { get; private set; }
  131. /// <summary>
  132. /// Gets or sets the installation manager.
  133. /// </summary>
  134. /// <value>The installation manager.</value>
  135. protected IInstallationManager InstallationManager { get; set; }
  136. /// <summary>
  137. /// Gets or sets the zip client.
  138. /// </summary>
  139. /// <value>The zip client.</value>
  140. protected IZipClient ZipClient { get; set; }
  141. protected IIsoManager IsoManager { get; set; }
  142. /// <summary>
  143. /// Initializes a new instance of the <see cref="BaseApplicationHost{TApplicationPathsType}"/> class.
  144. /// </summary>
  145. protected BaseApplicationHost(TApplicationPathsType applicationPaths, ILogManager logManager)
  146. {
  147. FailedAssemblies = new List<string>();
  148. ApplicationPaths = applicationPaths;
  149. LogManager = logManager;
  150. ConfigurationManager = GetConfigurationManager();
  151. }
  152. /// <summary>
  153. /// Inits this instance.
  154. /// </summary>
  155. /// <returns>Task.</returns>
  156. public virtual async Task Init()
  157. {
  158. IsFirstRun = !ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted;
  159. Logger = LogManager.GetLogger("App");
  160. LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
  161. ? LogSeverity.Debug
  162. : LogSeverity.Info;
  163. OnLoggerLoaded();
  164. DiscoverTypes();
  165. Logger.Info("Version {0} initializing", ApplicationVersion);
  166. SetHttpLimit();
  167. await RegisterResources().ConfigureAwait(false);
  168. FindParts();
  169. await InstallIsoMounters(CancellationToken.None).ConfigureAwait(false);
  170. }
  171. /// <summary>
  172. /// Called when [logger loaded].
  173. /// </summary>
  174. protected virtual void OnLoggerLoaded()
  175. {
  176. }
  177. private void SetHttpLimit()
  178. {
  179. try
  180. {
  181. ServicePointManager.DefaultConnectionLimit = Math.Min(48, ServicePointManager.DefaultConnectionLimit);
  182. }
  183. catch (Exception ex)
  184. {
  185. Logger.ErrorException("Error setting http limit", ex);
  186. }
  187. }
  188. /// <summary>
  189. /// Installs the iso mounters.
  190. /// </summary>
  191. /// <param name="cancellationToken">The cancellation token.</param>
  192. /// <returns>Task.</returns>
  193. private async Task InstallIsoMounters(CancellationToken cancellationToken)
  194. {
  195. var list = new List<IIsoMounter>();
  196. foreach (var isoMounter in GetExports<IIsoMounter>())
  197. {
  198. try
  199. {
  200. if (isoMounter.RequiresInstallation && !isoMounter.IsInstalled)
  201. {
  202. Logger.Info("Installing {0}", isoMounter.Name);
  203. await isoMounter.Install(cancellationToken).ConfigureAwait(false);
  204. }
  205. list.Add(isoMounter);
  206. }
  207. catch (Exception ex)
  208. {
  209. Logger.ErrorException("{0} failed to load.", ex, isoMounter.Name);
  210. }
  211. }
  212. IsoManager.AddParts(list);
  213. }
  214. /// <summary>
  215. /// Runs the startup tasks.
  216. /// </summary>
  217. /// <returns>Task.</returns>
  218. public virtual Task RunStartupTasks()
  219. {
  220. return Task.Run(() =>
  221. {
  222. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  223. Task.Run(() => ConfigureAutorun());
  224. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  225. });
  226. }
  227. /// <summary>
  228. /// Configures the autorun.
  229. /// </summary>
  230. private void ConfigureAutorun()
  231. {
  232. try
  233. {
  234. ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
  235. }
  236. catch (Exception ex)
  237. {
  238. Logger.ErrorException("Error configuring autorun", ex);
  239. }
  240. }
  241. /// <summary>
  242. /// Gets the composable part assemblies.
  243. /// </summary>
  244. /// <returns>IEnumerable{Assembly}.</returns>
  245. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  246. /// <summary>
  247. /// Gets the configuration manager.
  248. /// </summary>
  249. /// <returns>IConfigurationManager.</returns>
  250. protected abstract IConfigurationManager GetConfigurationManager();
  251. /// <summary>
  252. /// Finds the parts.
  253. /// </summary>
  254. protected virtual void FindParts()
  255. {
  256. Plugins = GetExports<IPlugin>();
  257. }
  258. /// <summary>
  259. /// Discovers the types.
  260. /// </summary>
  261. protected void DiscoverTypes()
  262. {
  263. FailedAssemblies.Clear();
  264. var assemblies = GetComposablePartAssemblies().ToList();
  265. foreach (var assembly in assemblies)
  266. {
  267. Logger.Info("Loading {0}", assembly.FullName);
  268. }
  269. AllTypes = assemblies.SelectMany(GetTypes).ToArray();
  270. AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
  271. }
  272. /// <summary>
  273. /// Registers resources that classes will depend on
  274. /// </summary>
  275. /// <returns>Task.</returns>
  276. protected virtual Task RegisterResources()
  277. {
  278. return Task.Run(() =>
  279. {
  280. RegisterSingleInstance(ConfigurationManager);
  281. RegisterSingleInstance<IApplicationHost>(this);
  282. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  283. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger);
  284. RegisterSingleInstance(JsonSerializer);
  285. RegisterSingleInstance(XmlSerializer);
  286. RegisterSingleInstance(LogManager);
  287. RegisterSingleInstance(Logger);
  288. RegisterSingleInstance(TaskManager);
  289. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger, CreateHttpClient);
  290. RegisterSingleInstance(HttpClient);
  291. NetworkManager = CreateNetworkManager();
  292. RegisterSingleInstance(NetworkManager);
  293. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, NetworkManager);
  294. RegisterSingleInstance(SecurityManager);
  295. InstallationManager = new InstallationManager(Logger, this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, NetworkManager, ConfigurationManager);
  296. RegisterSingleInstance(InstallationManager);
  297. ZipClient = new ZipClient();
  298. RegisterSingleInstance(ZipClient);
  299. IsoManager = new IsoManager();
  300. RegisterSingleInstance(IsoManager);
  301. });
  302. }
  303. protected abstract HttpClient CreateHttpClient(bool enableHttpCompression);
  304. /// <summary>
  305. /// Gets a list of types within an assembly
  306. /// 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
  307. /// </summary>
  308. /// <param name="assembly">The assembly.</param>
  309. /// <returns>IEnumerable{Type}.</returns>
  310. /// <exception cref="System.ArgumentNullException">assembly</exception>
  311. protected IEnumerable<Type> GetTypes(Assembly assembly)
  312. {
  313. if (assembly == null)
  314. {
  315. throw new ArgumentNullException("assembly");
  316. }
  317. try
  318. {
  319. return assembly.GetTypes();
  320. }
  321. catch (ReflectionTypeLoadException ex)
  322. {
  323. // If it fails we can still get a list of the Types it was able to resolve
  324. return ex.Types.Where(t => t != null);
  325. }
  326. }
  327. protected abstract INetworkManager CreateNetworkManager();
  328. /// <summary>
  329. /// Creates an instance of type and resolves all constructor dependancies
  330. /// </summary>
  331. /// <param name="type">The type.</param>
  332. /// <returns>System.Object.</returns>
  333. public object CreateInstance(Type type)
  334. {
  335. try
  336. {
  337. return Container.GetInstance(type);
  338. }
  339. catch (Exception ex)
  340. {
  341. Logger.Error("Error creating {0}", ex, type.Name);
  342. throw;
  343. }
  344. }
  345. /// <summary>
  346. /// Creates the instance safe.
  347. /// </summary>
  348. /// <param name="type">The type.</param>
  349. /// <returns>System.Object.</returns>
  350. protected object CreateInstanceSafe(Type type)
  351. {
  352. try
  353. {
  354. return Container.GetInstance(type);
  355. }
  356. catch (Exception ex)
  357. {
  358. Logger.Error("Error creating {0}", ex, type.Name);
  359. #if DEBUG
  360. throw;
  361. #endif
  362. // Don't blow up in release mode
  363. return null;
  364. }
  365. }
  366. /// <summary>
  367. /// Registers the specified obj.
  368. /// </summary>
  369. /// <typeparam name="T"></typeparam>
  370. /// <param name="obj">The obj.</param>
  371. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  372. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  373. where T : class
  374. {
  375. Container.RegisterSingle(obj);
  376. if (manageLifetime)
  377. {
  378. var disposable = obj as IDisposable;
  379. if (disposable != null)
  380. {
  381. DisposableParts.Add(disposable);
  382. }
  383. }
  384. }
  385. /// <summary>
  386. /// Registers the single instance.
  387. /// </summary>
  388. /// <typeparam name="T"></typeparam>
  389. /// <param name="func">The func.</param>
  390. protected void RegisterSingleInstance<T>(Func<T> func)
  391. where T : class
  392. {
  393. Container.RegisterSingle(func);
  394. }
  395. /// <summary>
  396. /// Resolves this instance.
  397. /// </summary>
  398. /// <typeparam name="T"></typeparam>
  399. /// <returns>``0.</returns>
  400. public T Resolve<T>()
  401. {
  402. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  403. }
  404. /// <summary>
  405. /// Resolves this instance.
  406. /// </summary>
  407. /// <typeparam name="T"></typeparam>
  408. /// <returns>``0.</returns>
  409. public T TryResolve<T>()
  410. {
  411. var result = Container.GetRegistration(typeof(T), false);
  412. if (result == null)
  413. {
  414. return default(T);
  415. }
  416. return (T)result.GetInstance();
  417. }
  418. /// <summary>
  419. /// Loads the assembly.
  420. /// </summary>
  421. /// <param name="file">The file.</param>
  422. /// <returns>Assembly.</returns>
  423. protected Assembly LoadAssembly(string file)
  424. {
  425. try
  426. {
  427. return Assembly.Load(File.ReadAllBytes((file)));
  428. }
  429. catch (Exception ex)
  430. {
  431. FailedAssemblies.Add(file);
  432. Logger.ErrorException("Error loading assembly {0}", ex, file);
  433. return null;
  434. }
  435. }
  436. /// <summary>
  437. /// Gets the export types.
  438. /// </summary>
  439. /// <typeparam name="T"></typeparam>
  440. /// <returns>IEnumerable{Type}.</returns>
  441. public IEnumerable<Type> GetExportTypes<T>()
  442. {
  443. var currentType = typeof(T);
  444. return AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom);
  445. }
  446. /// <summary>
  447. /// Gets the exports.
  448. /// </summary>
  449. /// <typeparam name="T"></typeparam>
  450. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  451. /// <returns>IEnumerable{``0}.</returns>
  452. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  453. {
  454. var parts = GetExportTypes<T>()
  455. .Select(CreateInstanceSafe)
  456. .Where(i => i != null)
  457. .Cast<T>()
  458. .ToList();
  459. if (manageLiftime)
  460. {
  461. lock (DisposableParts)
  462. {
  463. DisposableParts.AddRange(parts.OfType<IDisposable>());
  464. }
  465. }
  466. return parts;
  467. }
  468. /// <summary>
  469. /// Gets the current application version
  470. /// </summary>
  471. /// <value>The application version.</value>
  472. public Version ApplicationVersion
  473. {
  474. get
  475. {
  476. return GetType().Assembly.GetName().Version;
  477. }
  478. }
  479. /// <summary>
  480. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  481. /// </summary>
  482. /// <param name="sender">The source of the event.</param>
  483. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  484. /// <exception cref="System.NotImplementedException"></exception>
  485. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  486. {
  487. ConfigureAutorun();
  488. }
  489. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  490. /// <summary>
  491. /// Removes the plugin.
  492. /// </summary>
  493. /// <param name="plugin">The plugin.</param>
  494. public void RemovePlugin(IPlugin plugin)
  495. {
  496. var list = Plugins.ToList();
  497. list.Remove(plugin);
  498. Plugins = list;
  499. }
  500. /// <summary>
  501. /// Notifies that the kernel that a change has been made that requires a restart
  502. /// </summary>
  503. public void NotifyPendingRestart()
  504. {
  505. HasPendingRestart = true;
  506. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  507. }
  508. /// <summary>
  509. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  510. /// </summary>
  511. public void Dispose()
  512. {
  513. Dispose(true);
  514. }
  515. /// <summary>
  516. /// Releases unmanaged and - optionally - managed resources.
  517. /// </summary>
  518. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  519. protected virtual void Dispose(bool dispose)
  520. {
  521. if (dispose)
  522. {
  523. var type = GetType();
  524. Logger.Info("Disposing " + type.Name);
  525. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  526. DisposableParts.Clear();
  527. foreach (var part in parts)
  528. {
  529. Logger.Info("Disposing " + part.GetType().Name);
  530. part.Dispose();
  531. }
  532. }
  533. }
  534. /// <summary>
  535. /// Restarts this instance.
  536. /// </summary>
  537. public abstract Task Restart();
  538. /// <summary>
  539. /// Gets or sets a value indicating whether this instance can self update.
  540. /// </summary>
  541. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  542. public abstract bool CanSelfUpdate { get; }
  543. /// <summary>
  544. /// Checks for update.
  545. /// </summary>
  546. /// <param name="cancellationToken">The cancellation token.</param>
  547. /// <param name="progress">The progress.</param>
  548. /// <returns>Task{CheckForUpdateResult}.</returns>
  549. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  550. IProgress<double> progress);
  551. /// <summary>
  552. /// Updates the application.
  553. /// </summary>
  554. /// <param name="package">The package that contains the update</param>
  555. /// <param name="cancellationToken">The cancellation token.</param>
  556. /// <param name="progress">The progress.</param>
  557. /// <returns>Task.</returns>
  558. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  559. IProgress<double> progress);
  560. /// <summary>
  561. /// Shuts down.
  562. /// </summary>
  563. public abstract Task Shutdown();
  564. /// <summary>
  565. /// Called when [application updated].
  566. /// </summary>
  567. /// <param name="newVersion">The new version.</param>
  568. protected void OnApplicationUpdated(Version newVersion)
  569. {
  570. Logger.Info("Application has been updated to version {0}", newVersion);
  571. EventHelper.QueueEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<Version> { Argument = newVersion }, Logger);
  572. NotifyPendingRestart();
  573. }
  574. }
  575. }