Program.cs 12 KB

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