Program.cs 14 KB

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