Program.cs 12 KB

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