Program.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. await CreateLogger(appConfig, appPaths).ConfigureAwait(false);
  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, appConfig);
  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. {
  117. await appHost.Init(new ServiceCollection()).ConfigureAwait(false);
  118. appHost.ImageProcessor.ImageEncoder = GetImageEncoder(fileSystem, appPaths, appHost.LocalizationManager);
  119. await appHost.RunStartupTasks().ConfigureAwait(false);
  120. // TODO: read input for a stop command
  121. try
  122. {
  123. // Block main thread until shutdown
  124. await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
  125. }
  126. catch (TaskCanceledException)
  127. {
  128. // Don't throw on cancellation
  129. }
  130. }
  131. if (_restartOnShutdown)
  132. {
  133. StartNewInstance(options);
  134. }
  135. }
  136. /// <summary>
  137. /// Create the data, config and log paths from the variety of inputs(command line args,
  138. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  139. /// for everything else the XDG approach is followed:
  140. /// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
  141. /// </summary>
  142. /// <param name="options">StartupOptions</param>
  143. /// <returns>ServerApplicationPaths</returns>
  144. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  145. {
  146. // dataDir
  147. // IF --datadir
  148. // ELSE IF $JELLYFIN_DATA_PATH
  149. // ELSE IF windows, use <%APPDATA%>/jellyfin
  150. // ELSE IF $XDG_DATA_HOME then use $XDG_DATA_HOME/jellyfin
  151. // ELSE use $HOME/.local/share/jellyfin
  152. var dataDir = options.DataDir;
  153. if (string.IsNullOrEmpty(dataDir))
  154. {
  155. dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_PATH");
  156. if (string.IsNullOrEmpty(dataDir))
  157. {
  158. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  159. {
  160. dataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  161. }
  162. else
  163. {
  164. // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
  165. dataDir = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
  166. // If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used.
  167. if (string.IsNullOrEmpty(dataDir))
  168. {
  169. dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
  170. }
  171. }
  172. dataDir = Path.Combine(dataDir, "jellyfin");
  173. }
  174. }
  175. // configDir
  176. // IF --configdir
  177. // ELSE IF $JELLYFIN_CONFIG_DIR
  178. // ELSE IF --datadir, use <datadir>/config (assume portable run)
  179. // ELSE IF <datadir>/config exists, use that
  180. // ELSE IF windows, use <datadir>/config
  181. // ELSE IF $XDG_CONFIG_HOME use $XDG_CONFIG_HOME/jellyfin
  182. // ELSE $HOME/.config/jellyfin
  183. var configDir = options.ConfigDir;
  184. if (string.IsNullOrEmpty(configDir))
  185. {
  186. configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  187. if (string.IsNullOrEmpty(configDir))
  188. {
  189. if (options.DataDir != null || Directory.Exists(Path.Combine(dataDir, "config")) || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  190. {
  191. // Hang config folder off already set dataDir
  192. configDir = Path.Combine(dataDir, "config");
  193. }
  194. else
  195. {
  196. // $XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored.
  197. configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
  198. // If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME /.config should be used.
  199. if (string.IsNullOrEmpty(configDir))
  200. {
  201. configDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config");
  202. }
  203. configDir = Path.Combine(configDir, "jellyfin");
  204. }
  205. }
  206. }
  207. // cacheDir
  208. // IF --cachedir
  209. // ELSE IF $JELLYFIN_CACHE_DIR
  210. // ELSE IF windows, use <datadir>/cache
  211. // ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
  212. // ELSE HOME/.cache/jellyfin
  213. var cacheDir = options.CacheDir;
  214. if (string.IsNullOrEmpty(cacheDir))
  215. {
  216. cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  217. if (string.IsNullOrEmpty(cacheDir))
  218. {
  219. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  220. {
  221. // Hang cache folder off already set dataDir
  222. cacheDir = Path.Combine(dataDir, "cache");
  223. }
  224. else
  225. {
  226. // $XDG_CACHE_HOME defines the base directory relative to which user specific non-essential data files should be stored.
  227. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  228. // If $XDG_CACHE_HOME is either not set or empty, a default equal to $HOME/.cache should be used.
  229. if (string.IsNullOrEmpty(cacheDir))
  230. {
  231. cacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cache");
  232. }
  233. cacheDir = Path.Combine(cacheDir, "jellyfin");
  234. }
  235. }
  236. }
  237. // logDir
  238. // IF --logdir
  239. // ELSE IF $JELLYFIN_LOG_DIR
  240. // ELSE IF --datadir, use <datadir>/log (assume portable run)
  241. // ELSE <datadir>/log
  242. var logDir = options.LogDir;
  243. if (string.IsNullOrEmpty(logDir))
  244. {
  245. logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  246. if (string.IsNullOrEmpty(logDir))
  247. {
  248. // Hang log folder off already set dataDir
  249. logDir = Path.Combine(dataDir, "log");
  250. }
  251. }
  252. // Ensure the main folders exist before we continue
  253. try
  254. {
  255. Directory.CreateDirectory(dataDir);
  256. Directory.CreateDirectory(logDir);
  257. Directory.CreateDirectory(configDir);
  258. Directory.CreateDirectory(cacheDir);
  259. }
  260. catch (IOException ex)
  261. {
  262. Console.Error.WriteLine("Error whilst attempting to create folder");
  263. Console.Error.WriteLine(ex.ToString());
  264. Environment.Exit(1);
  265. }
  266. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir);
  267. }
  268. private static async Task<IConfiguration> CreateConfiguration(IApplicationPaths appPaths)
  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. return new ConfigurationBuilder()
  282. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  283. .AddJsonFile("logging.json")
  284. .AddEnvironmentVariables("JELLYFIN_")
  285. .AddInMemoryCollection(ConfigurationOptions.Configuration)
  286. .Build();
  287. }
  288. private static async Task CreateLogger(IConfiguration configuration, IApplicationPaths appPaths)
  289. {
  290. try
  291. {
  292. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  293. Serilog.Log.Logger = new LoggerConfiguration()
  294. .ReadFrom.Configuration(configuration)
  295. .Enrich.FromLogContext()
  296. .CreateLogger();
  297. }
  298. catch (Exception ex)
  299. {
  300. Serilog.Log.Logger = new LoggerConfiguration()
  301. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  302. .WriteTo.Async(x => x.File(
  303. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  304. rollingInterval: RollingInterval.Day,
  305. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
  306. .Enrich.FromLogContext()
  307. .CreateLogger();
  308. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  309. }
  310. }
  311. private static IImageEncoder GetImageEncoder(
  312. IFileSystem fileSystem,
  313. IApplicationPaths appPaths,
  314. ILocalizationManager localizationManager)
  315. {
  316. try
  317. {
  318. return new SkiaEncoder(_loggerFactory, appPaths, fileSystem, localizationManager);
  319. }
  320. catch (Exception ex)
  321. {
  322. _logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
  323. }
  324. return new NullImageEncoder();
  325. }
  326. private static MediaBrowser.Model.System.OperatingSystem GetOperatingSystem()
  327. {
  328. switch (Environment.OSVersion.Platform)
  329. {
  330. case PlatformID.MacOSX:
  331. return MediaBrowser.Model.System.OperatingSystem.OSX;
  332. case PlatformID.Win32NT:
  333. return MediaBrowser.Model.System.OperatingSystem.Windows;
  334. case PlatformID.Unix:
  335. default:
  336. {
  337. string osDescription = RuntimeInformation.OSDescription;
  338. if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
  339. {
  340. return MediaBrowser.Model.System.OperatingSystem.Linux;
  341. }
  342. else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
  343. {
  344. return MediaBrowser.Model.System.OperatingSystem.OSX;
  345. }
  346. else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
  347. {
  348. return MediaBrowser.Model.System.OperatingSystem.BSD;
  349. }
  350. throw new Exception($"Can't resolve OS with description: '{osDescription}'");
  351. }
  352. }
  353. }
  354. private static void StartNewInstance(StartupOptions options)
  355. {
  356. _logger.LogInformation("Starting new instance");
  357. string module = options.RestartPath;
  358. if (string.IsNullOrWhiteSpace(module))
  359. {
  360. module = Environment.GetCommandLineArgs().First();
  361. }
  362. string commandLineArgsString;
  363. if (options.RestartArgs != null)
  364. {
  365. commandLineArgsString = options.RestartArgs ?? string.Empty;
  366. }
  367. else
  368. {
  369. commandLineArgsString = string.Join(
  370. " ",
  371. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  372. }
  373. _logger.LogInformation("Executable: {0}", module);
  374. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  375. Process.Start(module, commandLineArgsString);
  376. }
  377. private static string NormalizeCommandLineArgument(string arg)
  378. {
  379. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  380. {
  381. return arg;
  382. }
  383. return "\"" + arg + "\"";
  384. }
  385. }
  386. }