Program.cs 22 KB

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