Program.cs 11 KB

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