SetupServer.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Common.Net;
  9. using MediaBrowser.Controller;
  10. using MediaBrowser.Model.System;
  11. using Microsoft.AspNetCore.Builder;
  12. using Microsoft.AspNetCore.Hosting;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.Extensions.DependencyInjection;
  15. using Microsoft.Extensions.Diagnostics.HealthChecks;
  16. using Microsoft.Extensions.Hosting;
  17. namespace Jellyfin.Server.ServerSetupApp;
  18. /// <summary>
  19. /// Creates a fake application pipeline that will only exist for as long as the main app is not started.
  20. /// </summary>
  21. public sealed class SetupServer : IDisposable
  22. {
  23. private IHost? _startupServer;
  24. private bool _disposed;
  25. /// <summary>
  26. /// Starts the Bind-All Setup aspcore server to provide a reflection on the current core setup.
  27. /// </summary>
  28. /// <param name="networkManagerFactory">The networkmanager.</param>
  29. /// <param name="applicationPaths">The application paths.</param>
  30. /// <param name="serverApplicationHost">The servers application host.</param>
  31. /// <returns>A Task.</returns>
  32. public async Task RunAsync(
  33. Func<INetworkManager?> networkManagerFactory,
  34. IApplicationPaths applicationPaths,
  35. Func<IServerApplicationHost?> serverApplicationHost)
  36. {
  37. ThrowIfDisposed();
  38. _startupServer = Host.CreateDefaultBuilder()
  39. .UseConsoleLifetime()
  40. .ConfigureServices(serv =>
  41. {
  42. serv.AddHealthChecks()
  43. .AddCheck<SetupHealthcheck>("StartupCheck");
  44. })
  45. .ConfigureWebHostDefaults(webHostBuilder =>
  46. {
  47. webHostBuilder
  48. .UseKestrel()
  49. .Configure(app =>
  50. {
  51. app.UseHealthChecks("/health");
  52. app.Map("/startup/logger", loggerRoute =>
  53. {
  54. loggerRoute.Run(async context =>
  55. {
  56. var networkManager = networkManagerFactory();
  57. if (context.Connection.RemoteIpAddress is null || networkManager is null || !networkManager.IsInLocalNetwork(context.Connection.RemoteIpAddress))
  58. {
  59. context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
  60. return;
  61. }
  62. var logFilePath = new DirectoryInfo(applicationPaths.LogDirectoryPath)
  63. .EnumerateFiles()
  64. .OrderBy(f => f.CreationTimeUtc)
  65. .FirstOrDefault()
  66. ?.FullName;
  67. if (logFilePath is not null)
  68. {
  69. await context.Response.SendFileAsync(logFilePath, CancellationToken.None).ConfigureAwait(false);
  70. }
  71. });
  72. });
  73. app.Map("/System/Info/Public", systemRoute =>
  74. {
  75. systemRoute.Run(async context =>
  76. {
  77. var jfApplicationHost = serverApplicationHost();
  78. var retryCounter = 0;
  79. while (jfApplicationHost is null && retryCounter < 5)
  80. {
  81. await Task.Delay(500).ConfigureAwait(false);
  82. jfApplicationHost = serverApplicationHost();
  83. retryCounter++;
  84. }
  85. if (jfApplicationHost is null)
  86. {
  87. context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
  88. context.Response.Headers.RetryAfter = new Microsoft.Extensions.Primitives.StringValues("60");
  89. return;
  90. }
  91. var sysInfo = new PublicSystemInfo
  92. {
  93. Version = jfApplicationHost.ApplicationVersionString,
  94. ProductName = jfApplicationHost.Name,
  95. Id = jfApplicationHost.SystemId,
  96. ServerName = jfApplicationHost.FriendlyName,
  97. LocalAddress = jfApplicationHost.GetSmartApiUrl(context.Request),
  98. StartupWizardCompleted = false
  99. };
  100. await context.Response.WriteAsJsonAsync(sysInfo).ConfigureAwait(false);
  101. });
  102. });
  103. app.Run((context) =>
  104. {
  105. context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
  106. context.Response.Headers.RetryAfter = new Microsoft.Extensions.Primitives.StringValues("60");
  107. context.Response.WriteAsync("<p>Jellyfin Server still starting. Please wait.</p>");
  108. var networkManager = networkManagerFactory();
  109. if (networkManager is not null && context.Connection.RemoteIpAddress is not null && networkManager.IsInLocalNetwork(context.Connection.RemoteIpAddress))
  110. {
  111. context.Response.WriteAsync("<p>You can download the current logfiles <a href='/startup/logger'>here</a>.</p>");
  112. }
  113. return Task.CompletedTask;
  114. });
  115. });
  116. })
  117. .Build();
  118. await _startupServer.StartAsync().ConfigureAwait(false);
  119. }
  120. /// <summary>
  121. /// Stops the Setup server.
  122. /// </summary>
  123. /// <returns>A task. Duh.</returns>
  124. public async Task StopAsync()
  125. {
  126. ThrowIfDisposed();
  127. if (_startupServer is null)
  128. {
  129. throw new InvalidOperationException("Tried to stop a non existing startup server");
  130. }
  131. await _startupServer.StopAsync().ConfigureAwait(false);
  132. }
  133. /// <inheritdoc/>
  134. public void Dispose()
  135. {
  136. if (_disposed)
  137. {
  138. return;
  139. }
  140. _disposed = true;
  141. _startupServer?.Dispose();
  142. }
  143. private void ThrowIfDisposed()
  144. {
  145. ObjectDisposedException.ThrowIf(_disposed, this);
  146. }
  147. private class SetupHealthcheck : IHealthCheck
  148. {
  149. public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
  150. {
  151. return Task.FromResult(HealthCheckResult.Degraded("Server is still starting up."));
  152. }
  153. }
  154. }