Program.cs 14 KB

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