Program.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. using MediaBrowser.Server.Mono.Native;
  2. using MediaBrowser.Server.Startup.Common;
  3. using System;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Security;
  10. using System.Reflection;
  11. using System.Text.RegularExpressions;
  12. using System.Threading.Tasks;
  13. using Emby.Drawing;
  14. using Emby.Server.Implementations;
  15. using Emby.Server.Implementations.EnvironmentInfo;
  16. using Emby.Server.Implementations.IO;
  17. using Emby.Server.Implementations.Networking;
  18. using MediaBrowser.Controller;
  19. using MediaBrowser.Model.IO;
  20. using MediaBrowser.Model.System;
  21. using Mono.Unix.Native;
  22. using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate;
  23. using System.Threading;
  24. using InteropServices = System.Runtime.InteropServices;
  25. using Microsoft.Extensions.Logging;
  26. using Microsoft.Extensions.Configuration;
  27. using ILogger = Microsoft.Extensions.Logging.ILogger;
  28. using Serilog;
  29. using Serilog.AspNetCore;
  30. namespace MediaBrowser.Server.Mono
  31. {
  32. public class MainClass
  33. {
  34. private static ILogger _logger;
  35. private static IFileSystem FileSystem;
  36. private static IServerApplicationPaths _appPaths;
  37. private static ILoggerFactory _loggerFactory;
  38. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  39. private static bool _restartOnShutdown;
  40. public static void Main(string[] args)
  41. {
  42. var applicationPath = Assembly.GetEntryAssembly().Location;
  43. SetSqliteProvider();
  44. var options = new StartupOptions(Environment.GetCommandLineArgs());
  45. // Allow this to be specified on the command line.
  46. var customProgramDataPath = options.GetOption("-programdata");
  47. var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);
  48. _appPaths = appPaths;
  49. createLogger();
  50. using (var loggerFactory = new SerilogLoggerFactory())
  51. {
  52. _loggerFactory = loggerFactory;
  53. _logger = loggerFactory.CreateLogger("Main");
  54. ApplicationHost.LogEnvironmentInfo(_logger, appPaths, true);
  55. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  56. RunApplication(appPaths, loggerFactory, options);
  57. _logger.LogInformation("Disposing app host");
  58. if (_restartOnShutdown)
  59. {
  60. StartNewInstance(options);
  61. }
  62. }
  63. }
  64. private static void SetSqliteProvider()
  65. {
  66. // SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  67. //SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  68. SQLitePCL.Batteries_V2.Init();
  69. }
  70. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  71. {
  72. if (string.IsNullOrEmpty(programDataPath))
  73. {
  74. if (InteropServices.RuntimeInformation.IsOSPlatform(InteropServices.OSPlatform.Windows))
  75. {
  76. programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  77. }
  78. else
  79. {
  80. // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
  81. programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
  82. // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
  83. if (string.IsNullOrEmpty(programDataPath)){
  84. programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
  85. }
  86. }
  87. programDataPath = Path.Combine(programDataPath, "jellyfin");
  88. }
  89. var appFolderPath = Path.GetDirectoryName(applicationPath);
  90. return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath);
  91. }
  92. private static void RunApplication(ServerApplicationPaths appPaths, ILoggerFactory loggerFactory, StartupOptions options)
  93. {
  94. // Allow all https requests
  95. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  96. var environmentInfo = GetEnvironmentInfo();
  97. var fileSystem = new ManagedFileSystem(loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true);
  98. FileSystem = fileSystem;
  99. using (var appHost = new MonoAppHost(appPaths,
  100. loggerFactory,
  101. options,
  102. fileSystem,
  103. new PowerManagement(),
  104. "embyserver-mono_{version}.zip",
  105. environmentInfo,
  106. new NullImageEncoder(),
  107. new SystemEvents(loggerFactory.CreateLogger("SystemEvents")),
  108. new NetworkManager(loggerFactory.CreateLogger("NetworkManager"), environmentInfo)))
  109. {
  110. if (options.ContainsOption("-v"))
  111. {
  112. Console.WriteLine(appHost.ApplicationVersion.ToString());
  113. return;
  114. }
  115. //Console.WriteLine("appHost.Init");
  116. appHost.Init();
  117. appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager);
  118. //Console.WriteLine("Running startup tasks");
  119. _logger.LogInformation("Running startup tasks");
  120. var task = appHost.RunStartupTasks();
  121. Task.WaitAll(task);
  122. task = ApplicationTaskCompletionSource.Task;
  123. Task.WaitAll(task);
  124. }
  125. }
  126. private static void createLogger()
  127. {
  128. var logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  129. if (string.IsNullOrEmpty(logDir)){
  130. logDir = Path.Combine(_appPaths.ProgramDataPath, "logs");
  131. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir);
  132. }
  133. try
  134. {
  135. string path = Path.Combine(_appPaths.ConfigurationDirectoryPath, "logging.json");
  136. if (!File.Exists(path))
  137. {
  138. var assembly = typeof(MainClass).Assembly;
  139. // For some reason the csproj name is used instead of the assembly name
  140. var resourcePath = "EmbyServer.Resources.Configuration.logging.json";
  141. using (Stream rscstr = assembly.GetManifestResourceStream(resourcePath))
  142. using (Stream fstr = File.Open(path, FileMode.CreateNew))
  143. {
  144. rscstr.CopyTo(fstr);
  145. }
  146. }
  147. var configuration = new ConfigurationBuilder()
  148. .SetBasePath(_appPaths.ConfigurationDirectoryPath)
  149. .AddJsonFile("logging.json")
  150. .AddEnvironmentVariables("JELLYFIN_")
  151. .Build();
  152. Serilog.Log.Logger = new LoggerConfiguration()
  153. .ReadFrom.Configuration(configuration)
  154. .Enrich.FromLogContext()
  155. .CreateLogger();
  156. }
  157. catch (Exception ex)
  158. {
  159. Serilog.Log.Logger = new LoggerConfiguration()
  160. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  161. .WriteTo.File(
  162. Path.Combine(logDir, "log_.log"),
  163. rollingInterval: RollingInterval.Day,
  164. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}")
  165. .Enrich.FromLogContext()
  166. .CreateLogger();
  167. Serilog.Log.Logger.Fatal(ex, "Failed to read logger config");
  168. }
  169. }
  170. private static MonoEnvironmentInfo GetEnvironmentInfo()
  171. {
  172. var info = new MonoEnvironmentInfo();
  173. var uname = GetUnixName();
  174. var sysName = uname.sysname ?? string.Empty;
  175. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  176. {
  177. info.OperatingSystem = Model.System.OperatingSystem.OSX;
  178. }
  179. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  180. {
  181. info.OperatingSystem = Model.System.OperatingSystem.Linux;
  182. }
  183. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  184. {
  185. info.OperatingSystem = Model.System.OperatingSystem.BSD;
  186. }
  187. var archX86 = new Regex("(i|I)[3-6]86");
  188. if (archX86.IsMatch(uname.machine))
  189. {
  190. info.SystemArchitecture = Architecture.X86;
  191. }
  192. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  193. {
  194. info.SystemArchitecture = Architecture.X64;
  195. }
  196. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  197. {
  198. info.SystemArchitecture = Architecture.Arm;
  199. }
  200. else if (System.Environment.Is64BitOperatingSystem)
  201. {
  202. info.SystemArchitecture = Architecture.X64;
  203. }
  204. else
  205. {
  206. info.SystemArchitecture = Architecture.X86;
  207. }
  208. return info;
  209. }
  210. private static Uname _unixName;
  211. private static Uname GetUnixName()
  212. {
  213. if (_unixName == null)
  214. {
  215. var uname = new Uname();
  216. try
  217. {
  218. Utsname utsname;
  219. var callResult = Syscall.uname(out utsname);
  220. if (callResult == 0)
  221. {
  222. uname.sysname = utsname.sysname ?? string.Empty;
  223. uname.machine = utsname.machine ?? string.Empty;
  224. }
  225. }
  226. catch (Exception ex)
  227. {
  228. _logger.LogError(ex, "Error getting unix name");
  229. }
  230. _unixName = uname;
  231. }
  232. return _unixName;
  233. }
  234. public class Uname
  235. {
  236. public string sysname = string.Empty;
  237. public string machine = string.Empty;
  238. }
  239. /// <summary>
  240. /// Handles the UnhandledException event of the CurrentDomain control.
  241. /// </summary>
  242. /// <param name="sender">The source of the event.</param>
  243. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  244. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  245. {
  246. var exception = (Exception)e.ExceptionObject;
  247. //new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception);
  248. _logger.LogCritical(exception, "Unhandled Exception");
  249. // TODO: @bond
  250. /*
  251. if (!Debugger.IsAttached)
  252. {
  253. var message = LogHelper.GetLogMessage(exception).ToString();
  254. if (message.IndexOf("InotifyWatcher", StringComparison.OrdinalIgnoreCase) == -1 &&
  255. message.IndexOf("_IOCompletionCallback", StringComparison.OrdinalIgnoreCase) == -1)
  256. {
  257. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  258. }
  259. }
  260. */
  261. }
  262. public static void Shutdown()
  263. {
  264. ApplicationTaskCompletionSource.SetResult(true);
  265. }
  266. public static void Restart()
  267. {
  268. _restartOnShutdown = true;
  269. Shutdown();
  270. }
  271. private static void StartNewInstance(StartupOptions startupOptions)
  272. {
  273. _logger.LogInformation("Starting new instance");
  274. string module = startupOptions.GetOption("-restartpath");
  275. string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  276. if (string.IsNullOrWhiteSpace(module))
  277. {
  278. module = Environment.GetCommandLineArgs().First();
  279. }
  280. if (!startupOptions.ContainsOption("-restartargs"))
  281. {
  282. var args = Environment.GetCommandLineArgs()
  283. .Skip(1)
  284. .Select(NormalizeCommandLineArgument)
  285. .ToArray();
  286. commandLineArgsString = string.Join(" ", args);
  287. }
  288. _logger.LogInformation("Executable: {0}", module);
  289. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  290. Process.Start(module, commandLineArgsString);
  291. }
  292. private static string NormalizeCommandLineArgument(string arg)
  293. {
  294. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  295. {
  296. return arg;
  297. }
  298. return "\"" + arg + "\"";
  299. }
  300. }
  301. // class NoCheckCertificatePolicy : ICertificatePolicy
  302. // {
  303. // public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  304. // {
  305. // return true;
  306. // }
  307. // }
  308. public class MonoEnvironmentInfo : EnvironmentInfo
  309. {
  310. //public override string GetUserId()
  311. //{
  312. // return Syscall.getuid().ToString(CultureInfo.InvariantCulture);
  313. //}
  314. }
  315. }