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