Program.cs 30 KB

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