Program.cs 24 KB

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