Program.cs 23 KB

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