Program.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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.Logging;
  25. using Serilog;
  26. using Serilog.AspNetCore;
  27. using ILogger = Microsoft.Extensions.Logging.ILogger;
  28. namespace Jellyfin.Server
  29. {
  30. public static class Program
  31. {
  32. private static readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
  33. private static readonly ILoggerFactory _loggerFactory = new SerilogLoggerFactory();
  34. private static ILogger _logger;
  35. private static bool _restartOnShutdown;
  36. public static async Task Main(string[] args)
  37. {
  38. // For backwards compatibility.
  39. // Modify any input arguments now which start with single-hyphen to POSIX standard
  40. // double-hyphen to allow parsing by CommandLineParser package.
  41. const string pattern = @"^(-[^-\s]{2})"; // Match -xx, not -x, not --xx, not xx
  42. const string substitution = @"-$1"; // Prepend with additional single-hyphen
  43. var regex = new Regex(pattern);
  44. for (var i = 0; i < args.Length; i++)
  45. {
  46. args[i] = regex.Replace(args[i], substitution);
  47. }
  48. // Parse the command line arguments and either start the app or exit indicating error
  49. await Parser.Default.ParseArguments<StartupOptions>(args)
  50. .MapResult(
  51. options => StartApp(options),
  52. errs => Task.FromResult(0)).ConfigureAwait(false);
  53. }
  54. private static async Task StartApp(StartupOptions options)
  55. {
  56. ServerApplicationPaths appPaths = CreateApplicationPaths(options);
  57. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  58. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  59. await CreateLogger(appPaths);
  60. _logger = _loggerFactory.CreateLogger("Main");
  61. AppDomain.CurrentDomain.UnhandledException += (sender, e)
  62. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  63. // Intercept Ctrl+C and Ctrl+Break
  64. Console.CancelKeyPress += (sender, e) =>
  65. {
  66. if (_tokenSource.IsCancellationRequested)
  67. {
  68. return; // Already shutting down
  69. }
  70. e.Cancel = true;
  71. _logger.LogInformation("Ctrl+C, shutting down");
  72. Environment.ExitCode = 128 + 2;
  73. Shutdown();
  74. };
  75. // Register a SIGTERM handler
  76. AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
  77. {
  78. if (_tokenSource.IsCancellationRequested)
  79. {
  80. return; // Already shutting down
  81. }
  82. _logger.LogInformation("Received a SIGTERM signal, shutting down");
  83. Environment.ExitCode = 128 + 15;
  84. Shutdown();
  85. };
  86. _logger.LogInformation("Jellyfin version: {Version}", Assembly.GetEntryAssembly().GetName().Version);
  87. EnvironmentInfo environmentInfo = new EnvironmentInfo(GetOperatingSystem());
  88. ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo);
  89. SQLitePCL.Batteries_V2.Init();
  90. // Allow all https requests
  91. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  92. var fileSystem = new ManagedFileSystem(_loggerFactory, environmentInfo, null, appPaths.TempDirectory, true);
  93. using (var appHost = new CoreAppHost(
  94. appPaths,
  95. _loggerFactory,
  96. options,
  97. fileSystem,
  98. environmentInfo,
  99. new NullImageEncoder(),
  100. new NetworkManager(_loggerFactory, environmentInfo)))
  101. {
  102. await appHost.Init();
  103. appHost.ImageProcessor.ImageEncoder = GetImageEncoder(fileSystem, appPaths, appHost.LocalizationManager);
  104. await appHost.RunStartupTasks();
  105. // TODO: read input for a stop command
  106. try
  107. {
  108. // Block main thread until shutdown
  109. await Task.Delay(-1, _tokenSource.Token);
  110. }
  111. catch (TaskCanceledException)
  112. {
  113. // Don't throw on cancellation
  114. }
  115. }
  116. if (_restartOnShutdown)
  117. {
  118. StartNewInstance(options);
  119. }
  120. }
  121. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  122. {
  123. string programDataPath = Environment.GetEnvironmentVariable("JELLYFIN_DATA_PATH");
  124. if (string.IsNullOrEmpty(programDataPath))
  125. {
  126. if (options.DataDir != null)
  127. {
  128. programDataPath = options.DataDir;
  129. }
  130. else
  131. {
  132. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  133. {
  134. programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  135. }
  136. else
  137. {
  138. // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
  139. programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
  140. // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
  141. if (string.IsNullOrEmpty(programDataPath))
  142. {
  143. programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
  144. }
  145. }
  146. programDataPath = Path.Combine(programDataPath, "jellyfin");
  147. }
  148. }
  149. if (string.IsNullOrEmpty(programDataPath))
  150. {
  151. Console.WriteLine("Cannot continue without path to program data folder (try -programdata)");
  152. Environment.Exit(1);
  153. }
  154. else
  155. {
  156. Directory.CreateDirectory(programDataPath);
  157. }
  158. string configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  159. if (string.IsNullOrEmpty(configDir))
  160. {
  161. if (options.ConfigDir != null)
  162. {
  163. configDir = options.ConfigDir;
  164. }
  165. else
  166. {
  167. // Let BaseApplicationPaths set up the default value
  168. configDir = null;
  169. }
  170. }
  171. if (configDir != null)
  172. {
  173. Directory.CreateDirectory(configDir);
  174. }
  175. string cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  176. if (string.IsNullOrEmpty(cacheDir))
  177. {
  178. if (options.CacheDir != null)
  179. {
  180. cacheDir = options.CacheDir;
  181. }
  182. else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  183. {
  184. // $XDG_CACHE_HOME defines the base directory relative to which user specific non-essential data files should be stored.
  185. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  186. // If $XDG_CACHE_HOME is either not set or empty, $HOME/.cache should be used.
  187. if (string.IsNullOrEmpty(cacheDir))
  188. {
  189. cacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cache");
  190. }
  191. cacheDir = Path.Combine(cacheDir, "jellyfin");
  192. }
  193. }
  194. if (cacheDir != null)
  195. {
  196. Directory.CreateDirectory(cacheDir);
  197. }
  198. string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  199. if (string.IsNullOrEmpty(logDir))
  200. {
  201. if (options.LogDir != null)
  202. {
  203. logDir = options.LogDir;
  204. }
  205. else
  206. {
  207. // Let BaseApplicationPaths set up the default value
  208. logDir = null;
  209. }
  210. }
  211. if (logDir != null)
  212. {
  213. Directory.CreateDirectory(logDir);
  214. }
  215. string appPath = AppContext.BaseDirectory;
  216. return new ServerApplicationPaths(programDataPath, appPath, appPath, logDir, configDir, cacheDir);
  217. }
  218. private static async Task CreateLogger(IApplicationPaths appPaths)
  219. {
  220. try
  221. {
  222. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
  223. if (!File.Exists(configPath))
  224. {
  225. // For some reason the csproj name is used instead of the assembly name
  226. using (Stream rscstr = typeof(Program).Assembly
  227. .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
  228. using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
  229. {
  230. await rscstr.CopyToAsync(fstr).ConfigureAwait(false);
  231. }
  232. }
  233. var configuration = new ConfigurationBuilder()
  234. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  235. .AddJsonFile("logging.json")
  236. .AddEnvironmentVariables("JELLYFIN_")
  237. .Build();
  238. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  239. Serilog.Log.Logger = new LoggerConfiguration()
  240. .ReadFrom.Configuration(configuration)
  241. .Enrich.FromLogContext()
  242. .CreateLogger();
  243. }
  244. catch (Exception ex)
  245. {
  246. Serilog.Log.Logger = new LoggerConfiguration()
  247. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  248. .WriteTo.Async(x => x.File(
  249. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  250. rollingInterval: RollingInterval.Day,
  251. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
  252. .Enrich.FromLogContext()
  253. .CreateLogger();
  254. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  255. }
  256. }
  257. public static IImageEncoder GetImageEncoder(
  258. IFileSystem fileSystem,
  259. IApplicationPaths appPaths,
  260. ILocalizationManager localizationManager)
  261. {
  262. try
  263. {
  264. return new SkiaEncoder(_loggerFactory, appPaths, fileSystem, localizationManager);
  265. }
  266. catch (Exception ex)
  267. {
  268. _logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
  269. }
  270. return new NullImageEncoder();
  271. }
  272. private static MediaBrowser.Model.System.OperatingSystem GetOperatingSystem()
  273. {
  274. switch (Environment.OSVersion.Platform)
  275. {
  276. case PlatformID.MacOSX:
  277. return MediaBrowser.Model.System.OperatingSystem.OSX;
  278. case PlatformID.Win32NT:
  279. return MediaBrowser.Model.System.OperatingSystem.Windows;
  280. case PlatformID.Unix:
  281. default:
  282. {
  283. string osDescription = RuntimeInformation.OSDescription;
  284. if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
  285. {
  286. return MediaBrowser.Model.System.OperatingSystem.Linux;
  287. }
  288. else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
  289. {
  290. return MediaBrowser.Model.System.OperatingSystem.OSX;
  291. }
  292. else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
  293. {
  294. return MediaBrowser.Model.System.OperatingSystem.BSD;
  295. }
  296. throw new Exception($"Can't resolve OS with description: '{osDescription}'");
  297. }
  298. }
  299. }
  300. public static void Shutdown()
  301. {
  302. if (!_tokenSource.IsCancellationRequested)
  303. {
  304. _tokenSource.Cancel();
  305. }
  306. }
  307. public static void Restart()
  308. {
  309. _restartOnShutdown = true;
  310. Shutdown();
  311. }
  312. private static void StartNewInstance(StartupOptions options)
  313. {
  314. _logger.LogInformation("Starting new instance");
  315. string module = options.RestartPath;
  316. if (string.IsNullOrWhiteSpace(module))
  317. {
  318. module = Environment.GetCommandLineArgs().First();
  319. }
  320. string commandLineArgsString;
  321. if (options.RestartArgs != null)
  322. {
  323. commandLineArgsString = options.RestartArgs ?? string.Empty;
  324. }
  325. else
  326. {
  327. commandLineArgsString = string.Join(
  328. " ",
  329. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  330. }
  331. _logger.LogInformation("Executable: {0}", module);
  332. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  333. Process.Start(module, commandLineArgsString);
  334. }
  335. private static string NormalizeCommandLineArgument(string arg)
  336. {
  337. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  338. {
  339. return arg;
  340. }
  341. return "\"" + arg + "\"";
  342. }
  343. }
  344. }