Program.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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.Extensions.Logging;
  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. var stopWatch = new Stopwatch();
  81. stopWatch.Start();
  82. ServerApplicationPaths appPaths = CreateApplicationPaths(options);
  83. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  84. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  85. IConfiguration appConfig = await CreateConfiguration(appPaths).ConfigureAwait(false);
  86. CreateLogger(appConfig, appPaths);
  87. _logger = _loggerFactory.CreateLogger("Main");
  88. AppDomain.CurrentDomain.UnhandledException += (sender, e)
  89. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  90. // Intercept Ctrl+C and Ctrl+Break
  91. Console.CancelKeyPress += (sender, e) =>
  92. {
  93. if (_tokenSource.IsCancellationRequested)
  94. {
  95. return; // Already shutting down
  96. }
  97. e.Cancel = true;
  98. _logger.LogInformation("Ctrl+C, shutting down");
  99. Environment.ExitCode = 128 + 2;
  100. Shutdown();
  101. };
  102. // Register a SIGTERM handler
  103. AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
  104. {
  105. if (_tokenSource.IsCancellationRequested)
  106. {
  107. return; // Already shutting down
  108. }
  109. _logger.LogInformation("Received a SIGTERM signal, shutting down");
  110. Environment.ExitCode = 128 + 15;
  111. Shutdown();
  112. };
  113. _logger.LogInformation(
  114. "Jellyfin version: {Version}",
  115. Assembly.GetEntryAssembly().GetName().Version.ToString(3));
  116. ApplicationHost.LogEnvironmentInfo(_logger, appPaths);
  117. // Increase the max http request limit
  118. // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
  119. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  120. // Disable the "Expect: 100-Continue" header by default
  121. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  122. ServicePointManager.Expect100Continue = false;
  123. // CA5359: Do Not Disable Certificate Validation
  124. #pragma warning disable CA5359
  125. // Allow all https requests
  126. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  127. #pragma warning restore CA5359
  128. Batteries_V2.Init();
  129. if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK)
  130. {
  131. _logger.LogWarning("Failed to enable shared cache for SQLite");
  132. }
  133. var appHost = new CoreAppHost(
  134. appPaths,
  135. _loggerFactory,
  136. options,
  137. new ManagedFileSystem(_loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths),
  138. new NullImageEncoder(),
  139. new NetworkManager(_loggerFactory.CreateLogger<NetworkManager>()),
  140. appConfig);
  141. try
  142. {
  143. await appHost.InitAsync(new ServiceCollection()).ConfigureAwait(false);
  144. appHost.ImageProcessor.ImageEncoder = GetImageEncoder(appPaths, appHost.LocalizationManager);
  145. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  146. stopWatch.Stop();
  147. _logger.LogInformation("Startup complete {Time:g}", stopWatch.Elapsed);
  148. // Block main thread until shutdown
  149. await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
  150. }
  151. catch (TaskCanceledException)
  152. {
  153. // Don't throw on cancellation
  154. }
  155. catch (Exception ex)
  156. {
  157. _logger.LogCritical(ex, "Error while starting server.");
  158. }
  159. finally
  160. {
  161. appHost?.Dispose();
  162. }
  163. if (_restartOnShutdown)
  164. {
  165. StartNewInstance(options);
  166. }
  167. }
  168. /// <summary>
  169. /// Create the data, config and log paths from the variety of inputs(command line args,
  170. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  171. /// for everything else the
  172. /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
  173. /// is followed.
  174. /// </summary>
  175. /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
  176. /// <returns><see cref="ServerApplicationPaths" />.</returns>
  177. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  178. {
  179. // dataDir
  180. // IF --datadir
  181. // ELSE IF $JELLYFIN_DATA_DIR
  182. // ELSE IF windows, use <%APPDATA%>/jellyfin
  183. // ELSE IF $XDG_DATA_HOME then use $XDG_DATA_HOME/jellyfin
  184. // ELSE use $HOME/.local/share/jellyfin
  185. var dataDir = options.DataDir;
  186. if (string.IsNullOrEmpty(dataDir))
  187. {
  188. dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR");
  189. if (string.IsNullOrEmpty(dataDir))
  190. {
  191. // LocalApplicationData follows the XDG spec on unix machines
  192. dataDir = Path.Combine(
  193. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  194. "jellyfin");
  195. }
  196. }
  197. // configDir
  198. // IF --configdir
  199. // ELSE IF $JELLYFIN_CONFIG_DIR
  200. // ELSE IF --datadir, use <datadir>/config (assume portable run)
  201. // ELSE IF <datadir>/config exists, use that
  202. // ELSE IF windows, use <datadir>/config
  203. // ELSE IF $XDG_CONFIG_HOME use $XDG_CONFIG_HOME/jellyfin
  204. // ELSE $HOME/.config/jellyfin
  205. var configDir = options.ConfigDir;
  206. if (string.IsNullOrEmpty(configDir))
  207. {
  208. configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  209. if (string.IsNullOrEmpty(configDir))
  210. {
  211. if (options.DataDir != null
  212. || Directory.Exists(Path.Combine(dataDir, "config"))
  213. || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  214. {
  215. // Hang config folder off already set dataDir
  216. configDir = Path.Combine(dataDir, "config");
  217. }
  218. else
  219. {
  220. // $XDG_CONFIG_HOME defines the base directory relative to which
  221. // user specific configuration files should be stored.
  222. configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
  223. // If $XDG_CONFIG_HOME is either not set or empty,
  224. // a default equal to $HOME /.config should be used.
  225. if (string.IsNullOrEmpty(configDir))
  226. {
  227. configDir = Path.Combine(
  228. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  229. ".config");
  230. }
  231. configDir = Path.Combine(configDir, "jellyfin");
  232. }
  233. }
  234. }
  235. // cacheDir
  236. // IF --cachedir
  237. // ELSE IF $JELLYFIN_CACHE_DIR
  238. // ELSE IF windows, use <datadir>/cache
  239. // ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
  240. // ELSE HOME/.cache/jellyfin
  241. var cacheDir = options.CacheDir;
  242. if (string.IsNullOrEmpty(cacheDir))
  243. {
  244. cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  245. if (string.IsNullOrEmpty(cacheDir))
  246. {
  247. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  248. {
  249. // Hang cache folder off already set dataDir
  250. cacheDir = Path.Combine(dataDir, "cache");
  251. }
  252. else
  253. {
  254. // $XDG_CACHE_HOME defines the base directory relative to which
  255. // user specific non-essential data files should be stored.
  256. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  257. // If $XDG_CACHE_HOME is either not set or empty,
  258. // a default equal to $HOME/.cache should be used.
  259. if (string.IsNullOrEmpty(cacheDir))
  260. {
  261. cacheDir = Path.Combine(
  262. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  263. ".cache");
  264. }
  265. cacheDir = Path.Combine(cacheDir, "jellyfin");
  266. }
  267. }
  268. }
  269. // webDir
  270. // IF --webdir
  271. // ELSE IF $JELLYFIN_WEB_DIR
  272. // ELSE use <bindir>/jellyfin-web
  273. var webDir = options.WebDir;
  274. if (string.IsNullOrEmpty(webDir))
  275. {
  276. webDir = Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
  277. if (string.IsNullOrEmpty(webDir))
  278. {
  279. // Use default location under ResourcesPath
  280. webDir = Path.Combine(AppContext.BaseDirectory, "jellyfin-web");
  281. }
  282. }
  283. // logDir
  284. // IF --logdir
  285. // ELSE IF $JELLYFIN_LOG_DIR
  286. // ELSE IF --datadir, use <datadir>/log (assume portable run)
  287. // ELSE <datadir>/log
  288. var logDir = options.LogDir;
  289. if (string.IsNullOrEmpty(logDir))
  290. {
  291. logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  292. if (string.IsNullOrEmpty(logDir))
  293. {
  294. // Hang log folder off already set dataDir
  295. logDir = Path.Combine(dataDir, "log");
  296. }
  297. }
  298. // Ensure the main folders exist before we continue
  299. try
  300. {
  301. Directory.CreateDirectory(dataDir);
  302. Directory.CreateDirectory(logDir);
  303. Directory.CreateDirectory(configDir);
  304. Directory.CreateDirectory(cacheDir);
  305. }
  306. catch (IOException ex)
  307. {
  308. Console.Error.WriteLine("Error whilst attempting to create folder");
  309. Console.Error.WriteLine(ex.ToString());
  310. Environment.Exit(1);
  311. }
  312. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
  313. }
  314. private static async Task<IConfiguration> CreateConfiguration(IApplicationPaths appPaths)
  315. {
  316. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
  317. if (!File.Exists(configPath))
  318. {
  319. // For some reason the csproj name is used instead of the assembly name
  320. using (Stream rscstr = typeof(Program).Assembly
  321. .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
  322. using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
  323. {
  324. await rscstr.CopyToAsync(fstr).ConfigureAwait(false);
  325. }
  326. }
  327. return new ConfigurationBuilder()
  328. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  329. .AddJsonFile("logging.json", false, true)
  330. .AddEnvironmentVariables("JELLYFIN_")
  331. .AddInMemoryCollection(ConfigurationOptions.Configuration)
  332. .Build();
  333. }
  334. private static void CreateLogger(IConfiguration configuration, IApplicationPaths appPaths)
  335. {
  336. try
  337. {
  338. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  339. Serilog.Log.Logger = new LoggerConfiguration()
  340. .ReadFrom.Configuration(configuration)
  341. .Enrich.FromLogContext()
  342. .CreateLogger();
  343. }
  344. catch (Exception ex)
  345. {
  346. Serilog.Log.Logger = new LoggerConfiguration()
  347. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  348. .WriteTo.Async(x => x.File(
  349. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  350. rollingInterval: RollingInterval.Day,
  351. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
  352. .Enrich.FromLogContext()
  353. .CreateLogger();
  354. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  355. }
  356. }
  357. private static IImageEncoder GetImageEncoder(
  358. IApplicationPaths appPaths,
  359. ILocalizationManager localizationManager)
  360. {
  361. try
  362. {
  363. // Test if the native lib is available
  364. SkiaEncoder.TestSkia();
  365. return new SkiaEncoder(
  366. _loggerFactory.CreateLogger<SkiaEncoder>(),
  367. appPaths,
  368. localizationManager);
  369. }
  370. catch (Exception ex)
  371. {
  372. _logger.LogWarning(ex, "Skia not available. Will fallback to NullIMageEncoder.");
  373. }
  374. return new NullImageEncoder();
  375. }
  376. private static void StartNewInstance(StartupOptions options)
  377. {
  378. _logger.LogInformation("Starting new instance");
  379. string module = options.RestartPath;
  380. if (string.IsNullOrWhiteSpace(module))
  381. {
  382. module = Environment.GetCommandLineArgs()[0];
  383. }
  384. string commandLineArgsString;
  385. if (options.RestartArgs != null)
  386. {
  387. commandLineArgsString = options.RestartArgs ?? string.Empty;
  388. }
  389. else
  390. {
  391. commandLineArgsString = string.Join(
  392. ' ',
  393. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  394. }
  395. _logger.LogInformation("Executable: {0}", module);
  396. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  397. Process.Start(module, commandLineArgsString);
  398. }
  399. private static string NormalizeCommandLineArgument(string arg)
  400. {
  401. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  402. {
  403. return arg;
  404. }
  405. return "\"" + arg + "\"";
  406. }
  407. }
  408. }