Program.cs 15 KB

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