Program.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. var task = appHost.RunStartupTasks();
  120. Task.WaitAll(task);
  121. task = ApplicationTaskCompletionSource.Task;
  122. Task.WaitAll(task);
  123. }
  124. }
  125. private static async Task createLogger()
  126. {
  127. try
  128. {
  129. string path = Path.Combine(_appPaths.ProgramDataPath, "logging.json");
  130. if (!File.Exists(path))
  131. {
  132. var assembly = typeof(MainClass).Assembly;
  133. // For some reason the csproj name is used instead of the assembly name
  134. var resourcePath = "EmbyServer.Resources.Configuration.logging.json";
  135. using (Stream rscstr = assembly.GetManifestResourceStream(resourcePath))
  136. using (Stream fstr = File.Open(path, FileMode.CreateNew))
  137. {
  138. await rscstr.CopyToAsync(fstr);
  139. }
  140. }
  141. var configuration = new ConfigurationBuilder()
  142. .AddJsonFile(path)
  143. .Build();
  144. Serilog.Log.Logger = new LoggerConfiguration()
  145. .ReadFrom.Configuration(configuration)
  146. .Enrich.FromLogContext()
  147. .CreateLogger();
  148. }
  149. catch (Exception ex)
  150. {
  151. Serilog.Log.Logger = new LoggerConfiguration()
  152. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  153. .WriteTo.File(
  154. Path.Combine(AppContext.BaseDirectory, "logs", "log_.log"),
  155. rollingInterval: RollingInterval.Day,
  156. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}")
  157. .Enrich.FromLogContext()
  158. .CreateLogger();
  159. Serilog.Log.Logger.Fatal(ex, "Failed to read logger config");
  160. }
  161. }
  162. private static MonoEnvironmentInfo GetEnvironmentInfo()
  163. {
  164. var info = new MonoEnvironmentInfo();
  165. var uname = GetUnixName();
  166. var sysName = uname.sysname ?? string.Empty;
  167. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  168. {
  169. info.OperatingSystem = Model.System.OperatingSystem.OSX;
  170. }
  171. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  172. {
  173. info.OperatingSystem = Model.System.OperatingSystem.Linux;
  174. }
  175. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  176. {
  177. info.OperatingSystem = Model.System.OperatingSystem.BSD;
  178. }
  179. var archX86 = new Regex("(i|I)[3-6]86");
  180. if (archX86.IsMatch(uname.machine))
  181. {
  182. info.SystemArchitecture = Architecture.X86;
  183. }
  184. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  185. {
  186. info.SystemArchitecture = Architecture.X64;
  187. }
  188. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  189. {
  190. info.SystemArchitecture = Architecture.Arm;
  191. }
  192. else if (System.Environment.Is64BitOperatingSystem)
  193. {
  194. info.SystemArchitecture = Architecture.X64;
  195. }
  196. else
  197. {
  198. info.SystemArchitecture = Architecture.X86;
  199. }
  200. return info;
  201. }
  202. private static Uname _unixName;
  203. private static Uname GetUnixName()
  204. {
  205. if (_unixName == null)
  206. {
  207. var uname = new Uname();
  208. try
  209. {
  210. Utsname utsname;
  211. var callResult = Syscall.uname(out utsname);
  212. if (callResult == 0)
  213. {
  214. uname.sysname = utsname.sysname ?? string.Empty;
  215. uname.machine = utsname.machine ?? string.Empty;
  216. }
  217. }
  218. catch (Exception ex)
  219. {
  220. _logger.LogError("Error getting unix name", ex);
  221. }
  222. _unixName = uname;
  223. }
  224. return _unixName;
  225. }
  226. public class Uname
  227. {
  228. public string sysname = string.Empty;
  229. public string machine = string.Empty;
  230. }
  231. /// <summary>
  232. /// Handles the UnhandledException event of the CurrentDomain control.
  233. /// </summary>
  234. /// <param name="sender">The source of the event.</param>
  235. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  236. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  237. {
  238. var exception = (Exception)e.ExceptionObject;
  239. // TODO
  240. /*
  241. new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception);
  242. if (!Debugger.IsAttached)
  243. {
  244. var message = LogHelper.GetLogMessage(exception).ToString();
  245. if (message.IndexOf("InotifyWatcher", StringComparison.OrdinalIgnoreCase) == -1 &&
  246. message.IndexOf("_IOCompletionCallback", StringComparison.OrdinalIgnoreCase) == -1)
  247. {
  248. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  249. }
  250. }*/
  251. }
  252. public static void Shutdown()
  253. {
  254. ApplicationTaskCompletionSource.SetResult(true);
  255. }
  256. public static void Restart()
  257. {
  258. _restartOnShutdown = true;
  259. Shutdown();
  260. }
  261. private static void StartNewInstance(StartupOptions startupOptions)
  262. {
  263. _logger.LogInformation("Starting new instance");
  264. string module = startupOptions.GetOption("-restartpath");
  265. string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  266. if (string.IsNullOrWhiteSpace(module))
  267. {
  268. module = Environment.GetCommandLineArgs().First();
  269. }
  270. if (!startupOptions.ContainsOption("-restartargs"))
  271. {
  272. var args = Environment.GetCommandLineArgs()
  273. .Skip(1)
  274. .Select(NormalizeCommandLineArgument)
  275. .ToArray();
  276. commandLineArgsString = string.Join(" ", args);
  277. }
  278. _logger.LogInformation("Executable: {0}", module);
  279. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  280. Process.Start(module, commandLineArgsString);
  281. }
  282. private static string NormalizeCommandLineArgument(string arg)
  283. {
  284. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  285. {
  286. return arg;
  287. }
  288. return "\"" + arg + "\"";
  289. }
  290. }
  291. // class NoCheckCertificatePolicy : ICertificatePolicy
  292. // {
  293. // public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  294. // {
  295. // return true;
  296. // }
  297. // }
  298. public class MonoEnvironmentInfo : EnvironmentInfo
  299. {
  300. //public override string GetUserId()
  301. //{
  302. // return Syscall.getuid().ToString(CultureInfo.InvariantCulture);
  303. //}
  304. }
  305. }