Program.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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.EnvironmentInfo;
  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 MediaBrowser.Model.IO;
  23. using Microsoft.Extensions.Configuration;
  24. using Microsoft.Extensions.Logging;
  25. using Serilog;
  26. using Serilog.AspNetCore;
  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 async 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. await Parser.Default.ParseArguments<StartupOptions>(args)
  50. .MapResult(
  51. options => StartApp(options),
  52. errs => Task.FromResult(0)).ConfigureAwait(false);
  53. }
  54. private static async Task StartApp(StartupOptions options)
  55. {
  56. ServerApplicationPaths appPaths = CreateApplicationPaths(options);
  57. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  58. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  59. await CreateLogger(appPaths);
  60. _logger = _loggerFactory.CreateLogger("Main");
  61. AppDomain.CurrentDomain.UnhandledException += (sender, e)
  62. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  63. // Intercept Ctrl+C and Ctrl+Break
  64. Console.CancelKeyPress += (sender, e) =>
  65. {
  66. if (_tokenSource.IsCancellationRequested)
  67. {
  68. return; // Already shutting down
  69. }
  70. e.Cancel = true;
  71. _logger.LogInformation("Ctrl+C, shutting down");
  72. Environment.ExitCode = 128 + 2;
  73. Shutdown();
  74. };
  75. // Register a SIGTERM handler
  76. AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
  77. {
  78. if (_tokenSource.IsCancellationRequested)
  79. {
  80. return; // Already shutting down
  81. }
  82. _logger.LogInformation("Received a SIGTERM signal, shutting down");
  83. Environment.ExitCode = 128 + 15;
  84. Shutdown();
  85. };
  86. _logger.LogInformation("Jellyfin version: {Version}", Assembly.GetEntryAssembly().GetName().Version);
  87. EnvironmentInfo environmentInfo = new EnvironmentInfo(GetOperatingSystem());
  88. ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo);
  89. SQLitePCL.Batteries_V2.Init();
  90. // Allow all https requests
  91. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  92. var fileSystem = new ManagedFileSystem(_loggerFactory, environmentInfo, null, appPaths.TempDirectory, true);
  93. using (var appHost = new CoreAppHost(
  94. appPaths,
  95. _loggerFactory,
  96. options,
  97. fileSystem,
  98. environmentInfo,
  99. new NullImageEncoder(),
  100. new NetworkManager(_loggerFactory, environmentInfo)))
  101. {
  102. await appHost.Init();
  103. appHost.ImageProcessor.ImageEncoder = GetImageEncoder(fileSystem, appPaths, appHost.LocalizationManager);
  104. await appHost.RunStartupTasks();
  105. // TODO: read input for a stop command
  106. try
  107. {
  108. // Block main thread until shutdown
  109. await Task.Delay(-1, _tokenSource.Token);
  110. }
  111. catch (TaskCanceledException)
  112. {
  113. // Don't throw on cancellation
  114. }
  115. }
  116. if (_restartOnShutdown)
  117. {
  118. StartNewInstance(options);
  119. }
  120. }
  121. /// <summary>
  122. /// Create the data, config and log paths from the variety of inputs(command line args,
  123. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  124. /// for everything else the XDG approach is followed:
  125. /// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
  126. /// </summary>
  127. /// <param name="options"></param>
  128. /// <returns>ServerApplicationPaths</returns>
  129. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  130. {
  131. // dataDir
  132. // IF --datadir
  133. // ELSE IF $JELLYFIN_DATA_PATH
  134. // ELSE IF windows, use <%APPDATA%>/jellyfin
  135. // ELSE IF $XDG_DATA_HOME then use $XDG_DATA_HOME/jellyfin
  136. // ELSE use $HOME/.local/share/jellyfin
  137. var dataDir = options.DataDir;
  138. if (string.IsNullOrEmpty(dataDir))
  139. {
  140. dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_PATH");
  141. if (string.IsNullOrEmpty(dataDir))
  142. {
  143. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  144. {
  145. dataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  146. }
  147. else
  148. {
  149. // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
  150. dataDir = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
  151. // If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used.
  152. if (string.IsNullOrEmpty(dataDir))
  153. {
  154. dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
  155. }
  156. }
  157. dataDir = Path.Combine(dataDir, "jellyfin");
  158. }
  159. }
  160. // configDir
  161. // IF --configdir
  162. // ELSE IF $JELLYFIN_CONFIG_DIR
  163. // ELSE IF --datadir, use <datadir>/config (assume portable run)
  164. // ELSE IF <datadir>/config exists, use that
  165. // ELSE IF windows, use <datadir>/config
  166. // ELSE IF $XDG_CONFIG_HOME use $XDG_CONFIG_HOME/jellyfin
  167. // ELSE $HOME/.config/jellyfin
  168. var configDir = options.ConfigDir;
  169. if (string.IsNullOrEmpty(configDir))
  170. {
  171. configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  172. if (string.IsNullOrEmpty(configDir))
  173. {
  174. if (options.DataDir != null || Directory.Exists(Path.Combine(dataDir, "config")) || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  175. {
  176. // Hang config folder off already set dataDir
  177. configDir = Path.Combine(dataDir, "config");
  178. }
  179. else
  180. {
  181. // $XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored.
  182. configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
  183. // If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME /.config should be used.
  184. if (string.IsNullOrEmpty(configDir))
  185. {
  186. configDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config");
  187. }
  188. configDir = Path.Combine(configDir, "jellyfin");
  189. }
  190. }
  191. }
  192. // cacheDir
  193. // IF --cachedir
  194. // ELSE IF $JELLYFIN_CACHE_DIR
  195. // ELSE IF windows, use <datadir>/cache
  196. // ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
  197. // ELSE HOME/.cache/jellyfin
  198. var cacheDir = options.CacheDir;
  199. if (string.IsNullOrEmpty(cacheDir))
  200. {
  201. cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  202. if (string.IsNullOrEmpty(cacheDir))
  203. {
  204. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  205. {
  206. // Hang cache folder off already set dataDir
  207. cacheDir = Path.Combine(dataDir, "cache");
  208. }
  209. else
  210. {
  211. // $XDG_CACHE_HOME defines the base directory relative to which user specific non-essential data files should be stored.
  212. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  213. // If $XDG_CACHE_HOME is either not set or empty, a default equal to $HOME/.cache should be used.
  214. if (string.IsNullOrEmpty(cacheDir))
  215. {
  216. cacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cache");
  217. }
  218. cacheDir = Path.Combine(cacheDir, "jellyfin");
  219. }
  220. }
  221. }
  222. // logDir
  223. // IF --logdir
  224. // ELSE IF $JELLYFIN_LOG_DIR
  225. // ELSE IF --datadir, use <datadir>/log (assume portable run)
  226. // ELSE <datadir>/log
  227. var logDir = options.LogDir;
  228. if (string.IsNullOrEmpty(logDir))
  229. {
  230. logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  231. if (string.IsNullOrEmpty(logDir))
  232. {
  233. // Hang log folder off already set dataDir
  234. logDir = Path.Combine(dataDir, "log");
  235. }
  236. }
  237. // Ensure the main folders exist before we continue
  238. try
  239. {
  240. Directory.CreateDirectory(dataDir);
  241. Directory.CreateDirectory(logDir);
  242. Directory.CreateDirectory(configDir);
  243. Directory.CreateDirectory(cacheDir);
  244. }
  245. catch (IOException ex)
  246. {
  247. Console.Error.WriteLine("Error whilst attempting to create folder");
  248. Console.Error.WriteLine(ex.ToString());
  249. Environment.Exit(1);
  250. }
  251. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir);
  252. }
  253. private static async Task CreateLogger(IApplicationPaths appPaths)
  254. {
  255. try
  256. {
  257. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
  258. if (!File.Exists(configPath))
  259. {
  260. // For some reason the csproj name is used instead of the assembly name
  261. using (Stream rscstr = typeof(Program).Assembly
  262. .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
  263. using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
  264. {
  265. await rscstr.CopyToAsync(fstr).ConfigureAwait(false);
  266. }
  267. }
  268. var configuration = new ConfigurationBuilder()
  269. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  270. .AddJsonFile("logging.json")
  271. .AddEnvironmentVariables("JELLYFIN_")
  272. .Build();
  273. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  274. Serilog.Log.Logger = new LoggerConfiguration()
  275. .ReadFrom.Configuration(configuration)
  276. .Enrich.FromLogContext()
  277. .CreateLogger();
  278. }
  279. catch (Exception ex)
  280. {
  281. Serilog.Log.Logger = new LoggerConfiguration()
  282. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  283. .WriteTo.Async(x => x.File(
  284. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  285. rollingInterval: RollingInterval.Day,
  286. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
  287. .Enrich.FromLogContext()
  288. .CreateLogger();
  289. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  290. }
  291. }
  292. public static IImageEncoder GetImageEncoder(
  293. IFileSystem fileSystem,
  294. IApplicationPaths appPaths,
  295. ILocalizationManager localizationManager)
  296. {
  297. try
  298. {
  299. return new SkiaEncoder(_loggerFactory, appPaths, fileSystem, localizationManager);
  300. }
  301. catch (Exception ex)
  302. {
  303. _logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
  304. }
  305. return new NullImageEncoder();
  306. }
  307. private static MediaBrowser.Model.System.OperatingSystem GetOperatingSystem()
  308. {
  309. switch (Environment.OSVersion.Platform)
  310. {
  311. case PlatformID.MacOSX:
  312. return MediaBrowser.Model.System.OperatingSystem.OSX;
  313. case PlatformID.Win32NT:
  314. return MediaBrowser.Model.System.OperatingSystem.Windows;
  315. case PlatformID.Unix:
  316. default:
  317. {
  318. string osDescription = RuntimeInformation.OSDescription;
  319. if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
  320. {
  321. return MediaBrowser.Model.System.OperatingSystem.Linux;
  322. }
  323. else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
  324. {
  325. return MediaBrowser.Model.System.OperatingSystem.OSX;
  326. }
  327. else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
  328. {
  329. return MediaBrowser.Model.System.OperatingSystem.BSD;
  330. }
  331. throw new Exception($"Can't resolve OS with description: '{osDescription}'");
  332. }
  333. }
  334. }
  335. public static void Shutdown()
  336. {
  337. if (!_tokenSource.IsCancellationRequested)
  338. {
  339. _tokenSource.Cancel();
  340. }
  341. }
  342. public static void Restart()
  343. {
  344. _restartOnShutdown = true;
  345. Shutdown();
  346. }
  347. private static void StartNewInstance(StartupOptions options)
  348. {
  349. _logger.LogInformation("Starting new instance");
  350. string module = options.RestartPath;
  351. if (string.IsNullOrWhiteSpace(module))
  352. {
  353. module = Environment.GetCommandLineArgs().First();
  354. }
  355. string commandLineArgsString;
  356. if (options.RestartArgs != null)
  357. {
  358. commandLineArgsString = options.RestartArgs ?? string.Empty;
  359. }
  360. else
  361. {
  362. commandLineArgsString = string.Join(
  363. " ",
  364. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  365. }
  366. _logger.LogInformation("Executable: {0}", module);
  367. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  368. Process.Start(module, commandLineArgsString);
  369. }
  370. private static string NormalizeCommandLineArgument(string arg)
  371. {
  372. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  373. {
  374. return arg;
  375. }
  376. return "\"" + arg + "\"";
  377. }
  378. }
  379. }