Program.cs 12 KB

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