StartupHelpers.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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("Web resources path: {WebPath}", appPaths.WebPath);
  59. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  60. }
  61. /// <summary>
  62. /// Create the data, config and log paths from the variety of inputs(command line args,
  63. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  64. /// for everything else the
  65. /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
  66. /// is followed.
  67. /// </summary>
  68. /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
  69. /// <returns><see cref="ServerApplicationPaths" />.</returns>
  70. public static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  71. {
  72. // LocalApplicationData
  73. // Windows: %LocalAppData%
  74. // macOS: NSApplicationSupportDirectory
  75. // UNIX: $XDG_DATA_HOME
  76. var dataDir = options.DataDir
  77. ?? Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR")
  78. ?? Path.Join(
  79. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  80. "jellyfin");
  81. var configDir = options.ConfigDir ?? Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  82. if (configDir is null)
  83. {
  84. configDir = Path.Join(dataDir, "config");
  85. if (options.DataDir is null
  86. && !Directory.Exists(configDir)
  87. && !OperatingSystem.IsWindows()
  88. && !OperatingSystem.IsMacOS())
  89. {
  90. // UNIX: $XDG_CONFIG_HOME
  91. configDir = Path.Join(
  92. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  93. "jellyfin");
  94. }
  95. }
  96. var cacheDir = options.CacheDir ?? Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  97. if (cacheDir is null)
  98. {
  99. if (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
  100. {
  101. cacheDir = Path.Join(dataDir, "cache");
  102. }
  103. else
  104. {
  105. cacheDir = Path.Join(GetXdgCacheHome(), "jellyfin");
  106. }
  107. }
  108. var webDir = options.WebDir ?? Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
  109. if (webDir is null)
  110. {
  111. webDir = Path.Join(AppContext.BaseDirectory, "jellyfin-web");
  112. }
  113. var logDir = options.LogDir ?? Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  114. if (logDir is null)
  115. {
  116. logDir = Path.Join(dataDir, "log");
  117. }
  118. // Normalize paths. Only possible with GetFullPath for now - https://github.com/dotnet/runtime/issues/2162
  119. dataDir = Path.GetFullPath(dataDir);
  120. logDir = Path.GetFullPath(logDir);
  121. configDir = Path.GetFullPath(configDir);
  122. cacheDir = Path.GetFullPath(cacheDir);
  123. webDir = Path.GetFullPath(webDir);
  124. // Ensure the main folders exist before we continue
  125. try
  126. {
  127. Directory.CreateDirectory(dataDir);
  128. Directory.CreateDirectory(logDir);
  129. Directory.CreateDirectory(configDir);
  130. Directory.CreateDirectory(cacheDir);
  131. }
  132. catch (IOException ex)
  133. {
  134. Console.Error.WriteLine("Error whilst attempting to create folder");
  135. Console.Error.WriteLine(ex.ToString());
  136. Environment.Exit(1);
  137. }
  138. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
  139. }
  140. private static string GetXdgCacheHome()
  141. {
  142. // $XDG_CACHE_HOME defines the base directory relative to which
  143. // user specific non-essential data files should be stored.
  144. var cacheHome = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  145. // If $XDG_CACHE_HOME is either not set or a relative path,
  146. // a default equal to $HOME/.cache should be used.
  147. if (cacheHome is null || !cacheHome.StartsWith('/'))
  148. {
  149. cacheHome = Path.Join(
  150. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  151. ".cache");
  152. }
  153. return cacheHome;
  154. }
  155. /// <summary>
  156. /// Gets the path for the unix socket Kestrel should bind to.
  157. /// </summary>
  158. /// <param name="startupConfig">The startup config.</param>
  159. /// <param name="appPaths">The application paths.</param>
  160. /// <returns>The path for Kestrel to bind to.</returns>
  161. public static string GetUnixSocketPath(IConfiguration startupConfig, IApplicationPaths appPaths)
  162. {
  163. var socketPath = startupConfig.GetUnixSocketPath();
  164. if (string.IsNullOrEmpty(socketPath))
  165. {
  166. const string SocketFile = "jellyfin.sock";
  167. var xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
  168. if (xdgRuntimeDir is null)
  169. {
  170. // Fall back to config dir
  171. socketPath = Path.Join(appPaths.ConfigurationDirectoryPath, SocketFile);
  172. }
  173. else
  174. {
  175. socketPath = Path.Join(xdgRuntimeDir, SocketFile);
  176. }
  177. }
  178. return socketPath;
  179. }
  180. /// <summary>
  181. /// Sets the unix file permissions for Kestrel's socket file.
  182. /// </summary>
  183. /// <param name="startupConfig">The startup config.</param>
  184. /// <param name="socketPath">The socket path.</param>
  185. /// <param name="logger">The logger.</param>
  186. [UnsupportedOSPlatform("windows")]
  187. public static void SetUnixSocketPermissions(IConfiguration startupConfig, string socketPath, ILogger logger)
  188. {
  189. var socketPerms = startupConfig.GetUnixSocketPermissions();
  190. if (!string.IsNullOrEmpty(socketPerms))
  191. {
  192. File.SetUnixFileMode(socketPath, (UnixFileMode)Convert.ToInt32(socketPerms, 8));
  193. logger.LogInformation("Kestrel unix socket permissions set to {SocketPerms}", socketPerms);
  194. }
  195. }
  196. /// <summary>
  197. /// Initialize the logging configuration file using the bundled resource file as a default if it doesn't exist
  198. /// already.
  199. /// </summary>
  200. /// <param name="appPaths">The application paths.</param>
  201. /// <returns>A task representing the creation of the configuration file, or a completed task if the file already exists.</returns>
  202. public static async Task InitLoggingConfigFile(IApplicationPaths appPaths)
  203. {
  204. // Do nothing if the config file already exists
  205. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, Program.LoggingConfigFileDefault);
  206. if (File.Exists(configPath))
  207. {
  208. return;
  209. }
  210. // Get a stream of the resource contents
  211. // NOTE: The .csproj name is used instead of the assembly name in the resource path
  212. const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json";
  213. Stream resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath)
  214. ?? throw new InvalidOperationException($"Invalid resource path: '{ResourcePath}'");
  215. await using (resource.ConfigureAwait(false))
  216. {
  217. Stream dst = new FileStream(configPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  218. await using (dst.ConfigureAwait(false))
  219. {
  220. // Copy the resource contents to the expected file path for the config file
  221. await resource.CopyToAsync(dst).ConfigureAwait(false);
  222. }
  223. }
  224. }
  225. /// <summary>
  226. /// Initialize Serilog using configuration and fall back to defaults on failure.
  227. /// </summary>
  228. /// <param name="configuration">The configuration object.</param>
  229. /// <param name="appPaths">The application paths.</param>
  230. public static void InitializeLoggingFramework(IConfiguration configuration, IApplicationPaths appPaths)
  231. {
  232. try
  233. {
  234. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  235. Log.Logger = new LoggerConfiguration()
  236. .ReadFrom.Configuration(configuration)
  237. .Enrich.FromLogContext()
  238. .Enrich.WithThreadId()
  239. .CreateLogger();
  240. }
  241. catch (Exception ex)
  242. {
  243. Log.Logger = new LoggerConfiguration()
  244. .WriteTo.Console(
  245. outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}",
  246. formatProvider: CultureInfo.InvariantCulture)
  247. .WriteTo.Async(x => x.File(
  248. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  249. rollingInterval: RollingInterval.Day,
  250. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}",
  251. formatProvider: CultureInfo.InvariantCulture,
  252. encoding: Encoding.UTF8))
  253. .Enrich.FromLogContext()
  254. .Enrich.WithThreadId()
  255. .CreateLogger();
  256. Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  257. }
  258. }
  259. /// <summary>
  260. /// Call static initialization methods for the application.
  261. /// </summary>
  262. public static void PerformStaticInitialization()
  263. {
  264. // Make sure we have all the code pages we can get
  265. // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.text.codepagesencodingprovider.instance?view=netcore-3.0#remarks
  266. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  267. // Increase the max http request limit
  268. // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
  269. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  270. // Disable the "Expect: 100-Continue" header by default
  271. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  272. ServicePointManager.Expect100Continue = false;
  273. }
  274. }