Program.cs 18 KB

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