Program.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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.Implementations;
  16. using Emby.Server.Implementations.EnvironmentInfo;
  17. using Emby.Server.Implementations.IO;
  18. using Emby.Server.Implementations.Logging;
  19. using Emby.Server.Implementations.Networking;
  20. using MediaBrowser.Controller;
  21. using MediaBrowser.Model.IO;
  22. using MediaBrowser.Model.System;
  23. using Mono.Unix.Native;
  24. using ILogger = MediaBrowser.Model.Logging.ILogger;
  25. using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate;
  26. using System.Threading;
  27. using InteropServices = System.Runtime.InteropServices;
  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. SetSqliteProvider();
  42. var options = new StartupOptions(Environment.GetCommandLineArgs());
  43. // Allow this to be specified on the command line.
  44. var customProgramDataPath = options.GetOption("-programdata");
  45. var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);
  46. _appPaths = appPaths;
  47. using (var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "server"))
  48. {
  49. _logManager = logManager;
  50. var task = logManager.ReloadLogger(LogSeverity.Debug, CancellationToken.None);
  51. Task.WaitAll(task);
  52. logManager.AddConsoleOutput();
  53. var logger = _logger = logManager.GetLogger("Main");
  54. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  55. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  56. RunApplication(appPaths, logManager, options);
  57. _logger.Info("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. }
  88. programDataPath = Path.Combine(programDataPath, "jellyfin");
  89. var appFolderPath = Path.GetDirectoryName(applicationPath);
  90. return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath);
  91. }
  92. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, 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(logManager.GetLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true);
  98. FileSystem = fileSystem;
  99. using (var appHost = new MonoAppHost(appPaths,
  100. logManager,
  101. options,
  102. fileSystem,
  103. new PowerManagement(),
  104. "embyserver-mono_{version}.zip",
  105. environmentInfo,
  106. new NullImageEncoder(),
  107. new SystemEvents(logManager.GetLogger("SystemEvents")),
  108. new NetworkManager(logManager.GetLogger("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, logManager, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager);
  118. Console.WriteLine("Running startup tasks");
  119. var task = appHost.RunStartupTasks();
  120. Task.WaitAll(task);
  121. task = ApplicationTaskCompletionSource.Task;
  122. Task.WaitAll(task);
  123. }
  124. }
  125. private static MonoEnvironmentInfo GetEnvironmentInfo()
  126. {
  127. var info = new MonoEnvironmentInfo();
  128. var uname = GetUnixName();
  129. var sysName = uname.sysname ?? string.Empty;
  130. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  131. {
  132. info.OperatingSystem = Model.System.OperatingSystem.OSX;
  133. }
  134. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  135. {
  136. info.OperatingSystem = Model.System.OperatingSystem.Linux;
  137. }
  138. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  139. {
  140. info.OperatingSystem = Model.System.OperatingSystem.BSD;
  141. }
  142. var archX86 = new Regex("(i|I)[3-6]86");
  143. if (archX86.IsMatch(uname.machine))
  144. {
  145. info.SystemArchitecture = Architecture.X86;
  146. }
  147. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  148. {
  149. info.SystemArchitecture = Architecture.X64;
  150. }
  151. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  152. {
  153. info.SystemArchitecture = Architecture.Arm;
  154. }
  155. else if (System.Environment.Is64BitOperatingSystem)
  156. {
  157. info.SystemArchitecture = Architecture.X64;
  158. }
  159. else
  160. {
  161. info.SystemArchitecture = Architecture.X86;
  162. }
  163. return info;
  164. }
  165. private static Uname _unixName;
  166. private static Uname GetUnixName()
  167. {
  168. if (_unixName == null)
  169. {
  170. var uname = new Uname();
  171. try
  172. {
  173. Utsname utsname;
  174. var callResult = Syscall.uname(out utsname);
  175. if (callResult == 0)
  176. {
  177. uname.sysname = utsname.sysname ?? string.Empty;
  178. uname.machine = utsname.machine ?? string.Empty;
  179. }
  180. }
  181. catch (Exception ex)
  182. {
  183. _logger.ErrorException("Error getting unix name", ex);
  184. }
  185. _unixName = uname;
  186. }
  187. return _unixName;
  188. }
  189. public class Uname
  190. {
  191. public string sysname = string.Empty;
  192. public string machine = string.Empty;
  193. }
  194. /// <summary>
  195. /// Handles the UnhandledException event of the CurrentDomain control.
  196. /// </summary>
  197. /// <param name="sender">The source of the event.</param>
  198. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  199. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  200. {
  201. var exception = (Exception)e.ExceptionObject;
  202. new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception);
  203. if (!Debugger.IsAttached)
  204. {
  205. var message = LogHelper.GetLogMessage(exception).ToString();
  206. if (message.IndexOf("InotifyWatcher", StringComparison.OrdinalIgnoreCase) == -1 &&
  207. message.IndexOf("_IOCompletionCallback", StringComparison.OrdinalIgnoreCase) == -1)
  208. {
  209. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  210. }
  211. }
  212. }
  213. public static void Shutdown()
  214. {
  215. ApplicationTaskCompletionSource.SetResult(true);
  216. }
  217. public static void Restart()
  218. {
  219. _restartOnShutdown = true;
  220. Shutdown();
  221. }
  222. private static void StartNewInstance(StartupOptions startupOptions)
  223. {
  224. _logger.Info("Starting new instance");
  225. string module = startupOptions.GetOption("-restartpath");
  226. string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  227. if (string.IsNullOrWhiteSpace(module))
  228. {
  229. module = Environment.GetCommandLineArgs().First();
  230. }
  231. if (!startupOptions.ContainsOption("-restartargs"))
  232. {
  233. var args = Environment.GetCommandLineArgs()
  234. .Skip(1)
  235. .Select(NormalizeCommandLineArgument)
  236. .ToArray();
  237. commandLineArgsString = string.Join(" ", args);
  238. }
  239. _logger.Info("Executable: {0}", module);
  240. _logger.Info("Arguments: {0}", commandLineArgsString);
  241. Process.Start(module, commandLineArgsString);
  242. }
  243. private static string NormalizeCommandLineArgument(string arg)
  244. {
  245. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  246. {
  247. return arg;
  248. }
  249. return "\"" + arg + "\"";
  250. }
  251. }
  252. // class NoCheckCertificatePolicy : ICertificatePolicy
  253. // {
  254. // public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  255. // {
  256. // return true;
  257. // }
  258. // }
  259. public class MonoEnvironmentInfo : EnvironmentInfo
  260. {
  261. //public override string GetUserId()
  262. //{
  263. // return Syscall.getuid().ToString(CultureInfo.InvariantCulture);
  264. //}
  265. }
  266. }