Program.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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.AspNetCore.Hosting;
  24. using Microsoft.Extensions.Configuration;
  25. using Microsoft.Extensions.DependencyInjection;
  26. using Microsoft.Extensions.Logging;
  27. using Serilog;
  28. using Serilog.AspNetCore;
  29. using ILogger = Microsoft.Extensions.Logging.ILogger;
  30. namespace Jellyfin.Server
  31. {
  32. public static class Program
  33. {
  34. private static readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
  35. private static readonly ILoggerFactory _loggerFactory = new SerilogLoggerFactory();
  36. private static ILogger _logger;
  37. private static bool _restartOnShutdown;
  38. private static IConfiguration appConfig;
  39. public static async Task Main(string[] args)
  40. {
  41. // For backwards compatibility.
  42. // Modify any input arguments now which start with single-hyphen to POSIX standard
  43. // double-hyphen to allow parsing by CommandLineParser package.
  44. const string pattern = @"^(-[^-\s]{2})"; // Match -xx, not -x, not --xx, not xx
  45. const string substitution = @"-$1"; // Prepend with additional single-hyphen
  46. var regex = new Regex(pattern);
  47. for (var i = 0; i < args.Length; i++)
  48. {
  49. args[i] = regex.Replace(args[i], substitution);
  50. }
  51. // Parse the command line arguments and either start the app or exit indicating error
  52. await Parser.Default.ParseArguments<StartupOptions>(args)
  53. .MapResult(
  54. options => StartApp(options),
  55. errs => Task.FromResult(0)).ConfigureAwait(false);
  56. }
  57. public static void Shutdown()
  58. {
  59. if (!_tokenSource.IsCancellationRequested)
  60. {
  61. _tokenSource.Cancel();
  62. }
  63. }
  64. public static void Restart()
  65. {
  66. _restartOnShutdown = true;
  67. Shutdown();
  68. }
  69. private static async Task StartApp(StartupOptions options)
  70. {
  71. ServerApplicationPaths appPaths = CreateApplicationPaths(options);
  72. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  73. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  74. appConfig = await CreateConfiguration(appPaths).ConfigureAwait(false);
  75. CreateLogger(appConfig, appPaths);
  76. _logger = _loggerFactory.CreateLogger("Main");
  77. AppDomain.CurrentDomain.UnhandledException += (sender, e)
  78. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  79. // Intercept Ctrl+C and Ctrl+Break
  80. Console.CancelKeyPress += (sender, e) =>
  81. {
  82. if (_tokenSource.IsCancellationRequested)
  83. {
  84. return; // Already shutting down
  85. }
  86. e.Cancel = true;
  87. _logger.LogInformation("Ctrl+C, shutting down");
  88. Environment.ExitCode = 128 + 2;
  89. Shutdown();
  90. };
  91. // Register a SIGTERM handler
  92. AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
  93. {
  94. if (_tokenSource.IsCancellationRequested)
  95. {
  96. return; // Already shutting down
  97. }
  98. _logger.LogInformation("Received a SIGTERM signal, shutting down");
  99. Environment.ExitCode = 128 + 15;
  100. Shutdown();
  101. };
  102. _logger.LogInformation("Jellyfin version: {Version}", Assembly.GetEntryAssembly().GetName().Version);
  103. EnvironmentInfo environmentInfo = new EnvironmentInfo(GetOperatingSystem());
  104. ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo);
  105. SQLitePCL.Batteries_V2.Init();
  106. // Allow all https requests
  107. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  108. var fileSystem = new ManagedFileSystem(_loggerFactory, environmentInfo, appPaths);
  109. using (var appHost = new CoreAppHost(
  110. appPaths,
  111. _loggerFactory,
  112. options,
  113. fileSystem,
  114. environmentInfo,
  115. new NullImageEncoder(),
  116. new NetworkManager(_loggerFactory, environmentInfo),
  117. appConfig))
  118. {
  119. await appHost.Init(new ServiceCollection()).ConfigureAwait(false);
  120. appHost.ImageProcessor.ImageEncoder = GetImageEncoder(fileSystem, appPaths, appHost.LocalizationManager);
  121. await appHost.RunStartupTasks().ConfigureAwait(false);
  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_DIR
  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_DIR");
  157. if (string.IsNullOrEmpty(dataDir))
  158. {
  159. // LocalApplicationData follows the XDG spec on unix machines
  160. dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "jellyfin");
  161. }
  162. }
  163. Directory.CreateDirectory(dataDir);
  164. // configDir
  165. // IF --configdir
  166. // ELSE IF $JELLYFIN_CONFIG_DIR
  167. // ELSE IF --datadir, use <datadir>/config (assume portable run)
  168. // ELSE IF <datadir>/config exists, use that
  169. // ELSE IF windows, use <datadir>/config
  170. // ELSE IF $XDG_CONFIG_HOME use $XDG_CONFIG_HOME/jellyfin
  171. // ELSE $HOME/.config/jellyfin
  172. var configDir = options.ConfigDir;
  173. if (string.IsNullOrEmpty(configDir))
  174. {
  175. configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  176. if (string.IsNullOrEmpty(configDir))
  177. {
  178. if (options.DataDir != null || Directory.Exists(Path.Combine(dataDir, "config")) || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  179. {
  180. // Hang config folder off already set dataDir
  181. configDir = Path.Combine(dataDir, "config");
  182. }
  183. else
  184. {
  185. // $XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored.
  186. configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
  187. // If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME /.config should be used.
  188. if (string.IsNullOrEmpty(configDir))
  189. {
  190. configDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config");
  191. }
  192. configDir = Path.Combine(configDir, "jellyfin");
  193. }
  194. }
  195. }
  196. // cacheDir
  197. // IF --cachedir
  198. // ELSE IF $JELLYFIN_CACHE_DIR
  199. // ELSE IF windows, use <datadir>/cache
  200. // ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
  201. // ELSE HOME/.cache/jellyfin
  202. var cacheDir = options.CacheDir;
  203. if (string.IsNullOrEmpty(cacheDir))
  204. {
  205. cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  206. if (string.IsNullOrEmpty(cacheDir))
  207. {
  208. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  209. {
  210. // Hang cache folder off already set dataDir
  211. cacheDir = Path.Combine(dataDir, "cache");
  212. }
  213. else
  214. {
  215. // $XDG_CACHE_HOME defines the base directory relative to which user specific non-essential data files should be stored.
  216. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  217. // If $XDG_CACHE_HOME is either not set or empty, a default equal to $HOME/.cache should be used.
  218. if (string.IsNullOrEmpty(cacheDir))
  219. {
  220. cacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cache");
  221. }
  222. cacheDir = Path.Combine(cacheDir, "jellyfin");
  223. }
  224. }
  225. }
  226. // logDir
  227. // IF --logdir
  228. // ELSE IF $JELLYFIN_LOG_DIR
  229. // ELSE IF --datadir, use <datadir>/log (assume portable run)
  230. // ELSE <datadir>/log
  231. var logDir = options.LogDir;
  232. if (string.IsNullOrEmpty(logDir))
  233. {
  234. logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  235. if (string.IsNullOrEmpty(logDir))
  236. {
  237. // Hang log folder off already set dataDir
  238. logDir = Path.Combine(dataDir, "log");
  239. }
  240. }
  241. // Ensure the main folders exist before we continue
  242. try
  243. {
  244. Directory.CreateDirectory(logDir);
  245. Directory.CreateDirectory(configDir);
  246. Directory.CreateDirectory(cacheDir);
  247. }
  248. catch (IOException ex)
  249. {
  250. Console.Error.WriteLine("Error whilst attempting to create folder");
  251. Console.Error.WriteLine(ex.ToString());
  252. Environment.Exit(1);
  253. }
  254. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir);
  255. }
  256. private static async Task<IConfiguration> CreateConfiguration(IApplicationPaths appPaths)
  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. return new ConfigurationBuilder()
  270. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  271. .AddJsonFile("logging.json")
  272. .AddEnvironmentVariables("JELLYFIN_")
  273. .AddInMemoryCollection(ConfigurationOptions.Configuration)
  274. .Build();
  275. }
  276. private static void CreateLogger(IConfiguration configuration, IApplicationPaths appPaths)
  277. {
  278. try
  279. {
  280. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  281. Serilog.Log.Logger = new LoggerConfiguration()
  282. .ReadFrom.Configuration(configuration)
  283. .Enrich.FromLogContext()
  284. .CreateLogger();
  285. }
  286. catch (Exception ex)
  287. {
  288. Serilog.Log.Logger = new LoggerConfiguration()
  289. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  290. .WriteTo.Async(x => x.File(
  291. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  292. rollingInterval: RollingInterval.Day,
  293. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
  294. .Enrich.FromLogContext()
  295. .CreateLogger();
  296. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  297. }
  298. }
  299. private static IImageEncoder GetImageEncoder(
  300. IFileSystem fileSystem,
  301. IApplicationPaths appPaths,
  302. ILocalizationManager localizationManager)
  303. {
  304. try
  305. {
  306. return new SkiaEncoder(_loggerFactory, appPaths, fileSystem, localizationManager);
  307. }
  308. catch (Exception ex)
  309. {
  310. _logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
  311. }
  312. return new NullImageEncoder();
  313. }
  314. private static MediaBrowser.Model.System.OperatingSystem GetOperatingSystem()
  315. {
  316. switch (Environment.OSVersion.Platform)
  317. {
  318. case PlatformID.MacOSX:
  319. return MediaBrowser.Model.System.OperatingSystem.OSX;
  320. case PlatformID.Win32NT:
  321. return MediaBrowser.Model.System.OperatingSystem.Windows;
  322. case PlatformID.Unix:
  323. default:
  324. {
  325. string osDescription = RuntimeInformation.OSDescription;
  326. if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
  327. {
  328. return MediaBrowser.Model.System.OperatingSystem.Linux;
  329. }
  330. else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
  331. {
  332. return MediaBrowser.Model.System.OperatingSystem.OSX;
  333. }
  334. else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
  335. {
  336. return MediaBrowser.Model.System.OperatingSystem.BSD;
  337. }
  338. throw new Exception($"Can't resolve OS with description: '{osDescription}'");
  339. }
  340. }
  341. }
  342. private static void StartNewInstance(StartupOptions options)
  343. {
  344. _logger.LogInformation("Starting new instance");
  345. string module = options.RestartPath;
  346. if (string.IsNullOrWhiteSpace(module))
  347. {
  348. module = Environment.GetCommandLineArgs().First();
  349. }
  350. string commandLineArgsString;
  351. if (options.RestartArgs != null)
  352. {
  353. commandLineArgsString = options.RestartArgs ?? string.Empty;
  354. }
  355. else
  356. {
  357. commandLineArgsString = string.Join(
  358. " ",
  359. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  360. }
  361. _logger.LogInformation("Executable: {0}", module);
  362. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  363. Process.Start(module, commandLineArgsString);
  364. }
  365. private static string NormalizeCommandLineArgument(string arg)
  366. {
  367. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  368. {
  369. return arg;
  370. }
  371. return "\"" + arg + "\"";
  372. }
  373. }
  374. }