Program.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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. IConfiguration appConfig = await CreateConfiguration(appPaths).ConfigureAwait(false);
  103. CreateLogger(appConfig, 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. appConfig);
  158. try
  159. {
  160. ServiceCollection serviceCollection = new ServiceCollection();
  161. await appHost.InitAsync(serviceCollection).ConfigureAwait(false);
  162. var host = CreateWebHostBuilder(appHost, serviceCollection).Build();
  163. // A bit hacky to re-use service provider since ASP.NET doesn't allow a custom service collection.
  164. appHost.ServiceProvider = host.Services;
  165. appHost.FindParts();
  166. Migrations.MigrationRunner.Run(appHost, _loggerFactory);
  167. try
  168. {
  169. await host.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. private static IWebHostBuilder CreateWebHostBuilder(ApplicationHost appHost, IServiceCollection serviceCollection)
  200. {
  201. return new WebHostBuilder()
  202. .UseKestrel(options =>
  203. {
  204. var addresses = appHost.ServerConfigurationManager
  205. .Configuration
  206. .LocalNetworkAddresses
  207. .Select(appHost.NormalizeConfiguredLocalAddress)
  208. .Where(i => i != null)
  209. .ToList();
  210. if (addresses.Any())
  211. {
  212. foreach (var address in addresses)
  213. {
  214. _logger.LogInformation("Kestrel listening on {IpAddress}", address);
  215. options.Listen(address, appHost.HttpPort);
  216. if (appHost.EnableHttps && appHost.Certificate != null)
  217. {
  218. options.Listen(
  219. address,
  220. appHost.HttpsPort,
  221. listenOptions => listenOptions.UseHttps(appHost.Certificate));
  222. }
  223. }
  224. }
  225. else
  226. {
  227. _logger.LogInformation("Kestrel listening on all interfaces");
  228. options.ListenAnyIP(appHost.HttpPort);
  229. if (appHost.EnableHttps && appHost.Certificate != null)
  230. {
  231. options.ListenAnyIP(
  232. appHost.HttpsPort,
  233. listenOptions => listenOptions.UseHttps(appHost.Certificate));
  234. }
  235. }
  236. })
  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. private static async Task<IConfiguration> CreateConfiguration(IApplicationPaths appPaths)
  393. {
  394. const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json";
  395. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, LoggingConfigFileDefault);
  396. if (!File.Exists(configPath))
  397. {
  398. // For some reason the csproj name is used instead of the assembly name
  399. await using Stream? resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath);
  400. if (resource == null)
  401. {
  402. throw new InvalidOperationException(
  403. string.Format(
  404. CultureInfo.InvariantCulture,
  405. "Invalid resource path: '{0}'",
  406. ResourcePath));
  407. }
  408. await using Stream dst = File.Open(configPath, FileMode.CreateNew);
  409. await resource.CopyToAsync(dst).ConfigureAwait(false);
  410. }
  411. return new ConfigurationBuilder()
  412. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  413. .AddInMemoryCollection(ConfigurationOptions.Configuration)
  414. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  415. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  416. .AddEnvironmentVariables("JELLYFIN_")
  417. .Build();
  418. }
  419. private static void CreateLogger(IConfiguration configuration, IApplicationPaths appPaths)
  420. {
  421. try
  422. {
  423. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  424. Serilog.Log.Logger = new LoggerConfiguration()
  425. .ReadFrom.Configuration(configuration)
  426. .Enrich.FromLogContext()
  427. .Enrich.WithThreadId()
  428. .CreateLogger();
  429. }
  430. catch (Exception ex)
  431. {
  432. Serilog.Log.Logger = new LoggerConfiguration()
  433. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}")
  434. .WriteTo.Async(x => x.File(
  435. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  436. rollingInterval: RollingInterval.Day,
  437. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}"))
  438. .Enrich.FromLogContext()
  439. .Enrich.WithThreadId()
  440. .CreateLogger();
  441. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  442. }
  443. }
  444. private static IImageEncoder GetImageEncoder(IApplicationPaths appPaths)
  445. {
  446. try
  447. {
  448. // Test if the native lib is available
  449. SkiaEncoder.TestSkia();
  450. return new SkiaEncoder(
  451. _loggerFactory.CreateLogger<SkiaEncoder>(),
  452. appPaths);
  453. }
  454. catch (Exception ex)
  455. {
  456. _logger.LogWarning(ex, "Skia not available. Will fallback to NullIMageEncoder.");
  457. }
  458. return new NullImageEncoder();
  459. }
  460. private static void StartNewInstance(StartupOptions options)
  461. {
  462. _logger.LogInformation("Starting new instance");
  463. var module = options.RestartPath;
  464. if (string.IsNullOrWhiteSpace(module))
  465. {
  466. module = Environment.GetCommandLineArgs()[0];
  467. }
  468. string commandLineArgsString;
  469. if (options.RestartArgs != null)
  470. {
  471. commandLineArgsString = options.RestartArgs ?? string.Empty;
  472. }
  473. else
  474. {
  475. commandLineArgsString = string.Join(
  476. ' ',
  477. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  478. }
  479. _logger.LogInformation("Executable: {0}", module);
  480. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  481. Process.Start(module, commandLineArgsString);
  482. }
  483. private static string NormalizeCommandLineArgument(string arg)
  484. {
  485. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  486. {
  487. return arg;
  488. }
  489. return "\"" + arg + "\"";
  490. }
  491. }
  492. }