Program.cs 29 KB

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