< Summary - Jellyfin

Information
Class: Jellyfin.Server.Program
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Program.cs
Line coverage
86%
Covered lines: 19
Uncovered lines: 3
Coverable lines: 22
Total lines: 348
Line coverage: 86.3%
Branch coverage
50%
Covered branches: 2
Total branches: 4
Branch coverage: 50%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
Main(...)100%210%
CreateAppConfiguration(...)100%11100%
ConfigureAppConfiguration(...)50%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? _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
 080            return Parser.Default.ParseArguments<StartupOptions>(args)
 081                .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
 107            // Use the logging framework for uncaught exceptions instead of std error
 108            AppDomain.CurrentDomain.UnhandledException += (_, e)
 109                => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
 110
 111            _logger.LogInformation(
 112                "Jellyfin version: {Version}",
 113                Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
 114
 115            StartupHelpers.LogEnvironmentInfo(_logger, appPaths);
 116
 117            // If hosting the web client, validate the client content path
 118            if (startupConfig.HostWebClient())
 119            {
 120                var webContentPath = appPaths.WebPath;
 121                if (!Directory.Exists(webContentPath) || !Directory.EnumerateFiles(webContentPath).Any())
 122                {
 123                    _logger.LogError(
 124                        "The server is expected to host the web client, but the provided content directory is either " +
 125                        "invalid or empty: {WebContentPath}. If you do not want to host the web client with the " +
 126                        "server, you may set the '--nowebclient' command line flag, or set" +
 127                        "'{ConfigKey}=false' in your config settings",
 128                        webContentPath,
 129                        HostWebClientKey);
 130                    Environment.ExitCode = 1;
 131                    return;
 132                }
 133            }
 134
 135            StorageHelper.TestCommonPathsForStorageCapacity(appPaths, StartupLogger.Logger.With(_loggerFactory.CreateLog
 136
 137            StartupHelpers.PerformStaticInitialization();
 138
 139            await ApplyStartupMigrationAsync(appPaths, startupConfig).ConfigureAwait(false);
 140
 141            do
 142            {
 143                await StartServer(appPaths, options, startupConfig).ConfigureAwait(false);
 144
 145                if (_restartOnShutdown)
 146                {
 147                    _startTimestamp = Stopwatch.GetTimestamp();
 148                    await _setupServer.StopAsync().ConfigureAwait(false);
 149                    await _setupServer.RunAsync().ConfigureAwait(false);
 150                }
 151            } while (_restartOnShutdown);
 152
 153            _setupServer.Dispose();
 154        }
 155
 156        private static async Task StartServer(IServerApplicationPaths appPaths, StartupOptions options, IConfiguration s
 157        {
 158            using CoreAppHost appHost = new CoreAppHost(
 159                            appPaths,
 160                            _loggerFactory,
 161                            options,
 162                            startupConfig);
 163            _appHost = appHost;
 164            var configurationCompleted = false;
 165            try
 166            {
 167                _jellyfinHost = Host.CreateDefaultBuilder()
 168                    .UseConsoleLifetime()
 169                    .ConfigureServices(services => appHost.Init(services))
 170                    .ConfigureWebHostDefaults(webHostBuilder =>
 171                    {
 172                        webHostBuilder.ConfigureWebHostBuilder(appHost, startupConfig, appPaths, _logger);
 173                        if (bool.TryParse(Environment.GetEnvironmentVariable("JELLYFIN_ENABLE_IIS"), out var iisEnabled)
 174                        {
 175                            _logger.LogCritical("UNSUPPORTED HOSTING ENVIRONMENT Microsoft Internet Information Services
 176                            webHostBuilder.UseIIS();
 177                        }
 178                    })
 179                    .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(options, appPaths, startupConf
 180                    .UseSerilog()
 181                    .ConfigureServices(e => e.AddTransient<IStartupLogger, StartupLogger>().AddSingleton<IServiceCollect
 182                    .Build();
 183
 184                // Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collect
 185                appHost.ServiceProvider = _jellyfinHost.Services;
 186                PrepareDatabaseProvider(appHost.ServiceProvider);
 187
 188                if (!string.IsNullOrWhiteSpace(_restoreFromBackup))
 189                {
 190                    await appHost.ServiceProvider.GetService<IBackupService>()!.RestoreBackupAsync(_restoreFromBackup).C
 191                    _restoreFromBackup = null;
 192                    _restartOnShutdown = true;
 193                    return;
 194                }
 195
 196                var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(appHost.Servi
 197                await jellyfinMigrationService.PrepareSystemForMigration(_logger).ConfigureAwait(false);
 198                await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStageTypes.CoreInitialisation, appHost.
 199
 200                await appHost.InitializeServices(startupConfig).ConfigureAwait(false);
 201
 202                await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStageTypes.AppInitialisation, appHost.S
 203                await jellyfinMigrationService.CleanupSystemAfterMigration(_logger).ConfigureAwait(false);
 204                try
 205                {
 206                    configurationCompleted = true;
 207                    await _setupServer!.StopAsync().ConfigureAwait(false);
 208                    await _jellyfinHost.StartAsync().ConfigureAwait(false);
 209
 210                    if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
 211                    {
 212                        var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
 213
 214                        StartupHelpers.SetUnixSocketPermissions(startupConfig, socketPath, _logger);
 215                    }
 216                }
 217                catch (Exception)
 218                {
 219                    _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bin
 220                    throw;
 221                }
 222
 223                await appHost.RunStartupTasksAsync().ConfigureAwait(false);
 224
 225                _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(_startTimestamp));
 226
 227                await _jellyfinHost.WaitForShutdownAsync().ConfigureAwait(false);
 228                _restartOnShutdown = appHost.ShouldRestart;
 229                _restoreFromBackup = appHost.RestoreBackupPath;
 230            }
 231            catch (Exception ex)
 232            {
 233                _restartOnShutdown = false;
 234                _logger.LogCritical(ex, "Error while starting server");
 235                if (_setupServer!.IsAlive && !configurationCompleted)
 236                {
 237                    _setupServer!.SoftStop();
 238                    await Task.Delay(TimeSpan.FromMinutes(10)).ConfigureAwait(false);
 239                    await _setupServer!.StopAsync().ConfigureAwait(false);
 240                }
 241            }
 242            finally
 243            {
 244                // Don't throw additional exception if startup failed.
 245                if (appHost.ServiceProvider is not null)
 246                {
 247                    _logger.LogInformation("Running query planner optimizations in the database... This might take a whi
 248
 249                    var databaseProvider = appHost.ServiceProvider.GetRequiredService<IJellyfinDatabaseProvider>();
 250                    using var shutdownSource = new CancellationTokenSource();
 251                    shutdownSource.CancelAfter((int)TimeSpan.FromSeconds(60).TotalMicroseconds);
 252                    await databaseProvider.RunShutdownTask(shutdownSource.Token).ConfigureAwait(false);
 253                }
 254
 255                _appHost = null;
 256                _jellyfinHost?.Dispose();
 257            }
 258        }
 259
 260        /// <summary>
 261        /// [Internal]Runs the startup Migrations.
 262        /// </summary>
 263        /// <remarks>
 264        /// Not intended to be used other then by jellyfin and its tests.
 265        /// </remarks>
 266        /// <param name="appPaths">Application Paths.</param>
 267        /// <param name="startupConfig">Startup Config.</param>
 268        /// <returns>A task.</returns>
 269        public static async Task ApplyStartupMigrationAsync(ServerApplicationPaths appPaths, IConfiguration startupConfi
 270        {
 271            _migrationLogger = StartupLogger.Logger.BeginGroup($"Migration Service");
 272            var startupConfigurationManager = new ServerConfigurationManager(appPaths, _loggerFactory, new MyXmlSerializ
 273            startupConfigurationManager.AddParts([new DatabaseConfigurationFactory()]);
 274            var migrationStartupServiceProvider = new ServiceCollection()
 275                .AddLogging(d => d.AddSerilog())
 276                .AddJellyfinDbContext(startupConfigurationManager, startupConfig)
 277                .AddSingleton<IApplicationPaths>(appPaths)
 278                .AddSingleton<ServerApplicationPaths>(appPaths)
 279                .AddSingleton<IStartupLogger>(_migrationLogger);
 280
 281            migrationStartupServiceProvider.AddSingleton(migrationStartupServiceProvider);
 282            var startupService = migrationStartupServiceProvider.BuildServiceProvider();
 283
 284            PrepareDatabaseProvider(startupService);
 285
 286            var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(startupService);
 287            await jellyfinMigrationService.CheckFirstTimeRunOrMigration(appPaths).ConfigureAwait(false);
 288            await jellyfinMigrationService.MigrateStepAsync(Migrations.Stages.JellyfinMigrationStageTypes.PreInitialisat
 289        }
 290
 291        /// <summary>
 292        /// [Internal]Runs the Jellyfin migrator service with the Core stage.
 293        /// </summary>
 294        /// <remarks>
 295        /// Not intended to be used other then by jellyfin and its tests.
 296        /// </remarks>
 297        /// <param name="serviceProvider">The service provider.</param>
 298        /// <param name="jellyfinMigrationStage">The stage to run.</param>
 299        /// <returns>A task.</returns>
 300        public static async Task ApplyCoreMigrationsAsync(IServiceProvider serviceProvider, Migrations.Stages.JellyfinMi
 301        {
 302            var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(serviceProvider, 
 303            await jellyfinMigrationService.MigrateStepAsync(jellyfinMigrationStage, serviceProvider).ConfigureAwait(fals
 304        }
 305
 306        /// <summary>
 307        /// Create the application configuration.
 308        /// </summary>
 309        /// <param name="commandLineOpts">The command line options passed to the program.</param>
 310        /// <param name="appPaths">The application paths.</param>
 311        /// <returns>The application configuration.</returns>
 312        public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
 313        {
 21314            return new ConfigurationBuilder()
 21315                .ConfigureAppConfiguration(commandLineOpts, appPaths)
 21316                .Build();
 317        }
 318
 319        private static IConfigurationBuilder ConfigureAppConfiguration(
 320            this IConfigurationBuilder config,
 321            StartupOptions commandLineOpts,
 322            IApplicationPaths appPaths,
 323            IConfiguration? startupConfig = null)
 324        {
 325            // Use the swagger API page as the default redirect path if not hosting the web client
 21326            var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
 21327            if (startupConfig is not null && !startupConfig.HostWebClient())
 328            {
 0329                inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger";
 330            }
 331
 21332            return config
 21333                .SetBasePath(appPaths.ConfigurationDirectoryPath)
 21334                .AddInMemoryCollection(inMemoryDefaultConfig)
 21335                .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
 21336                .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
 21337                .AddEnvironmentVariables("JELLYFIN_")
 21338                .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
 339        }
 340
 341        private static void PrepareDatabaseProvider(IServiceProvider services)
 342        {
 21343            var factory = services.GetRequiredService<IDbContextFactory<JellyfinDbContext>>();
 21344            var provider = services.GetRequiredService<IJellyfinDatabaseProvider>();
 21345            provider.DbContextFactory = factory;
 21346        }
 347    }
 348}