Program.cs 13 KB

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