Program.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. appHost.Init();
  103. appHost.ImageProcessor.ImageEncoder = GetImageEncoder(fileSystem, appPaths, appHost.LocalizationManager);
  104. _logger.LogInformation("Running startup tasks");
  105. await appHost.RunStartupTasks();
  106. // TODO: read input for a stop command
  107. try
  108. {
  109. // Block main thread until shutdown
  110. await Task.Delay(-1, _tokenSource.Token);
  111. }
  112. catch (TaskCanceledException)
  113. {
  114. // Don't throw on cancellation
  115. }
  116. _logger.LogInformation("Disposing app host");
  117. }
  118. if (_restartOnShutdown)
  119. {
  120. StartNewInstance(options);
  121. }
  122. }
  123. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  124. {
  125. string programDataPath = Environment.GetEnvironmentVariable("JELLYFIN_DATA_PATH");
  126. if (string.IsNullOrEmpty(programDataPath))
  127. {
  128. if (options.DataDir != null)
  129. {
  130. programDataPath = options.DataDir;
  131. }
  132. else
  133. {
  134. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  135. {
  136. programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  137. }
  138. else
  139. {
  140. // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
  141. programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
  142. // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
  143. if (string.IsNullOrEmpty(programDataPath))
  144. {
  145. programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
  146. }
  147. }
  148. programDataPath = Path.Combine(programDataPath, "jellyfin");
  149. }
  150. }
  151. if (string.IsNullOrEmpty(programDataPath))
  152. {
  153. Console.WriteLine("Cannot continue without path to program data folder (try -programdata)");
  154. Environment.Exit(1);
  155. }
  156. else
  157. {
  158. Directory.CreateDirectory(programDataPath);
  159. }
  160. string configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  161. if (string.IsNullOrEmpty(configDir))
  162. {
  163. if (options.ConfigDir != null)
  164. {
  165. configDir = options.ConfigDir;
  166. }
  167. else
  168. {
  169. // Let BaseApplicationPaths set up the default value
  170. configDir = null;
  171. }
  172. }
  173. if (configDir != null)
  174. {
  175. Directory.CreateDirectory(configDir);
  176. }
  177. string cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  178. if (string.IsNullOrEmpty(cacheDir))
  179. {
  180. if (options.CacheDir != null)
  181. {
  182. cacheDir = options.CacheDir;
  183. }
  184. else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  185. {
  186. // $XDG_CACHE_HOME defines the base directory relative to which user specific non-essential data files should be stored.
  187. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  188. // If $XDG_CACHE_HOME is either not set or empty, $HOME/.cache should be used.
  189. if (string.IsNullOrEmpty(cacheDir))
  190. {
  191. cacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cache");
  192. }
  193. cacheDir = Path.Combine(cacheDir, "jellyfin");
  194. }
  195. }
  196. if (cacheDir != null)
  197. {
  198. Directory.CreateDirectory(cacheDir);
  199. }
  200. string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  201. if (string.IsNullOrEmpty(logDir))
  202. {
  203. if (options.LogDir != null)
  204. {
  205. logDir = options.LogDir;
  206. }
  207. else
  208. {
  209. // Let BaseApplicationPaths set up the default value
  210. logDir = null;
  211. }
  212. }
  213. if (logDir != null)
  214. {
  215. Directory.CreateDirectory(logDir);
  216. }
  217. string appPath = AppContext.BaseDirectory;
  218. return new ServerApplicationPaths(programDataPath, appPath, appPath, logDir, configDir, cacheDir);
  219. }
  220. private static async Task createLogger(IApplicationPaths appPaths)
  221. {
  222. try
  223. {
  224. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
  225. if (!File.Exists(configPath))
  226. {
  227. // For some reason the csproj name is used instead of the assembly name
  228. using (Stream rscstr = typeof(Program).Assembly
  229. .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
  230. using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
  231. {
  232. await rscstr.CopyToAsync(fstr).ConfigureAwait(false);
  233. }
  234. }
  235. var configuration = new ConfigurationBuilder()
  236. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  237. .AddJsonFile("logging.json")
  238. .AddEnvironmentVariables("JELLYFIN_")
  239. .Build();
  240. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  241. Serilog.Log.Logger = new LoggerConfiguration()
  242. .ReadFrom.Configuration(configuration)
  243. .Enrich.FromLogContext()
  244. .CreateLogger();
  245. }
  246. catch (Exception ex)
  247. {
  248. Serilog.Log.Logger = new LoggerConfiguration()
  249. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  250. .WriteTo.Async(x => x.File(
  251. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  252. rollingInterval: RollingInterval.Day,
  253. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
  254. .Enrich.FromLogContext()
  255. .CreateLogger();
  256. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  257. }
  258. }
  259. public static IImageEncoder GetImageEncoder(
  260. IFileSystem fileSystem,
  261. IApplicationPaths appPaths,
  262. ILocalizationManager localizationManager)
  263. {
  264. try
  265. {
  266. return new SkiaEncoder(_loggerFactory, appPaths, fileSystem, localizationManager);
  267. }
  268. catch (Exception ex)
  269. {
  270. _logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
  271. }
  272. return new NullImageEncoder();
  273. }
  274. private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem()
  275. {
  276. switch (Environment.OSVersion.Platform)
  277. {
  278. case PlatformID.MacOSX:
  279. return MediaBrowser.Model.System.OperatingSystem.OSX;
  280. case PlatformID.Win32NT:
  281. return MediaBrowser.Model.System.OperatingSystem.Windows;
  282. case PlatformID.Unix:
  283. default:
  284. {
  285. string osDescription = RuntimeInformation.OSDescription;
  286. if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
  287. {
  288. return MediaBrowser.Model.System.OperatingSystem.Linux;
  289. }
  290. else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
  291. {
  292. return MediaBrowser.Model.System.OperatingSystem.OSX;
  293. }
  294. else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
  295. {
  296. return MediaBrowser.Model.System.OperatingSystem.BSD;
  297. }
  298. throw new Exception($"Can't resolve OS with description: '{osDescription}'");
  299. }
  300. }
  301. }
  302. public static void Shutdown()
  303. {
  304. if (!_tokenSource.IsCancellationRequested)
  305. {
  306. _tokenSource.Cancel();
  307. }
  308. }
  309. public static void Restart()
  310. {
  311. _restartOnShutdown = true;
  312. Shutdown();
  313. }
  314. private static void StartNewInstance(StartupOptions options)
  315. {
  316. _logger.LogInformation("Starting new instance");
  317. string module = options.RestartPath;
  318. if (string.IsNullOrWhiteSpace(module))
  319. {
  320. module = Environment.GetCommandLineArgs().First();
  321. }
  322. string commandLineArgsString;
  323. if (options.RestartArgs != null)
  324. {
  325. commandLineArgsString = options.RestartArgs ?? string.Empty;
  326. }
  327. else
  328. {
  329. commandLineArgsString = string.Join(
  330. " ",
  331. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  332. }
  333. _logger.LogInformation("Executable: {0}", module);
  334. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  335. Process.Start(module, commandLineArgsString);
  336. }
  337. private static string NormalizeCommandLineArgument(string arg)
  338. {
  339. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  340. {
  341. return arg;
  342. }
  343. return "\"" + arg + "\"";
  344. }
  345. }
  346. }