Program.cs 22 KB

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