BaseApplicationHost.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. LogManager.ReloadLogger(ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info);
  145. DiscoverTypes();
  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. var assemblies = GetComposablePartAssemblies().ToArray();
  183. foreach (var assembly in assemblies)
  184. {
  185. Logger.Info("Loading {0}", assembly.FullName);
  186. }
  187. AllTypes = assemblies.SelectMany(GetTypes).ToArray();
  188. AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
  189. }
  190. /// <summary>
  191. /// Registers resources that classes will depend on
  192. /// </summary>
  193. protected virtual Task RegisterResources()
  194. {
  195. return Task.Run(() =>
  196. {
  197. RegisterSingleInstance(ConfigurationManager);
  198. RegisterSingleInstance<IApplicationHost>(this);
  199. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  200. var networkManager = new NetworkManager();
  201. var serverManager = new ServerManager.ServerManager(this, Kernel, networkManager, JsonSerializer, Logger, ConfigurationManager);
  202. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger, serverManager);
  203. RegisterSingleInstance(JsonSerializer);
  204. RegisterSingleInstance(XmlSerializer);
  205. RegisterSingleInstance(LogManager);
  206. RegisterSingleInstance(Logger);
  207. RegisterSingleInstance(Kernel);
  208. RegisterSingleInstance(TaskManager);
  209. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  210. RegisterSingleInstance(ProtobufSerializer);
  211. RegisterSingleInstance<IUdpServer>(new UdpServer(Logger), false);
  212. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger);
  213. RegisterSingleInstance(HttpClient);
  214. RegisterSingleInstance<INetworkManager>(networkManager);
  215. RegisterSingleInstance<IServerManager>(serverManager);
  216. SecurityManager = new PluginSecurityManager(Kernel, HttpClient, JsonSerializer, ApplicationPaths);
  217. RegisterSingleInstance(SecurityManager);
  218. PackageManager = new PackageManager(SecurityManager, networkManager, HttpClient, ApplicationPaths, JsonSerializer, Logger);
  219. RegisterSingleInstance(PackageManager);
  220. });
  221. }
  222. /// <summary>
  223. /// Gets a list of types within an assembly
  224. /// 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
  225. /// </summary>
  226. /// <param name="assembly">The assembly.</param>
  227. /// <returns>IEnumerable{Type}.</returns>
  228. /// <exception cref="System.ArgumentNullException">assembly</exception>
  229. protected IEnumerable<Type> GetTypes(Assembly assembly)
  230. {
  231. if (assembly == null)
  232. {
  233. throw new ArgumentNullException("assembly");
  234. }
  235. try
  236. {
  237. return assembly.GetTypes();
  238. }
  239. catch (ReflectionTypeLoadException ex)
  240. {
  241. // If it fails we can still get a list of the Types it was able to resolve
  242. return ex.Types.Where(t => t != null);
  243. }
  244. }
  245. /// <summary>
  246. /// Creates an instance of type and resolves all constructor dependancies
  247. /// </summary>
  248. /// <param name="type">The type.</param>
  249. /// <returns>System.Object.</returns>
  250. public object CreateInstance(Type type)
  251. {
  252. try
  253. {
  254. return Container.GetInstance(type);
  255. }
  256. catch
  257. {
  258. Logger.Error("Error creating {0}", type.Name);
  259. throw;
  260. }
  261. }
  262. /// <summary>
  263. /// Registers the specified obj.
  264. /// </summary>
  265. /// <typeparam name="T"></typeparam>
  266. /// <param name="obj">The obj.</param>
  267. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  268. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  269. where T : class
  270. {
  271. Container.RegisterSingle(obj);
  272. if (manageLifetime)
  273. {
  274. var disposable = obj as IDisposable;
  275. if (disposable != null)
  276. {
  277. Logger.Info("Registering " + disposable.GetType().Name);
  278. DisposableParts.Add(disposable);
  279. }
  280. }
  281. }
  282. /// <summary>
  283. /// Registers the single instance.
  284. /// </summary>
  285. /// <typeparam name="T"></typeparam>
  286. /// <param name="func">The func.</param>
  287. protected void RegisterSingleInstance<T>(Func<T> func)
  288. where T : class
  289. {
  290. Container.RegisterSingle(func);
  291. }
  292. /// <summary>
  293. /// Resolves this instance.
  294. /// </summary>
  295. /// <typeparam name="T"></typeparam>
  296. /// <returns>``0.</returns>
  297. public T Resolve<T>()
  298. {
  299. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  300. }
  301. /// <summary>
  302. /// Resolves this instance.
  303. /// </summary>
  304. /// <typeparam name="T"></typeparam>
  305. /// <returns>``0.</returns>
  306. public T TryResolve<T>()
  307. {
  308. var result = Container.GetRegistration(typeof(T), false);
  309. if (result == null)
  310. {
  311. return default(T);
  312. }
  313. return (T)result.GetInstance();
  314. }
  315. /// <summary>
  316. /// Loads the assembly.
  317. /// </summary>
  318. /// <param name="file">The file.</param>
  319. /// <returns>Assembly.</returns>
  320. protected Assembly LoadAssembly(string file)
  321. {
  322. try
  323. {
  324. return Assembly.Load(File.ReadAllBytes((file)));
  325. }
  326. catch (Exception ex)
  327. {
  328. FailedAssemblies.Add(file);
  329. Logger.ErrorException("Error loading assembly {0}", ex, file);
  330. return null;
  331. }
  332. }
  333. /// <summary>
  334. /// Gets the exports.
  335. /// </summary>
  336. /// <typeparam name="T"></typeparam>
  337. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  338. /// <returns>IEnumerable{``0}.</returns>
  339. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  340. {
  341. var currentType = typeof(T);
  342. Logger.Info("Composing instances of " + currentType.Name);
  343. var parts = AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom).Select(CreateInstance).Cast<T>().ToArray();
  344. if (manageLiftime)
  345. {
  346. DisposableParts.AddRange(parts.OfType<IDisposable>());
  347. }
  348. return parts;
  349. }
  350. /// <summary>
  351. /// Gets the current application version
  352. /// </summary>
  353. /// <value>The application version.</value>
  354. public Version ApplicationVersion
  355. {
  356. get
  357. {
  358. return GetType().Assembly.GetName().Version;
  359. }
  360. }
  361. /// <summary>
  362. /// Configures the auto run at startup.
  363. /// </summary>
  364. private void ConfigureAutoRunAtStartup()
  365. {
  366. }
  367. /// <summary>
  368. /// Removes the plugin.
  369. /// </summary>
  370. /// <param name="plugin">The plugin.</param>
  371. public void RemovePlugin(IPlugin plugin)
  372. {
  373. var list = Plugins.ToList();
  374. list.Remove(plugin);
  375. Plugins = list;
  376. }
  377. /// <summary>
  378. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  379. /// </summary>
  380. public void Dispose()
  381. {
  382. Dispose(true);
  383. }
  384. /// <summary>
  385. /// Releases unmanaged and - optionally - managed resources.
  386. /// </summary>
  387. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  388. protected virtual void Dispose(bool dispose)
  389. {
  390. if (dispose)
  391. {
  392. var type = GetType();
  393. Logger.Info("Disposing " + type.Name);
  394. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  395. DisposableParts.Clear();
  396. foreach (var part in parts)
  397. {
  398. Logger.Info("Disposing " + part.GetType().Name);
  399. part.Dispose();
  400. }
  401. }
  402. }
  403. public abstract void Restart();
  404. public abstract bool CanSelfUpdate { get; }
  405. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress);
  406. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress);
  407. public abstract void Shutdown();
  408. }
  409. }