Program.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using CommandLine;
  11. using Emby.Server.Implementations;
  12. using Emby.Server.Implementations.Configuration;
  13. using Emby.Server.Implementations.Serialization;
  14. using Jellyfin.Database.Implementations;
  15. using Jellyfin.Server.Extensions;
  16. using Jellyfin.Server.Helpers;
  17. using Jellyfin.Server.Implementations.DatabaseConfiguration;
  18. using Jellyfin.Server.Implementations.Extensions;
  19. using Jellyfin.Server.Implementations.StorageHelpers;
  20. using Jellyfin.Server.Migrations;
  21. using Jellyfin.Server.ServerSetupApp;
  22. using MediaBrowser.Common.Configuration;
  23. using MediaBrowser.Common.Net;
  24. using MediaBrowser.Controller;
  25. using Microsoft.AspNetCore.Hosting;
  26. using Microsoft.Extensions.Configuration;
  27. using Microsoft.Extensions.DependencyInjection;
  28. using Microsoft.Extensions.Hosting;
  29. using Microsoft.Extensions.Logging;
  30. using Microsoft.Extensions.Logging.Abstractions;
  31. using Serilog;
  32. using Serilog.Extensions.Logging;
  33. using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
  34. using ILogger = Microsoft.Extensions.Logging.ILogger;
  35. namespace Jellyfin.Server
  36. {
  37. /// <summary>
  38. /// Class containing the entry point of the application.
  39. /// </summary>
  40. public static class Program
  41. {
  42. /// <summary>
  43. /// The name of logging configuration file containing application defaults.
  44. /// </summary>
  45. public const string LoggingConfigFileDefault = "logging.default.json";
  46. /// <summary>
  47. /// The name of the logging configuration file containing the system-specific override settings.
  48. /// </summary>
  49. public const string LoggingConfigFileSystem = "logging.json";
  50. private static readonly SerilogLoggerFactory _loggerFactory = new SerilogLoggerFactory();
  51. private static SetupServer? _setupServer;
  52. private static CoreAppHost? _appHost;
  53. private static IHost? _jellyfinHost = null;
  54. private static long _startTimestamp;
  55. private static ILogger _logger = NullLogger.Instance;
  56. private static bool _restartOnShutdown;
  57. /// <summary>
  58. /// The entry point of the application.
  59. /// </summary>
  60. /// <param name="args">The command line arguments passed.</param>
  61. /// <returns><see cref="Task" />.</returns>
  62. public static Task Main(string[] args)
  63. {
  64. static Task ErrorParsingArguments(IEnumerable<Error> errors)
  65. {
  66. Environment.ExitCode = 1;
  67. return Task.CompletedTask;
  68. }
  69. // Parse the command line arguments and either start the app or exit indicating error
  70. return Parser.Default.ParseArguments<StartupOptions>(args)
  71. .MapResult(StartApp, ErrorParsingArguments);
  72. }
  73. private static async Task StartApp(StartupOptions options)
  74. {
  75. _startTimestamp = Stopwatch.GetTimestamp();
  76. ServerApplicationPaths appPaths = StartupHelpers.CreateApplicationPaths(options);
  77. appPaths.MakeSanityCheckOrThrow();
  78. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  79. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  80. // Enable cl-va P010 interop for tonemapping on Intel VAAPI
  81. Environment.SetEnvironmentVariable("NEOReadDebugKeys", "1");
  82. Environment.SetEnvironmentVariable("EnableExtendedVaFormats", "1");
  83. await StartupHelpers.InitLoggingConfigFile(appPaths).ConfigureAwait(false);
  84. // Create an instance of the application configuration to use for application startup
  85. IConfiguration startupConfig = CreateAppConfiguration(options, appPaths);
  86. _setupServer = new SetupServer(static () => _jellyfinHost?.Services?.GetService<INetworkManager>(), appPaths, static () => _appHost, _loggerFactory, startupConfig);
  87. await _setupServer.RunAsync().ConfigureAwait(false);
  88. StartupHelpers.InitializeLoggingFramework(startupConfig, appPaths);
  89. _logger = _loggerFactory.CreateLogger("Main");
  90. // Use the logging framework for uncaught exceptions instead of std error
  91. AppDomain.CurrentDomain.UnhandledException += (_, e)
  92. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  93. _logger.LogInformation(
  94. "Jellyfin version: {Version}",
  95. Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
  96. StartupHelpers.LogEnvironmentInfo(_logger, appPaths);
  97. // If hosting the web client, validate the client content path
  98. if (startupConfig.HostWebClient())
  99. {
  100. var webContentPath = appPaths.WebPath;
  101. if (!Directory.Exists(webContentPath) || !Directory.EnumerateFiles(webContentPath).Any())
  102. {
  103. _logger.LogError(
  104. "The server is expected to host the web client, but the provided content directory is either " +
  105. "invalid or empty: {WebContentPath}. If you do not want to host the web client with the " +
  106. "server, you may set the '--nowebclient' command line flag, or set" +
  107. "'{ConfigKey}=false' in your config settings",
  108. webContentPath,
  109. HostWebClientKey);
  110. Environment.ExitCode = 1;
  111. return;
  112. }
  113. }
  114. StorageHelper.TestCommonPathsForStorageCapacity(appPaths, _loggerFactory.CreateLogger<Startup>());
  115. StartupHelpers.PerformStaticInitialization();
  116. await ApplyStartupMigrationAsync(appPaths, startupConfig).ConfigureAwait(false);
  117. do
  118. {
  119. await StartServer(appPaths, options, startupConfig).ConfigureAwait(false);
  120. if (_restartOnShutdown)
  121. {
  122. _startTimestamp = Stopwatch.GetTimestamp();
  123. await _setupServer.StopAsync().ConfigureAwait(false);
  124. await _setupServer.RunAsync().ConfigureAwait(false);
  125. }
  126. } while (_restartOnShutdown);
  127. _setupServer.Dispose();
  128. }
  129. private static async Task StartServer(IServerApplicationPaths appPaths, StartupOptions options, IConfiguration startupConfig)
  130. {
  131. using CoreAppHost appHost = new CoreAppHost(
  132. appPaths,
  133. _loggerFactory,
  134. options,
  135. startupConfig);
  136. _appHost = appHost;
  137. try
  138. {
  139. _jellyfinHost = Host.CreateDefaultBuilder()
  140. .UseConsoleLifetime()
  141. .ConfigureServices(services => appHost.Init(services))
  142. .ConfigureWebHostDefaults(webHostBuilder =>
  143. {
  144. webHostBuilder.ConfigureWebHostBuilder(appHost, startupConfig, appPaths, _logger);
  145. if (bool.TryParse(Environment.GetEnvironmentVariable("JELLYFIN_ENABLE_IIS"), out var iisEnabled) && iisEnabled)
  146. {
  147. _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.");
  148. webHostBuilder.UseIIS();
  149. }
  150. })
  151. .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(options, appPaths, startupConfig))
  152. .UseSerilog()
  153. .Build();
  154. // Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collection.
  155. appHost.ServiceProvider = _jellyfinHost.Services;
  156. await ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.CoreInitialisaition).ConfigureAwait(false);
  157. await appHost.InitializeServices(startupConfig).ConfigureAwait(false);
  158. await ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.AppInitialisation).ConfigureAwait(false);
  159. try
  160. {
  161. await _setupServer!.StopAsync().ConfigureAwait(false);
  162. await _jellyfinHost.StartAsync().ConfigureAwait(false);
  163. if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
  164. {
  165. var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
  166. StartupHelpers.SetUnixSocketPermissions(startupConfig, socketPath, _logger);
  167. }
  168. }
  169. catch (Exception)
  170. {
  171. _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");
  172. throw;
  173. }
  174. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  175. _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(_startTimestamp));
  176. await _jellyfinHost.WaitForShutdownAsync().ConfigureAwait(false);
  177. _restartOnShutdown = appHost.ShouldRestart;
  178. }
  179. catch (Exception ex)
  180. {
  181. _restartOnShutdown = false;
  182. _logger.LogCritical(ex, "Error while starting server");
  183. }
  184. finally
  185. {
  186. // Don't throw additional exception if startup failed.
  187. if (appHost.ServiceProvider is not null)
  188. {
  189. _logger.LogInformation("Running query planner optimizations in the database... This might take a while");
  190. var databaseProvider = appHost.ServiceProvider.GetRequiredService<IJellyfinDatabaseProvider>();
  191. using var shutdownSource = new CancellationTokenSource();
  192. shutdownSource.CancelAfter((int)TimeSpan.FromSeconds(60).TotalMicroseconds);
  193. await databaseProvider.RunShutdownTask(shutdownSource.Token).ConfigureAwait(false);
  194. }
  195. _appHost = null;
  196. _jellyfinHost?.Dispose();
  197. }
  198. }
  199. /// <summary>
  200. /// [Internal]Runs the startup Migrations.
  201. /// </summary>
  202. /// <remarks>
  203. /// Not intended to be used other then by jellyfin and its tests.
  204. /// </remarks>
  205. /// <param name="appPaths">Application Paths.</param>
  206. /// <param name="startupConfig">Startup Config.</param>
  207. /// <returns>A task.</returns>
  208. public static async Task ApplyStartupMigrationAsync(ServerApplicationPaths appPaths, IConfiguration startupConfig)
  209. {
  210. var startupConfigurationManager = new ServerConfigurationManager(appPaths, _loggerFactory, new MyXmlSerializer());
  211. startupConfigurationManager.AddParts([new DatabaseConfigurationFactory()]);
  212. var migrationStartupServiceProvider = new ServiceCollection()
  213. .AddLogging(d => d.AddSerilog())
  214. .AddJellyfinDbContext(startupConfigurationManager, startupConfig)
  215. .AddSingleton<IApplicationPaths>(appPaths)
  216. .AddSingleton<ServerApplicationPaths>(appPaths);
  217. var startupService = migrationStartupServiceProvider.BuildServiceProvider();
  218. var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(startupService);
  219. await jellyfinMigrationService.CheckFirstTimeRunOrMigration(appPaths).ConfigureAwait(false);
  220. await jellyfinMigrationService.MigrateStepAsync(Migrations.Stages.JellyfinMigrationStageTypes.PreInitialisation, startupService).ConfigureAwait(false);
  221. }
  222. /// <summary>
  223. /// [Internal]Runs the Jellyfin migrator service with the Core stage.
  224. /// </summary>
  225. /// <remarks>
  226. /// Not intended to be used other then by jellyfin and its tests.
  227. /// </remarks>
  228. /// <param name="serviceProvider">The service provider.</param>
  229. /// <param name="jellyfinMigrationStage">The stage to run.</param>
  230. /// <returns>A task.</returns>
  231. public static async Task ApplyCoreMigrationsAsync(IServiceProvider serviceProvider, Migrations.Stages.JellyfinMigrationStageTypes jellyfinMigrationStage)
  232. {
  233. var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(serviceProvider);
  234. await jellyfinMigrationService.MigrateStepAsync(jellyfinMigrationStage, serviceProvider).ConfigureAwait(false);
  235. }
  236. /// <summary>
  237. /// Create the application configuration.
  238. /// </summary>
  239. /// <param name="commandLineOpts">The command line options passed to the program.</param>
  240. /// <param name="appPaths">The application paths.</param>
  241. /// <returns>The application configuration.</returns>
  242. public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  243. {
  244. return new ConfigurationBuilder()
  245. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  246. .Build();
  247. }
  248. private static IConfigurationBuilder ConfigureAppConfiguration(
  249. this IConfigurationBuilder config,
  250. StartupOptions commandLineOpts,
  251. IApplicationPaths appPaths,
  252. IConfiguration? startupConfig = null)
  253. {
  254. // Use the swagger API page as the default redirect path if not hosting the web client
  255. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  256. if (startupConfig is not null && !startupConfig.HostWebClient())
  257. {
  258. inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger";
  259. }
  260. return config
  261. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  262. .AddInMemoryCollection(inMemoryDefaultConfig)
  263. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  264. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  265. .AddEnvironmentVariables("JELLYFIN_")
  266. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  267. }
  268. }
  269. }