Program.cs 29 KB

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