2
0

Program.cs 18 KB

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