BaseApplicationHost.cs 13 KB

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