Program.cs 28 KB

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