Program.cs 28 KB

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