Program.cs 17 KB

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