SetupServer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Emby.Server.Implementations.Configuration;
  8. using Emby.Server.Implementations.Serialization;
  9. using Jellyfin.Networking.Manager;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Model.System;
  14. using Microsoft.AspNetCore.Builder;
  15. using Microsoft.AspNetCore.Hosting;
  16. using Microsoft.AspNetCore.Http;
  17. using Microsoft.Extensions.Configuration;
  18. using Microsoft.Extensions.DependencyInjection;
  19. using Microsoft.Extensions.Diagnostics.HealthChecks;
  20. using Microsoft.Extensions.Hosting;
  21. using Microsoft.Extensions.Logging;
  22. using Microsoft.Extensions.Primitives;
  23. namespace Jellyfin.Server.ServerSetupApp;
  24. /// <summary>
  25. /// Creates a fake application pipeline that will only exist for as long as the main app is not started.
  26. /// </summary>
  27. public sealed class SetupServer : IDisposable
  28. {
  29. private readonly Func<INetworkManager?> _networkManagerFactory;
  30. private readonly IApplicationPaths _applicationPaths;
  31. private readonly Func<IServerApplicationHost?> _serverFactory;
  32. private readonly ILoggerFactory _loggerFactory;
  33. private readonly IConfiguration _startupConfiguration;
  34. private readonly ServerConfigurationManager _configurationManager;
  35. private IHost? _startupServer;
  36. private bool _disposed;
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="SetupServer"/> class.
  39. /// </summary>
  40. /// <param name="networkManagerFactory">The networkmanager.</param>
  41. /// <param name="applicationPaths">The application paths.</param>
  42. /// <param name="serverApplicationHostFactory">The servers application host.</param>
  43. /// <param name="loggerFactory">The logger factory.</param>
  44. /// <param name="startupConfiguration">The startup configuration.</param>
  45. public SetupServer(
  46. Func<INetworkManager?> networkManagerFactory,
  47. IApplicationPaths applicationPaths,
  48. Func<IServerApplicationHost?> serverApplicationHostFactory,
  49. ILoggerFactory loggerFactory,
  50. IConfiguration startupConfiguration)
  51. {
  52. _networkManagerFactory = networkManagerFactory;
  53. _applicationPaths = applicationPaths;
  54. _serverFactory = serverApplicationHostFactory;
  55. _loggerFactory = loggerFactory;
  56. _startupConfiguration = startupConfiguration;
  57. var xmlSerializer = new MyXmlSerializer();
  58. _configurationManager = new ServerConfigurationManager(_applicationPaths, loggerFactory, xmlSerializer);
  59. _configurationManager.RegisterConfiguration<NetworkConfigurationFactory>();
  60. }
  61. /// <summary>
  62. /// Starts the Bind-All Setup aspcore server to provide a reflection on the current core setup.
  63. /// </summary>
  64. /// <returns>A Task.</returns>
  65. public async Task RunAsync()
  66. {
  67. ThrowIfDisposed();
  68. _startupServer = Host.CreateDefaultBuilder()
  69. .UseConsoleLifetime()
  70. .ConfigureServices(serv =>
  71. {
  72. serv.AddHealthChecks()
  73. .AddCheck<SetupHealthcheck>("StartupCheck");
  74. })
  75. .ConfigureWebHostDefaults(webHostBuilder =>
  76. {
  77. webHostBuilder
  78. .UseKestrel((builderContext, options) =>
  79. {
  80. var config = _configurationManager.GetNetworkConfiguration()!;
  81. var knownBindInterfaces = NetworkManager.GetInterfacesCore(_loggerFactory.CreateLogger<SetupServer>(), config.EnableIPv4, config.EnableIPv6);
  82. knownBindInterfaces = NetworkManager.FilterBindSettings(config, knownBindInterfaces.ToList(), config.EnableIPv4, config.EnableIPv6);
  83. var bindInterfaces = NetworkManager.GetAllBindInterfaces(false, _configurationManager, knownBindInterfaces, config.EnableIPv4, config.EnableIPv6);
  84. Extensions.WebHostBuilderExtensions.SetupJellyfinWebServer(
  85. bindInterfaces,
  86. config.InternalHttpPort,
  87. null,
  88. null,
  89. _startupConfiguration,
  90. _applicationPaths,
  91. _loggerFactory.CreateLogger<SetupServer>(),
  92. builderContext,
  93. options);
  94. })
  95. .Configure(app =>
  96. {
  97. app.UseHealthChecks("/health");
  98. app.Map("/startup/logger", loggerRoute =>
  99. {
  100. loggerRoute.Run(async context =>
  101. {
  102. var networkManager = _networkManagerFactory();
  103. if (context.Connection.RemoteIpAddress is null || networkManager is null || !networkManager.IsInLocalNetwork(context.Connection.RemoteIpAddress))
  104. {
  105. context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
  106. return;
  107. }
  108. var logFilePath = new DirectoryInfo(_applicationPaths.LogDirectoryPath)
  109. .EnumerateFiles()
  110. .OrderByDescending(f => f.CreationTimeUtc)
  111. .FirstOrDefault()
  112. ?.FullName;
  113. if (logFilePath is not null)
  114. {
  115. await context.Response.SendFileAsync(logFilePath, CancellationToken.None).ConfigureAwait(false);
  116. }
  117. });
  118. });
  119. app.Map("/System/Info/Public", systemRoute =>
  120. {
  121. systemRoute.Run(async context =>
  122. {
  123. var jfApplicationHost = _serverFactory();
  124. var retryCounter = 0;
  125. while (jfApplicationHost is null && retryCounter < 5)
  126. {
  127. await Task.Delay(500).ConfigureAwait(false);
  128. jfApplicationHost = _serverFactory();
  129. retryCounter++;
  130. }
  131. if (jfApplicationHost is null)
  132. {
  133. context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
  134. context.Response.Headers.RetryAfter = new StringValues("5");
  135. return;
  136. }
  137. var sysInfo = new PublicSystemInfo
  138. {
  139. Version = jfApplicationHost.ApplicationVersionString,
  140. ProductName = jfApplicationHost.Name,
  141. Id = jfApplicationHost.SystemId,
  142. ServerName = jfApplicationHost.FriendlyName,
  143. LocalAddress = jfApplicationHost.GetSmartApiUrl(context.Request),
  144. StartupWizardCompleted = false
  145. };
  146. await context.Response.WriteAsJsonAsync(sysInfo).ConfigureAwait(false);
  147. });
  148. });
  149. app.Run((context) =>
  150. {
  151. context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
  152. context.Response.Headers.RetryAfter = new StringValues("5");
  153. context.Response.Headers.ContentType = new StringValues("text/html");
  154. context.Response.WriteAsync("<p>Jellyfin Server still starting. Please wait.</p>");
  155. var networkManager = _networkManagerFactory();
  156. if (networkManager is not null && context.Connection.RemoteIpAddress is not null && networkManager.IsInLocalNetwork(context.Connection.RemoteIpAddress))
  157. {
  158. context.Response.WriteAsync("<p>You can download the current logfiles <a href='/startup/logger'>here</a>.</p>");
  159. }
  160. return Task.CompletedTask;
  161. });
  162. });
  163. })
  164. .Build();
  165. await _startupServer.StartAsync().ConfigureAwait(false);
  166. }
  167. /// <summary>
  168. /// Stops the Setup server.
  169. /// </summary>
  170. /// <returns>A task. Duh.</returns>
  171. public async Task StopAsync()
  172. {
  173. ThrowIfDisposed();
  174. if (_startupServer is null)
  175. {
  176. throw new InvalidOperationException("Tried to stop a non existing startup server");
  177. }
  178. await _startupServer.StopAsync().ConfigureAwait(false);
  179. }
  180. /// <inheritdoc/>
  181. public void Dispose()
  182. {
  183. if (_disposed)
  184. {
  185. return;
  186. }
  187. _disposed = true;
  188. _startupServer?.Dispose();
  189. }
  190. private void ThrowIfDisposed()
  191. {
  192. ObjectDisposedException.ThrowIf(_disposed, this);
  193. }
  194. private class SetupHealthcheck : IHealthCheck
  195. {
  196. public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
  197. {
  198. return Task.FromResult(HealthCheckResult.Degraded("Server is still starting up."));
  199. }
  200. }
  201. }