Program.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. .ToHashSet();
  210. if (addresses.Any() && !addresses.Contains(IPAddress.Any))
  211. {
  212. if (!addresses.Contains(IPAddress.Loopback))
  213. {
  214. // we must listen on loopback for LiveTV to function regardless of the settings
  215. addresses.Add(IPAddress.Loopback);
  216. }
  217. foreach (var address in addresses)
  218. {
  219. _logger.LogInformation("Kestrel listening on {IpAddress}", address);
  220. options.Listen(address, appHost.HttpPort);
  221. if (appHost.EnableHttps && appHost.Certificate != null)
  222. {
  223. options.Listen(
  224. address,
  225. appHost.HttpsPort,
  226. listenOptions => listenOptions.UseHttps(appHost.Certificate));
  227. }
  228. }
  229. }
  230. else
  231. {
  232. _logger.LogInformation("Kestrel listening on all interfaces");
  233. options.ListenAnyIP(appHost.HttpPort);
  234. if (appHost.EnableHttps && appHost.Certificate != null)
  235. {
  236. options.ListenAnyIP(
  237. appHost.HttpsPort,
  238. listenOptions => listenOptions.UseHttps(appHost.Certificate));
  239. }
  240. }
  241. })
  242. .UseSerilog()
  243. .UseContentRoot(appHost.ContentRoot)
  244. .ConfigureServices(services =>
  245. {
  246. // Merge the external ServiceCollection into ASP.NET DI
  247. services.TryAdd(serviceCollection);
  248. })
  249. .UseStartup<Startup>();
  250. }
  251. /// <summary>
  252. /// Create the data, config and log paths from the variety of inputs(command line args,
  253. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  254. /// for everything else the
  255. /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
  256. /// is followed.
  257. /// </summary>
  258. /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
  259. /// <returns><see cref="ServerApplicationPaths" />.</returns>
  260. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  261. {
  262. // dataDir
  263. // IF --datadir
  264. // ELSE IF $JELLYFIN_DATA_DIR
  265. // ELSE IF windows, use <%APPDATA%>/jellyfin
  266. // ELSE IF $XDG_DATA_HOME then use $XDG_DATA_HOME/jellyfin
  267. // ELSE use $HOME/.local/share/jellyfin
  268. var dataDir = options.DataDir;
  269. if (string.IsNullOrEmpty(dataDir))
  270. {
  271. dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR");
  272. if (string.IsNullOrEmpty(dataDir))
  273. {
  274. // LocalApplicationData follows the XDG spec on unix machines
  275. dataDir = Path.Combine(
  276. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  277. "jellyfin");
  278. }
  279. }
  280. // configDir
  281. // IF --configdir
  282. // ELSE IF $JELLYFIN_CONFIG_DIR
  283. // ELSE IF --datadir, use <datadir>/config (assume portable run)
  284. // ELSE IF <datadir>/config exists, use that
  285. // ELSE IF windows, use <datadir>/config
  286. // ELSE IF $XDG_CONFIG_HOME use $XDG_CONFIG_HOME/jellyfin
  287. // ELSE $HOME/.config/jellyfin
  288. var configDir = options.ConfigDir;
  289. if (string.IsNullOrEmpty(configDir))
  290. {
  291. configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  292. if (string.IsNullOrEmpty(configDir))
  293. {
  294. if (options.DataDir != null
  295. || Directory.Exists(Path.Combine(dataDir, "config"))
  296. || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  297. {
  298. // Hang config folder off already set dataDir
  299. configDir = Path.Combine(dataDir, "config");
  300. }
  301. else
  302. {
  303. // $XDG_CONFIG_HOME defines the base directory relative to which
  304. // user specific configuration files should be stored.
  305. configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
  306. // If $XDG_CONFIG_HOME is either not set or empty,
  307. // a default equal to $HOME /.config should be used.
  308. if (string.IsNullOrEmpty(configDir))
  309. {
  310. configDir = Path.Combine(
  311. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  312. ".config");
  313. }
  314. configDir = Path.Combine(configDir, "jellyfin");
  315. }
  316. }
  317. }
  318. // cacheDir
  319. // IF --cachedir
  320. // ELSE IF $JELLYFIN_CACHE_DIR
  321. // ELSE IF windows, use <datadir>/cache
  322. // ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
  323. // ELSE HOME/.cache/jellyfin
  324. var cacheDir = options.CacheDir;
  325. if (string.IsNullOrEmpty(cacheDir))
  326. {
  327. cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  328. if (string.IsNullOrEmpty(cacheDir))
  329. {
  330. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  331. {
  332. // Hang cache folder off already set dataDir
  333. cacheDir = Path.Combine(dataDir, "cache");
  334. }
  335. else
  336. {
  337. // $XDG_CACHE_HOME defines the base directory relative to which
  338. // user specific non-essential data files should be stored.
  339. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  340. // If $XDG_CACHE_HOME is either not set or empty,
  341. // a default equal to $HOME/.cache should be used.
  342. if (string.IsNullOrEmpty(cacheDir))
  343. {
  344. cacheDir = Path.Combine(
  345. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  346. ".cache");
  347. }
  348. cacheDir = Path.Combine(cacheDir, "jellyfin");
  349. }
  350. }
  351. }
  352. // webDir
  353. // IF --webdir
  354. // ELSE IF $JELLYFIN_WEB_DIR
  355. // ELSE use <bindir>/jellyfin-web
  356. var webDir = options.WebDir;
  357. if (string.IsNullOrEmpty(webDir))
  358. {
  359. webDir = Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
  360. if (string.IsNullOrEmpty(webDir))
  361. {
  362. // Use default location under ResourcesPath
  363. webDir = Path.Combine(AppContext.BaseDirectory, "jellyfin-web");
  364. }
  365. }
  366. // logDir
  367. // IF --logdir
  368. // ELSE IF $JELLYFIN_LOG_DIR
  369. // ELSE IF --datadir, use <datadir>/log (assume portable run)
  370. // ELSE <datadir>/log
  371. var logDir = options.LogDir;
  372. if (string.IsNullOrEmpty(logDir))
  373. {
  374. logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  375. if (string.IsNullOrEmpty(logDir))
  376. {
  377. // Hang log folder off already set dataDir
  378. logDir = Path.Combine(dataDir, "log");
  379. }
  380. }
  381. // Ensure the main folders exist before we continue
  382. try
  383. {
  384. Directory.CreateDirectory(dataDir);
  385. Directory.CreateDirectory(logDir);
  386. Directory.CreateDirectory(configDir);
  387. Directory.CreateDirectory(cacheDir);
  388. }
  389. catch (IOException ex)
  390. {
  391. Console.Error.WriteLine("Error whilst attempting to create folder");
  392. Console.Error.WriteLine(ex.ToString());
  393. Environment.Exit(1);
  394. }
  395. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
  396. }
  397. private static async Task<IConfiguration> CreateConfiguration(IApplicationPaths appPaths)
  398. {
  399. const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json";
  400. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, LoggingConfigFileDefault);
  401. if (!File.Exists(configPath))
  402. {
  403. // For some reason the csproj name is used instead of the assembly name
  404. await using Stream? resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath);
  405. if (resource == null)
  406. {
  407. throw new InvalidOperationException(
  408. string.Format(
  409. CultureInfo.InvariantCulture,
  410. "Invalid resource path: '{0}'",
  411. ResourcePath));
  412. }
  413. await using Stream dst = File.Open(configPath, FileMode.CreateNew);
  414. await resource.CopyToAsync(dst).ConfigureAwait(false);
  415. }
  416. return new ConfigurationBuilder()
  417. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  418. .AddInMemoryCollection(ConfigurationOptions.Configuration)
  419. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  420. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  421. .AddEnvironmentVariables("JELLYFIN_")
  422. .Build();
  423. }
  424. private static void CreateLogger(IConfiguration configuration, IApplicationPaths appPaths)
  425. {
  426. try
  427. {
  428. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  429. Serilog.Log.Logger = new LoggerConfiguration()
  430. .ReadFrom.Configuration(configuration)
  431. .Enrich.FromLogContext()
  432. .Enrich.WithThreadId()
  433. .CreateLogger();
  434. }
  435. catch (Exception ex)
  436. {
  437. Serilog.Log.Logger = new LoggerConfiguration()
  438. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}")
  439. .WriteTo.Async(x => x.File(
  440. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  441. rollingInterval: RollingInterval.Day,
  442. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}"))
  443. .Enrich.FromLogContext()
  444. .Enrich.WithThreadId()
  445. .CreateLogger();
  446. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  447. }
  448. }
  449. private static IImageEncoder GetImageEncoder(IApplicationPaths appPaths)
  450. {
  451. try
  452. {
  453. // Test if the native lib is available
  454. SkiaEncoder.TestSkia();
  455. return new SkiaEncoder(
  456. _loggerFactory.CreateLogger<SkiaEncoder>(),
  457. appPaths);
  458. }
  459. catch (Exception ex)
  460. {
  461. _logger.LogWarning(ex, "Skia not available. Will fallback to NullIMageEncoder.");
  462. }
  463. return new NullImageEncoder();
  464. }
  465. private static void StartNewInstance(StartupOptions options)
  466. {
  467. _logger.LogInformation("Starting new instance");
  468. var module = options.RestartPath;
  469. if (string.IsNullOrWhiteSpace(module))
  470. {
  471. module = Environment.GetCommandLineArgs()[0];
  472. }
  473. string commandLineArgsString;
  474. if (options.RestartArgs != null)
  475. {
  476. commandLineArgsString = options.RestartArgs ?? string.Empty;
  477. }
  478. else
  479. {
  480. commandLineArgsString = string.Join(
  481. ' ',
  482. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  483. }
  484. _logger.LogInformation("Executable: {0}", module);
  485. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  486. Process.Start(module, commandLineArgsString);
  487. }
  488. private static string NormalizeCommandLineArgument(string arg)
  489. {
  490. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  491. {
  492. return arg;
  493. }
  494. return "\"" + arg + "\"";
  495. }
  496. }
  497. }