Program.cs 30 KB

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