Program.cs 13 KB

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