BaseApplicationHost.cs 13 KB

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