ApplicationHost.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. using BDInfo;
  2. using MediaBrowser.ClickOnce;
  3. using MediaBrowser.Common.Implementations.ScheduledTasks;
  4. using MediaBrowser.Common.Implementations.Serialization;
  5. using MediaBrowser.Common.IO;
  6. using MediaBrowser.Common.Kernel;
  7. using MediaBrowser.Common.Net;
  8. using MediaBrowser.Common.ScheduledTasks;
  9. using MediaBrowser.Controller;
  10. using MediaBrowser.IsoMounter;
  11. using MediaBrowser.Logging.Nlog;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.Logging;
  14. using MediaBrowser.Model.MediaInfo;
  15. using MediaBrowser.Model.Serialization;
  16. using MediaBrowser.Model.System;
  17. using MediaBrowser.Model.Updates;
  18. using MediaBrowser.Networking.HttpManager;
  19. using MediaBrowser.Networking.HttpServer;
  20. using MediaBrowser.Networking.Management;
  21. using MediaBrowser.Networking.Udp;
  22. using MediaBrowser.Networking.WebSocket;
  23. using MediaBrowser.Server.Implementations;
  24. using MediaBrowser.ServerApplication.Implementations;
  25. using SimpleInjector;
  26. using System;
  27. using System.Collections.Generic;
  28. using System.Diagnostics;
  29. using System.IO;
  30. using System.Linq;
  31. using System.Reflection;
  32. using System.Threading;
  33. using System.Threading.Tasks;
  34. namespace MediaBrowser.ServerApplication
  35. {
  36. /// <summary>
  37. /// Class CompositionRoot
  38. /// </summary>
  39. public class ApplicationHost : IApplicationHost, IDisposable
  40. {
  41. /// <summary>
  42. /// Gets or sets the logger.
  43. /// </summary>
  44. /// <value>The logger.</value>
  45. private ILogger Logger { get; set; }
  46. /// <summary>
  47. /// Gets or sets the log file path.
  48. /// </summary>
  49. /// <value>The log file path.</value>
  50. public string LogFilePath { get; private set; }
  51. /// <summary>
  52. /// The container
  53. /// </summary>
  54. private readonly Container _container = new Container();
  55. /// <summary>
  56. /// Gets or sets the kernel.
  57. /// </summary>
  58. /// <value>The kernel.</value>
  59. public Kernel Kernel { get; private set; }
  60. private readonly List<string> _failedAssemblies = new List<string>();
  61. /// <summary>
  62. /// Gets assemblies that failed to load
  63. /// </summary>
  64. public IEnumerable<string> FailedAssemblies
  65. {
  66. get { return _failedAssemblies; }
  67. }
  68. /// <summary>
  69. /// Gets all types within all running assemblies
  70. /// </summary>
  71. /// <value>All types.</value>
  72. public Type[] AllTypes { get; private set; }
  73. /// <summary>
  74. /// Gets all concrete types.
  75. /// </summary>
  76. /// <value>All concrete types.</value>
  77. public Type[] AllConcreteTypes { get; private set; }
  78. /// <summary>
  79. /// The disposable parts
  80. /// </summary>
  81. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  82. /// <summary>
  83. /// The json serializer
  84. /// </summary>
  85. private readonly IJsonSerializer _jsonSerializer = new JsonSerializer();
  86. /// <summary>
  87. /// The _XML serializer
  88. /// </summary>
  89. private readonly IXmlSerializer _xmlSerializer = new XmlSerializer();
  90. /// <summary>
  91. /// The _application paths
  92. /// </summary>
  93. private readonly IServerApplicationPaths _applicationPaths = new ServerApplicationPaths();
  94. /// <summary>
  95. /// The _task manager
  96. /// </summary>
  97. private readonly ITaskManager _taskManager;
  98. /// <summary>
  99. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  100. /// </summary>
  101. /// <param name="logger">The logger.</param>
  102. public ApplicationHost(ILogger logger)
  103. {
  104. Logger = logger;
  105. _taskManager = new TaskManager(_applicationPaths, _jsonSerializer, Logger);
  106. Kernel = new Kernel(this, _applicationPaths, _xmlSerializer, _taskManager, Logger);
  107. RegisterResources();
  108. FindParts();
  109. }
  110. /// <summary>
  111. /// Registers resources that classes will depend on
  112. /// </summary>
  113. internal void RegisterResources()
  114. {
  115. DiscoverTypes();
  116. RegisterSingleInstance<IKernel>(Kernel);
  117. RegisterSingleInstance(Kernel);
  118. RegisterSingleInstance<IApplicationHost>(this);
  119. RegisterSingleInstance(Logger);
  120. RegisterSingleInstance(_applicationPaths);
  121. RegisterSingleInstance<IApplicationPaths>(_applicationPaths);
  122. RegisterSingleInstance(_taskManager);
  123. RegisterSingleInstance<IIsoManager>(() => new PismoIsoManager(Logger));
  124. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  125. RegisterSingleInstance<IHttpClient>(() => new HttpManager(_applicationPaths, Logger));
  126. RegisterSingleInstance<INetworkManager>(() => new NetworkManager());
  127. RegisterSingleInstance<IZipClient>(() => new DotNetZipClient());
  128. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  129. RegisterSingleInstance(_jsonSerializer);
  130. RegisterSingleInstance(_xmlSerializer);
  131. RegisterSingleInstance<IProtobufSerializer>(() => ProtobufSerializer);
  132. Register(typeof(IUdpServer), typeof(UdpServer));
  133. RegisterSingleInstance(() => ServerFactory.CreateServer(this, Kernel, ProtobufSerializer, Logger, "Media Browser", "index.html"));
  134. }
  135. /// <summary>
  136. /// Discovers the types.
  137. /// </summary>
  138. private void DiscoverTypes()
  139. {
  140. _failedAssemblies.Clear();
  141. AllTypes = GetComposablePartAssemblies().SelectMany(GetTypes).ToArray();
  142. AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
  143. }
  144. /// <summary>
  145. /// Finds the parts.
  146. /// </summary>
  147. private void FindParts()
  148. {
  149. _taskManager.AddTasks(GetExports<IScheduledTask>(false));
  150. }
  151. /// <summary>
  152. /// Gets a list of types within an assembly
  153. /// 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
  154. /// </summary>
  155. /// <param name="assembly">The assembly.</param>
  156. /// <returns>IEnumerable{Type}.</returns>
  157. /// <exception cref="System.ArgumentNullException">assembly</exception>
  158. private IEnumerable<Type> GetTypes(Assembly assembly)
  159. {
  160. if (assembly == null)
  161. {
  162. throw new ArgumentNullException("assembly");
  163. }
  164. try
  165. {
  166. return assembly.GetTypes();
  167. }
  168. catch (ReflectionTypeLoadException ex)
  169. {
  170. // If it fails we can still get a list of the Types it was able to resolve
  171. return ex.Types.Where(t => t != null);
  172. }
  173. }
  174. /// <summary>
  175. /// The _protobuf serializer initialized
  176. /// </summary>
  177. private bool _protobufSerializerInitialized;
  178. /// <summary>
  179. /// The _protobuf serializer sync lock
  180. /// </summary>
  181. private object _protobufSerializerSyncLock = new object();
  182. /// <summary>
  183. /// Gets a dynamically compiled generated serializer that can serialize protocontracts without reflection
  184. /// </summary>
  185. private ProtobufSerializer _protobufSerializer;
  186. /// <summary>
  187. /// Gets the protobuf serializer.
  188. /// </summary>
  189. /// <value>The protobuf serializer.</value>
  190. public ProtobufSerializer ProtobufSerializer
  191. {
  192. get
  193. {
  194. // Lazy load
  195. LazyInitializer.EnsureInitialized(ref _protobufSerializer, ref _protobufSerializerInitialized, ref _protobufSerializerSyncLock, () => ProtobufSerializer.Create(AllTypes));
  196. return _protobufSerializer;
  197. }
  198. private set
  199. {
  200. _protobufSerializer = value;
  201. _protobufSerializerInitialized = value != null;
  202. }
  203. }
  204. /// <summary>
  205. /// Creates an instance of type and resolves all constructor dependancies
  206. /// </summary>
  207. /// <param name="type">The type.</param>
  208. /// <returns>System.Object.</returns>
  209. public object CreateInstance(Type type)
  210. {
  211. try
  212. {
  213. return _container.GetInstance(type);
  214. }
  215. catch
  216. {
  217. Logger.Error("Error creating {0}", type.Name);
  218. throw;
  219. }
  220. }
  221. /// <summary>
  222. /// Registers the specified obj.
  223. /// </summary>
  224. /// <typeparam name="T"></typeparam>
  225. /// <param name="obj">The obj.</param>
  226. public void RegisterSingleInstance<T>(T obj)
  227. where T : class
  228. {
  229. _container.RegisterSingle(obj);
  230. }
  231. /// <summary>
  232. /// Registers the specified func.
  233. /// </summary>
  234. /// <typeparam name="T"></typeparam>
  235. /// <param name="func">The func.</param>
  236. public void Register<T>(Func<T> func)
  237. where T : class
  238. {
  239. _container.Register(func);
  240. }
  241. /// <summary>
  242. /// Registers the single instance.
  243. /// </summary>
  244. /// <typeparam name="T"></typeparam>
  245. /// <param name="func">The func.</param>
  246. public void RegisterSingleInstance<T>(Func<T> func)
  247. where T : class
  248. {
  249. _container.RegisterSingle(func);
  250. }
  251. /// <summary>
  252. /// Resolves this instance.
  253. /// </summary>
  254. /// <typeparam name="T"></typeparam>
  255. /// <returns>``0.</returns>
  256. public T Resolve<T>()
  257. {
  258. return (T)_container.GetRegistration(typeof(T), true).GetInstance();
  259. }
  260. /// <summary>
  261. /// Resolves this instance.
  262. /// </summary>
  263. /// <typeparam name="T"></typeparam>
  264. /// <returns>``0.</returns>
  265. public T TryResolve<T>()
  266. {
  267. var result = _container.GetRegistration(typeof(T), false);
  268. if (result == null)
  269. {
  270. return default(T);
  271. }
  272. return (T)result.GetInstance();
  273. }
  274. /// <summary>
  275. /// Registers the specified service type.
  276. /// </summary>
  277. /// <param name="serviceType">Type of the service.</param>
  278. /// <param name="implementation">Type of the concrete.</param>
  279. public void Register(Type serviceType, Type implementation)
  280. {
  281. _container.Register(serviceType, implementation);
  282. }
  283. /// <summary>
  284. /// Restarts this instance.
  285. /// </summary>
  286. /// <exception cref="System.NotImplementedException"></exception>
  287. public void Restart()
  288. {
  289. App.Instance.Restart();
  290. }
  291. /// <summary>
  292. /// Reloads the logger.
  293. /// </summary>
  294. /// <exception cref="System.NotImplementedException"></exception>
  295. public void ReloadLogger()
  296. {
  297. LogFilePath = Path.Combine(Kernel.ApplicationPaths.LogDirectoryPath, "Server-" + DateTime.Now.Ticks + ".log");
  298. NlogManager.AddFileTarget(LogFilePath, Kernel.Configuration.EnableDebugLevelLogging);
  299. }
  300. /// <summary>
  301. /// Gets or sets a value indicating whether this instance can self update.
  302. /// </summary>
  303. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  304. public bool CanSelfUpdate
  305. {
  306. get { return ClickOnceHelper.IsNetworkDeployed; }
  307. }
  308. /// <summary>
  309. /// Checks for update.
  310. /// </summary>
  311. /// <param name="cancellationToken">The cancellation token.</param>
  312. /// <param name="progress">The progress.</param>
  313. /// <returns>Task{CheckForUpdateResult}.</returns>
  314. public Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  315. {
  316. return new ApplicationUpdateCheck().CheckForApplicationUpdate(cancellationToken, progress);
  317. }
  318. /// <summary>
  319. /// Updates the application.
  320. /// </summary>
  321. /// <param name="cancellationToken">The cancellation token.</param>
  322. /// <param name="progress">The progress.</param>
  323. /// <returns>Task.</returns>
  324. public Task UpdateApplication(CancellationToken cancellationToken, IProgress<double> progress)
  325. {
  326. return new ApplicationUpdater().UpdateApplication(cancellationToken, progress);
  327. }
  328. /// <summary>
  329. /// Gets the composable part assemblies.
  330. /// </summary>
  331. /// <returns>IEnumerable{Assembly}.</returns>
  332. private IEnumerable<Assembly> GetComposablePartAssemblies()
  333. {
  334. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  335. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  336. foreach (var pluginAssembly in Directory
  337. .EnumerateFiles(Kernel.ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  338. .Select(LoadAssembly).Where(a => a != null))
  339. {
  340. yield return pluginAssembly;
  341. }
  342. var runningDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
  343. var corePluginDirectory = Path.Combine(runningDirectory, "CorePlugins");
  344. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  345. foreach (var pluginAssembly in Directory
  346. .EnumerateFiles(corePluginDirectory, "*.dll", SearchOption.TopDirectoryOnly)
  347. .Select(LoadAssembly).Where(a => a != null))
  348. {
  349. yield return pluginAssembly;
  350. }
  351. // Include composable parts in the Model assembly
  352. yield return typeof(SystemInfo).Assembly;
  353. // Include composable parts in the Common assembly
  354. yield return typeof(IKernel).Assembly;
  355. // Include composable parts in the Controller assembly
  356. yield return typeof(Kernel).Assembly;
  357. // Common implementations
  358. yield return typeof(TaskManager).Assembly;
  359. // Server implementations
  360. yield return typeof(ServerApplicationPaths).Assembly;
  361. // Include composable parts in the running assembly
  362. yield return GetType().Assembly;
  363. }
  364. /// <summary>
  365. /// Loads the assembly.
  366. /// </summary>
  367. /// <param name="file">The file.</param>
  368. /// <returns>Assembly.</returns>
  369. private Assembly LoadAssembly(string file)
  370. {
  371. try
  372. {
  373. return Assembly.Load(File.ReadAllBytes((file)));
  374. }
  375. catch (Exception ex)
  376. {
  377. _failedAssemblies.Add(file);
  378. Logger.ErrorException("Error loading assembly {0}", ex, file);
  379. return null;
  380. }
  381. }
  382. /// <summary>
  383. /// Gets the exports.
  384. /// </summary>
  385. /// <typeparam name="T"></typeparam>
  386. /// <param name="allTypes">All types.</param>
  387. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  388. /// <returns>IEnumerable{``0}.</returns>
  389. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  390. {
  391. var currentType = typeof(T);
  392. Logger.Info("Composing instances of " + currentType.Name);
  393. var parts = AllConcreteTypes.Where(currentType.IsAssignableFrom).Select(CreateInstance).Cast<T>().ToArray();
  394. if (manageLiftime)
  395. {
  396. _disposableParts.AddRange(parts.OfType<IDisposable>());
  397. }
  398. return parts;
  399. }
  400. /// <summary>
  401. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  402. /// </summary>
  403. public void Dispose()
  404. {
  405. Dispose(true);
  406. }
  407. /// <summary>
  408. /// Releases unmanaged and - optionally - managed resources.
  409. /// </summary>
  410. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  411. protected virtual void Dispose(bool dispose)
  412. {
  413. foreach (var part in _disposableParts)
  414. {
  415. part.Dispose();
  416. }
  417. _disposableParts.Clear();
  418. }
  419. }
  420. }