Program.cs 23 KB

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