Program.cs 18 KB

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