2
0

Program.cs 22 KB

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