Program.cs 17 KB

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