Program.cs 17 KB

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