Program.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 NetworkManager(_loggerFactory, environmentInfo)))
  86. {
  87. await appHost.Init();
  88. appHost.ImageProcessor.ImageEncoder = GetImageEncoder(fileSystem, appPaths, appHost.LocalizationManager);
  89. _logger.LogInformation("Running startup tasks");
  90. await appHost.RunStartupTasks();
  91. // TODO: read input for a stop command
  92. try
  93. {
  94. // Block main thread until shutdown
  95. await Task.Delay(-1, _tokenSource.Token);
  96. }
  97. catch (TaskCanceledException)
  98. {
  99. // Don't throw on cancellation
  100. }
  101. _logger.LogInformation("Disposing app host");
  102. }
  103. if (_restartOnShutdown)
  104. {
  105. StartNewInstance(options);
  106. }
  107. }
  108. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  109. {
  110. string programDataPath = Environment.GetEnvironmentVariable("JELLYFIN_DATA_PATH");
  111. if (string.IsNullOrEmpty(programDataPath))
  112. {
  113. if (options.ContainsOption("-programdata"))
  114. {
  115. programDataPath = options.GetOption("-programdata");
  116. }
  117. else
  118. {
  119. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  120. {
  121. programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  122. }
  123. else
  124. {
  125. // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
  126. programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
  127. // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
  128. if (string.IsNullOrEmpty(programDataPath))
  129. {
  130. programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
  131. }
  132. }
  133. programDataPath = Path.Combine(programDataPath, "jellyfin");
  134. }
  135. }
  136. if (string.IsNullOrEmpty(programDataPath))
  137. {
  138. Console.WriteLine("Cannot continue without path to program data folder (try -programdata)");
  139. Environment.Exit(1);
  140. }
  141. else
  142. {
  143. Directory.CreateDirectory(programDataPath);
  144. }
  145. string configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  146. if (string.IsNullOrEmpty(configDir))
  147. {
  148. if (options.ContainsOption("-configdir"))
  149. {
  150. configDir = options.GetOption("-configdir");
  151. }
  152. else
  153. {
  154. // Let BaseApplicationPaths set up the default value
  155. configDir = null;
  156. }
  157. }
  158. if (configDir != null)
  159. {
  160. Directory.CreateDirectory(configDir);
  161. }
  162. string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  163. if (string.IsNullOrEmpty(logDir))
  164. {
  165. if (options.ContainsOption("-logdir"))
  166. {
  167. logDir = options.GetOption("-logdir");
  168. }
  169. else
  170. {
  171. // Let BaseApplicationPaths set up the default value
  172. logDir = null;
  173. }
  174. }
  175. if (logDir != null)
  176. {
  177. Directory.CreateDirectory(logDir);
  178. }
  179. string appPath = AppContext.BaseDirectory;
  180. return new ServerApplicationPaths(programDataPath, appPath, appPath, logDir, configDir);
  181. }
  182. private static async Task createLogger(IApplicationPaths appPaths)
  183. {
  184. try
  185. {
  186. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
  187. if (!File.Exists(configPath))
  188. {
  189. // For some reason the csproj name is used instead of the assembly name
  190. using (Stream rscstr = typeof(Program).Assembly
  191. .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
  192. using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
  193. {
  194. await rscstr.CopyToAsync(fstr).ConfigureAwait(false);
  195. }
  196. }
  197. var configuration = new ConfigurationBuilder()
  198. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  199. .AddJsonFile("logging.json")
  200. .AddEnvironmentVariables("JELLYFIN_")
  201. .Build();
  202. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  203. Serilog.Log.Logger = new LoggerConfiguration()
  204. .ReadFrom.Configuration(configuration)
  205. .Enrich.FromLogContext()
  206. .CreateLogger();
  207. }
  208. catch (Exception ex)
  209. {
  210. Serilog.Log.Logger = new LoggerConfiguration()
  211. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  212. .WriteTo.Async(x => x.File(
  213. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  214. rollingInterval: RollingInterval.Day,
  215. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
  216. .Enrich.FromLogContext()
  217. .CreateLogger();
  218. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  219. }
  220. }
  221. public static IImageEncoder GetImageEncoder(
  222. IFileSystem fileSystem,
  223. IApplicationPaths appPaths,
  224. ILocalizationManager localizationManager)
  225. {
  226. try
  227. {
  228. return new SkiaEncoder(_loggerFactory, appPaths, fileSystem, localizationManager);
  229. }
  230. catch (Exception ex)
  231. {
  232. _logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
  233. }
  234. return new NullImageEncoder();
  235. }
  236. private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem()
  237. {
  238. switch (Environment.OSVersion.Platform)
  239. {
  240. case PlatformID.MacOSX:
  241. return MediaBrowser.Model.System.OperatingSystem.OSX;
  242. case PlatformID.Win32NT:
  243. return MediaBrowser.Model.System.OperatingSystem.Windows;
  244. case PlatformID.Unix:
  245. default:
  246. {
  247. string osDescription = RuntimeInformation.OSDescription;
  248. if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
  249. {
  250. return MediaBrowser.Model.System.OperatingSystem.Linux;
  251. }
  252. else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
  253. {
  254. return MediaBrowser.Model.System.OperatingSystem.OSX;
  255. }
  256. else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
  257. {
  258. return MediaBrowser.Model.System.OperatingSystem.BSD;
  259. }
  260. throw new Exception($"Can't resolve OS with description: '{osDescription}'");
  261. }
  262. }
  263. }
  264. public static void Shutdown()
  265. {
  266. if (!_tokenSource.IsCancellationRequested)
  267. {
  268. _tokenSource.Cancel();
  269. }
  270. }
  271. public static void Restart()
  272. {
  273. _restartOnShutdown = true;
  274. Shutdown();
  275. }
  276. private static void StartNewInstance(StartupOptions startupOptions)
  277. {
  278. _logger.LogInformation("Starting new instance");
  279. string module = startupOptions.GetOption("-restartpath");
  280. if (string.IsNullOrWhiteSpace(module))
  281. {
  282. module = Environment.GetCommandLineArgs().First();
  283. }
  284. string commandLineArgsString;
  285. if (startupOptions.ContainsOption("-restartargs"))
  286. {
  287. commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  288. }
  289. else
  290. {
  291. commandLineArgsString = string.Join(
  292. " ",
  293. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  294. }
  295. _logger.LogInformation("Executable: {0}", module);
  296. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  297. Process.Start(module, commandLineArgsString);
  298. }
  299. private static string NormalizeCommandLineArgument(string arg)
  300. {
  301. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  302. {
  303. return arg;
  304. }
  305. return "\"" + arg + "\"";
  306. }
  307. }
  308. }