Program.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. // Ensure the dir exists
  139. Directory.CreateDirectory(programDataPath);
  140. }
  141. }
  142. string configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  143. if (string.IsNullOrEmpty(configDir))
  144. {
  145. if (options.ContainsOption("-configdir"))
  146. {
  147. configDir = options.GetOption("-configdir");
  148. }
  149. else
  150. {
  151. // Let BaseApplicationPaths set up the default value
  152. configDir = null;
  153. }
  154. }
  155. string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  156. if (string.IsNullOrEmpty(logDir))
  157. {
  158. if (options.ContainsOption("-logdir"))
  159. {
  160. logDir = options.GetOption("-logdir");
  161. }
  162. else
  163. {
  164. // Let BaseApplicationPaths set up the default value
  165. logDir = null;
  166. }
  167. }
  168. string appPath = AppContext.BaseDirectory;
  169. return new ServerApplicationPaths(programDataPath, appPath, appPath, logDir, configDir);
  170. }
  171. private static async Task createLogger(IApplicationPaths appPaths)
  172. {
  173. try
  174. {
  175. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
  176. if (!File.Exists(configPath))
  177. {
  178. // For some reason the csproj name is used instead of the assembly name
  179. using (Stream rscstr = typeof(Program).Assembly
  180. .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
  181. using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
  182. {
  183. await rscstr.CopyToAsync(fstr);
  184. }
  185. }
  186. var configuration = new ConfigurationBuilder()
  187. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  188. .AddJsonFile("logging.json")
  189. .AddEnvironmentVariables("JELLYFIN_")
  190. .Build();
  191. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  192. Serilog.Log.Logger = new LoggerConfiguration()
  193. .ReadFrom.Configuration(configuration)
  194. .Enrich.FromLogContext()
  195. .CreateLogger();
  196. }
  197. catch (Exception ex)
  198. {
  199. Serilog.Log.Logger = new LoggerConfiguration()
  200. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  201. .WriteTo.Async(x => x.File(
  202. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  203. rollingInterval: RollingInterval.Day,
  204. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
  205. .Enrich.FromLogContext()
  206. .CreateLogger();
  207. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  208. }
  209. }
  210. public static IImageEncoder getImageEncoder(
  211. ILogger logger,
  212. IFileSystem fileSystem,
  213. StartupOptions startupOptions,
  214. Func<IHttpClient> httpClient,
  215. IApplicationPaths appPaths,
  216. IEnvironmentInfo environment,
  217. ILocalizationManager localizationManager)
  218. {
  219. try
  220. {
  221. return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager);
  222. }
  223. catch (Exception ex)
  224. {
  225. logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
  226. }
  227. return new NullImageEncoder();
  228. }
  229. private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem() {
  230. switch (Environment.OSVersion.Platform)
  231. {
  232. case PlatformID.MacOSX:
  233. return MediaBrowser.Model.System.OperatingSystem.OSX;
  234. case PlatformID.Win32NT:
  235. return MediaBrowser.Model.System.OperatingSystem.Windows;
  236. case PlatformID.Unix:
  237. default:
  238. {
  239. string osDescription = RuntimeInformation.OSDescription;
  240. if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
  241. {
  242. return MediaBrowser.Model.System.OperatingSystem.Linux;
  243. }
  244. else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
  245. {
  246. return MediaBrowser.Model.System.OperatingSystem.OSX;
  247. }
  248. else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
  249. {
  250. return MediaBrowser.Model.System.OperatingSystem.BSD;
  251. }
  252. throw new Exception($"Can't resolve OS with description: '{osDescription}'");
  253. }
  254. }
  255. }
  256. public static void Shutdown()
  257. {
  258. if (!_tokenSource.IsCancellationRequested)
  259. {
  260. _tokenSource.Cancel();
  261. }
  262. }
  263. public static void Restart()
  264. {
  265. _restartOnShutdown = true;
  266. Shutdown();
  267. }
  268. private static void StartNewInstance(StartupOptions startupOptions)
  269. {
  270. _logger.LogInformation("Starting new instance");
  271. string module = startupOptions.GetOption("-restartpath");
  272. if (string.IsNullOrWhiteSpace(module))
  273. {
  274. module = Environment.GetCommandLineArgs().First();
  275. }
  276. string commandLineArgsString;
  277. if (startupOptions.ContainsOption("-restartargs"))
  278. {
  279. commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  280. }
  281. else
  282. {
  283. commandLineArgsString = string .Join(" ",
  284. Environment.GetCommandLineArgs()
  285. .Skip(1)
  286. .Select(NormalizeCommandLineArgument)
  287. );
  288. }
  289. _logger.LogInformation("Executable: {0}", module);
  290. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  291. Process.Start(module, commandLineArgsString);
  292. }
  293. private static string NormalizeCommandLineArgument(string arg)
  294. {
  295. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  296. {
  297. return arg;
  298. }
  299. return "\"" + arg + "\"";
  300. }
  301. }
  302. }