Program.cs 17 KB

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