StartupHelpers.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Runtime.InteropServices;
  8. using System.Runtime.Versioning;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using Emby.Server.Implementations;
  12. using MediaBrowser.Common.Configuration;
  13. using MediaBrowser.Controller.Extensions;
  14. using MediaBrowser.Model.IO;
  15. using Microsoft.Extensions.Configuration;
  16. using Microsoft.Extensions.Logging;
  17. using Serilog;
  18. using ILogger = Microsoft.Extensions.Logging.ILogger;
  19. namespace Jellyfin.Server.Helpers;
  20. /// <summary>
  21. /// A class containing helper methods for server startup.
  22. /// </summary>
  23. public static class StartupHelpers
  24. {
  25. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  26. /// <summary>
  27. /// Logs relevant environment variables and information about the host.
  28. /// </summary>
  29. /// <param name="logger">The logger to use.</param>
  30. /// <param name="appPaths">The application paths to use.</param>
  31. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  32. {
  33. // Distinct these to prevent users from reporting problems that aren't actually problems
  34. var commandLineArgs = Environment
  35. .GetCommandLineArgs()
  36. .Distinct();
  37. // Get all relevant environment variables
  38. var allEnvVars = Environment.GetEnvironmentVariables();
  39. var relevantEnvVars = new Dictionary<object, object>();
  40. foreach (var key in allEnvVars.Keys)
  41. {
  42. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString()!.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  43. {
  44. relevantEnvVars.Add(key, allEnvVars[key]!);
  45. }
  46. }
  47. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  48. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  49. logger.LogInformation("Operating system: {OS}", RuntimeInformation.OSDescription);
  50. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  51. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  52. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  53. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  54. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  55. logger.LogInformation("Log directory path: {LogDirectoryPath}", appPaths.LogDirectoryPath);
  56. logger.LogInformation("Config directory path: {ConfigurationDirectoryPath}", appPaths.ConfigurationDirectoryPath);
  57. logger.LogInformation("Cache path: {CachePath}", appPaths.CachePath);
  58. logger.LogInformation("Temp directory path: {TempDirPath}", appPaths.TempDirectory);
  59. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  60. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  61. }
  62. /// <summary>
  63. /// Create the data, config and log paths from the variety of inputs(command line args,
  64. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  65. /// for everything else the
  66. /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
  67. /// is followed.
  68. /// </summary>
  69. /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
  70. /// <returns><see cref="ServerApplicationPaths" />.</returns>
  71. public static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  72. {
  73. // LocalApplicationData
  74. // Windows: %LocalAppData%
  75. // macOS: NSApplicationSupportDirectory
  76. // UNIX: $XDG_DATA_HOME
  77. var dataDir = options.DataDir
  78. ?? Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR")
  79. ?? Path.Join(
  80. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify),
  81. "jellyfin");
  82. var configDir = options.ConfigDir ?? Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  83. if (configDir is null)
  84. {
  85. configDir = Path.Join(dataDir, "config");
  86. if (options.DataDir is null
  87. && !Directory.Exists(configDir)
  88. && !OperatingSystem.IsWindows()
  89. && !OperatingSystem.IsMacOS())
  90. {
  91. // UNIX: $XDG_CONFIG_HOME
  92. configDir = Path.Join(
  93. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify),
  94. "jellyfin");
  95. }
  96. }
  97. var cacheDir = options.CacheDir ?? Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  98. if (cacheDir is null)
  99. {
  100. if (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
  101. {
  102. cacheDir = Path.Join(dataDir, "cache");
  103. }
  104. else
  105. {
  106. cacheDir = Path.Join(GetXdgCacheHome(), "jellyfin");
  107. }
  108. }
  109. var webDir = options.WebDir ?? Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
  110. if (webDir is null)
  111. {
  112. webDir = Path.Join(AppContext.BaseDirectory, "jellyfin-web");
  113. }
  114. var logDir = options.LogDir ?? Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  115. if (logDir is null)
  116. {
  117. logDir = Path.Join(dataDir, "log");
  118. }
  119. // Normalize paths. Only possible with GetFullPath for now - https://github.com/dotnet/runtime/issues/2162
  120. dataDir = Path.GetFullPath(dataDir);
  121. logDir = Path.GetFullPath(logDir);
  122. configDir = Path.GetFullPath(configDir);
  123. cacheDir = Path.GetFullPath(cacheDir);
  124. webDir = Path.GetFullPath(webDir);
  125. // Ensure the main folders exist before we continue
  126. try
  127. {
  128. Directory.CreateDirectory(dataDir);
  129. Directory.CreateDirectory(logDir);
  130. Directory.CreateDirectory(configDir);
  131. Directory.CreateDirectory(cacheDir);
  132. }
  133. catch (IOException ex)
  134. {
  135. Console.Error.WriteLine("Error whilst attempting to create folder");
  136. Console.Error.WriteLine(ex.ToString());
  137. Environment.Exit(1);
  138. }
  139. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
  140. }
  141. private static string GetXdgCacheHome()
  142. {
  143. // $XDG_CACHE_HOME defines the base directory relative to which
  144. // user specific non-essential data files should be stored.
  145. var cacheHome = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  146. // If $XDG_CACHE_HOME is either not set or a relative path,
  147. // a default equal to $HOME/.cache should be used.
  148. if (cacheHome is null || !cacheHome.StartsWith('/'))
  149. {
  150. cacheHome = Path.Join(
  151. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.DoNotVerify),
  152. ".cache");
  153. }
  154. return cacheHome;
  155. }
  156. /// <summary>
  157. /// Gets the path for the unix socket Kestrel should bind to.
  158. /// </summary>
  159. /// <param name="startupConfig">The startup config.</param>
  160. /// <param name="appPaths">The application paths.</param>
  161. /// <returns>The path for Kestrel to bind to.</returns>
  162. public static string GetUnixSocketPath(IConfiguration startupConfig, IApplicationPaths appPaths)
  163. {
  164. var socketPath = startupConfig.GetUnixSocketPath();
  165. if (string.IsNullOrEmpty(socketPath))
  166. {
  167. const string SocketFile = "jellyfin.sock";
  168. var xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
  169. if (xdgRuntimeDir is null)
  170. {
  171. // Fall back to config dir
  172. socketPath = Path.Join(appPaths.ConfigurationDirectoryPath, SocketFile);
  173. }
  174. else
  175. {
  176. socketPath = Path.Join(xdgRuntimeDir, SocketFile);
  177. }
  178. }
  179. return socketPath;
  180. }
  181. /// <summary>
  182. /// Sets the unix file permissions for Kestrel's socket file.
  183. /// </summary>
  184. /// <param name="startupConfig">The startup config.</param>
  185. /// <param name="socketPath">The socket path.</param>
  186. /// <param name="logger">The logger.</param>
  187. [UnsupportedOSPlatform("windows")]
  188. public static void SetUnixSocketPermissions(IConfiguration startupConfig, string socketPath, ILogger logger)
  189. {
  190. var socketPerms = startupConfig.GetUnixSocketPermissions();
  191. if (!string.IsNullOrEmpty(socketPerms))
  192. {
  193. File.SetUnixFileMode(socketPath, (UnixFileMode)Convert.ToInt32(socketPerms, 8));
  194. logger.LogInformation("Kestrel unix socket permissions set to {SocketPerms}", socketPerms);
  195. }
  196. }
  197. /// <summary>
  198. /// Initialize the logging configuration file using the bundled resource file as a default if it doesn't exist
  199. /// already.
  200. /// </summary>
  201. /// <param name="appPaths">The application paths.</param>
  202. /// <returns>A task representing the creation of the configuration file, or a completed task if the file already exists.</returns>
  203. public static async Task InitLoggingConfigFile(IApplicationPaths appPaths)
  204. {
  205. // Do nothing if the config file already exists
  206. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, Program.LoggingConfigFileDefault);
  207. if (File.Exists(configPath))
  208. {
  209. return;
  210. }
  211. // Get a stream of the resource contents
  212. // NOTE: The .csproj name is used instead of the assembly name in the resource path
  213. const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json";
  214. Stream resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath)
  215. ?? throw new InvalidOperationException($"Invalid resource path: '{ResourcePath}'");
  216. await using (resource.ConfigureAwait(false))
  217. {
  218. Stream dst = new FileStream(configPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  219. await using (dst.ConfigureAwait(false))
  220. {
  221. // Copy the resource contents to the expected file path for the config file
  222. await resource.CopyToAsync(dst).ConfigureAwait(false);
  223. }
  224. }
  225. }
  226. /// <summary>
  227. /// Initialize Serilog using configuration and fall back to defaults on failure.
  228. /// </summary>
  229. /// <param name="configuration">The configuration object.</param>
  230. /// <param name="appPaths">The application paths.</param>
  231. public static void InitializeLoggingFramework(IConfiguration configuration, IApplicationPaths appPaths)
  232. {
  233. try
  234. {
  235. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  236. Log.Logger = new LoggerConfiguration()
  237. .ReadFrom.Configuration(configuration)
  238. .Enrich.FromLogContext()
  239. .Enrich.WithThreadId()
  240. .CreateLogger();
  241. }
  242. catch (Exception ex)
  243. {
  244. Log.Logger = new LoggerConfiguration()
  245. .WriteTo.Console(
  246. outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}",
  247. formatProvider: CultureInfo.InvariantCulture)
  248. .WriteTo.Async(x => x.File(
  249. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  250. rollingInterval: RollingInterval.Day,
  251. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}",
  252. formatProvider: CultureInfo.InvariantCulture,
  253. encoding: Encoding.UTF8))
  254. .Enrich.FromLogContext()
  255. .Enrich.WithThreadId()
  256. .CreateLogger();
  257. Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  258. }
  259. }
  260. /// <summary>
  261. /// Call static initialization methods for the application.
  262. /// </summary>
  263. public static void PerformStaticInitialization()
  264. {
  265. // Make sure we have all the code pages we can get
  266. // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.text.codepagesencodingprovider.instance?view=netcore-3.0#remarks
  267. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  268. }
  269. }