| | | 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 | | |
| | | 39 | | namespace Jellyfin.Server |
| | | 40 | | { |
| | | 41 | | /// <summary> |
| | | 42 | | /// Class containing the entry point of the application. |
| | | 43 | | /// </summary> |
| | | 44 | | public static class Program |
| | | 45 | | { |
| | | 46 | | /// <summary> |
| | | 47 | | /// The name of logging configuration file containing application defaults. |
| | | 48 | | /// </summary> |
| | | 49 | | public const string LoggingConfigFileDefault = "logging.default.json"; |
| | | 50 | | |
| | | 51 | | /// <summary> |
| | | 52 | | /// The name of the logging configuration file containing the system-specific override settings. |
| | | 53 | | /// </summary> |
| | | 54 | | public const string LoggingConfigFileSystem = "logging.json"; |
| | | 55 | | |
| | 1 | 56 | | private static readonly SerilogLoggerFactory _loggerFactory = new SerilogLoggerFactory(); |
| | | 57 | | private static SetupServer? _setupServer; |
| | | 58 | | private static CoreAppHost? _appHost; |
| | 1 | 59 | | private static IHost? _jellyfinHost = null; |
| | | 60 | | private static long _startTimestamp; |
| | 1 | 61 | | private static ILogger _logger = NullLogger.Instance; |
| | | 62 | | private static bool _restartOnShutdown; |
| | | 63 | | private static IStartupLogger<JellyfinMigrationService>? _migrationLogger; |
| | | 64 | | private static string? _restoreFromBackup; |
| | | 65 | | |
| | | 66 | | /// <summary> |
| | | 67 | | /// The entry point of the application. |
| | | 68 | | /// </summary> |
| | | 69 | | /// <param name="args">The command line arguments passed.</param> |
| | | 70 | | /// <returns><see cref="Task" />.</returns> |
| | | 71 | | public static Task Main(string[] args) |
| | | 72 | | { |
| | | 73 | | static Task ErrorParsingArguments(IEnumerable<Error> errors) |
| | | 74 | | { |
| | | 75 | | Environment.ExitCode = 1; |
| | | 76 | | return Task.CompletedTask; |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | // Parse the command line arguments and either start the app or exit indicating error |
| | 0 | 80 | | return Parser.Default.ParseArguments<StartupOptions>(args) |
| | 0 | 81 | | .MapResult(StartApp, ErrorParsingArguments); |
| | | 82 | | } |
| | | 83 | | |
| | | 84 | | private static async Task StartApp(StartupOptions options) |
| | | 85 | | { |
| | | 86 | | _restoreFromBackup = options.RestoreArchive; |
| | | 87 | | _startTimestamp = Stopwatch.GetTimestamp(); |
| | | 88 | | ServerApplicationPaths appPaths = StartupHelpers.CreateApplicationPaths(options); |
| | | 89 | | appPaths.MakeSanityCheckOrThrow(); |
| | | 90 | | |
| | | 91 | | // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager |
| | | 92 | | Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath); |
| | | 93 | | |
| | | 94 | | // Enable cl-va P010 interop for tonemapping on Intel VAAPI |
| | | 95 | | Environment.SetEnvironmentVariable("NEOReadDebugKeys", "1"); |
| | | 96 | | Environment.SetEnvironmentVariable("EnableExtendedVaFormats", "1"); |
| | | 97 | | |
| | | 98 | | await StartupHelpers.InitLoggingConfigFile(appPaths).ConfigureAwait(false); |
| | | 99 | | |
| | | 100 | | // Create an instance of the application configuration to use for application startup |
| | | 101 | | IConfiguration startupConfig = CreateAppConfiguration(options, appPaths); |
| | | 102 | | StartupHelpers.InitializeLoggingFramework(startupConfig, appPaths); |
| | | 103 | | _setupServer = new SetupServer(static () => _jellyfinHost?.Services?.GetService<INetworkManager>(), appPaths |
| | | 104 | | await _setupServer.RunAsync().ConfigureAwait(false); |
| | | 105 | | _logger = _loggerFactory.CreateLogger("Main"); |
| | | 106 | | StartupLogger.Logger = new StartupLogger(_logger); |
| | | 107 | | |
| | | 108 | | // Use the logging framework for uncaught exceptions instead of std error |
| | | 109 | | AppDomain.CurrentDomain.UnhandledException += (_, e) |
| | | 110 | | => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception"); |
| | | 111 | | |
| | | 112 | | _logger.LogInformation( |
| | | 113 | | "Jellyfin version: {Version}", |
| | | 114 | | Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3)); |
| | | 115 | | |
| | | 116 | | StartupHelpers.LogEnvironmentInfo(_logger, appPaths); |
| | | 117 | | |
| | | 118 | | // If hosting the web client, validate the client content path |
| | | 119 | | if (startupConfig.HostWebClient()) |
| | | 120 | | { |
| | | 121 | | var webContentPath = appPaths.WebPath; |
| | | 122 | | if (!Directory.Exists(webContentPath) || !Directory.EnumerateFiles(webContentPath).Any()) |
| | | 123 | | { |
| | | 124 | | _logger.LogError( |
| | | 125 | | "The server is expected to host the web client, but the provided content directory is either " + |
| | | 126 | | "invalid or empty: {WebContentPath}. If you do not want to host the web client with the " + |
| | | 127 | | "server, you may set the '--nowebclient' command line flag, or set" + |
| | | 128 | | "'{ConfigKey}=false' in your config settings", |
| | | 129 | | webContentPath, |
| | | 130 | | HostWebClientKey); |
| | | 131 | | Environment.ExitCode = 1; |
| | | 132 | | return; |
| | | 133 | | } |
| | | 134 | | } |
| | | 135 | | |
| | | 136 | | StorageHelper.TestCommonPathsForStorageCapacity(appPaths, StartupLogger.Logger.With(_loggerFactory.CreateLog |
| | | 137 | | |
| | | 138 | | StartupHelpers.PerformStaticInitialization(); |
| | | 139 | | |
| | | 140 | | await ApplyStartupMigrationAsync(appPaths, startupConfig).ConfigureAwait(false); |
| | | 141 | | |
| | | 142 | | do |
| | | 143 | | { |
| | | 144 | | await StartServer(appPaths, options, startupConfig).ConfigureAwait(false); |
| | | 145 | | |
| | | 146 | | if (_restartOnShutdown) |
| | | 147 | | { |
| | | 148 | | _startTimestamp = Stopwatch.GetTimestamp(); |
| | | 149 | | await _setupServer.StopAsync().ConfigureAwait(false); |
| | | 150 | | await _setupServer.RunAsync().ConfigureAwait(false); |
| | | 151 | | } |
| | | 152 | | } while (_restartOnShutdown); |
| | | 153 | | |
| | | 154 | | _setupServer.Dispose(); |
| | | 155 | | } |
| | | 156 | | |
| | | 157 | | private static async Task StartServer(IServerApplicationPaths appPaths, StartupOptions options, IConfiguration s |
| | | 158 | | { |
| | | 159 | | using CoreAppHost appHost = new CoreAppHost( |
| | | 160 | | appPaths, |
| | | 161 | | _loggerFactory, |
| | | 162 | | options, |
| | | 163 | | startupConfig); |
| | | 164 | | _appHost = appHost; |
| | | 165 | | var configurationCompleted = false; |
| | | 166 | | try |
| | | 167 | | { |
| | | 168 | | _jellyfinHost = Host.CreateDefaultBuilder() |
| | | 169 | | .UseConsoleLifetime() |
| | | 170 | | .ConfigureServices(services => appHost.Init(services)) |
| | | 171 | | .ConfigureWebHostDefaults(webHostBuilder => |
| | | 172 | | { |
| | | 173 | | webHostBuilder.ConfigureWebHostBuilder(appHost, startupConfig, appPaths, _logger); |
| | | 174 | | if (bool.TryParse(Environment.GetEnvironmentVariable("JELLYFIN_ENABLE_IIS"), out var iisEnabled) |
| | | 175 | | { |
| | | 176 | | _logger.LogCritical("UNSUPPORTED HOSTING ENVIRONMENT Microsoft Internet Information Services |
| | | 177 | | webHostBuilder.UseIIS(); |
| | | 178 | | } |
| | | 179 | | }) |
| | | 180 | | .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(options, appPaths, startupConf |
| | | 181 | | .UseSerilog() |
| | | 182 | | .ConfigureServices(e => e |
| | | 183 | | .RegisterStartupLogger() |
| | | 184 | | .AddSingleton<IServiceCollection>(e)) |
| | | 185 | | .Build(); |
| | | 186 | | |
| | | 187 | | /* |
| | | 188 | | * Initialize the transcode path marker so we avoid starting Jellyfin in a broken state. |
| | | 189 | | * This should really be a part of IApplicationPaths but this path is configured differently. |
| | | 190 | | */ |
| | | 191 | | _ = appHost.ConfigurationManager.GetTranscodePath(); |
| | | 192 | | |
| | | 193 | | // Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collect |
| | | 194 | | appHost.ServiceProvider = _jellyfinHost.Services; |
| | | 195 | | PrepareDatabaseProvider(appHost.ServiceProvider); |
| | | 196 | | |
| | | 197 | | if (!string.IsNullOrWhiteSpace(_restoreFromBackup)) |
| | | 198 | | { |
| | | 199 | | await appHost.ServiceProvider.GetService<IBackupService>()!.RestoreBackupAsync(_restoreFromBackup).C |
| | | 200 | | _restoreFromBackup = null; |
| | | 201 | | _restartOnShutdown = true; |
| | | 202 | | return; |
| | | 203 | | } |
| | | 204 | | |
| | | 205 | | var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(appHost.Servi |
| | | 206 | | await jellyfinMigrationService.PrepareSystemForMigration(_logger).ConfigureAwait(false); |
| | | 207 | | await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStageTypes.CoreInitialisation, appHost. |
| | | 208 | | |
| | | 209 | | await appHost.InitializeServices(startupConfig).ConfigureAwait(false); |
| | | 210 | | |
| | | 211 | | await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStageTypes.AppInitialisation, appHost.S |
| | | 212 | | await jellyfinMigrationService.CleanupSystemAfterMigration(_logger).ConfigureAwait(false); |
| | | 213 | | try |
| | | 214 | | { |
| | | 215 | | configurationCompleted = true; |
| | | 216 | | await _setupServer!.StopAsync().ConfigureAwait(false); |
| | | 217 | | await _jellyfinHost.StartAsync().ConfigureAwait(false); |
| | | 218 | | |
| | | 219 | | if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket()) |
| | | 220 | | { |
| | | 221 | | var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths); |
| | | 222 | | |
| | | 223 | | StartupHelpers.SetUnixSocketPermissions(startupConfig, socketPath, _logger); |
| | | 224 | | } |
| | | 225 | | } |
| | | 226 | | catch (Exception) |
| | | 227 | | { |
| | | 228 | | _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bin |
| | | 229 | | throw; |
| | | 230 | | } |
| | | 231 | | |
| | | 232 | | await appHost.RunStartupTasksAsync().ConfigureAwait(false); |
| | | 233 | | |
| | | 234 | | _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(_startTimestamp)); |
| | | 235 | | |
| | | 236 | | await _jellyfinHost.WaitForShutdownAsync().ConfigureAwait(false); |
| | | 237 | | _restartOnShutdown = appHost.ShouldRestart; |
| | | 238 | | _restoreFromBackup = appHost.RestoreBackupPath; |
| | | 239 | | } |
| | | 240 | | catch (Exception ex) |
| | | 241 | | { |
| | | 242 | | _restartOnShutdown = false; |
| | | 243 | | _logger.LogCritical(ex, "Error while starting server"); |
| | | 244 | | if (_setupServer!.IsAlive && !configurationCompleted) |
| | | 245 | | { |
| | | 246 | | _setupServer!.SoftStop(); |
| | | 247 | | await Task.Delay(TimeSpan.FromMinutes(10)).ConfigureAwait(false); |
| | | 248 | | await _setupServer!.StopAsync().ConfigureAwait(false); |
| | | 249 | | } |
| | | 250 | | } |
| | | 251 | | finally |
| | | 252 | | { |
| | | 253 | | // Don't throw additional exception if startup failed. |
| | | 254 | | if (appHost.ServiceProvider is not null) |
| | | 255 | | { |
| | | 256 | | _logger.LogInformation("Running query planner optimizations in the database... This might take a whi |
| | | 257 | | |
| | | 258 | | var databaseProvider = appHost.ServiceProvider.GetRequiredService<IJellyfinDatabaseProvider>(); |
| | | 259 | | using var shutdownSource = new CancellationTokenSource(); |
| | | 260 | | shutdownSource.CancelAfter((int)TimeSpan.FromSeconds(60).TotalMicroseconds); |
| | | 261 | | await databaseProvider.RunShutdownTask(shutdownSource.Token).ConfigureAwait(false); |
| | | 262 | | } |
| | | 263 | | |
| | | 264 | | _appHost = null; |
| | | 265 | | _jellyfinHost?.Dispose(); |
| | | 266 | | } |
| | | 267 | | } |
| | | 268 | | |
| | | 269 | | /// <summary> |
| | | 270 | | /// [Internal]Runs the startup Migrations. |
| | | 271 | | /// </summary> |
| | | 272 | | /// <remarks> |
| | | 273 | | /// Not intended to be used other then by jellyfin and its tests. |
| | | 274 | | /// </remarks> |
| | | 275 | | /// <param name="appPaths">Application Paths.</param> |
| | | 276 | | /// <param name="startupConfig">Startup Config.</param> |
| | | 277 | | /// <returns>A task.</returns> |
| | | 278 | | public static async Task ApplyStartupMigrationAsync(ServerApplicationPaths appPaths, IConfiguration startupConfi |
| | | 279 | | { |
| | | 280 | | _migrationLogger = StartupLogger.Logger.BeginGroup<JellyfinMigrationService>($"Migration Service"); |
| | | 281 | | var startupConfigurationManager = new ServerConfigurationManager(appPaths, _loggerFactory, new MyXmlSerializ |
| | | 282 | | startupConfigurationManager.AddParts([new DatabaseConfigurationFactory()]); |
| | | 283 | | var migrationStartupServiceProvider = new ServiceCollection() |
| | | 284 | | .AddLogging(d => d.AddSerilog()) |
| | | 285 | | .AddJellyfinDbContext(startupConfigurationManager, startupConfig) |
| | | 286 | | .AddSingleton<IApplicationPaths>(appPaths) |
| | | 287 | | .AddSingleton<ServerApplicationPaths>(appPaths) |
| | | 288 | | .RegisterStartupLogger(); |
| | | 289 | | |
| | | 290 | | migrationStartupServiceProvider.AddSingleton(migrationStartupServiceProvider); |
| | | 291 | | var startupService = migrationStartupServiceProvider.BuildServiceProvider(); |
| | | 292 | | |
| | | 293 | | PrepareDatabaseProvider(startupService); |
| | | 294 | | |
| | | 295 | | var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(startupService); |
| | | 296 | | await jellyfinMigrationService.CheckFirstTimeRunOrMigration(appPaths).ConfigureAwait(false); |
| | | 297 | | await jellyfinMigrationService.MigrateStepAsync(Migrations.Stages.JellyfinMigrationStageTypes.PreInitialisat |
| | | 298 | | } |
| | | 299 | | |
| | | 300 | | /// <summary> |
| | | 301 | | /// [Internal]Runs the Jellyfin migrator service with the Core stage. |
| | | 302 | | /// </summary> |
| | | 303 | | /// <remarks> |
| | | 304 | | /// Not intended to be used other then by jellyfin and its tests. |
| | | 305 | | /// </remarks> |
| | | 306 | | /// <param name="serviceProvider">The service provider.</param> |
| | | 307 | | /// <param name="jellyfinMigrationStage">The stage to run.</param> |
| | | 308 | | /// <returns>A task.</returns> |
| | | 309 | | public static async Task ApplyCoreMigrationsAsync(IServiceProvider serviceProvider, Migrations.Stages.JellyfinMi |
| | | 310 | | { |
| | | 311 | | var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(serviceProvider, |
| | | 312 | | await jellyfinMigrationService.MigrateStepAsync(jellyfinMigrationStage, serviceProvider).ConfigureAwait(fals |
| | | 313 | | } |
| | | 314 | | |
| | | 315 | | /// <summary> |
| | | 316 | | /// Create the application configuration. |
| | | 317 | | /// </summary> |
| | | 318 | | /// <param name="commandLineOpts">The command line options passed to the program.</param> |
| | | 319 | | /// <param name="appPaths">The application paths.</param> |
| | | 320 | | /// <returns>The application configuration.</returns> |
| | | 321 | | public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths) |
| | | 322 | | { |
| | 21 | 323 | | return new ConfigurationBuilder() |
| | 21 | 324 | | .ConfigureAppConfiguration(commandLineOpts, appPaths) |
| | 21 | 325 | | .Build(); |
| | | 326 | | } |
| | | 327 | | |
| | | 328 | | private static IConfigurationBuilder ConfigureAppConfiguration( |
| | | 329 | | this IConfigurationBuilder config, |
| | | 330 | | StartupOptions commandLineOpts, |
| | | 331 | | IApplicationPaths appPaths, |
| | | 332 | | IConfiguration? startupConfig = null) |
| | | 333 | | { |
| | | 334 | | // Use the swagger API page as the default redirect path if not hosting the web client |
| | 21 | 335 | | var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration; |
| | 21 | 336 | | if (startupConfig is not null && !startupConfig.HostWebClient()) |
| | | 337 | | { |
| | 0 | 338 | | inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger"; |
| | | 339 | | } |
| | | 340 | | |
| | 21 | 341 | | return config |
| | 21 | 342 | | .SetBasePath(appPaths.ConfigurationDirectoryPath) |
| | 21 | 343 | | .AddInMemoryCollection(inMemoryDefaultConfig) |
| | 21 | 344 | | .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true) |
| | 21 | 345 | | .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true) |
| | 21 | 346 | | .AddEnvironmentVariables("JELLYFIN_") |
| | 21 | 347 | | .AddInMemoryCollection(commandLineOpts.ConvertToConfig()); |
| | | 348 | | } |
| | | 349 | | |
| | | 350 | | private static void PrepareDatabaseProvider(IServiceProvider services) |
| | | 351 | | { |
| | 21 | 352 | | var factory = services.GetRequiredService<IDbContextFactory<JellyfinDbContext>>(); |
| | 21 | 353 | | var provider = services.GetRequiredService<IJellyfinDatabaseProvider>(); |
| | 21 | 354 | | provider.DbContextFactory = factory; |
| | 21 | 355 | | } |
| | | 356 | | } |
| | | 357 | | } |