ApplicationHost.cs 17 KB

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