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.Drawing.Skia;
  13. using Emby.Server.Implementations;
  14. using Emby.Server.Implementations.EnvironmentInfo;
  15. using Emby.Server.Implementations.IO;
  16. using Emby.Server.Implementations.Networking;
  17. using MediaBrowser.Common.Configuration;
  18. using MediaBrowser.Common.Net;
  19. using MediaBrowser.Controller.Drawing;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Model.Globalization;
  22. using MediaBrowser.Model.System;
  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. StartupOptions options = new StartupOptions(args);
  39. Version version = Assembly.GetEntryAssembly().GetName().Version;
  40. if (options.ContainsOption("-v") || options.ContainsOption("--version"))
  41. {
  42. Console.WriteLine(version.ToString());
  43. }
  44. ServerApplicationPaths appPaths = CreateApplicationPaths(options);
  45. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  46. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  47. await createLogger(appPaths);
  48. _logger = _loggerFactory.CreateLogger("Main");
  49. AppDomain.CurrentDomain.UnhandledException += (sender, e)
  50. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  51. // Intercept Ctrl+C and Ctrl+Break
  52. Console.CancelKeyPress += (sender, e) =>
  53. {
  54. if (_tokenSource.IsCancellationRequested)
  55. {
  56. return; // Already shutting down
  57. }
  58. e.Cancel = true;
  59. _logger.LogInformation("Ctrl+C, shutting down");
  60. Environment.ExitCode = 128 + 2;
  61. Shutdown();
  62. };
  63. // Register a SIGTERM handler
  64. AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
  65. {
  66. if (_tokenSource.IsCancellationRequested)
  67. {
  68. return; // Already shutting down
  69. }
  70. _logger.LogInformation("Received a SIGTERM signal, shutting down");
  71. Environment.ExitCode = 128 + 15;
  72. Shutdown();
  73. };
  74. _logger.LogInformation("Jellyfin version: {Version}", version);
  75. EnvironmentInfo environmentInfo = new EnvironmentInfo(getOperatingSystem());
  76. ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo);
  77. SQLitePCL.Batteries_V2.Init();
  78. // Allow all https requests
  79. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  80. var fileSystem = new ManagedFileSystem(_loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true);
  81. using (var appHost = new CoreAppHost(
  82. appPaths,
  83. _loggerFactory,
  84. options,
  85. fileSystem,
  86. environmentInfo,
  87. new NullImageEncoder(),
  88. new SystemEvents(_loggerFactory.CreateLogger("SystemEvents")),
  89. new NetworkManager(_loggerFactory.CreateLogger("NetworkManager"), environmentInfo)))
  90. {
  91. appHost.Init();
  92. appHost.ImageProcessor.ImageEncoder = getImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager);
  93. _logger.LogInformation("Running startup tasks");
  94. await appHost.RunStartupTasks();
  95. // TODO: read input for a stop command
  96. try
  97. {
  98. // Block main thread until shutdown
  99. await Task.Delay(-1, _tokenSource.Token);
  100. }
  101. catch (TaskCanceledException)
  102. {
  103. // Don't throw on cancellation
  104. }
  105. _logger.LogInformation("Disposing app host");
  106. }
  107. if (_restartOnShutdown)
  108. {
  109. StartNewInstance(options);
  110. }
  111. }
  112. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  113. {
  114. string programDataPath = Environment.GetEnvironmentVariable("JELLYFIN_DATA_PATH");
  115. if (string.IsNullOrEmpty(programDataPath))
  116. {
  117. if (options.ContainsOption("-programdata"))
  118. {
  119. programDataPath = options.GetOption("-programdata");
  120. }
  121. else
  122. {
  123. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  124. {
  125. programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  126. }
  127. else
  128. {
  129. // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
  130. programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
  131. // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
  132. if (string.IsNullOrEmpty(programDataPath))
  133. {
  134. programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
  135. }
  136. }
  137. programDataPath = Path.Combine(programDataPath, "jellyfin");
  138. }
  139. }
  140. if (string.IsNullOrEmpty(programDataPath))
  141. {
  142. Console.WriteLine("Cannot continue without path to program data folder (try -programdata)");
  143. Environment.Exit(1);
  144. }
  145. else
  146. {
  147. Directory.CreateDirectory(programDataPath);
  148. }
  149. string configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  150. if (string.IsNullOrEmpty(configDir))
  151. {
  152. if (options.ContainsOption("-configdir"))
  153. {
  154. configDir = options.GetOption("-configdir");
  155. }
  156. else
  157. {
  158. // Let BaseApplicationPaths set up the default value
  159. configDir = null;
  160. }
  161. }
  162. if (!string.IsNullOrEmpty(configDir))
  163. {
  164. Directory.CreateDirectory(configDir);
  165. }
  166. string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  167. if (string.IsNullOrEmpty(logDir))
  168. {
  169. if (options.ContainsOption("-logdir"))
  170. {
  171. logDir = options.GetOption("-logdir");
  172. }
  173. else
  174. {
  175. // Let BaseApplicationPaths set up the default value
  176. logDir = null;
  177. }
  178. }
  179. if (!string.IsNullOrEmpty(logDir))
  180. {
  181. Directory.CreateDirectory(logDir);
  182. }
  183. string appPath = AppContext.BaseDirectory;
  184. return new ServerApplicationPaths(programDataPath, appPath, appPath, logDir, configDir);
  185. }
  186. private static async Task createLogger(IApplicationPaths appPaths)
  187. {
  188. try
  189. {
  190. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
  191. if (!File.Exists(configPath))
  192. {
  193. // For some reason the csproj name is used instead of the assembly name
  194. using (Stream rscstr = typeof(Program).Assembly
  195. .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
  196. using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
  197. {
  198. await rscstr.CopyToAsync(fstr);
  199. }
  200. }
  201. var configuration = new ConfigurationBuilder()
  202. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  203. .AddJsonFile("logging.json")
  204. .AddEnvironmentVariables("JELLYFIN_")
  205. .Build();
  206. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  207. Serilog.Log.Logger = new LoggerConfiguration()
  208. .ReadFrom.Configuration(configuration)
  209. .Enrich.FromLogContext()
  210. .CreateLogger();
  211. }
  212. catch (Exception ex)
  213. {
  214. Serilog.Log.Logger = new LoggerConfiguration()
  215. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  216. .WriteTo.Async(x => x.File(
  217. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  218. rollingInterval: RollingInterval.Day,
  219. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
  220. .Enrich.FromLogContext()
  221. .CreateLogger();
  222. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  223. }
  224. }
  225. public static IImageEncoder getImageEncoder(
  226. ILogger logger,
  227. IFileSystem fileSystem,
  228. StartupOptions startupOptions,
  229. Func<IHttpClient> httpClient,
  230. IApplicationPaths appPaths,
  231. IEnvironmentInfo environment,
  232. ILocalizationManager localizationManager)
  233. {
  234. try
  235. {
  236. return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager);
  237. }
  238. catch (Exception ex)
  239. {
  240. logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
  241. }
  242. return new NullImageEncoder();
  243. }
  244. private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem() {
  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. }