BaseApplicationHost.cs 23 KB

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