Program.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 ILogger = Microsoft.Extensions.Logging.ILogger;
  27. using Serilog;
  28. using Serilog.AspNetCore;
  29. namespace MediaBrowser.Server.Mono
  30. {
  31. public class MainClass
  32. {
  33. private static ILogger _logger;
  34. private static IFileSystem FileSystem;
  35. private static IServerApplicationPaths _appPaths;
  36. private static ILoggerFactory _loggerFactory;
  37. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  38. private static bool _restartOnShutdown;
  39. public static void Main(string[] args)
  40. {
  41. var applicationPath = Assembly.GetEntryAssembly().Location;
  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 loggerFactory = new SerilogLoggerFactory(
  49. new LoggerConfiguration()
  50. .Enrich.FromLogContext()
  51. .WriteTo.Console()
  52. .CreateLogger()
  53. , true))
  54. {
  55. _loggerFactory = loggerFactory;
  56. _logger = loggerFactory.CreateLogger("Main");
  57. ApplicationHost.LogEnvironmentInfo(_logger, appPaths, true);
  58. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  59. RunApplication(appPaths, loggerFactory, options);
  60. _logger.LogInformation("Disposing app host");
  61. if (_restartOnShutdown)
  62. {
  63. StartNewInstance(options);
  64. }
  65. }
  66. }
  67. private static void SetSqliteProvider()
  68. {
  69. // SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  70. //SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  71. SQLitePCL.Batteries_V2.Init();
  72. }
  73. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  74. {
  75. if (string.IsNullOrEmpty(programDataPath))
  76. {
  77. if (InteropServices.RuntimeInformation.IsOSPlatform(InteropServices.OSPlatform.Windows))
  78. {
  79. programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  80. }
  81. else
  82. {
  83. // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
  84. programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
  85. // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
  86. if (string.IsNullOrEmpty(programDataPath)){
  87. programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
  88. }
  89. }
  90. programDataPath = Path.Combine(programDataPath, "jellyfin");
  91. }
  92. var appFolderPath = Path.GetDirectoryName(applicationPath);
  93. return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath);
  94. }
  95. private static void RunApplication(ServerApplicationPaths appPaths, ILoggerFactory loggerFactory, StartupOptions options)
  96. {
  97. // Allow all https requests
  98. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  99. var environmentInfo = GetEnvironmentInfo();
  100. var fileSystem = new ManagedFileSystem(loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true);
  101. FileSystem = fileSystem;
  102. using (var appHost = new MonoAppHost(appPaths,
  103. loggerFactory,
  104. options,
  105. fileSystem,
  106. new PowerManagement(),
  107. "embyserver-mono_{version}.zip",
  108. environmentInfo,
  109. new NullImageEncoder(),
  110. new SystemEvents(loggerFactory.CreateLogger("SystemEvents")),
  111. new NetworkManager(loggerFactory.CreateLogger("NetworkManager"), environmentInfo)))
  112. {
  113. if (options.ContainsOption("-v"))
  114. {
  115. Console.WriteLine(appHost.ApplicationVersion.ToString());
  116. return;
  117. }
  118. Console.WriteLine("appHost.Init");
  119. appHost.Init();
  120. appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager);
  121. Console.WriteLine("Running startup tasks");
  122. var task = appHost.RunStartupTasks();
  123. Task.WaitAll(task);
  124. task = ApplicationTaskCompletionSource.Task;
  125. Task.WaitAll(task);
  126. }
  127. }
  128. private static MonoEnvironmentInfo GetEnvironmentInfo()
  129. {
  130. var info = new MonoEnvironmentInfo();
  131. var uname = GetUnixName();
  132. var sysName = uname.sysname ?? string.Empty;
  133. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  134. {
  135. info.OperatingSystem = Model.System.OperatingSystem.OSX;
  136. }
  137. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  138. {
  139. info.OperatingSystem = Model.System.OperatingSystem.Linux;
  140. }
  141. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  142. {
  143. info.OperatingSystem = Model.System.OperatingSystem.BSD;
  144. }
  145. var archX86 = new Regex("(i|I)[3-6]86");
  146. if (archX86.IsMatch(uname.machine))
  147. {
  148. info.SystemArchitecture = Architecture.X86;
  149. }
  150. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  151. {
  152. info.SystemArchitecture = Architecture.X64;
  153. }
  154. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  155. {
  156. info.SystemArchitecture = Architecture.Arm;
  157. }
  158. else if (System.Environment.Is64BitOperatingSystem)
  159. {
  160. info.SystemArchitecture = Architecture.X64;
  161. }
  162. else
  163. {
  164. info.SystemArchitecture = Architecture.X86;
  165. }
  166. return info;
  167. }
  168. private static Uname _unixName;
  169. private static Uname GetUnixName()
  170. {
  171. if (_unixName == null)
  172. {
  173. var uname = new Uname();
  174. try
  175. {
  176. Utsname utsname;
  177. var callResult = Syscall.uname(out utsname);
  178. if (callResult == 0)
  179. {
  180. uname.sysname = utsname.sysname ?? string.Empty;
  181. uname.machine = utsname.machine ?? string.Empty;
  182. }
  183. }
  184. catch (Exception ex)
  185. {
  186. _logger.LogError("Error getting unix name", ex);
  187. }
  188. _unixName = uname;
  189. }
  190. return _unixName;
  191. }
  192. public class Uname
  193. {
  194. public string sysname = string.Empty;
  195. public string machine = string.Empty;
  196. }
  197. /// <summary>
  198. /// Handles the UnhandledException event of the CurrentDomain control.
  199. /// </summary>
  200. /// <param name="sender">The source of the event.</param>
  201. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  202. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  203. {
  204. var exception = (Exception)e.ExceptionObject;
  205. // TODO
  206. /*
  207. new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception);
  208. if (!Debugger.IsAttached)
  209. {
  210. var message = LogHelper.GetLogMessage(exception).ToString();
  211. if (message.IndexOf("InotifyWatcher", StringComparison.OrdinalIgnoreCase) == -1 &&
  212. message.IndexOf("_IOCompletionCallback", StringComparison.OrdinalIgnoreCase) == -1)
  213. {
  214. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  215. }
  216. }*/
  217. }
  218. public static void Shutdown()
  219. {
  220. ApplicationTaskCompletionSource.SetResult(true);
  221. }
  222. public static void Restart()
  223. {
  224. _restartOnShutdown = true;
  225. Shutdown();
  226. }
  227. private static void StartNewInstance(StartupOptions startupOptions)
  228. {
  229. _logger.LogInformation("Starting new instance");
  230. string module = startupOptions.GetOption("-restartpath");
  231. string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  232. if (string.IsNullOrWhiteSpace(module))
  233. {
  234. module = Environment.GetCommandLineArgs().First();
  235. }
  236. if (!startupOptions.ContainsOption("-restartargs"))
  237. {
  238. var args = Environment.GetCommandLineArgs()
  239. .Skip(1)
  240. .Select(NormalizeCommandLineArgument)
  241. .ToArray();
  242. commandLineArgsString = string.Join(" ", args);
  243. }
  244. _logger.LogInformation("Executable: {0}", module);
  245. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  246. Process.Start(module, commandLineArgsString);
  247. }
  248. private static string NormalizeCommandLineArgument(string arg)
  249. {
  250. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  251. {
  252. return arg;
  253. }
  254. return "\"" + arg + "\"";
  255. }
  256. }
  257. // class NoCheckCertificatePolicy : ICertificatePolicy
  258. // {
  259. // public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  260. // {
  261. // return true;
  262. // }
  263. // }
  264. public class MonoEnvironmentInfo : EnvironmentInfo
  265. {
  266. //public override string GetUserId()
  267. //{
  268. // return Syscall.getuid().ToString(CultureInfo.InvariantCulture);
  269. //}
  270. }
  271. }