BaseApplicationHost.cs 22 KB

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