Program.cs 12 KB

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