Program.cs 30 KB

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