Program.cs 18 KB

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