BaseApplicationHost.cs 20 KB

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