BaseApplicationHost.cs 21 KB

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