Program.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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.Server.Extensions;
  12. using Jellyfin.Server.Helpers;
  13. using Jellyfin.Server.Implementations;
  14. using MediaBrowser.Common.Configuration;
  15. using MediaBrowser.Controller;
  16. using Microsoft.EntityFrameworkCore;
  17. using Microsoft.Extensions.Configuration;
  18. using Microsoft.Extensions.DependencyInjection;
  19. using Microsoft.Extensions.Hosting;
  20. using Microsoft.Extensions.Logging;
  21. using Microsoft.Extensions.Logging.Abstractions;
  22. using Serilog;
  23. using Serilog.Extensions.Logging;
  24. using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
  25. using ILogger = Microsoft.Extensions.Logging.ILogger;
  26. namespace Jellyfin.Server
  27. {
  28. /// <summary>
  29. /// Class containing the entry point of the application.
  30. /// </summary>
  31. public static class Program
  32. {
  33. /// <summary>
  34. /// The name of logging configuration file containing application defaults.
  35. /// </summary>
  36. public const string LoggingConfigFileDefault = "logging.default.json";
  37. /// <summary>
  38. /// The name of the logging configuration file containing the system-specific override settings.
  39. /// </summary>
  40. public const string LoggingConfigFileSystem = "logging.json";
  41. private static readonly ILoggerFactory _loggerFactory = new SerilogLoggerFactory();
  42. private static CancellationTokenSource _tokenSource = new();
  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. /// <summary>
  63. /// Shuts down the application.
  64. /// </summary>
  65. internal static void Shutdown()
  66. {
  67. if (!_tokenSource.IsCancellationRequested)
  68. {
  69. _tokenSource.Cancel();
  70. }
  71. }
  72. /// <summary>
  73. /// Restarts the application.
  74. /// </summary>
  75. internal static void Restart()
  76. {
  77. _restartOnShutdown = true;
  78. Shutdown();
  79. }
  80. private static async Task StartApp(StartupOptions options)
  81. {
  82. _startTimestamp = Stopwatch.GetTimestamp();
  83. // Log all uncaught exceptions to std error
  84. static void UnhandledExceptionToConsole(object sender, UnhandledExceptionEventArgs e) =>
  85. Console.Error.WriteLine("Unhandled Exception\n" + e.ExceptionObject);
  86. AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionToConsole;
  87. ServerApplicationPaths appPaths = StartupHelpers.CreateApplicationPaths(options);
  88. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  89. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  90. // Enable cl-va P010 interop for tonemapping on Intel VAAPI
  91. Environment.SetEnvironmentVariable("NEOReadDebugKeys", "1");
  92. Environment.SetEnvironmentVariable("EnableExtendedVaFormats", "1");
  93. await StartupHelpers.InitLoggingConfigFile(appPaths).ConfigureAwait(false);
  94. // Create an instance of the application configuration to use for application startup
  95. IConfiguration startupConfig = CreateAppConfiguration(options, appPaths);
  96. StartupHelpers.InitializeLoggingFramework(startupConfig, appPaths);
  97. _logger = _loggerFactory.CreateLogger("Main");
  98. // Log uncaught exceptions to the logging instead of std error
  99. AppDomain.CurrentDomain.UnhandledException -= UnhandledExceptionToConsole;
  100. AppDomain.CurrentDomain.UnhandledException += (_, e)
  101. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  102. // Intercept Ctrl+C and Ctrl+Break
  103. Console.CancelKeyPress += (_, e) =>
  104. {
  105. if (_tokenSource.IsCancellationRequested)
  106. {
  107. return; // Already shutting down
  108. }
  109. e.Cancel = true;
  110. _logger.LogInformation("Ctrl+C, shutting down");
  111. Environment.ExitCode = 128 + 2;
  112. Shutdown();
  113. };
  114. // Register a SIGTERM handler
  115. AppDomain.CurrentDomain.ProcessExit += (_, _) =>
  116. {
  117. if (_tokenSource.IsCancellationRequested)
  118. {
  119. return; // Already shutting down
  120. }
  121. _logger.LogInformation("Received a SIGTERM signal, shutting down");
  122. Environment.ExitCode = 128 + 15;
  123. Shutdown();
  124. };
  125. _logger.LogInformation(
  126. "Jellyfin version: {Version}",
  127. Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
  128. ApplicationHost.LogEnvironmentInfo(_logger, appPaths);
  129. // If hosting the web client, validate the client content path
  130. if (startupConfig.HostWebClient())
  131. {
  132. var webContentPath = appPaths.WebPath;
  133. if (!Directory.Exists(webContentPath) || !Directory.EnumerateFiles(webContentPath).Any())
  134. {
  135. _logger.LogError(
  136. "The server is expected to host the web client, but the provided content directory is either " +
  137. "invalid or empty: {WebContentPath}. If you do not want to host the web client with the " +
  138. "server, you may set the '--nowebclient' command line flag, or set" +
  139. "'{ConfigKey}=false' in your config settings",
  140. webContentPath,
  141. HostWebClientKey);
  142. Environment.ExitCode = 1;
  143. return;
  144. }
  145. }
  146. StartupHelpers.PerformStaticInitialization();
  147. Migrations.MigrationRunner.RunPreStartup(appPaths, _loggerFactory);
  148. do
  149. {
  150. _restartOnShutdown = false;
  151. await StartServer(appPaths, options, startupConfig).ConfigureAwait(false);
  152. if (_restartOnShutdown)
  153. {
  154. _tokenSource = new CancellationTokenSource();
  155. _startTimestamp = Stopwatch.GetTimestamp();
  156. }
  157. } while (_restartOnShutdown);
  158. }
  159. private static async Task StartServer(IServerApplicationPaths appPaths, StartupOptions options, IConfiguration startupConfig)
  160. {
  161. var appHost = new CoreAppHost(
  162. appPaths,
  163. _loggerFactory,
  164. options,
  165. startupConfig);
  166. IHost? host = null;
  167. try
  168. {
  169. host = Host.CreateDefaultBuilder()
  170. .ConfigureServices(services => appHost.Init(services))
  171. .ConfigureWebHostDefaults(webHostBuilder => webHostBuilder.ConfigureWebHostBuilder(appHost, startupConfig, appPaths, _logger))
  172. .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(options, appPaths, startupConfig))
  173. .UseSerilog()
  174. .Build();
  175. // Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collection.
  176. appHost.ServiceProvider = host.Services;
  177. await appHost.InitializeServices().ConfigureAwait(false);
  178. Migrations.MigrationRunner.Run(appHost, _loggerFactory);
  179. try
  180. {
  181. await host.StartAsync(_tokenSource.Token).ConfigureAwait(false);
  182. if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
  183. {
  184. var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
  185. StartupHelpers.SetUnixSocketPermissions(startupConfig, socketPath, _logger);
  186. }
  187. }
  188. catch (Exception ex) when (ex is not TaskCanceledException)
  189. {
  190. _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");
  191. throw;
  192. }
  193. await appHost.RunStartupTasksAsync(_tokenSource.Token).ConfigureAwait(false);
  194. _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(_startTimestamp));
  195. // Block main thread until shutdown
  196. await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
  197. }
  198. catch (TaskCanceledException)
  199. {
  200. // Don't throw on cancellation
  201. }
  202. catch (Exception ex)
  203. {
  204. _logger.LogCritical(ex, "Error while starting server");
  205. }
  206. finally
  207. {
  208. // Don't throw additional exception if startup failed.
  209. if (appHost.ServiceProvider is not null)
  210. {
  211. _logger.LogInformation("Running query planner optimizations in the database... This might take a while");
  212. // Run before disposing the application
  213. var context = await appHost.ServiceProvider.GetRequiredService<IDbContextFactory<JellyfinDb>>().CreateDbContextAsync().ConfigureAwait(false);
  214. await using (context.ConfigureAwait(false))
  215. {
  216. if (context.Database.IsSqlite())
  217. {
  218. await context.Database.ExecuteSqlRawAsync("PRAGMA optimize").ConfigureAwait(false);
  219. }
  220. }
  221. }
  222. await appHost.DisposeAsync().ConfigureAwait(false);
  223. host?.Dispose();
  224. }
  225. }
  226. /// <summary>
  227. /// Create the application configuration.
  228. /// </summary>
  229. /// <param name="commandLineOpts">The command line options passed to the program.</param>
  230. /// <param name="appPaths">The application paths.</param>
  231. /// <returns>The application configuration.</returns>
  232. public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  233. {
  234. return new ConfigurationBuilder()
  235. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  236. .Build();
  237. }
  238. private static IConfigurationBuilder ConfigureAppConfiguration(
  239. this IConfigurationBuilder config,
  240. StartupOptions commandLineOpts,
  241. IApplicationPaths appPaths,
  242. IConfiguration? startupConfig = null)
  243. {
  244. // Use the swagger API page as the default redirect path if not hosting the web client
  245. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  246. if (startupConfig is not null && !startupConfig.HostWebClient())
  247. {
  248. inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger";
  249. }
  250. return config
  251. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  252. .AddInMemoryCollection(inMemoryDefaultConfig)
  253. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  254. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  255. .AddEnvironmentVariables("JELLYFIN_")
  256. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  257. }
  258. }
  259. }