Program.cs 13 KB

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