Program.cs 28 KB

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