< Summary - Jellyfin

Information
Class: Jellyfin.Server.Program
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Program.cs
Line coverage
20%
Covered lines: 37
Uncovered lines: 145
Coverable lines: 182
Total lines: 421
Line coverage: 20.3%
Branch coverage
1%
Covered branches: 1
Total branches: 54
Branch coverage: 1.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/31/2026 - 12:15:44 AM Line coverage: 23.7% (38/160) Branch coverage: 2% (1/48) Total lines: 3706/28/2026 - 12:15:35 AM Line coverage: 23% (38/165) Branch coverage: 2% (1/48) Total lines: 37710/29/2026 - 12:17:11 AM Line coverage: 20.5% (37/180) Branch coverage: 2% (1/48) Total lines: 41511/13/2026 - 12:19:51 AM Line coverage: 20.3% (37/182) Branch coverage: 1.8% (1/54) Total lines: 421 5/31/2026 - 12:15:44 AM Line coverage: 23.7% (38/160) Branch coverage: 2% (1/48) Total lines: 3706/28/2026 - 12:15:35 AM Line coverage: 23% (38/165) Branch coverage: 2% (1/48) Total lines: 37710/29/2026 - 12:17:11 AM Line coverage: 20.5% (37/180) Branch coverage: 2% (1/48) Total lines: 41511/13/2026 - 12:19:51 AM Line coverage: 20.3% (37/182) Branch coverage: 1.8% (1/54) Total lines: 421

Coverage delta

Coverage delta 3 -3

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
Main(...)100%210%
StartApp()0%110100%
StartServer()0%1640400%
ApplyStartupMigrationAsync()100%11100%
ApplyCoreMigrationsAsync()100%11100%
OptimizeDatabaseAfterMigrationAsync()100%210%
CreateAppConfiguration(...)100%11100%
ConfigureAppConfiguration(...)25%4490%
PrepareDatabaseProvider(...)100%11100%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Program.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Diagnostics;
 4using System.Globalization;
 5using System.IO;
 6using System.Linq;
 7using System.Reflection;
 8using System.Threading;
 9using System.Threading.Tasks;
 10using CommandLine;
 11using Emby.Server.Implementations;
 12using Emby.Server.Implementations.Configuration;
 13using Emby.Server.Implementations.Serialization;
 14using Jellyfin.Database.Implementations;
 15using Jellyfin.Server.Extensions;
 16using Jellyfin.Server.Helpers;
 17using Jellyfin.Server.Implementations.DatabaseConfiguration;
 18using Jellyfin.Server.Implementations.Extensions;
 19using Jellyfin.Server.Implementations.StorageHelpers;
 20using Jellyfin.Server.Implementations.SystemBackupService;
 21using Jellyfin.Server.Migrations;
 22using Jellyfin.Server.Migrations.Stages;
 23using Jellyfin.Server.ServerSetupApp;
 24using MediaBrowser.Common.Configuration;
 25using MediaBrowser.Common.Net;
 26using MediaBrowser.Controller;
 27using Microsoft.AspNetCore.Hosting;
 28using Microsoft.EntityFrameworkCore;
 29using Microsoft.Extensions.Configuration;
 30using Microsoft.Extensions.DependencyInjection;
 31using Microsoft.Extensions.Hosting;
 32using Microsoft.Extensions.Logging;
 33using Microsoft.Extensions.Logging.Abstractions;
 34using Serilog;
 35using Serilog.Extensions.Logging;
 36using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
 37using ILogger = Microsoft.Extensions.Logging.ILogger;
 38
 39namespace 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
 156        private static readonly SerilogLoggerFactory _loggerFactory = new SerilogLoggerFactory();
 57        private static SetupServer? _setupServer;
 58        private static CoreAppHost? _appHost;
 159        private static IHost? _jellyfinHost = null;
 60        private static long _startTimestamp;
 161        private static ILogger _logger = NullLogger.Instance;
 62        private static bool _restartOnShutdown;
 63        private static IStartupLogger<JellyfinMigrationService>? _migrationLogger;
 64        private static bool _optimizeDatabaseAfterMigration;
 65        private static string? _restoreFromBackup;
 66
 67        /// <summary>
 68        /// The entry point of the application.
 69        /// </summary>
 70        /// <param name="args">The command line arguments passed.</param>
 71        /// <returns><see cref="Task" />.</returns>
 72        public static Task Main(string[] args)
 73        {
 74            static Task ErrorParsingArguments(IEnumerable<Error> errors)
 75            {
 76                Environment.ExitCode = 1;
 77                return Task.CompletedTask;
 78            }
 79
 80            // Parse the command line arguments and either start the app or exit indicating error
 081            return Parser.Default.ParseArguments<StartupOptions>(args)
 082                .MapResult(StartApp, ErrorParsingArguments);
 83        }
 84
 85        private static async Task StartApp(StartupOptions options)
 86        {
 087            _restoreFromBackup = options.RestoreArchive;
 088            _startTimestamp = Stopwatch.GetTimestamp();
 089            ServerApplicationPaths appPaths = StartupHelpers.CreateApplicationPaths(options);
 090            appPaths.MakeSanityCheckOrThrow();
 91
 92            // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
 093            Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
 94
 95            // Enable cl-va P010 interop for tonemapping on Intel VAAPI
 096            Environment.SetEnvironmentVariable("NEOReadDebugKeys", "1");
 097            Environment.SetEnvironmentVariable("EnableExtendedVaFormats", "1");
 98
 099            await StartupHelpers.InitLoggingConfigFile(appPaths).ConfigureAwait(false);
 100
 101            // Create an instance of the application configuration to use for application startup
 0102            IConfiguration startupConfig = CreateAppConfiguration(options, appPaths);
 0103            StartupHelpers.InitializeLoggingFramework(startupConfig, appPaths);
 0104            _setupServer = new SetupServer(static () => _jellyfinHost?.Services?.GetService<INetworkManager>(), appPaths
 0105            await _setupServer.RunAsync().ConfigureAwait(false);
 0106            _logger = _loggerFactory.CreateLogger("Main");
 0107            StartupLogger.Logger = new StartupLogger(_logger);
 108
 109            // Use the logging framework for uncaught exceptions instead of std error
 0110            AppDomain.CurrentDomain.UnhandledException += (_, e)
 0111                => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
 112
 0113            _logger.LogInformation(
 0114                "Jellyfin version: {Version}",
 0115                Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
 116
 0117            StartupHelpers.LogEnvironmentInfo(_logger, appPaths);
 118
 119            // If hosting the web client, validate the client content path
 0120            if (startupConfig.HostWebClient())
 121            {
 0122                var webContentPath = appPaths.WebPath;
 0123                if (!Directory.Exists(webContentPath) || !Directory.EnumerateFiles(webContentPath).Any())
 124                {
 0125                    _logger.LogError(
 0126                        "The server is expected to host the web client, but the provided content directory is either " +
 0127                        "invalid or empty: {WebContentPath}. If you do not want to host the web client with the " +
 0128                        "server, you may set the '--nowebclient' command line flag, or set" +
 0129                        "'{ConfigKey}=false' in your config settings",
 0130                        webContentPath,
 0131                        HostWebClientKey);
 0132                    Environment.ExitCode = 1;
 0133                    return;
 134                }
 135            }
 136
 0137            SetupServer.ReportActivity(StartupActivity.CheckingStorage);
 0138            StorageHelper.TestCommonPathsForStorageCapacity(appPaths, StartupLogger.Logger.With(_loggerFactory.CreateLog
 139
 0140            StartupHelpers.PerformStaticInitialization();
 141
 0142            SetupServer.ReportActivity(StartupActivity.Initializing);
 0143            await ApplyStartupMigrationAsync(appPaths, startupConfig, options).ConfigureAwait(false);
 144
 145            do
 146            {
 0147                await StartServer(appPaths, options, startupConfig).ConfigureAwait(false);
 148
 0149                if (_restartOnShutdown)
 150                {
 0151                    _startTimestamp = Stopwatch.GetTimestamp();
 152                    try
 153                    {
 0154                        await _setupServer.StopAsync().ConfigureAwait(false);
 0155                        await _setupServer.RunAsync().ConfigureAwait(false);
 0156                    }
 0157                    catch (Exception ex)
 158                    {
 159                        // The startup page is optional, losing it must not take the restart down with it.
 0160                        _logger.LogError(ex, "Failed to bring the startup server back up");
 0161                    }
 162                }
 0163            } while (_restartOnShutdown);
 164
 0165            _setupServer.Dispose();
 0166        }
 167
 168        private static async Task StartServer(IServerApplicationPaths appPaths, StartupOptions options, IConfiguration s
 169        {
 0170            using CoreAppHost appHost = new CoreAppHost(
 0171                            appPaths,
 0172                            _loggerFactory,
 0173                            options,
 0174                            startupConfig);
 0175            var configurationCompleted = false;
 176            try
 177            {
 0178                _jellyfinHost = Host.CreateDefaultBuilder()
 0179                    .UseConsoleLifetime()
 0180                    .ConfigureServices(services => appHost.Init(services))
 0181                    .ConfigureWebHostDefaults(webHostBuilder =>
 0182                    {
 0183                        webHostBuilder.ConfigureWebHostBuilder(appHost, startupConfig, appPaths, _logger);
 0184                        if (bool.TryParse(Environment.GetEnvironmentVariable("JELLYFIN_ENABLE_IIS"), out var iisEnabled)
 0185                        {
 0186                            _logger.LogCritical("UNSUPPORTED HOSTING ENVIRONMENT Microsoft Internet Information Services
 0187                            webHostBuilder.UseIIS();
 0188                        }
 0189                    })
 0190                    .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(options, appPaths, startupConf
 0191                    .UseSerilog()
 0192                    .ConfigureServices(e => e.RegisterStartupLogger())
 0193                    .Build();
 194
 195                /*
 196                 * Initialize the transcode path marker so we avoid starting Jellyfin in a broken state.
 197                 * This should really be a part of IApplicationPaths but this path is configured differently.
 198                 */
 0199                _ = appHost.ConfigurationManager.GetTranscodePath();
 200
 201                // Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collect
 0202                appHost.ServiceProvider = _jellyfinHost.Services;
 0203                PrepareDatabaseProvider(appHost.ServiceProvider);
 204
 0205                if (!string.IsNullOrWhiteSpace(_restoreFromBackup))
 206                {
 0207                    SetupServer.ReportActivity(StartupActivity.RestoringBackup);
 0208                    await appHost.ServiceProvider.GetService<IBackupService>()!.RestoreBackupAsync(_restoreFromBackup).C
 0209                    _restoreFromBackup = null;
 0210                    _restartOnShutdown = true;
 0211                    return;
 212                }
 213
 0214                var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(appHost.Servi
 0215                SetupServer.ReportActivity(StartupActivity.PreparingMigrations);
 0216                await jellyfinMigrationService.PrepareSystemForMigration(_logger).ConfigureAwait(false);
 217                // "Preparing migrations" carries through the DB read; per-migration progress is reported
 218                // as "Running migration X of Y" from inside the step once the pending set is known.
 0219                _optimizeDatabaseAfterMigration |= await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStag
 220
 0221                SetupServer.ReportActivity(StartupActivity.InitializingServices);
 0222                await appHost.InitializeServices(startupConfig).ConfigureAwait(false);
 0223                _appHost = appHost;
 224
 0225                _optimizeDatabaseAfterMigration |= await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStag
 0226                await jellyfinMigrationService.CleanupSystemAfterMigration(_logger).ConfigureAwait(false);
 0227                await OptimizeDatabaseAfterMigrationAsync(appHost.ServiceProvider).ConfigureAwait(false);
 228                try
 229                {
 0230                    configurationCompleted = true;
 0231                    await _setupServer!.StopAsync().ConfigureAwait(false);
 232
 0233                    if (options.StartupMode is null or Configuration.StartupMode.MediaServer)
 234                    {
 0235                        await _jellyfinHost.StartAsync().ConfigureAwait(false);
 236
 0237                        if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
 238                        {
 0239                            var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
 240
 0241                            StartupHelpers.SetUnixSocketPermissions(startupConfig, socketPath, _logger);
 242                        }
 243                    }
 0244                }
 0245                catch (Exception)
 246                {
 0247                    _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bin
 0248                    throw;
 249                }
 250
 0251                if (options.StartupMode is null or Configuration.StartupMode.MediaServer)
 252                {
 0253                    await appHost.RunStartupTasksAsync().ConfigureAwait(false);
 0254                    _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(_startTimestamp));
 255
 256                    try
 257                    {
 0258                        await _jellyfinHost.WaitForShutdownAsync().ConfigureAwait(false);
 0259                    }
 0260                    catch (Exception ex)
 261                    {
 262                        // A hosted service that throws or times out while stopping must not cancel a pending restart.
 0263                        _logger.LogError(ex, "Failure while stopping the server");
 0264                    }
 265                }
 266
 0267                _restartOnShutdown = appHost.ShouldRestart;
 0268                _restoreFromBackup = appHost.RestoreBackupPath;
 0269            }
 0270            catch (Exception ex)
 271            {
 0272                _restartOnShutdown = false;
 0273                _logger.LogCritical(ex, "Error while starting server");
 0274                if (options.StartupMode is not (null or Configuration.StartupMode.MediaServer))
 275                {
 276                    // A MigrateSystem or SeedSystem run is started from a script, which can only tell that it failed by
 0277                    Environment.ExitCode = 1;
 278                }
 279
 0280                if (_setupServer!.IsAlive && !configurationCompleted)
 281                {
 0282                    _setupServer!.SoftStop();
 0283                    if (options.StartupMode is null or Configuration.StartupMode.MediaServer)
 284                    {
 0285                        await Task.Delay(TimeSpan.FromMinutes(10)).ConfigureAwait(false);
 286                    }
 287
 0288                    await _setupServer!.StopAsync().ConfigureAwait(false);
 289                }
 290            }
 291            finally
 292            {
 293                // Don't throw additional exception if startup failed.
 0294                if (appHost.ServiceProvider is not null)
 295                {
 0296                    _logger.LogInformation("Preparing the database for shutdown...");
 297
 0298                    var databaseProvider = appHost.ServiceProvider.GetRequiredService<IJellyfinDatabaseProvider>();
 0299                    await databaseProvider.RunShutdownTask(CancellationToken.None).ConfigureAwait(false);
 300                }
 301
 0302                _appHost = null;
 0303                _jellyfinHost?.Dispose();
 0304                _jellyfinHost = null;
 305            }
 0306        }
 307
 308        /// <summary>
 309        /// [Internal]Runs the startup Migrations.
 310        /// </summary>
 311        /// <remarks>
 312        /// Not intended to be used other then by jellyfin and its tests.
 313        /// </remarks>
 314        /// <param name="appPaths">Application Paths.</param>
 315        /// <param name="startupConfig">Startup Config.</param>
 316        /// <param name="startupOptions">The applications startup options.</param>
 317        /// <returns>A task.</returns>
 318        public static async Task ApplyStartupMigrationAsync(ServerApplicationPaths appPaths, IConfiguration startupConfi
 319        {
 28320            _migrationLogger = StartupLogger.Logger.BeginGroup<JellyfinMigrationService>($"Migration Service");
 28321            var startupConfigurationManager = new ServerConfigurationManager(appPaths, _loggerFactory, new MyXmlSerializ
 28322            startupConfigurationManager.AddParts([new DatabaseConfigurationFactory()]);
 28323            var migrationStartupServiceProvider = new ServiceCollection()
 28324                .AddLogging(d => d.AddSerilog())
 28325                .AddJellyfinDbContext(startupConfigurationManager, startupConfig)
 28326                .AddSingleton<IApplicationPaths>(appPaths)
 28327                .AddSingleton<ServerApplicationPaths>(appPaths)
 28328                .RegisterStartupLogger();
 329
 28330            var startupService = migrationStartupServiceProvider.BuildServiceProvider();
 331
 28332            PrepareDatabaseProvider(startupService);
 333
 28334            var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(startupService);
 28335            await jellyfinMigrationService.CheckFirstTimeRunOrMigration(appPaths, startupOptions).ConfigureAwait(false);
 27336            _optimizeDatabaseAfterMigration |= await jellyfinMigrationService.MigrateStepAsync(Migrations.Stages.Jellyfi
 27337        }
 338
 339        /// <summary>
 340        /// [Internal]Runs the Jellyfin migrator service with the Core stage.
 341        /// </summary>
 342        /// <remarks>
 343        /// Not intended to be used other then by jellyfin and its tests.
 344        /// </remarks>
 345        /// <param name="serviceProvider">The service provider.</param>
 346        /// <param name="jellyfinMigrationStage">The stage to run.</param>
 347        /// <returns>A task.</returns>
 348        public static async Task ApplyCoreMigrationsAsync(IServiceProvider serviceProvider, Migrations.Stages.JellyfinMi
 349        {
 54350            var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(serviceProvider, 
 54351            _optimizeDatabaseAfterMigration |= await jellyfinMigrationService.MigrateStepAsync(jellyfinMigrationStage, s
 54352        }
 353
 354        private static async Task OptimizeDatabaseAfterMigrationAsync(IServiceProvider serviceProvider)
 355        {
 0356            if (!_optimizeDatabaseAfterMigration)
 357            {
 0358                return;
 359            }
 360
 361            // Reset first: a restart runs no migrations and must not optimize again.
 0362            _optimizeDatabaseAfterMigration = false;
 0363            SetupServer.ReportActivity(StartupActivity.OptimizingDatabase);
 0364            _logger.LogInformation("Migrations have been applied, optimizing the database... This might take a while");
 365
 366            try
 367            {
 368                // Deliberately untimed: incomplete statistics are worse than a slow start.
 0369                var databaseProvider = serviceProvider.GetRequiredService<IJellyfinDatabaseProvider>();
 0370                await databaseProvider.RunScheduledOptimisation(CancellationToken.None).ConfigureAwait(false);
 0371            }
 0372            catch (Exception ex)
 373            {
 374                // A missed optimization only costs performance, so never fail startup over this.
 0375                _logger.LogError(ex, "Error while optimizing the database after migration");
 0376            }
 0377        }
 378
 379        /// <summary>
 380        /// Create the application configuration.
 381        /// </summary>
 382        /// <param name="commandLineOpts">The command line options passed to the program.</param>
 383        /// <param name="appPaths">The application paths.</param>
 384        /// <returns>The application configuration.</returns>
 385        public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
 386        {
 28387            return new ConfigurationBuilder()
 28388                .ConfigureAppConfiguration(commandLineOpts, appPaths)
 28389                .Build();
 390        }
 391
 392        private static IConfigurationBuilder ConfigureAppConfiguration(
 393            this IConfigurationBuilder config,
 394            StartupOptions commandLineOpts,
 395            IApplicationPaths appPaths,
 396            IConfiguration? startupConfig = null)
 397        {
 398            // Use the swagger API page as the default redirect path if not hosting the web client
 28399            var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
 28400            if (startupConfig is not null && !startupConfig.HostWebClient())
 401            {
 0402                inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger";
 403            }
 404
 28405            return config
 28406                .SetBasePath(appPaths.ConfigurationDirectoryPath)
 28407                .AddInMemoryCollection(inMemoryDefaultConfig)
 28408                .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
 28409                .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
 28410                .AddEnvironmentVariables("JELLYFIN_")
 28411                .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
 412        }
 413
 414        private static void PrepareDatabaseProvider(IServiceProvider services)
 415        {
 28416            var factory = services.GetRequiredService<IDbContextFactory<JellyfinDbContext>>();
 28417            var provider = services.GetRequiredService<IJellyfinDatabaseProvider>();
 28418            provider.DbContextFactory = factory;
 28419        }
 420    }
 421}