Program.cs 28 KB

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