Program.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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.FullSystemBackup;
  20. using Jellyfin.Server.Implementations.StorageHelpers;
  21. using Jellyfin.Server.Implementations.SystemBackupService;
  22. using Jellyfin.Server.Migrations;
  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. await ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.CoreInitialisaition).ConfigureAwait(false);
  170. await appHost.InitializeServices(startupConfig).ConfigureAwait(false);
  171. await ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.AppInitialisation).ConfigureAwait(false);
  172. try
  173. {
  174. await _setupServer!.StopAsync().ConfigureAwait(false);
  175. await _jellyfinHost.StartAsync().ConfigureAwait(false);
  176. if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
  177. {
  178. var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
  179. StartupHelpers.SetUnixSocketPermissions(startupConfig, socketPath, _logger);
  180. }
  181. }
  182. catch (Exception)
  183. {
  184. _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");
  185. throw;
  186. }
  187. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  188. _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(_startTimestamp));
  189. await _jellyfinHost.WaitForShutdownAsync().ConfigureAwait(false);
  190. _restartOnShutdown = appHost.ShouldRestart;
  191. _restoreFromBackup = appHost.RestoreBackupPath;
  192. }
  193. catch (Exception ex)
  194. {
  195. _restartOnShutdown = false;
  196. _logger.LogCritical(ex, "Error while starting server");
  197. }
  198. finally
  199. {
  200. // Don't throw additional exception if startup failed.
  201. if (appHost.ServiceProvider is not null)
  202. {
  203. _logger.LogInformation("Running query planner optimizations in the database... This might take a while");
  204. var databaseProvider = appHost.ServiceProvider.GetRequiredService<IJellyfinDatabaseProvider>();
  205. using var shutdownSource = new CancellationTokenSource();
  206. shutdownSource.CancelAfter((int)TimeSpan.FromSeconds(60).TotalMicroseconds);
  207. await databaseProvider.RunShutdownTask(shutdownSource.Token).ConfigureAwait(false);
  208. }
  209. _appHost = null;
  210. _jellyfinHost?.Dispose();
  211. }
  212. }
  213. /// <summary>
  214. /// [Internal]Runs the startup Migrations.
  215. /// </summary>
  216. /// <remarks>
  217. /// Not intended to be used other then by jellyfin and its tests.
  218. /// </remarks>
  219. /// <param name="appPaths">Application Paths.</param>
  220. /// <param name="startupConfig">Startup Config.</param>
  221. /// <returns>A task.</returns>
  222. public static async Task ApplyStartupMigrationAsync(ServerApplicationPaths appPaths, IConfiguration startupConfig)
  223. {
  224. var startupConfigurationManager = new ServerConfigurationManager(appPaths, _loggerFactory, new MyXmlSerializer());
  225. startupConfigurationManager.AddParts([new DatabaseConfigurationFactory()]);
  226. var migrationStartupServiceProvider = new ServiceCollection()
  227. .AddLogging(d => d.AddSerilog())
  228. .AddJellyfinDbContext(startupConfigurationManager, startupConfig)
  229. .AddSingleton<IApplicationPaths>(appPaths)
  230. .AddSingleton<ServerApplicationPaths>(appPaths);
  231. var startupService = migrationStartupServiceProvider.BuildServiceProvider();
  232. PrepareDatabaseProvider(startupService);
  233. var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(startupService);
  234. await jellyfinMigrationService.CheckFirstTimeRunOrMigration(appPaths).ConfigureAwait(false);
  235. await jellyfinMigrationService.MigrateStepAsync(Migrations.Stages.JellyfinMigrationStageTypes.PreInitialisation, startupService).ConfigureAwait(false);
  236. }
  237. /// <summary>
  238. /// [Internal]Runs the Jellyfin migrator service with the Core stage.
  239. /// </summary>
  240. /// <remarks>
  241. /// Not intended to be used other then by jellyfin and its tests.
  242. /// </remarks>
  243. /// <param name="serviceProvider">The service provider.</param>
  244. /// <param name="jellyfinMigrationStage">The stage to run.</param>
  245. /// <returns>A task.</returns>
  246. public static async Task ApplyCoreMigrationsAsync(IServiceProvider serviceProvider, Migrations.Stages.JellyfinMigrationStageTypes jellyfinMigrationStage)
  247. {
  248. var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(serviceProvider);
  249. await jellyfinMigrationService.MigrateStepAsync(jellyfinMigrationStage, serviceProvider).ConfigureAwait(false);
  250. }
  251. /// <summary>
  252. /// Create the application configuration.
  253. /// </summary>
  254. /// <param name="commandLineOpts">The command line options passed to the program.</param>
  255. /// <param name="appPaths">The application paths.</param>
  256. /// <returns>The application configuration.</returns>
  257. public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  258. {
  259. return new ConfigurationBuilder()
  260. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  261. .Build();
  262. }
  263. private static IConfigurationBuilder ConfigureAppConfiguration(
  264. this IConfigurationBuilder config,
  265. StartupOptions commandLineOpts,
  266. IApplicationPaths appPaths,
  267. IConfiguration? startupConfig = null)
  268. {
  269. // Use the swagger API page as the default redirect path if not hosting the web client
  270. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  271. if (startupConfig is not null && !startupConfig.HostWebClient())
  272. {
  273. inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger";
  274. }
  275. return config
  276. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  277. .AddInMemoryCollection(inMemoryDefaultConfig)
  278. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  279. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  280. .AddEnvironmentVariables("JELLYFIN_")
  281. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  282. }
  283. private static void PrepareDatabaseProvider(IServiceProvider services)
  284. {
  285. var factory = services.GetRequiredService<IDbContextFactory<JellyfinDbContext>>();
  286. var provider = services.GetRequiredService<IJellyfinDatabaseProvider>();
  287. provider.DbContextFactory = factory;
  288. }
  289. }
  290. }