Program.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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? _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. // Use the logging framework for uncaught exceptions instead of std error
  97. AppDomain.CurrentDomain.UnhandledException += (_, e)
  98. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  99. _logger.LogInformation(
  100. "Jellyfin version: {Version}",
  101. Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
  102. StartupHelpers.LogEnvironmentInfo(_logger, appPaths);
  103. // If hosting the web client, validate the client content path
  104. if (startupConfig.HostWebClient())
  105. {
  106. var webContentPath = appPaths.WebPath;
  107. if (!Directory.Exists(webContentPath) || !Directory.EnumerateFiles(webContentPath).Any())
  108. {
  109. _logger.LogError(
  110. "The server is expected to host the web client, but the provided content directory is either " +
  111. "invalid or empty: {WebContentPath}. If you do not want to host the web client with the " +
  112. "server, you may set the '--nowebclient' command line flag, or set" +
  113. "'{ConfigKey}=false' in your config settings",
  114. webContentPath,
  115. HostWebClientKey);
  116. Environment.ExitCode = 1;
  117. return;
  118. }
  119. }
  120. StorageHelper.TestCommonPathsForStorageCapacity(appPaths, StartupLogger.Logger.With(_loggerFactory.CreateLogger<Startup>()).BeginGroup($"Storage Check"));
  121. StartupHelpers.PerformStaticInitialization();
  122. await ApplyStartupMigrationAsync(appPaths, startupConfig).ConfigureAwait(false);
  123. do
  124. {
  125. await StartServer(appPaths, options, startupConfig).ConfigureAwait(false);
  126. if (_restartOnShutdown)
  127. {
  128. _startTimestamp = Stopwatch.GetTimestamp();
  129. await _setupServer.StopAsync().ConfigureAwait(false);
  130. await _setupServer.RunAsync().ConfigureAwait(false);
  131. }
  132. } while (_restartOnShutdown);
  133. _setupServer.Dispose();
  134. }
  135. private static async Task StartServer(IServerApplicationPaths appPaths, StartupOptions options, IConfiguration startupConfig)
  136. {
  137. using CoreAppHost appHost = new CoreAppHost(
  138. appPaths,
  139. _loggerFactory,
  140. options,
  141. startupConfig);
  142. _appHost = appHost;
  143. var configurationCompleted = false;
  144. try
  145. {
  146. _jellyfinHost = Host.CreateDefaultBuilder()
  147. .UseConsoleLifetime()
  148. .ConfigureServices(services => appHost.Init(services))
  149. .ConfigureWebHostDefaults(webHostBuilder =>
  150. {
  151. webHostBuilder.ConfigureWebHostBuilder(appHost, startupConfig, appPaths, _logger);
  152. if (bool.TryParse(Environment.GetEnvironmentVariable("JELLYFIN_ENABLE_IIS"), out var iisEnabled) && iisEnabled)
  153. {
  154. _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.");
  155. webHostBuilder.UseIIS();
  156. }
  157. })
  158. .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(options, appPaths, startupConfig))
  159. .UseSerilog()
  160. .ConfigureServices(e => e.AddTransient<IStartupLogger, StartupLogger>().AddSingleton<IServiceCollection>(e))
  161. .Build();
  162. // Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collection.
  163. appHost.ServiceProvider = _jellyfinHost.Services;
  164. PrepareDatabaseProvider(appHost.ServiceProvider);
  165. if (!string.IsNullOrWhiteSpace(_restoreFromBackup))
  166. {
  167. await appHost.ServiceProvider.GetService<IBackupService>()!.RestoreBackupAsync(_restoreFromBackup).ConfigureAwait(false);
  168. _restoreFromBackup = null;
  169. _restartOnShutdown = true;
  170. return;
  171. }
  172. var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(appHost.ServiceProvider);
  173. await jellyfinMigrationService.PrepareSystemForMigration(_logger).ConfigureAwait(false);
  174. await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStageTypes.CoreInitialisation, appHost.ServiceProvider).ConfigureAwait(false);
  175. await appHost.InitializeServices(startupConfig).ConfigureAwait(false);
  176. await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStageTypes.AppInitialisation, appHost.ServiceProvider).ConfigureAwait(false);
  177. await jellyfinMigrationService.CleanupSystemAfterMigration(_logger).ConfigureAwait(false);
  178. try
  179. {
  180. configurationCompleted = true;
  181. await _setupServer!.StopAsync().ConfigureAwait(false);
  182. await _jellyfinHost.StartAsync().ConfigureAwait(false);
  183. if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
  184. {
  185. var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
  186. StartupHelpers.SetUnixSocketPermissions(startupConfig, socketPath, _logger);
  187. }
  188. }
  189. catch (Exception)
  190. {
  191. _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");
  192. throw;
  193. }
  194. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  195. _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(_startTimestamp));
  196. await _jellyfinHost.WaitForShutdownAsync().ConfigureAwait(false);
  197. _restartOnShutdown = appHost.ShouldRestart;
  198. _restoreFromBackup = appHost.RestoreBackupPath;
  199. }
  200. catch (Exception ex)
  201. {
  202. _restartOnShutdown = false;
  203. _logger.LogCritical(ex, "Error while starting server");
  204. if (_setupServer!.IsAlive && !configurationCompleted)
  205. {
  206. _setupServer!.SoftStop();
  207. await Task.Delay(TimeSpan.FromMinutes(10)).ConfigureAwait(false);
  208. await _setupServer!.StopAsync().ConfigureAwait(false);
  209. }
  210. }
  211. finally
  212. {
  213. // Don't throw additional exception if startup failed.
  214. if (appHost.ServiceProvider is not null)
  215. {
  216. _logger.LogInformation("Running query planner optimizations in the database... This might take a while");
  217. var databaseProvider = appHost.ServiceProvider.GetRequiredService<IJellyfinDatabaseProvider>();
  218. using var shutdownSource = new CancellationTokenSource();
  219. shutdownSource.CancelAfter((int)TimeSpan.FromSeconds(60).TotalMicroseconds);
  220. await databaseProvider.RunShutdownTask(shutdownSource.Token).ConfigureAwait(false);
  221. }
  222. _appHost = null;
  223. _jellyfinHost?.Dispose();
  224. }
  225. }
  226. /// <summary>
  227. /// [Internal]Runs the startup Migrations.
  228. /// </summary>
  229. /// <remarks>
  230. /// Not intended to be used other then by jellyfin and its tests.
  231. /// </remarks>
  232. /// <param name="appPaths">Application Paths.</param>
  233. /// <param name="startupConfig">Startup Config.</param>
  234. /// <returns>A task.</returns>
  235. public static async Task ApplyStartupMigrationAsync(ServerApplicationPaths appPaths, IConfiguration startupConfig)
  236. {
  237. _migrationLogger = StartupLogger.Logger.BeginGroup($"Migration Service");
  238. var startupConfigurationManager = new ServerConfigurationManager(appPaths, _loggerFactory, new MyXmlSerializer());
  239. startupConfigurationManager.AddParts([new DatabaseConfigurationFactory()]);
  240. var migrationStartupServiceProvider = new ServiceCollection()
  241. .AddLogging(d => d.AddSerilog())
  242. .AddJellyfinDbContext(startupConfigurationManager, startupConfig)
  243. .AddSingleton<IApplicationPaths>(appPaths)
  244. .AddSingleton<ServerApplicationPaths>(appPaths)
  245. .AddSingleton<IStartupLogger>(_migrationLogger);
  246. migrationStartupServiceProvider.AddSingleton(migrationStartupServiceProvider);
  247. var startupService = migrationStartupServiceProvider.BuildServiceProvider();
  248. PrepareDatabaseProvider(startupService);
  249. var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(startupService);
  250. await jellyfinMigrationService.CheckFirstTimeRunOrMigration(appPaths).ConfigureAwait(false);
  251. await jellyfinMigrationService.MigrateStepAsync(Migrations.Stages.JellyfinMigrationStageTypes.PreInitialisation, startupService).ConfigureAwait(false);
  252. }
  253. /// <summary>
  254. /// [Internal]Runs the Jellyfin migrator service with the Core stage.
  255. /// </summary>
  256. /// <remarks>
  257. /// Not intended to be used other then by jellyfin and its tests.
  258. /// </remarks>
  259. /// <param name="serviceProvider">The service provider.</param>
  260. /// <param name="jellyfinMigrationStage">The stage to run.</param>
  261. /// <returns>A task.</returns>
  262. public static async Task ApplyCoreMigrationsAsync(IServiceProvider serviceProvider, Migrations.Stages.JellyfinMigrationStageTypes jellyfinMigrationStage)
  263. {
  264. var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(serviceProvider, _migrationLogger!);
  265. await jellyfinMigrationService.MigrateStepAsync(jellyfinMigrationStage, serviceProvider).ConfigureAwait(false);
  266. }
  267. /// <summary>
  268. /// Create the application configuration.
  269. /// </summary>
  270. /// <param name="commandLineOpts">The command line options passed to the program.</param>
  271. /// <param name="appPaths">The application paths.</param>
  272. /// <returns>The application configuration.</returns>
  273. public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  274. {
  275. return new ConfigurationBuilder()
  276. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  277. .Build();
  278. }
  279. private static IConfigurationBuilder ConfigureAppConfiguration(
  280. this IConfigurationBuilder config,
  281. StartupOptions commandLineOpts,
  282. IApplicationPaths appPaths,
  283. IConfiguration? startupConfig = null)
  284. {
  285. // Use the swagger API page as the default redirect path if not hosting the web client
  286. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  287. if (startupConfig is not null && !startupConfig.HostWebClient())
  288. {
  289. inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger";
  290. }
  291. return config
  292. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  293. .AddInMemoryCollection(inMemoryDefaultConfig)
  294. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  295. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  296. .AddEnvironmentVariables("JELLYFIN_")
  297. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  298. }
  299. private static void PrepareDatabaseProvider(IServiceProvider services)
  300. {
  301. var factory = services.GetRequiredService<IDbContextFactory<JellyfinDbContext>>();
  302. var provider = services.GetRequiredService<IJellyfinDatabaseProvider>();
  303. provider.DbContextFactory = factory;
  304. }
  305. }
  306. }