Program.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. /*
  166. * Initialize the transcode path marker so we avoid starting Jellyfin in a broken state.
  167. * This should really be a part of IApplicationPaths but this path is configured differently.
  168. */
  169. _ = appHost.ConfigurationManager.GetTranscodePath();
  170. // Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collection.
  171. appHost.ServiceProvider = _jellyfinHost.Services;
  172. PrepareDatabaseProvider(appHost.ServiceProvider);
  173. if (!string.IsNullOrWhiteSpace(_restoreFromBackup))
  174. {
  175. await appHost.ServiceProvider.GetService<IBackupService>()!.RestoreBackupAsync(_restoreFromBackup).ConfigureAwait(false);
  176. _restoreFromBackup = null;
  177. _restartOnShutdown = true;
  178. return;
  179. }
  180. var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(appHost.ServiceProvider);
  181. await jellyfinMigrationService.PrepareSystemForMigration(_logger).ConfigureAwait(false);
  182. await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStageTypes.CoreInitialisation, appHost.ServiceProvider).ConfigureAwait(false);
  183. await appHost.InitializeServices(startupConfig).ConfigureAwait(false);
  184. await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStageTypes.AppInitialisation, appHost.ServiceProvider).ConfigureAwait(false);
  185. await jellyfinMigrationService.CleanupSystemAfterMigration(_logger).ConfigureAwait(false);
  186. try
  187. {
  188. configurationCompleted = true;
  189. await _setupServer!.StopAsync().ConfigureAwait(false);
  190. await _jellyfinHost.StartAsync().ConfigureAwait(false);
  191. if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
  192. {
  193. var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
  194. StartupHelpers.SetUnixSocketPermissions(startupConfig, socketPath, _logger);
  195. }
  196. }
  197. catch (Exception)
  198. {
  199. _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");
  200. throw;
  201. }
  202. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  203. _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(_startTimestamp));
  204. await _jellyfinHost.WaitForShutdownAsync().ConfigureAwait(false);
  205. _restartOnShutdown = appHost.ShouldRestart;
  206. _restoreFromBackup = appHost.RestoreBackupPath;
  207. }
  208. catch (Exception ex)
  209. {
  210. _restartOnShutdown = false;
  211. _logger.LogCritical(ex, "Error while starting server");
  212. if (_setupServer!.IsAlive && !configurationCompleted)
  213. {
  214. _setupServer!.SoftStop();
  215. await Task.Delay(TimeSpan.FromMinutes(10)).ConfigureAwait(false);
  216. await _setupServer!.StopAsync().ConfigureAwait(false);
  217. }
  218. }
  219. finally
  220. {
  221. // Don't throw additional exception if startup failed.
  222. if (appHost.ServiceProvider is not null)
  223. {
  224. _logger.LogInformation("Running query planner optimizations in the database... This might take a while");
  225. var databaseProvider = appHost.ServiceProvider.GetRequiredService<IJellyfinDatabaseProvider>();
  226. using var shutdownSource = new CancellationTokenSource();
  227. shutdownSource.CancelAfter((int)TimeSpan.FromSeconds(60).TotalMicroseconds);
  228. await databaseProvider.RunShutdownTask(shutdownSource.Token).ConfigureAwait(false);
  229. }
  230. _appHost = null;
  231. _jellyfinHost?.Dispose();
  232. }
  233. }
  234. /// <summary>
  235. /// [Internal]Runs the startup Migrations.
  236. /// </summary>
  237. /// <remarks>
  238. /// Not intended to be used other then by jellyfin and its tests.
  239. /// </remarks>
  240. /// <param name="appPaths">Application Paths.</param>
  241. /// <param name="startupConfig">Startup Config.</param>
  242. /// <returns>A task.</returns>
  243. public static async Task ApplyStartupMigrationAsync(ServerApplicationPaths appPaths, IConfiguration startupConfig)
  244. {
  245. _migrationLogger = StartupLogger.Logger.BeginGroup<JellyfinMigrationService>($"Migration Service");
  246. var startupConfigurationManager = new ServerConfigurationManager(appPaths, _loggerFactory, new MyXmlSerializer());
  247. startupConfigurationManager.AddParts([new DatabaseConfigurationFactory()]);
  248. var migrationStartupServiceProvider = new ServiceCollection()
  249. .AddLogging(d => d.AddSerilog())
  250. .AddJellyfinDbContext(startupConfigurationManager, startupConfig)
  251. .AddSingleton<IApplicationPaths>(appPaths)
  252. .AddSingleton<ServerApplicationPaths>(appPaths)
  253. .RegisterStartupLogger();
  254. migrationStartupServiceProvider.AddSingleton(migrationStartupServiceProvider);
  255. var startupService = migrationStartupServiceProvider.BuildServiceProvider();
  256. PrepareDatabaseProvider(startupService);
  257. var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(startupService);
  258. await jellyfinMigrationService.CheckFirstTimeRunOrMigration(appPaths).ConfigureAwait(false);
  259. await jellyfinMigrationService.MigrateStepAsync(Migrations.Stages.JellyfinMigrationStageTypes.PreInitialisation, startupService).ConfigureAwait(false);
  260. }
  261. /// <summary>
  262. /// [Internal]Runs the Jellyfin migrator service with the Core stage.
  263. /// </summary>
  264. /// <remarks>
  265. /// Not intended to be used other then by jellyfin and its tests.
  266. /// </remarks>
  267. /// <param name="serviceProvider">The service provider.</param>
  268. /// <param name="jellyfinMigrationStage">The stage to run.</param>
  269. /// <returns>A task.</returns>
  270. public static async Task ApplyCoreMigrationsAsync(IServiceProvider serviceProvider, Migrations.Stages.JellyfinMigrationStageTypes jellyfinMigrationStage)
  271. {
  272. var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(serviceProvider, _migrationLogger!);
  273. await jellyfinMigrationService.MigrateStepAsync(jellyfinMigrationStage, serviceProvider).ConfigureAwait(false);
  274. }
  275. /// <summary>
  276. /// Create the application configuration.
  277. /// </summary>
  278. /// <param name="commandLineOpts">The command line options passed to the program.</param>
  279. /// <param name="appPaths">The application paths.</param>
  280. /// <returns>The application configuration.</returns>
  281. public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  282. {
  283. return new ConfigurationBuilder()
  284. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  285. .Build();
  286. }
  287. private static IConfigurationBuilder ConfigureAppConfiguration(
  288. this IConfigurationBuilder config,
  289. StartupOptions commandLineOpts,
  290. IApplicationPaths appPaths,
  291. IConfiguration? startupConfig = null)
  292. {
  293. // Use the swagger API page as the default redirect path if not hosting the web client
  294. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  295. if (startupConfig is not null && !startupConfig.HostWebClient())
  296. {
  297. inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger";
  298. }
  299. return config
  300. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  301. .AddInMemoryCollection(inMemoryDefaultConfig)
  302. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  303. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  304. .AddEnvironmentVariables("JELLYFIN_")
  305. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  306. }
  307. private static void PrepareDatabaseProvider(IServiceProvider services)
  308. {
  309. var factory = services.GetRequiredService<IDbContextFactory<JellyfinDbContext>>();
  310. var provider = services.GetRequiredService<IJellyfinDatabaseProvider>();
  311. provider.DbContextFactory = factory;
  312. }
  313. }
  314. }