Program.cs 10 KB

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