Program.cs 18 KB

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