Program.cs 17 KB

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