Program.cs 17 KB

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