BaseApplicationHost.cs 16 KB

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