BaseApplicationHost.cs 18 KB

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