Program.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Reflection;
  9. using System.Runtime.InteropServices;
  10. using System.Runtime.Versioning;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using CommandLine;
  15. using Emby.Server.Implementations;
  16. using Jellyfin.Server.Implementations;
  17. using MediaBrowser.Common.Configuration;
  18. using MediaBrowser.Common.Net;
  19. using MediaBrowser.Model.IO;
  20. using Microsoft.AspNetCore.Hosting;
  21. using Microsoft.EntityFrameworkCore;
  22. using Microsoft.Extensions.Configuration;
  23. using Microsoft.Extensions.DependencyInjection;
  24. using Microsoft.Extensions.DependencyInjection.Extensions;
  25. using Microsoft.Extensions.Hosting;
  26. using Microsoft.Extensions.Logging;
  27. using Microsoft.Extensions.Logging.Abstractions;
  28. using Serilog;
  29. using Serilog.Extensions.Logging;
  30. using SQLitePCL;
  31. using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
  32. using ILogger = Microsoft.Extensions.Logging.ILogger;
  33. namespace Jellyfin.Server
  34. {
  35. /// <summary>
  36. /// Class containing the entry point of the application.
  37. /// </summary>
  38. public static class Program
  39. {
  40. /// <summary>
  41. /// The name of logging configuration file containing application defaults.
  42. /// </summary>
  43. public const string LoggingConfigFileDefault = "logging.default.json";
  44. /// <summary>
  45. /// The name of the logging configuration file containing the system-specific override settings.
  46. /// </summary>
  47. public const string LoggingConfigFileSystem = "logging.json";
  48. private static readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
  49. private static readonly ILoggerFactory _loggerFactory = new SerilogLoggerFactory();
  50. private static ILogger _logger = NullLogger.Instance;
  51. private static bool _restartOnShutdown;
  52. /// <summary>
  53. /// The entry point of the application.
  54. /// </summary>
  55. /// <param name="args">The command line arguments passed.</param>
  56. /// <returns><see cref="Task" />.</returns>
  57. public static Task Main(string[] args)
  58. {
  59. static Task ErrorParsingArguments(IEnumerable<Error> errors)
  60. {
  61. Environment.ExitCode = 1;
  62. return Task.CompletedTask;
  63. }
  64. // Parse the command line arguments and either start the app or exit indicating error
  65. return Parser.Default.ParseArguments<StartupOptions>(args)
  66. .MapResult(StartApp, ErrorParsingArguments);
  67. }
  68. /// <summary>
  69. /// Shuts down the application.
  70. /// </summary>
  71. internal static void Shutdown()
  72. {
  73. if (!_tokenSource.IsCancellationRequested)
  74. {
  75. _tokenSource.Cancel();
  76. }
  77. }
  78. /// <summary>
  79. /// Restarts the application.
  80. /// </summary>
  81. internal static void Restart()
  82. {
  83. _restartOnShutdown = true;
  84. Shutdown();
  85. }
  86. private static async Task StartApp(StartupOptions options)
  87. {
  88. var startTimestamp = Stopwatch.GetTimestamp();
  89. // Log all uncaught exceptions to std error
  90. static void UnhandledExceptionToConsole(object sender, UnhandledExceptionEventArgs e) =>
  91. Console.Error.WriteLine("Unhandled Exception\n" + e.ExceptionObject.ToString());
  92. AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionToConsole;
  93. ServerApplicationPaths appPaths = CreateApplicationPaths(options);
  94. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  95. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  96. // Enable cl-va P010 interop for tonemapping on Intel VAAPI
  97. Environment.SetEnvironmentVariable("NEOReadDebugKeys", "1");
  98. Environment.SetEnvironmentVariable("EnableExtendedVaFormats", "1");
  99. await InitLoggingConfigFile(appPaths).ConfigureAwait(false);
  100. // Create an instance of the application configuration to use for application startup
  101. IConfiguration startupConfig = CreateAppConfiguration(options, appPaths);
  102. // Initialize logging framework
  103. InitializeLoggingFramework(startupConfig, appPaths);
  104. _logger = _loggerFactory.CreateLogger("Main");
  105. // Log uncaught exceptions to the logging instead of std error
  106. AppDomain.CurrentDomain.UnhandledException -= UnhandledExceptionToConsole;
  107. AppDomain.CurrentDomain.UnhandledException += (_, e)
  108. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  109. // Intercept Ctrl+C and Ctrl+Break
  110. Console.CancelKeyPress += (_, e) =>
  111. {
  112. if (_tokenSource.IsCancellationRequested)
  113. {
  114. return; // Already shutting down
  115. }
  116. e.Cancel = true;
  117. _logger.LogInformation("Ctrl+C, shutting down");
  118. Environment.ExitCode = 128 + 2;
  119. Shutdown();
  120. };
  121. // Register a SIGTERM handler
  122. AppDomain.CurrentDomain.ProcessExit += (_, _) =>
  123. {
  124. if (_tokenSource.IsCancellationRequested)
  125. {
  126. return; // Already shutting down
  127. }
  128. _logger.LogInformation("Received a SIGTERM signal, shutting down");
  129. Environment.ExitCode = 128 + 15;
  130. Shutdown();
  131. };
  132. _logger.LogInformation(
  133. "Jellyfin version: {Version}",
  134. Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
  135. ApplicationHost.LogEnvironmentInfo(_logger, appPaths);
  136. // If hosting the web client, validate the client content path
  137. if (startupConfig.HostWebClient())
  138. {
  139. string? webContentPath = appPaths.WebPath;
  140. if (!Directory.Exists(webContentPath) || !Directory.EnumerateFiles(webContentPath).Any())
  141. {
  142. _logger.LogError(
  143. "The server is expected to host the web client, but the provided content directory is either " +
  144. "invalid or empty: {WebContentPath}. If you do not want to host the web client with the " +
  145. "server, you may set the '--nowebclient' command line flag, or set" +
  146. "'{ConfigKey}=false' in your config settings.",
  147. webContentPath,
  148. HostWebClientKey);
  149. Environment.ExitCode = 1;
  150. return;
  151. }
  152. }
  153. PerformStaticInitialization();
  154. Migrations.MigrationRunner.RunPreStartup(appPaths, _loggerFactory);
  155. var appHost = new CoreAppHost(
  156. appPaths,
  157. _loggerFactory,
  158. options,
  159. startupConfig);
  160. try
  161. {
  162. var serviceCollection = new ServiceCollection();
  163. appHost.Init(serviceCollection);
  164. var webHost = new WebHostBuilder().ConfigureWebHostBuilder(appHost, serviceCollection, options, startupConfig, appPaths).Build();
  165. // Re-use the web host service provider in the app host since ASP.NET doesn't allow a custom service collection.
  166. appHost.ServiceProvider = webHost.Services;
  167. await appHost.InitializeServices().ConfigureAwait(false);
  168. Migrations.MigrationRunner.Run(appHost, _loggerFactory);
  169. try
  170. {
  171. await webHost.StartAsync(_tokenSource.Token).ConfigureAwait(false);
  172. if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
  173. {
  174. var socketPath = GetUnixSocketPath(startupConfig, appPaths);
  175. SetUnixSocketPermissions(startupConfig, socketPath);
  176. }
  177. }
  178. catch (Exception ex) when (ex is not TaskCanceledException)
  179. {
  180. _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in network.xml and try again.");
  181. throw;
  182. }
  183. await appHost.RunStartupTasksAsync(_tokenSource.Token).ConfigureAwait(false);
  184. _logger.LogInformation("Startup complete {Time:g}", Stopwatch.GetElapsedTime(startTimestamp));
  185. // Block main thread until shutdown
  186. await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
  187. }
  188. catch (TaskCanceledException)
  189. {
  190. // Don't throw on cancellation
  191. }
  192. catch (Exception ex)
  193. {
  194. _logger.LogCritical(ex, "Error while starting server.");
  195. }
  196. finally
  197. {
  198. // Don't throw additional exception if startup failed.
  199. if (appHost.ServiceProvider is not null)
  200. {
  201. _logger.LogInformation("Running query planner optimizations in the database... This might take a while");
  202. // Run before disposing the application
  203. var context = await appHost.ServiceProvider.GetRequiredService<IDbContextFactory<JellyfinDb>>().CreateDbContextAsync().ConfigureAwait(false);
  204. await using (context.ConfigureAwait(false))
  205. {
  206. if (context.Database.IsSqlite())
  207. {
  208. await context.Database.ExecuteSqlRawAsync("PRAGMA optimize").ConfigureAwait(false);
  209. }
  210. }
  211. }
  212. await appHost.DisposeAsync().ConfigureAwait(false);
  213. }
  214. if (_restartOnShutdown)
  215. {
  216. StartNewInstance(options);
  217. }
  218. }
  219. /// <summary>
  220. /// Call static initialization methods for the application.
  221. /// </summary>
  222. public static void PerformStaticInitialization()
  223. {
  224. // Make sure we have all the code pages we can get
  225. // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.text.codepagesencodingprovider.instance?view=netcore-3.0#remarks
  226. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  227. // Increase the max http request limit
  228. // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
  229. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  230. // Disable the "Expect: 100-Continue" header by default
  231. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  232. ServicePointManager.Expect100Continue = false;
  233. Batteries_V2.Init();
  234. if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK)
  235. {
  236. _logger.LogWarning("Failed to enable shared cache for SQLite");
  237. }
  238. }
  239. /// <summary>
  240. /// Configure the web host builder.
  241. /// </summary>
  242. /// <param name="builder">The builder to configure.</param>
  243. /// <param name="appHost">The application host.</param>
  244. /// <param name="serviceCollection">The application service collection.</param>
  245. /// <param name="commandLineOpts">The command line options passed to the application.</param>
  246. /// <param name="startupConfig">The application configuration.</param>
  247. /// <param name="appPaths">The application paths.</param>
  248. /// <returns>The configured web host builder.</returns>
  249. public static IWebHostBuilder ConfigureWebHostBuilder(
  250. this IWebHostBuilder builder,
  251. ApplicationHost appHost,
  252. IServiceCollection serviceCollection,
  253. StartupOptions commandLineOpts,
  254. IConfiguration startupConfig,
  255. IApplicationPaths appPaths)
  256. {
  257. return builder
  258. .UseKestrel((builderContext, options) =>
  259. {
  260. var addresses = appHost.NetManager.GetAllBindInterfaces();
  261. bool flagged = false;
  262. foreach (IPObject netAdd in addresses)
  263. {
  264. _logger.LogInformation("Kestrel listening on {Address}", netAdd.Address == IPAddress.IPv6Any ? "All Addresses" : netAdd);
  265. options.Listen(netAdd.Address, appHost.HttpPort);
  266. if (appHost.ListenWithHttps)
  267. {
  268. options.Listen(
  269. netAdd.Address,
  270. appHost.HttpsPort,
  271. listenOptions => listenOptions.UseHttps(appHost.Certificate));
  272. }
  273. else if (builderContext.HostingEnvironment.IsDevelopment())
  274. {
  275. try
  276. {
  277. options.Listen(
  278. netAdd.Address,
  279. appHost.HttpsPort,
  280. listenOptions => listenOptions.UseHttps());
  281. }
  282. catch (InvalidOperationException)
  283. {
  284. if (!flagged)
  285. {
  286. _logger.LogWarning("Failed to listen to HTTPS using the ASP.NET Core HTTPS development certificate. Please ensure it has been installed and set as trusted.");
  287. flagged = true;
  288. }
  289. }
  290. }
  291. }
  292. // Bind to unix socket (only on unix systems)
  293. if (startupConfig.UseUnixSocket() && Environment.OSVersion.Platform == PlatformID.Unix)
  294. {
  295. var socketPath = GetUnixSocketPath(startupConfig, appPaths);
  296. // Workaround for https://github.com/aspnet/AspNetCore/issues/14134
  297. if (File.Exists(socketPath))
  298. {
  299. File.Delete(socketPath);
  300. }
  301. options.ListenUnixSocket(socketPath);
  302. _logger.LogInformation("Kestrel listening to unix socket {SocketPath}", socketPath);
  303. }
  304. })
  305. .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(commandLineOpts, appPaths, startupConfig))
  306. .UseSerilog()
  307. .ConfigureServices(services =>
  308. {
  309. // Merge the external ServiceCollection into ASP.NET DI
  310. services.Add(serviceCollection);
  311. })
  312. .UseStartup<Startup>();
  313. }
  314. /// <summary>
  315. /// Create the data, config and log paths from the variety of inputs(command line args,
  316. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  317. /// for everything else the
  318. /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
  319. /// is followed.
  320. /// </summary>
  321. /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
  322. /// <returns><see cref="ServerApplicationPaths" />.</returns>
  323. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  324. {
  325. // dataDir
  326. // IF --datadir
  327. // ELSE IF $JELLYFIN_DATA_DIR
  328. // ELSE IF windows, use <%APPDATA%>/jellyfin
  329. // ELSE IF $XDG_DATA_HOME then use $XDG_DATA_HOME/jellyfin
  330. // ELSE use $HOME/.local/share/jellyfin
  331. var dataDir = options.DataDir;
  332. if (string.IsNullOrEmpty(dataDir))
  333. {
  334. dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR");
  335. if (string.IsNullOrEmpty(dataDir))
  336. {
  337. // LocalApplicationData follows the XDG spec on unix machines
  338. dataDir = Path.Combine(
  339. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  340. "jellyfin");
  341. }
  342. }
  343. // configDir
  344. // IF --configdir
  345. // ELSE IF $JELLYFIN_CONFIG_DIR
  346. // ELSE IF --datadir, use <datadir>/config (assume portable run)
  347. // ELSE IF <datadir>/config exists, use that
  348. // ELSE IF windows, use <datadir>/config
  349. // ELSE IF $XDG_CONFIG_HOME use $XDG_CONFIG_HOME/jellyfin
  350. // ELSE $HOME/.config/jellyfin
  351. var configDir = options.ConfigDir;
  352. if (string.IsNullOrEmpty(configDir))
  353. {
  354. configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  355. if (string.IsNullOrEmpty(configDir))
  356. {
  357. if (options.DataDir is not null
  358. || Directory.Exists(Path.Combine(dataDir, "config"))
  359. || OperatingSystem.IsWindows())
  360. {
  361. // Hang config folder off already set dataDir
  362. configDir = Path.Combine(dataDir, "config");
  363. }
  364. else
  365. {
  366. // $XDG_CONFIG_HOME defines the base directory relative to which
  367. // user specific configuration files should be stored.
  368. configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
  369. // If $XDG_CONFIG_HOME is either not set or empty,
  370. // a default equal to $HOME /.config should be used.
  371. if (string.IsNullOrEmpty(configDir))
  372. {
  373. configDir = Path.Combine(
  374. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  375. ".config");
  376. }
  377. configDir = Path.Combine(configDir, "jellyfin");
  378. }
  379. }
  380. }
  381. // cacheDir
  382. // IF --cachedir
  383. // ELSE IF $JELLYFIN_CACHE_DIR
  384. // ELSE IF windows, use <datadir>/cache
  385. // ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
  386. // ELSE HOME/.cache/jellyfin
  387. var cacheDir = options.CacheDir;
  388. if (string.IsNullOrEmpty(cacheDir))
  389. {
  390. cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  391. if (string.IsNullOrEmpty(cacheDir))
  392. {
  393. if (OperatingSystem.IsWindows())
  394. {
  395. // Hang cache folder off already set dataDir
  396. cacheDir = Path.Combine(dataDir, "cache");
  397. }
  398. else
  399. {
  400. // $XDG_CACHE_HOME defines the base directory relative to which
  401. // user specific non-essential data files should be stored.
  402. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  403. // If $XDG_CACHE_HOME is either not set or empty,
  404. // a default equal to $HOME/.cache should be used.
  405. if (string.IsNullOrEmpty(cacheDir))
  406. {
  407. cacheDir = Path.Combine(
  408. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  409. ".cache");
  410. }
  411. cacheDir = Path.Combine(cacheDir, "jellyfin");
  412. }
  413. }
  414. }
  415. // webDir
  416. // IF --webdir
  417. // ELSE IF $JELLYFIN_WEB_DIR
  418. // ELSE <bindir>/jellyfin-web
  419. var webDir = options.WebDir;
  420. if (string.IsNullOrEmpty(webDir))
  421. {
  422. webDir = Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
  423. if (string.IsNullOrEmpty(webDir))
  424. {
  425. // Use default location under ResourcesPath
  426. webDir = Path.Combine(AppContext.BaseDirectory, "jellyfin-web");
  427. }
  428. }
  429. // logDir
  430. // IF --logdir
  431. // ELSE IF $JELLYFIN_LOG_DIR
  432. // ELSE IF --datadir, use <datadir>/log (assume portable run)
  433. // ELSE <datadir>/log
  434. var logDir = options.LogDir;
  435. if (string.IsNullOrEmpty(logDir))
  436. {
  437. logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  438. if (string.IsNullOrEmpty(logDir))
  439. {
  440. // Hang log folder off already set dataDir
  441. logDir = Path.Combine(dataDir, "log");
  442. }
  443. }
  444. // Normalize paths. Only possible with GetFullPath for now - https://github.com/dotnet/runtime/issues/2162
  445. dataDir = Path.GetFullPath(dataDir);
  446. logDir = Path.GetFullPath(logDir);
  447. configDir = Path.GetFullPath(configDir);
  448. cacheDir = Path.GetFullPath(cacheDir);
  449. webDir = Path.GetFullPath(webDir);
  450. // Ensure the main folders exist before we continue
  451. try
  452. {
  453. Directory.CreateDirectory(dataDir);
  454. Directory.CreateDirectory(logDir);
  455. Directory.CreateDirectory(configDir);
  456. Directory.CreateDirectory(cacheDir);
  457. }
  458. catch (IOException ex)
  459. {
  460. Console.Error.WriteLine("Error whilst attempting to create folder");
  461. Console.Error.WriteLine(ex.ToString());
  462. Environment.Exit(1);
  463. }
  464. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
  465. }
  466. /// <summary>
  467. /// Initialize the logging configuration file using the bundled resource file as a default if it doesn't exist
  468. /// already.
  469. /// </summary>
  470. /// <param name="appPaths">The application paths.</param>
  471. /// <returns>A task representing the creation of the configuration file, or a completed task if the file already exists.</returns>
  472. public static async Task InitLoggingConfigFile(IApplicationPaths appPaths)
  473. {
  474. // Do nothing if the config file already exists
  475. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, LoggingConfigFileDefault);
  476. if (File.Exists(configPath))
  477. {
  478. return;
  479. }
  480. // Get a stream of the resource contents
  481. // NOTE: The .csproj name is used instead of the assembly name in the resource path
  482. const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json";
  483. Stream resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath)
  484. ?? throw new InvalidOperationException($"Invalid resource path: '{ResourcePath}'");
  485. await using (resource.ConfigureAwait(false))
  486. {
  487. Stream dst = new FileStream(configPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  488. await using (dst.ConfigureAwait(false))
  489. {
  490. // Copy the resource contents to the expected file path for the config file
  491. await resource.CopyToAsync(dst).ConfigureAwait(false);
  492. }
  493. }
  494. }
  495. /// <summary>
  496. /// Create the application configuration.
  497. /// </summary>
  498. /// <param name="commandLineOpts">The command line options passed to the program.</param>
  499. /// <param name="appPaths">The application paths.</param>
  500. /// <returns>The application configuration.</returns>
  501. public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  502. {
  503. return new ConfigurationBuilder()
  504. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  505. .Build();
  506. }
  507. private static IConfigurationBuilder ConfigureAppConfiguration(
  508. this IConfigurationBuilder config,
  509. StartupOptions commandLineOpts,
  510. IApplicationPaths appPaths,
  511. IConfiguration? startupConfig = null)
  512. {
  513. // Use the swagger API page as the default redirect path if not hosting the web client
  514. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  515. if (startupConfig is not null && !startupConfig.HostWebClient())
  516. {
  517. inMemoryDefaultConfig[DefaultRedirectKey] = "api-docs/swagger";
  518. }
  519. return config
  520. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  521. .AddInMemoryCollection(inMemoryDefaultConfig)
  522. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  523. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  524. .AddEnvironmentVariables("JELLYFIN_")
  525. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  526. }
  527. /// <summary>
  528. /// Initialize Serilog using configuration and fall back to defaults on failure.
  529. /// </summary>
  530. private static void InitializeLoggingFramework(IConfiguration configuration, IApplicationPaths appPaths)
  531. {
  532. try
  533. {
  534. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  535. Log.Logger = new LoggerConfiguration()
  536. .ReadFrom.Configuration(configuration)
  537. .Enrich.FromLogContext()
  538. .Enrich.WithThreadId()
  539. .CreateLogger();
  540. }
  541. catch (Exception ex)
  542. {
  543. Log.Logger = new LoggerConfiguration()
  544. .WriteTo.Console(
  545. outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}",
  546. formatProvider: CultureInfo.InvariantCulture)
  547. .WriteTo.Async(x => x.File(
  548. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  549. rollingInterval: RollingInterval.Day,
  550. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}",
  551. formatProvider: CultureInfo.InvariantCulture,
  552. encoding: Encoding.UTF8))
  553. .Enrich.FromLogContext()
  554. .Enrich.WithThreadId()
  555. .CreateLogger();
  556. Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  557. }
  558. }
  559. private static void StartNewInstance(StartupOptions options)
  560. {
  561. _logger.LogInformation("Starting new instance");
  562. var module = options.RestartPath;
  563. if (string.IsNullOrWhiteSpace(module))
  564. {
  565. module = Environment.GetCommandLineArgs()[0];
  566. }
  567. string commandLineArgsString;
  568. if (options.RestartArgs is not null)
  569. {
  570. commandLineArgsString = options.RestartArgs;
  571. }
  572. else
  573. {
  574. commandLineArgsString = string.Join(
  575. ' ',
  576. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  577. }
  578. _logger.LogInformation("Executable: {0}", module);
  579. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  580. Process.Start(module, commandLineArgsString);
  581. }
  582. private static string NormalizeCommandLineArgument(string arg)
  583. {
  584. if (!arg.Contains(' ', StringComparison.Ordinal))
  585. {
  586. return arg;
  587. }
  588. return "\"" + arg + "\"";
  589. }
  590. private static string GetUnixSocketPath(IConfiguration startupConfig, IApplicationPaths appPaths)
  591. {
  592. var socketPath = startupConfig.GetUnixSocketPath();
  593. if (string.IsNullOrEmpty(socketPath))
  594. {
  595. var xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
  596. var socketFile = "jellyfin.sock";
  597. if (xdgRuntimeDir is null)
  598. {
  599. // Fall back to config dir
  600. socketPath = Path.Join(appPaths.ConfigurationDirectoryPath, socketFile);
  601. }
  602. else
  603. {
  604. socketPath = Path.Join(xdgRuntimeDir, socketFile);
  605. }
  606. }
  607. return socketPath;
  608. }
  609. [UnsupportedOSPlatform("windows")]
  610. private static void SetUnixSocketPermissions(IConfiguration startupConfig, string socketPath)
  611. {
  612. var socketPerms = startupConfig.GetUnixSocketPermissions();
  613. if (!string.IsNullOrEmpty(socketPerms))
  614. {
  615. File.SetUnixFileMode(socketPath, (UnixFileMode)Convert.ToInt32(socketPerms, 8));
  616. _logger.LogInformation("Kestrel unix socket permissions set to {SocketPerms}", socketPerms);
  617. }
  618. }
  619. }
  620. }