Program.cs 11 KB

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