Program.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Threading.Tasks;
  8. using CommandLine;
  9. using Emby.Server.Implementations;
  10. using Jellyfin.Networking.Manager;
  11. using Jellyfin.Server.Extensions;
  12. using Jellyfin.Server.Helpers;
  13. using Jellyfin.Server.Implementations;
  14. using Jellyfin.Server.ServerSetupApp;
  15. using MediaBrowser.Common.Configuration;
  16. using MediaBrowser.Common.Net;
  17. using MediaBrowser.Controller;
  18. using Microsoft.AspNetCore.Hosting;
  19. using Microsoft.EntityFrameworkCore;
  20. using Microsoft.Extensions.Configuration;
  21. using Microsoft.Extensions.DependencyInjection;
  22. using Microsoft.Extensions.Hosting;
  23. using Microsoft.Extensions.Logging;
  24. using Microsoft.Extensions.Logging.Abstractions;
  25. using Serilog;
  26. using Serilog.Extensions.Logging;
  27. using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
  28. using ILogger = Microsoft.Extensions.Logging.ILogger;
  29. namespace Jellyfin.Server
  30. {
  31. /// <summary>
  32. /// Class containing the entry point of the application.
  33. /// </summary>
  34. public static class Program
  35. {
  36. /// <summary>
  37. /// The name of logging configuration file containing application defaults.
  38. /// </summary>
  39. public const string LoggingConfigFileDefault = "logging.default.json";
  40. /// <summary>
  41. /// The name of the logging configuration file containing the system-specific override settings.
  42. /// </summary>
  43. public const string LoggingConfigFileSystem = "logging.json";
  44. private static readonly SerilogLoggerFactory _loggerFactory = new SerilogLoggerFactory();
  45. private static SetupServer? _setupServer = new();
  46. private static IHost? _jfHost = null;
  47. private static long _startTimestamp;
  48. private static ILogger _logger = NullLogger.Instance;
  49. private static bool _restartOnShutdown;
  50. /// <summary>
  51. /// The entry point of the application.
  52. /// </summary>
  53. /// <param name="args">The command line arguments passed.</param>
  54. /// <returns><see cref="Task" />.</returns>
  55. public static Task Main(string[] args)
  56. {
  57. static Task ErrorParsingArguments(IEnumerable<Error> errors)
  58. {
  59. Environment.ExitCode = 1;
  60. return Task.CompletedTask;
  61. }
  62. // Parse the command line arguments and either start the app or exit indicating error
  63. return Parser.Default.ParseArguments<StartupOptions>(args)
  64. .MapResult(StartApp, ErrorParsingArguments);
  65. }
  66. private static async Task StartApp(StartupOptions options)
  67. {
  68. _startTimestamp = Stopwatch.GetTimestamp();
  69. ServerApplicationPaths appPaths = StartupHelpers.CreateApplicationPaths(options);
  70. await _setupServer!.RunAsync(static () => _jfHost?.Services?.GetService<INetworkManager>(), appPaths).ConfigureAwait(false);
  71. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  72. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  73. // Enable cl-va P010 interop for tonemapping on Intel VAAPI
  74. Environment.SetEnvironmentVariable("NEOReadDebugKeys", "1");
  75. Environment.SetEnvironmentVariable("EnableExtendedVaFormats", "1");
  76. await StartupHelpers.InitLoggingConfigFile(appPaths).ConfigureAwait(false);
  77. // Create an instance of the application configuration to use for application startup
  78. IConfiguration startupConfig = CreateAppConfiguration(options, appPaths);
  79. StartupHelpers.InitializeLoggingFramework(startupConfig, appPaths);
  80. _logger = _loggerFactory.CreateLogger("Main");
  81. // Use the logging framework for uncaught exceptions instead of std error
  82. AppDomain.CurrentDomain.UnhandledException += (_, e)
  83. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  84. _logger.LogInformation(
  85. "Jellyfin version: {Version}",
  86. Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
  87. StartupHelpers.LogEnvironmentInfo(_logger, appPaths);
  88. // If hosting the web client, validate the client content path
  89. if (startupConfig.HostWebClient())
  90. {
  91. var webContentPath = appPaths.WebPath;
  92. if (!Directory.Exists(webContentPath) || !Directory.EnumerateFiles(webContentPath).Any())
  93. {
  94. _logger.LogError(
  95. "The server is expected to host the web client, but the provided content directory is either " +
  96. "invalid or empty: {WebContentPath}. If you do not want to host the web client with the " +
  97. "server, you may set the '--nowebclient' command line flag, or set" +
  98. "'{ConfigKey}=false' in your config settings",
  99. webContentPath,
  100. HostWebClientKey);
  101. Environment.ExitCode = 1;
  102. return;
  103. }
  104. }
  105. StartupHelpers.PerformStaticInitialization();
  106. Migrations.MigrationRunner.RunPreStartup(appPaths, _loggerFactory);
  107. do
  108. {
  109. await StartServer(appPaths, options, startupConfig).ConfigureAwait(false);
  110. if (_restartOnShutdown)
  111. {
  112. _startTimestamp = Stopwatch.GetTimestamp();
  113. _setupServer = new SetupServer();
  114. await _setupServer.RunAsync(static () => _jfHost?.Services?.GetService<INetworkManager>(), appPaths).ConfigureAwait(false);
  115. }
  116. } while (_restartOnShutdown);
  117. }
  118. private static async Task StartServer(IServerApplicationPaths appPaths, StartupOptions options, IConfiguration startupConfig)
  119. {
  120. using var appHost = new CoreAppHost(
  121. appPaths,
  122. _loggerFactory,
  123. options,
  124. startupConfig);
  125. try
  126. {
  127. _jfHost = Host.CreateDefaultBuilder()
  128. .UseConsoleLifetime()
  129. .ConfigureServices(services => appHost.Init(services))
  130. .ConfigureWebHostDefaults(webHostBuilder =>
  131. {
  132. webHostBuilder.ConfigureWebHostBuilder(appHost, startupConfig, appPaths, _logger);
  133. if (bool.TryParse(Environment.GetEnvironmentVariable("JELLYFIN_ENABLE_IIS"), out var iisEnabled) && iisEnabled)
  134. {
  135. _logger.LogCritical("UNSUPPORTED HOSTING ENVIRONMENT Microsoft Internet Information Services. The option to run Jellyfin on IIS is an unsupported and untested feature. Only use at your own discretion.");
  136. webHostBuilder.UseIIS();
  137. }
  138. })
  139. .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(options, appPaths, startupConfig))
  140. .UseSerilog()
  141. .Build();
  142. // Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collection.
  143. appHost.ServiceProvider = _jfHost.Services;
  144. await appHost.InitializeServices().ConfigureAwait(false);
  145. Migrations.MigrationRunner.Run(appHost, _loggerFactory);
  146. try
  147. {
  148. await Task.Delay(50000).ConfigureAwait(false);
  149. await _setupServer!.StopAsync().ConfigureAwait(false);
  150. _setupServer.Dispose();
  151. _setupServer = null!;
  152. await _jfHost.StartAsync().ConfigureAwait(false);
  153. if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
  154. {
  155. var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
  156. StartupHelpers.SetUnixSocketPermissions(startupConfig, socketPath, _logger);
  157. }
  158. }
  159. catch (Exception)
  160. {
  161. _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in network.xml and try again");
  162. throw;
  163. }
  164. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  165. _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(_startTimestamp));
  166. await _jfHost.WaitForShutdownAsync().ConfigureAwait(false);
  167. _restartOnShutdown = appHost.ShouldRestart;
  168. }
  169. catch (Exception ex)
  170. {
  171. _restartOnShutdown = false;
  172. _logger.LogCritical(ex, "Error while starting server");
  173. }
  174. finally
  175. {
  176. // Don't throw additional exception if startup failed.
  177. if (appHost.ServiceProvider is not null)
  178. {
  179. _logger.LogInformation("Running query planner optimizations in the database... This might take a while");
  180. // Run before disposing the application
  181. var context = await appHost.ServiceProvider.GetRequiredService<IDbContextFactory<JellyfinDbContext>>().CreateDbContextAsync().ConfigureAwait(false);
  182. await using (context.ConfigureAwait(false))
  183. {
  184. if (context.Database.IsSqlite())
  185. {
  186. await context.Database.ExecuteSqlRawAsync("PRAGMA optimize").ConfigureAwait(false);
  187. }
  188. }
  189. }
  190. _jfHost?.Dispose();
  191. }
  192. }
  193. /// <summary>
  194. /// Create the application configuration.
  195. /// </summary>
  196. /// <param name="commandLineOpts">The command line options passed to the program.</param>
  197. /// <param name="appPaths">The application paths.</param>
  198. /// <returns>The application configuration.</returns>
  199. public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  200. {
  201. return new ConfigurationBuilder()
  202. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  203. .Build();
  204. }
  205. private static IConfigurationBuilder ConfigureAppConfiguration(
  206. this IConfigurationBuilder config,
  207. StartupOptions commandLineOpts,
  208. IApplicationPaths appPaths,
  209. IConfiguration? startupConfig = null)
  210. {
  211. // Use the swagger API page as the default redirect path if not hosting the web client
  212. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  213. if (startupConfig is not null && !startupConfig.HostWebClient())
  214. {
  215. inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger";
  216. }
  217. return config
  218. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  219. .AddInMemoryCollection(inMemoryDefaultConfig)
  220. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  221. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  222. .AddEnvironmentVariables("JELLYFIN_")
  223. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  224. }
  225. }
  226. }