Program.cs 12 KB

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