Program.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  75. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  76. // Enable cl-va P010 interop for tonemapping on Intel VAAPI
  77. Environment.SetEnvironmentVariable("NEOReadDebugKeys", "1");
  78. Environment.SetEnvironmentVariable("EnableExtendedVaFormats", "1");
  79. await StartupHelpers.InitLoggingConfigFile(appPaths).ConfigureAwait(false);
  80. // Create an instance of the application configuration to use for application startup
  81. IConfiguration startupConfig = CreateAppConfiguration(options, appPaths);
  82. _setupServer = new SetupServer(static () => _jellyfinHost?.Services?.GetService<INetworkManager>(), appPaths, static () => _appHost, _loggerFactory, startupConfig);
  83. await _setupServer.RunAsync().ConfigureAwait(false);
  84. StartupHelpers.InitializeLoggingFramework(startupConfig, appPaths);
  85. _logger = _loggerFactory.CreateLogger("Main");
  86. // Use the logging framework for uncaught exceptions instead of std error
  87. AppDomain.CurrentDomain.UnhandledException += (_, e)
  88. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  89. _logger.LogInformation(
  90. "Jellyfin version: {Version}",
  91. Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
  92. StartupHelpers.LogEnvironmentInfo(_logger, appPaths);
  93. // If hosting the web client, validate the client content path
  94. if (startupConfig.HostWebClient())
  95. {
  96. var webContentPath = appPaths.WebPath;
  97. if (!Directory.Exists(webContentPath) || !Directory.EnumerateFiles(webContentPath).Any())
  98. {
  99. _logger.LogError(
  100. "The server is expected to host the web client, but the provided content directory is either " +
  101. "invalid or empty: {WebContentPath}. If you do not want to host the web client with the " +
  102. "server, you may set the '--nowebclient' command line flag, or set" +
  103. "'{ConfigKey}=false' in your config settings",
  104. webContentPath,
  105. HostWebClientKey);
  106. Environment.ExitCode = 1;
  107. return;
  108. }
  109. }
  110. StorageHelper.TestCommonPathsForStorageCapacity(appPaths, _loggerFactory.CreateLogger<Startup>());
  111. StartupHelpers.PerformStaticInitialization();
  112. await Migrations.MigrationRunner.RunPreStartup(appPaths, _loggerFactory).ConfigureAwait(false);
  113. do
  114. {
  115. await StartServer(appPaths, options, startupConfig).ConfigureAwait(false);
  116. if (_restartOnShutdown)
  117. {
  118. _startTimestamp = Stopwatch.GetTimestamp();
  119. await _setupServer.StopAsync().ConfigureAwait(false);
  120. await _setupServer.RunAsync().ConfigureAwait(false);
  121. }
  122. } while (_restartOnShutdown);
  123. _setupServer.Dispose();
  124. }
  125. private static async Task StartServer(IServerApplicationPaths appPaths, StartupOptions options, IConfiguration startupConfig)
  126. {
  127. using CoreAppHost appHost = new CoreAppHost(
  128. appPaths,
  129. _loggerFactory,
  130. options,
  131. startupConfig);
  132. _appHost = appHost;
  133. try
  134. {
  135. _jellyfinHost = Host.CreateDefaultBuilder()
  136. .UseConsoleLifetime()
  137. .ConfigureServices(services => appHost.Init(services))
  138. .ConfigureWebHostDefaults(webHostBuilder =>
  139. {
  140. webHostBuilder.ConfigureWebHostBuilder(appHost, startupConfig, appPaths, _logger);
  141. if (bool.TryParse(Environment.GetEnvironmentVariable("JELLYFIN_ENABLE_IIS"), out var iisEnabled) && iisEnabled)
  142. {
  143. _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.");
  144. webHostBuilder.UseIIS();
  145. }
  146. })
  147. .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(options, appPaths, startupConfig))
  148. .UseSerilog()
  149. .Build();
  150. // Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collection.
  151. appHost.ServiceProvider = _jellyfinHost.Services;
  152. await appHost.InitializeServices(startupConfig).ConfigureAwait(false);
  153. await Migrations.MigrationRunner.Run(appHost, _loggerFactory).ConfigureAwait(false);
  154. try
  155. {
  156. await _setupServer!.StopAsync().ConfigureAwait(false);
  157. await _jellyfinHost.StartAsync().ConfigureAwait(false);
  158. if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
  159. {
  160. var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
  161. StartupHelpers.SetUnixSocketPermissions(startupConfig, socketPath, _logger);
  162. }
  163. }
  164. catch (Exception)
  165. {
  166. _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");
  167. throw;
  168. }
  169. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  170. _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(_startTimestamp));
  171. await _jellyfinHost.WaitForShutdownAsync().ConfigureAwait(false);
  172. _restartOnShutdown = appHost.ShouldRestart;
  173. }
  174. catch (Exception ex)
  175. {
  176. _restartOnShutdown = false;
  177. _logger.LogCritical(ex, "Error while starting server");
  178. }
  179. finally
  180. {
  181. // Don't throw additional exception if startup failed.
  182. if (appHost.ServiceProvider is not null)
  183. {
  184. _logger.LogInformation("Running query planner optimizations in the database... This might take a while");
  185. var databaseProvider = appHost.ServiceProvider.GetRequiredService<IJellyfinDatabaseProvider>();
  186. using var shutdownSource = new CancellationTokenSource();
  187. shutdownSource.CancelAfter((int)TimeSpan.FromSeconds(60).TotalMicroseconds);
  188. await databaseProvider.RunShutdownTask(shutdownSource.Token).ConfigureAwait(false);
  189. }
  190. _appHost = null;
  191. _jellyfinHost?.Dispose();
  192. }
  193. }
  194. /// <summary>
  195. /// Create the application configuration.
  196. /// </summary>
  197. /// <param name="commandLineOpts">The command line options passed to the program.</param>
  198. /// <param name="appPaths">The application paths.</param>
  199. /// <returns>The application configuration.</returns>
  200. public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  201. {
  202. return new ConfigurationBuilder()
  203. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  204. .Build();
  205. }
  206. private static IConfigurationBuilder ConfigureAppConfiguration(
  207. this IConfigurationBuilder config,
  208. StartupOptions commandLineOpts,
  209. IApplicationPaths appPaths,
  210. IConfiguration? startupConfig = null)
  211. {
  212. // Use the swagger API page as the default redirect path if not hosting the web client
  213. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  214. if (startupConfig is not null && !startupConfig.HostWebClient())
  215. {
  216. inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger";
  217. }
  218. return config
  219. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  220. .AddInMemoryCollection(inMemoryDefaultConfig)
  221. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  222. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  223. .AddEnvironmentVariables("JELLYFIN_")
  224. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  225. }
  226. }
  227. }