BaseApplicationHost.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. // Increase the max http request limit
  182. ServicePointManager.DefaultConnectionLimit = Math.Max(48, ServicePointManager.DefaultConnectionLimit);
  183. }
  184. catch (Exception ex)
  185. {
  186. Logger.ErrorException("Error setting http limit", ex);
  187. }
  188. }
  189. /// <summary>
  190. /// Installs the iso mounters.
  191. /// </summary>
  192. /// <param name="cancellationToken">The cancellation token.</param>
  193. /// <returns>Task.</returns>
  194. private async Task InstallIsoMounters(CancellationToken cancellationToken)
  195. {
  196. var list = new List<IIsoMounter>();
  197. foreach (var isoMounter in GetExports<IIsoMounter>())
  198. {
  199. try
  200. {
  201. if (isoMounter.RequiresInstallation && !isoMounter.IsInstalled)
  202. {
  203. Logger.Info("Installing {0}", isoMounter.Name);
  204. await isoMounter.Install(cancellationToken).ConfigureAwait(false);
  205. }
  206. list.Add(isoMounter);
  207. }
  208. catch (Exception ex)
  209. {
  210. Logger.ErrorException("{0} failed to load.", ex, isoMounter.Name);
  211. }
  212. }
  213. IsoManager.AddParts(list);
  214. }
  215. /// <summary>
  216. /// Runs the startup tasks.
  217. /// </summary>
  218. /// <returns>Task.</returns>
  219. public virtual Task RunStartupTasks()
  220. {
  221. return Task.Run(() =>
  222. {
  223. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  224. Task.Run(() => ConfigureAutorun());
  225. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  226. });
  227. }
  228. /// <summary>
  229. /// Configures the autorun.
  230. /// </summary>
  231. private void ConfigureAutorun()
  232. {
  233. try
  234. {
  235. ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
  236. }
  237. catch (Exception ex)
  238. {
  239. Logger.ErrorException("Error configuring autorun", ex);
  240. }
  241. }
  242. /// <summary>
  243. /// Gets the composable part assemblies.
  244. /// </summary>
  245. /// <returns>IEnumerable{Assembly}.</returns>
  246. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  247. /// <summary>
  248. /// Gets the configuration manager.
  249. /// </summary>
  250. /// <returns>IConfigurationManager.</returns>
  251. protected abstract IConfigurationManager GetConfigurationManager();
  252. /// <summary>
  253. /// Finds the parts.
  254. /// </summary>
  255. protected virtual void FindParts()
  256. {
  257. Plugins = GetExports<IPlugin>();
  258. }
  259. /// <summary>
  260. /// Discovers the types.
  261. /// </summary>
  262. protected void DiscoverTypes()
  263. {
  264. FailedAssemblies.Clear();
  265. var assemblies = GetComposablePartAssemblies().ToList();
  266. foreach (var assembly in assemblies)
  267. {
  268. Logger.Info("Loading {0}", assembly.FullName);
  269. }
  270. AllTypes = assemblies.SelectMany(GetTypes).ToArray();
  271. AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
  272. }
  273. /// <summary>
  274. /// Registers resources that classes will depend on
  275. /// </summary>
  276. /// <returns>Task.</returns>
  277. protected virtual Task RegisterResources()
  278. {
  279. return Task.Run(() =>
  280. {
  281. RegisterSingleInstance(ConfigurationManager);
  282. RegisterSingleInstance<IApplicationHost>(this);
  283. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  284. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger);
  285. RegisterSingleInstance(JsonSerializer);
  286. RegisterSingleInstance(XmlSerializer);
  287. RegisterSingleInstance(LogManager);
  288. RegisterSingleInstance(Logger);
  289. RegisterSingleInstance(TaskManager);
  290. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger, CreateHttpClient);
  291. RegisterSingleInstance(HttpClient);
  292. NetworkManager = CreateNetworkManager();
  293. RegisterSingleInstance(NetworkManager);
  294. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, NetworkManager);
  295. RegisterSingleInstance(SecurityManager);
  296. InstallationManager = new InstallationManager(Logger, this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, NetworkManager, ConfigurationManager);
  297. RegisterSingleInstance(InstallationManager);
  298. ZipClient = new ZipClient();
  299. RegisterSingleInstance(ZipClient);
  300. IsoManager = new IsoManager();
  301. RegisterSingleInstance(IsoManager);
  302. });
  303. }
  304. protected abstract HttpClient CreateHttpClient(bool enableHttpCompression);
  305. /// <summary>
  306. /// Gets a list of types within an assembly
  307. /// 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
  308. /// </summary>
  309. /// <param name="assembly">The assembly.</param>
  310. /// <returns>IEnumerable{Type}.</returns>
  311. /// <exception cref="System.ArgumentNullException">assembly</exception>
  312. protected IEnumerable<Type> GetTypes(Assembly assembly)
  313. {
  314. if (assembly == null)
  315. {
  316. throw new ArgumentNullException("assembly");
  317. }
  318. try
  319. {
  320. return assembly.GetTypes();
  321. }
  322. catch (ReflectionTypeLoadException ex)
  323. {
  324. // If it fails we can still get a list of the Types it was able to resolve
  325. return ex.Types.Where(t => t != null);
  326. }
  327. }
  328. protected abstract INetworkManager CreateNetworkManager();
  329. /// <summary>
  330. /// Creates an instance of type and resolves all constructor dependancies
  331. /// </summary>
  332. /// <param name="type">The type.</param>
  333. /// <returns>System.Object.</returns>
  334. public object CreateInstance(Type type)
  335. {
  336. try
  337. {
  338. return Container.GetInstance(type);
  339. }
  340. catch (Exception ex)
  341. {
  342. Logger.Error("Error creating {0}", ex, type.Name);
  343. throw;
  344. }
  345. }
  346. /// <summary>
  347. /// Creates the instance safe.
  348. /// </summary>
  349. /// <param name="type">The type.</param>
  350. /// <returns>System.Object.</returns>
  351. protected object CreateInstanceSafe(Type type)
  352. {
  353. try
  354. {
  355. return Container.GetInstance(type);
  356. }
  357. catch (Exception ex)
  358. {
  359. Logger.Error("Error creating {0}", ex, type.Name);
  360. #if DEBUG
  361. throw;
  362. #endif
  363. // Don't blow up in release mode
  364. return null;
  365. }
  366. }
  367. /// <summary>
  368. /// Registers the specified obj.
  369. /// </summary>
  370. /// <typeparam name="T"></typeparam>
  371. /// <param name="obj">The obj.</param>
  372. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  373. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  374. where T : class
  375. {
  376. Container.RegisterSingle(obj);
  377. if (manageLifetime)
  378. {
  379. var disposable = obj as IDisposable;
  380. if (disposable != null)
  381. {
  382. DisposableParts.Add(disposable);
  383. }
  384. }
  385. }
  386. /// <summary>
  387. /// Registers the single instance.
  388. /// </summary>
  389. /// <typeparam name="T"></typeparam>
  390. /// <param name="func">The func.</param>
  391. protected void RegisterSingleInstance<T>(Func<T> func)
  392. where T : class
  393. {
  394. Container.RegisterSingle(func);
  395. }
  396. /// <summary>
  397. /// Resolves this instance.
  398. /// </summary>
  399. /// <typeparam name="T"></typeparam>
  400. /// <returns>``0.</returns>
  401. public T Resolve<T>()
  402. {
  403. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  404. }
  405. /// <summary>
  406. /// Resolves this instance.
  407. /// </summary>
  408. /// <typeparam name="T"></typeparam>
  409. /// <returns>``0.</returns>
  410. public T TryResolve<T>()
  411. {
  412. var result = Container.GetRegistration(typeof(T), false);
  413. if (result == null)
  414. {
  415. return default(T);
  416. }
  417. return (T)result.GetInstance();
  418. }
  419. /// <summary>
  420. /// Loads the assembly.
  421. /// </summary>
  422. /// <param name="file">The file.</param>
  423. /// <returns>Assembly.</returns>
  424. protected Assembly LoadAssembly(string file)
  425. {
  426. try
  427. {
  428. return Assembly.Load(File.ReadAllBytes((file)));
  429. }
  430. catch (Exception ex)
  431. {
  432. FailedAssemblies.Add(file);
  433. Logger.ErrorException("Error loading assembly {0}", ex, file);
  434. return null;
  435. }
  436. }
  437. /// <summary>
  438. /// Gets the export types.
  439. /// </summary>
  440. /// <typeparam name="T"></typeparam>
  441. /// <returns>IEnumerable{Type}.</returns>
  442. public IEnumerable<Type> GetExportTypes<T>()
  443. {
  444. var currentType = typeof(T);
  445. return AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom);
  446. }
  447. /// <summary>
  448. /// Gets the exports.
  449. /// </summary>
  450. /// <typeparam name="T"></typeparam>
  451. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  452. /// <returns>IEnumerable{``0}.</returns>
  453. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  454. {
  455. var parts = GetExportTypes<T>()
  456. .Select(CreateInstanceSafe)
  457. .Where(i => i != null)
  458. .Cast<T>()
  459. .ToList();
  460. if (manageLiftime)
  461. {
  462. lock (DisposableParts)
  463. {
  464. DisposableParts.AddRange(parts.OfType<IDisposable>());
  465. }
  466. }
  467. return parts;
  468. }
  469. /// <summary>
  470. /// Gets the current application version
  471. /// </summary>
  472. /// <value>The application version.</value>
  473. public Version ApplicationVersion
  474. {
  475. get
  476. {
  477. return GetType().Assembly.GetName().Version;
  478. }
  479. }
  480. /// <summary>
  481. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  482. /// </summary>
  483. /// <param name="sender">The source of the event.</param>
  484. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  485. /// <exception cref="System.NotImplementedException"></exception>
  486. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  487. {
  488. ConfigureAutorun();
  489. }
  490. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  491. /// <summary>
  492. /// Removes the plugin.
  493. /// </summary>
  494. /// <param name="plugin">The plugin.</param>
  495. public void RemovePlugin(IPlugin plugin)
  496. {
  497. var list = Plugins.ToList();
  498. list.Remove(plugin);
  499. Plugins = list;
  500. }
  501. /// <summary>
  502. /// Gets a value indicating whether this instance can self restart.
  503. /// </summary>
  504. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  505. public abstract bool CanSelfRestart { get; }
  506. /// <summary>
  507. /// Notifies that the kernel that a change has been made that requires a restart
  508. /// </summary>
  509. public void NotifyPendingRestart()
  510. {
  511. HasPendingRestart = true;
  512. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  513. }
  514. /// <summary>
  515. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  516. /// </summary>
  517. public void Dispose()
  518. {
  519. Dispose(true);
  520. }
  521. /// <summary>
  522. /// Releases unmanaged and - optionally - managed resources.
  523. /// </summary>
  524. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  525. protected virtual void Dispose(bool dispose)
  526. {
  527. if (dispose)
  528. {
  529. var type = GetType();
  530. Logger.Info("Disposing " + type.Name);
  531. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  532. DisposableParts.Clear();
  533. foreach (var part in parts)
  534. {
  535. Logger.Info("Disposing " + part.GetType().Name);
  536. part.Dispose();
  537. }
  538. }
  539. }
  540. /// <summary>
  541. /// Restarts this instance.
  542. /// </summary>
  543. public abstract Task Restart();
  544. /// <summary>
  545. /// Gets or sets a value indicating whether this instance can self update.
  546. /// </summary>
  547. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  548. public abstract bool CanSelfUpdate { get; }
  549. /// <summary>
  550. /// Checks for update.
  551. /// </summary>
  552. /// <param name="cancellationToken">The cancellation token.</param>
  553. /// <param name="progress">The progress.</param>
  554. /// <returns>Task{CheckForUpdateResult}.</returns>
  555. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  556. IProgress<double> progress);
  557. /// <summary>
  558. /// Updates the application.
  559. /// </summary>
  560. /// <param name="package">The package that contains the update</param>
  561. /// <param name="cancellationToken">The cancellation token.</param>
  562. /// <param name="progress">The progress.</param>
  563. /// <returns>Task.</returns>
  564. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  565. IProgress<double> progress);
  566. /// <summary>
  567. /// Shuts down.
  568. /// </summary>
  569. public abstract Task Shutdown();
  570. /// <summary>
  571. /// Called when [application updated].
  572. /// </summary>
  573. /// <param name="newVersion">The new version.</param>
  574. protected void OnApplicationUpdated(Version newVersion)
  575. {
  576. Logger.Info("Application has been updated to version {0}", newVersion);
  577. EventHelper.QueueEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<Version> { Argument = newVersion }, Logger);
  578. NotifyPendingRestart();
  579. }
  580. }
  581. }