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