Program.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Security;
  7. using System.Reflection;
  8. using System.Runtime.InteropServices;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using CommandLine;
  13. using Emby.Drawing;
  14. using Emby.Server.Implementations;
  15. using Emby.Server.Implementations.IO;
  16. using Emby.Server.Implementations.Networking;
  17. using Jellyfin.Drawing.Skia;
  18. using MediaBrowser.Common.Configuration;
  19. using MediaBrowser.Controller.Drawing;
  20. using MediaBrowser.Model.Globalization;
  21. using Microsoft.Extensions.Configuration;
  22. using Microsoft.Extensions.DependencyInjection;
  23. using Microsoft.Extensions.Logging;
  24. using Serilog;
  25. using Serilog.AspNetCore;
  26. using SQLitePCL;
  27. using ILogger = Microsoft.Extensions.Logging.ILogger;
  28. namespace Jellyfin.Server
  29. {
  30. /// <summary>
  31. /// Class containing the entry point of the application.
  32. /// </summary>
  33. public static class Program
  34. {
  35. private static readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
  36. private static readonly ILoggerFactory _loggerFactory = new SerilogLoggerFactory();
  37. private static ILogger _logger;
  38. private static bool _restartOnShutdown;
  39. /// <summary>
  40. /// The entry point of the application.
  41. /// </summary>
  42. /// <param name="args">The command line arguments passed.</param>
  43. /// <returns><see cref="Task" />.</returns>
  44. public static Task Main(string[] args)
  45. {
  46. // For backwards compatibility.
  47. // Modify any input arguments now which start with single-hyphen to POSIX standard
  48. // double-hyphen to allow parsing by CommandLineParser package.
  49. const string Pattern = @"^(-[^-\s]{2})"; // Match -xx, not -x, not --xx, not xx
  50. const string Substitution = @"-$1"; // Prepend with additional single-hyphen
  51. var regex = new Regex(Pattern);
  52. for (var i = 0; i < args.Length; i++)
  53. {
  54. args[i] = regex.Replace(args[i], Substitution);
  55. }
  56. // Parse the command line arguments and either start the app or exit indicating error
  57. return Parser.Default.ParseArguments<StartupOptions>(args)
  58. .MapResult(StartApp, _ => Task.CompletedTask);
  59. }
  60. /// <summary>
  61. /// Shuts down the application.
  62. /// </summary>
  63. internal static void Shutdown()
  64. {
  65. if (!_tokenSource.IsCancellationRequested)
  66. {
  67. _tokenSource.Cancel();
  68. }
  69. }
  70. /// <summary>
  71. /// Restarts the application.
  72. /// </summary>
  73. internal static void Restart()
  74. {
  75. _restartOnShutdown = true;
  76. Shutdown();
  77. }
  78. private static async Task StartApp(StartupOptions options)
  79. {
  80. ServerApplicationPaths appPaths = CreateApplicationPaths(options);
  81. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  82. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  83. IConfiguration appConfig = await CreateConfiguration(appPaths).ConfigureAwait(false);
  84. CreateLogger(appConfig, appPaths);
  85. _logger = _loggerFactory.CreateLogger("Main");
  86. AppDomain.CurrentDomain.UnhandledException += (sender, e)
  87. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  88. // Intercept Ctrl+C and Ctrl+Break
  89. Console.CancelKeyPress += (sender, e) =>
  90. {
  91. if (_tokenSource.IsCancellationRequested)
  92. {
  93. return; // Already shutting down
  94. }
  95. e.Cancel = true;
  96. _logger.LogInformation("Ctrl+C, shutting down");
  97. Environment.ExitCode = 128 + 2;
  98. Shutdown();
  99. };
  100. // Register a SIGTERM handler
  101. AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
  102. {
  103. if (_tokenSource.IsCancellationRequested)
  104. {
  105. return; // Already shutting down
  106. }
  107. _logger.LogInformation("Received a SIGTERM signal, shutting down");
  108. Environment.ExitCode = 128 + 15;
  109. Shutdown();
  110. };
  111. _logger.LogInformation("Jellyfin version: {Version}", Assembly.GetEntryAssembly().GetName().Version);
  112. ApplicationHost.LogEnvironmentInfo(_logger, appPaths);
  113. // Increase the max http request limit
  114. // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
  115. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  116. // Disable the "Expect: 100-Continue" header by default
  117. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  118. ServicePointManager.Expect100Continue = false;
  119. // CA5359: Do Not Disable Certificate Validation
  120. #pragma warning disable CA5359
  121. // Allow all https requests
  122. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  123. #pragma warning restore CA5359
  124. Batteries_V2.Init();
  125. if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK)
  126. {
  127. _logger.LogWarning("Failed to enable shared cache for SQLite");
  128. }
  129. using (var appHost = new CoreAppHost(
  130. appPaths,
  131. _loggerFactory,
  132. options,
  133. new ManagedFileSystem(_loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths),
  134. new NullImageEncoder(),
  135. new NetworkManager(_loggerFactory.CreateLogger<NetworkManager>()),
  136. appConfig))
  137. {
  138. await appHost.InitAsync(new ServiceCollection()).ConfigureAwait(false);
  139. appHost.ImageProcessor.ImageEncoder = GetImageEncoder(appPaths, appHost.LocalizationManager);
  140. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  141. try
  142. {
  143. // Block main thread until shutdown
  144. await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
  145. }
  146. catch (TaskCanceledException)
  147. {
  148. // Don't throw on cancellation
  149. }
  150. }
  151. if (_restartOnShutdown)
  152. {
  153. StartNewInstance(options);
  154. }
  155. }
  156. /// <summary>
  157. /// Create the data, config and log paths from the variety of inputs(command line args,
  158. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  159. /// for everything else the
  160. /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
  161. /// is followed.
  162. /// </summary>
  163. /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
  164. /// <returns><see cref="ServerApplicationPaths" />.</returns>
  165. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  166. {
  167. // dataDir
  168. // IF --datadir
  169. // ELSE IF $JELLYFIN_DATA_DIR
  170. // ELSE IF windows, use <%APPDATA%>/jellyfin
  171. // ELSE IF $XDG_DATA_HOME then use $XDG_DATA_HOME/jellyfin
  172. // ELSE use $HOME/.local/share/jellyfin
  173. var dataDir = options.DataDir;
  174. if (string.IsNullOrEmpty(dataDir))
  175. {
  176. dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR");
  177. if (string.IsNullOrEmpty(dataDir))
  178. {
  179. // LocalApplicationData follows the XDG spec on unix machines
  180. dataDir = Path.Combine(
  181. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  182. "jellyfin");
  183. }
  184. }
  185. // configDir
  186. // IF --configdir
  187. // ELSE IF $JELLYFIN_CONFIG_DIR
  188. // ELSE IF --datadir, use <datadir>/config (assume portable run)
  189. // ELSE IF <datadir>/config exists, use that
  190. // ELSE IF windows, use <datadir>/config
  191. // ELSE IF $XDG_CONFIG_HOME use $XDG_CONFIG_HOME/jellyfin
  192. // ELSE $HOME/.config/jellyfin
  193. var configDir = options.ConfigDir;
  194. if (string.IsNullOrEmpty(configDir))
  195. {
  196. configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  197. if (string.IsNullOrEmpty(configDir))
  198. {
  199. if (options.DataDir != null
  200. || Directory.Exists(Path.Combine(dataDir, "config"))
  201. || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  202. {
  203. // Hang config folder off already set dataDir
  204. configDir = Path.Combine(dataDir, "config");
  205. }
  206. else
  207. {
  208. // $XDG_CONFIG_HOME defines the base directory relative to which
  209. // user specific configuration files should be stored.
  210. configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
  211. // If $XDG_CONFIG_HOME is either not set or empty,
  212. // a default equal to $HOME /.config should be used.
  213. if (string.IsNullOrEmpty(configDir))
  214. {
  215. configDir = Path.Combine(
  216. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  217. ".config");
  218. }
  219. configDir = Path.Combine(configDir, "jellyfin");
  220. }
  221. }
  222. }
  223. // cacheDir
  224. // IF --cachedir
  225. // ELSE IF $JELLYFIN_CACHE_DIR
  226. // ELSE IF windows, use <datadir>/cache
  227. // ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
  228. // ELSE HOME/.cache/jellyfin
  229. var cacheDir = options.CacheDir;
  230. if (string.IsNullOrEmpty(cacheDir))
  231. {
  232. cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  233. if (string.IsNullOrEmpty(cacheDir))
  234. {
  235. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  236. {
  237. // Hang cache folder off already set dataDir
  238. cacheDir = Path.Combine(dataDir, "cache");
  239. }
  240. else
  241. {
  242. // $XDG_CACHE_HOME defines the base directory relative to which
  243. // user specific non-essential data files should be stored.
  244. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  245. // If $XDG_CACHE_HOME is either not set or empty,
  246. // a default equal to $HOME/.cache should be used.
  247. if (string.IsNullOrEmpty(cacheDir))
  248. {
  249. cacheDir = Path.Combine(
  250. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  251. ".cache");
  252. }
  253. cacheDir = Path.Combine(cacheDir, "jellyfin");
  254. }
  255. }
  256. }
  257. // webDir
  258. // IF --webdir
  259. // ELSE IF $JELLYFIN_WEB_DIR
  260. // ELSE use <bindir>/jellyfin-web
  261. var webDir = options.WebDir;
  262. if (string.IsNullOrEmpty(webDir))
  263. {
  264. webDir = Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
  265. if (string.IsNullOrEmpty(webDir))
  266. {
  267. // Use default location under ResourcesPath
  268. webDir = Path.Combine(AppContext.BaseDirectory, "jellyfin-web", "src");
  269. }
  270. }
  271. // logDir
  272. // IF --logdir
  273. // ELSE IF $JELLYFIN_LOG_DIR
  274. // ELSE IF --datadir, use <datadir>/log (assume portable run)
  275. // ELSE <datadir>/log
  276. var logDir = options.LogDir;
  277. if (string.IsNullOrEmpty(logDir))
  278. {
  279. logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  280. if (string.IsNullOrEmpty(logDir))
  281. {
  282. // Hang log folder off already set dataDir
  283. logDir = Path.Combine(dataDir, "log");
  284. }
  285. }
  286. // Ensure the main folders exist before we continue
  287. try
  288. {
  289. Directory.CreateDirectory(dataDir);
  290. Directory.CreateDirectory(logDir);
  291. Directory.CreateDirectory(configDir);
  292. Directory.CreateDirectory(cacheDir);
  293. }
  294. catch (IOException ex)
  295. {
  296. Console.Error.WriteLine("Error whilst attempting to create folder");
  297. Console.Error.WriteLine(ex.ToString());
  298. Environment.Exit(1);
  299. }
  300. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
  301. }
  302. private static async Task<IConfiguration> CreateConfiguration(IApplicationPaths appPaths)
  303. {
  304. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
  305. if (!File.Exists(configPath))
  306. {
  307. // For some reason the csproj name is used instead of the assembly name
  308. using (Stream rscstr = typeof(Program).Assembly
  309. .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
  310. using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
  311. {
  312. await rscstr.CopyToAsync(fstr).ConfigureAwait(false);
  313. }
  314. }
  315. return new ConfigurationBuilder()
  316. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  317. .AddJsonFile("logging.json")
  318. .AddEnvironmentVariables("JELLYFIN_")
  319. .AddInMemoryCollection(ConfigurationOptions.Configuration)
  320. .Build();
  321. }
  322. private static void CreateLogger(IConfiguration configuration, IApplicationPaths appPaths)
  323. {
  324. try
  325. {
  326. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  327. Serilog.Log.Logger = new LoggerConfiguration()
  328. .ReadFrom.Configuration(configuration)
  329. .Enrich.FromLogContext()
  330. .CreateLogger();
  331. }
  332. catch (Exception ex)
  333. {
  334. Serilog.Log.Logger = new LoggerConfiguration()
  335. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  336. .WriteTo.Async(x => x.File(
  337. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  338. rollingInterval: RollingInterval.Day,
  339. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
  340. .Enrich.FromLogContext()
  341. .CreateLogger();
  342. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  343. }
  344. }
  345. private static IImageEncoder GetImageEncoder(
  346. IApplicationPaths appPaths,
  347. ILocalizationManager localizationManager)
  348. {
  349. try
  350. {
  351. // Test if the native lib is available
  352. SkiaEncoder.TestSkia();
  353. return new SkiaEncoder(
  354. _loggerFactory.CreateLogger<SkiaEncoder>(),
  355. appPaths,
  356. localizationManager);
  357. }
  358. catch (Exception ex)
  359. {
  360. _logger.LogWarning(ex, "Skia not available. Will fallback to NullIMageEncoder.");
  361. }
  362. return new NullImageEncoder();
  363. }
  364. private static void StartNewInstance(StartupOptions options)
  365. {
  366. _logger.LogInformation("Starting new instance");
  367. string module = options.RestartPath;
  368. if (string.IsNullOrWhiteSpace(module))
  369. {
  370. module = Environment.GetCommandLineArgs()[0];
  371. }
  372. string commandLineArgsString;
  373. if (options.RestartArgs != null)
  374. {
  375. commandLineArgsString = options.RestartArgs ?? string.Empty;
  376. }
  377. else
  378. {
  379. commandLineArgsString = string.Join(
  380. ' ',
  381. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  382. }
  383. _logger.LogInformation("Executable: {0}", module);
  384. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  385. Process.Start(module, commandLineArgsString);
  386. }
  387. private static string NormalizeCommandLineArgument(string arg)
  388. {
  389. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  390. {
  391. return arg;
  392. }
  393. return "\"" + arg + "\"";
  394. }
  395. }
  396. }