Program.cs 16 KB

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