StartupHelpers.cs 13 KB

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