Program.cs 31 KB

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