< Summary - Jellyfin

Information
Class: Jellyfin.Server.Helpers.StartupHelpers
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Helpers/StartupHelpers.cs
Line coverage
3%
Covered lines: 4
Uncovered lines: 107
Coverable lines: 111
Total lines: 304
Line coverage: 3.6%
Branch coverage
0%
Covered branches: 0
Total branches: 46
Branch coverage: 0%
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%210%
LogEnvironmentInfo(...)0%2040%
CreateApplicationPaths(...)0%1056320%
GetXdgCacheHome()0%2040%
GetUnixSocketPath(...)0%2040%
SetUnixSocketPermissions(...)0%620%
InitializeLoggingFramework(...)100%210%
PerformStaticInitialization()100%11100%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Helpers/StartupHelpers.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Globalization;
 4using System.IO;
 5using System.Linq;
 6using System.Net;
 7using System.Runtime.InteropServices;
 8using System.Runtime.Versioning;
 9using System.Text;
 10using System.Threading.Tasks;
 11using Emby.Server.Implementations;
 12using MediaBrowser.Common.Configuration;
 13using MediaBrowser.Controller.Extensions;
 14using MediaBrowser.Model.IO;
 15using Microsoft.Extensions.Configuration;
 16using Microsoft.Extensions.Logging;
 17using Serilog;
 18using ILogger = Microsoft.Extensions.Logging.ILogger;
 19
 20namespace Jellyfin.Server.Helpers;
 21
 22/// <summary>
 23/// A class containing helper methods for server startup.
 24/// </summary>
 25public static class StartupHelpers
 26{
 027    private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
 28
 29    /// <summary>
 30    /// Logs relevant environment variables and information about the host.
 31    /// </summary>
 32    /// <param name="logger">The logger to use.</param>
 33    /// <param name="appPaths">The application paths to use.</param>
 34    public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
 35    {
 36        // Distinct these to prevent users from reporting problems that aren't actually problems
 037        var commandLineArgs = Environment
 038            .GetCommandLineArgs()
 039            .Distinct();
 40
 41        // Get all relevant environment variables
 042        var allEnvVars = Environment.GetEnvironmentVariables();
 043        var relevantEnvVars = new Dictionary<object, object>();
 044        foreach (var key in allEnvVars.Keys)
 45        {
 046            if (_relevantEnvVarPrefixes.Any(prefix => key.ToString()!.StartsWith(prefix, StringComparison.OrdinalIgnoreC
 47            {
 048                relevantEnvVars.Add(key, allEnvVars[key]!);
 49            }
 50        }
 51
 052        logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
 053        logger.LogInformation("Arguments: {Args}", commandLineArgs);
 054        logger.LogInformation("Operating system: {OS}", RuntimeInformation.OSDescription);
 055        logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
 056        logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
 057        logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
 058        logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
 059        logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
 060        logger.LogInformation("Log directory path: {LogDirectoryPath}", appPaths.LogDirectoryPath);
 061        logger.LogInformation("Config directory path: {ConfigurationDirectoryPath}", appPaths.ConfigurationDirectoryPath
 062        logger.LogInformation("Cache path: {CachePath}", appPaths.CachePath);
 063        logger.LogInformation("Temp directory path: {TempDirPath}", appPaths.TempDirectory);
 064        logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
 065        logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
 066    }
 67
 68    /// <summary>
 69    /// Create the data, config and log paths from the variety of inputs(command line args,
 70    /// environment variables) or decide on what default to use. For Windows it's %AppPath%
 71    /// for everything else the
 72    /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
 73    /// is followed.
 74    /// </summary>
 75    /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
 76    /// <returns><see cref="ServerApplicationPaths" />.</returns>
 77    public static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
 78    {
 79        // LocalApplicationData
 80        // Windows: %LocalAppData%
 81        // macOS: NSApplicationSupportDirectory
 82        // UNIX: $XDG_DATA_HOME
 083        var dataDir = options.DataDir
 084            ?? Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR")
 085            ?? Path.Join(
 086                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
 087                "jellyfin");
 88
 089        var configDir = options.ConfigDir ?? Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
 090        if (configDir is null)
 91        {
 092            configDir = Path.Join(dataDir, "config");
 093            if (options.DataDir is null
 094                && !Directory.Exists(configDir)
 095                && !OperatingSystem.IsWindows()
 096                && !OperatingSystem.IsMacOS())
 97            {
 98                // UNIX: $XDG_CONFIG_HOME
 099                configDir = Path.Join(
 0100                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
 0101                    "jellyfin");
 102            }
 103        }
 104
 0105        var cacheDir = options.CacheDir ?? Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
 0106        if (cacheDir is null)
 107        {
 0108            if (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
 109            {
 0110                cacheDir = Path.Join(dataDir, "cache");
 111            }
 112            else
 113            {
 0114                cacheDir = Path.Join(GetXdgCacheHome(), "jellyfin");
 115            }
 116        }
 117
 0118        var webDir = options.WebDir ?? Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
 0119        if (webDir is null)
 120        {
 0121            webDir = Path.Join(AppContext.BaseDirectory, "jellyfin-web");
 122        }
 123
 0124        var logDir = options.LogDir ?? Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
 0125        if (logDir is null)
 126        {
 0127            logDir = Path.Join(dataDir, "log");
 128        }
 129
 130        // Normalize paths. Only possible with GetFullPath for now - https://github.com/dotnet/runtime/issues/2162
 0131        dataDir = Path.GetFullPath(dataDir);
 0132        logDir = Path.GetFullPath(logDir);
 0133        configDir = Path.GetFullPath(configDir);
 0134        cacheDir = Path.GetFullPath(cacheDir);
 0135        webDir = Path.GetFullPath(webDir);
 136
 137        // Ensure the main folders exist before we continue
 138        try
 139        {
 0140            Directory.CreateDirectory(dataDir);
 0141            Directory.CreateDirectory(logDir);
 0142            Directory.CreateDirectory(configDir);
 0143            Directory.CreateDirectory(cacheDir);
 0144        }
 0145        catch (IOException ex)
 146        {
 0147            Console.Error.WriteLine("Error whilst attempting to create folder");
 0148            Console.Error.WriteLine(ex.ToString());
 0149            Environment.Exit(1);
 0150        }
 151
 0152        return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
 153    }
 154
 155    private static string GetXdgCacheHome()
 156    {
 157        // $XDG_CACHE_HOME defines the base directory relative to which
 158        // user specific non-essential data files should be stored.
 0159        var cacheHome = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
 160
 161        // If $XDG_CACHE_HOME is either not set or a relative path,
 162        // a default equal to $HOME/.cache should be used.
 0163        if (cacheHome is null || !cacheHome.StartsWith('/'))
 164        {
 0165            cacheHome = Path.Join(
 0166                Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
 0167                ".cache");
 168        }
 169
 0170        return cacheHome;
 171    }
 172
 173    /// <summary>
 174    /// Gets the path for the unix socket Kestrel should bind to.
 175    /// </summary>
 176    /// <param name="startupConfig">The startup config.</param>
 177    /// <param name="appPaths">The application paths.</param>
 178    /// <returns>The path for Kestrel to bind to.</returns>
 179    public static string GetUnixSocketPath(IConfiguration startupConfig, IApplicationPaths appPaths)
 180    {
 0181        var socketPath = startupConfig.GetUnixSocketPath();
 182
 0183        if (string.IsNullOrEmpty(socketPath))
 184        {
 185            const string SocketFile = "jellyfin.sock";
 186
 0187            var xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
 0188            if (xdgRuntimeDir is null)
 189            {
 190                // Fall back to config dir
 0191                socketPath = Path.Join(appPaths.ConfigurationDirectoryPath, SocketFile);
 192            }
 193            else
 194            {
 0195                socketPath = Path.Join(xdgRuntimeDir, SocketFile);
 196            }
 197        }
 198
 0199        return socketPath;
 200    }
 201
 202    /// <summary>
 203    /// Sets the unix file permissions for Kestrel's socket file.
 204    /// </summary>
 205    /// <param name="startupConfig">The startup config.</param>
 206    /// <param name="socketPath">The socket path.</param>
 207    /// <param name="logger">The logger.</param>
 208    [UnsupportedOSPlatform("windows")]
 209    public static void SetUnixSocketPermissions(IConfiguration startupConfig, string socketPath, ILogger logger)
 210    {
 0211        var socketPerms = startupConfig.GetUnixSocketPermissions();
 212
 0213        if (!string.IsNullOrEmpty(socketPerms))
 214        {
 0215            File.SetUnixFileMode(socketPath, (UnixFileMode)Convert.ToInt32(socketPerms, 8));
 0216            logger.LogInformation("Kestrel unix socket permissions set to {SocketPerms}", socketPerms);
 217        }
 0218    }
 219
 220    /// <summary>
 221    /// Initialize the logging configuration file using the bundled resource file as a default if it doesn't exist
 222    /// already.
 223    /// </summary>
 224    /// <param name="appPaths">The application paths.</param>
 225    /// <returns>A task representing the creation of the configuration file, or a completed task if the file already exi
 226    public static async Task InitLoggingConfigFile(IApplicationPaths appPaths)
 227    {
 228        // Do nothing if the config file already exists
 229        string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, Program.LoggingConfigFileDefault);
 230        if (File.Exists(configPath))
 231        {
 232            return;
 233        }
 234
 235        // Get a stream of the resource contents
 236        // NOTE: The .csproj name is used instead of the assembly name in the resource path
 237        const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json";
 238        Stream resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath)
 239                          ?? throw new InvalidOperationException($"Invalid resource path: '{ResourcePath}'");
 240        await using (resource.ConfigureAwait(false))
 241        {
 242            Stream dst = new FileStream(configPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, IODefaults.Fil
 243            await using (dst.ConfigureAwait(false))
 244            {
 245                // Copy the resource contents to the expected file path for the config file
 246                await resource.CopyToAsync(dst).ConfigureAwait(false);
 247            }
 248        }
 249    }
 250
 251    /// <summary>
 252    /// Initialize Serilog using configuration and fall back to defaults on failure.
 253    /// </summary>
 254    /// <param name="configuration">The configuration object.</param>
 255    /// <param name="appPaths">The application paths.</param>
 256    public static void InitializeLoggingFramework(IConfiguration configuration, IApplicationPaths appPaths)
 257    {
 258        try
 259        {
 260            // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
 0261            Log.Logger = new LoggerConfiguration()
 0262                .ReadFrom.Configuration(configuration)
 0263                .Enrich.FromLogContext()
 0264                .Enrich.WithThreadId()
 0265                .CreateLogger();
 0266        }
 0267        catch (Exception ex)
 268        {
 0269            Log.Logger = new LoggerConfiguration()
 0270                .WriteTo.Console(
 0271                    outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewL
 0272                    formatProvider: CultureInfo.InvariantCulture)
 0273                .WriteTo.Async(x => x.File(
 0274                    Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
 0275                    rollingInterval: RollingInterval.Day,
 0276                    outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}
 0277                    formatProvider: CultureInfo.InvariantCulture,
 0278                    encoding: Encoding.UTF8))
 0279                .Enrich.FromLogContext()
 0280                .Enrich.WithThreadId()
 0281                .CreateLogger();
 282
 0283            Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
 0284        }
 0285    }
 286
 287    /// <summary>
 288    /// Call static initialization methods for the application.
 289    /// </summary>
 290    public static void PerformStaticInitialization()
 291    {
 292        // Make sure we have all the code pages we can get
 293        // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.text.codepagesencodingprovider.instance?view=netcore-
 1294        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
 295
 296        // Increase the max http request limit
 297        // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
 1298        ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
 299
 300        // Disable the "Expect: 100-Continue" header by default
 301        // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
 1302        ServicePointManager.Expect100Continue = false;
 1303    }
 304}