2
0

Program.cs 16 KB

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