Program.cs 30 KB

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