Program.cs 23 KB

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