Program.cs 29 KB

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