Program.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. using MediaBrowser.Model.Logging;
  2. using MediaBrowser.Server.Mono.Native;
  3. using MediaBrowser.Server.Startup.Common;
  4. using System;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Security;
  11. using System.Reflection;
  12. using System.Text.RegularExpressions;
  13. using System.Threading.Tasks;
  14. using Emby.Drawing;
  15. using Emby.Server.Core.Cryptography;
  16. using Emby.Server.Core;
  17. using Emby.Server.Implementations;
  18. using Emby.Server.Implementations.EnvironmentInfo;
  19. using Emby.Server.Implementations.IO;
  20. using Emby.Server.Implementations.Logging;
  21. using Emby.Server.Implementations.Networking;
  22. using MediaBrowser.Controller;
  23. using MediaBrowser.Model.IO;
  24. using MediaBrowser.Model.System;
  25. using Mono.Unix.Native;
  26. using ILogger = MediaBrowser.Model.Logging.ILogger;
  27. using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate;
  28. namespace MediaBrowser.Server.Mono
  29. {
  30. public class MainClass
  31. {
  32. private static ILogger _logger;
  33. private static IFileSystem FileSystem;
  34. private static IServerApplicationPaths _appPaths;
  35. private static ILogManager _logManager;
  36. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  37. private static bool _restartOnShutdown;
  38. public static void Main(string[] args)
  39. {
  40. var applicationPath = Assembly.GetEntryAssembly().Location;
  41. var appFolderPath = Path.GetDirectoryName(applicationPath);
  42. SetSqliteProvider();
  43. var options = new StartupOptions(Environment.GetCommandLineArgs());
  44. // Allow this to be specified on the command line.
  45. var customProgramDataPath = options.GetOption("-programdata");
  46. var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);
  47. _appPaths = appPaths;
  48. using (var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "server"))
  49. {
  50. _logManager = logManager;
  51. logManager.ReloadLogger(LogSeverity.Info);
  52. logManager.AddConsoleOutput();
  53. var logger = _logger = logManager.GetLogger("Main");
  54. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  55. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  56. try
  57. {
  58. RunApplication(appPaths, logManager, options);
  59. }
  60. finally
  61. {
  62. _logger.Info("Disposing app host");
  63. if (_restartOnShutdown)
  64. {
  65. StartNewInstance(options);
  66. }
  67. }
  68. }
  69. }
  70. private static void SetSqliteProvider()
  71. {
  72. SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  73. }
  74. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  75. {
  76. if (string.IsNullOrEmpty(programDataPath))
  77. {
  78. programDataPath = ApplicationPathHelper.GetProgramDataPath(applicationPath);
  79. }
  80. var appFolderPath = Path.GetDirectoryName(applicationPath);
  81. return new ServerApplicationPaths(programDataPath, appFolderPath, Path.GetDirectoryName(applicationPath));
  82. }
  83. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options)
  84. {
  85. // Allow all https requests
  86. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  87. var environmentInfo = GetEnvironmentInfo();
  88. var fileSystem = new MonoFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, appPaths.TempDirectory);
  89. FileSystem = fileSystem;
  90. using (var appHost = new MonoAppHost(appPaths,
  91. logManager,
  92. options,
  93. fileSystem,
  94. new PowerManagement(),
  95. "emby.mono.zip",
  96. environmentInfo,
  97. new NullImageEncoder(),
  98. new SystemEvents(logManager.GetLogger("SystemEvents")),
  99. new NetworkManager(logManager.GetLogger("NetworkManager"))))
  100. {
  101. appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo);
  102. if (options.ContainsOption("-v"))
  103. {
  104. Console.WriteLine(appHost.ApplicationVersion.ToString());
  105. return;
  106. }
  107. Console.WriteLine("appHost.Init");
  108. var initProgress = new Progress<double>();
  109. var task = appHost.Init(initProgress);
  110. Task.WaitAll(task);
  111. Console.WriteLine("Running startup tasks");
  112. task = appHost.RunStartupTasks();
  113. Task.WaitAll(task);
  114. task = ApplicationTaskCompletionSource.Task;
  115. Task.WaitAll(task);
  116. }
  117. }
  118. private static MonoEnvironmentInfo GetEnvironmentInfo()
  119. {
  120. var info = new MonoEnvironmentInfo();
  121. var uname = GetUnixName();
  122. var sysName = uname.sysname ?? string.Empty;
  123. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  124. {
  125. info.OperatingSystem = Model.System.OperatingSystem.OSX;
  126. }
  127. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  128. {
  129. info.OperatingSystem = Model.System.OperatingSystem.Linux;
  130. }
  131. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  132. {
  133. info.OperatingSystem = Model.System.OperatingSystem.BSD;
  134. }
  135. var archX86 = new Regex("(i|I)[3-6]86");
  136. if (archX86.IsMatch(uname.machine))
  137. {
  138. info.SystemArchitecture = Architecture.X86;
  139. }
  140. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  141. {
  142. info.SystemArchitecture = Architecture.X64;
  143. }
  144. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  145. {
  146. info.SystemArchitecture = Architecture.Arm;
  147. }
  148. else if (System.Environment.Is64BitOperatingSystem)
  149. {
  150. info.SystemArchitecture = Architecture.X64;
  151. }
  152. else
  153. {
  154. info.SystemArchitecture = Architecture.X86;
  155. }
  156. return info;
  157. }
  158. private static Uname _unixName;
  159. private static Uname GetUnixName()
  160. {
  161. if (_unixName == null)
  162. {
  163. var uname = new Uname();
  164. try
  165. {
  166. Utsname utsname;
  167. var callResult = Syscall.uname(out utsname);
  168. if (callResult == 0)
  169. {
  170. uname.sysname = utsname.sysname ?? string.Empty;
  171. uname.machine = utsname.machine ?? string.Empty;
  172. }
  173. }
  174. catch (Exception ex)
  175. {
  176. _logger.ErrorException("Error getting unix name", ex);
  177. }
  178. _unixName = uname;
  179. }
  180. return _unixName;
  181. }
  182. public class Uname
  183. {
  184. public string sysname = string.Empty;
  185. public string machine = string.Empty;
  186. }
  187. /// <summary>
  188. /// Handles the UnhandledException event of the CurrentDomain control.
  189. /// </summary>
  190. /// <param name="sender">The source of the event.</param>
  191. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  192. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  193. {
  194. var exception = (Exception)e.ExceptionObject;
  195. new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception);
  196. if (!Debugger.IsAttached)
  197. {
  198. var message = LogHelper.GetLogMessage(exception).ToString();
  199. if (message.IndexOf("InotifyWatcher", StringComparison.OrdinalIgnoreCase) == -1 &&
  200. message.IndexOf("_IOCompletionCallback", StringComparison.OrdinalIgnoreCase) == -1)
  201. {
  202. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  203. }
  204. }
  205. }
  206. public static void Shutdown()
  207. {
  208. ApplicationTaskCompletionSource.SetResult(true);
  209. }
  210. public static void Restart()
  211. {
  212. _restartOnShutdown = true;
  213. Shutdown();
  214. }
  215. private static void StartNewInstance(StartupOptions startupOptions)
  216. {
  217. _logger.Info("Starting new instance");
  218. string module = startupOptions.GetOption("-restartpath");
  219. string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  220. if (string.IsNullOrWhiteSpace(module))
  221. {
  222. module = Environment.GetCommandLineArgs().First();
  223. }
  224. if (!startupOptions.ContainsOption("-restartargs"))
  225. {
  226. var args = Environment.GetCommandLineArgs()
  227. .Skip(1)
  228. .Select(NormalizeCommandLineArgument)
  229. .ToArray();
  230. commandLineArgsString = string.Join(" ", args);
  231. }
  232. _logger.Info("Executable: {0}", module);
  233. _logger.Info("Arguments: {0}", commandLineArgsString);
  234. Process.Start(module, commandLineArgsString);
  235. }
  236. private static string NormalizeCommandLineArgument(string arg)
  237. {
  238. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  239. {
  240. return arg;
  241. }
  242. return "\"" + arg + "\"";
  243. }
  244. }
  245. class NoCheckCertificatePolicy : ICertificatePolicy
  246. {
  247. public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  248. {
  249. return true;
  250. }
  251. }
  252. public class MonoEnvironmentInfo : EnvironmentInfo
  253. {
  254. public override string GetUserId()
  255. {
  256. return Syscall.getuid().ToString(CultureInfo.InvariantCulture);
  257. }
  258. }
  259. }