Program.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Implementations.IO;
  3. using MediaBrowser.Common.Implementations.Logging;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Server.Implementations;
  6. using MediaBrowser.ServerApplication;
  7. using MediaBrowser.ServerApplication.IO;
  8. using Microsoft.Win32;
  9. using System;
  10. using System.Diagnostics;
  11. using System.IO;
  12. using System.Net;
  13. using System.Net.Security;
  14. using System.Reflection;
  15. using System.Security.Cryptography.X509Certificates;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Server.Mono
  18. {
  19. public class MainClass
  20. {
  21. private static ApplicationHost _appHost;
  22. private static ILogger _logger;
  23. public static void Main (string[] args)
  24. {
  25. //GetEntryAssembly is empty when running from a mkbundle package
  26. #if MONOMKBUNDLE
  27. var applicationPath = GetExecutablePath();
  28. #else
  29. var applicationPath = Assembly.GetEntryAssembly ().Location;
  30. #endif
  31. var options = new StartupOptions();
  32. // Allow this to be specified on the command line.
  33. var customProgramDataPath = options.GetOption("-programdata");
  34. var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);
  35. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  36. logManager.ReloadLogger(LogSeverity.Info);
  37. logManager.AddConsoleOutput();
  38. var logger = _logger = logManager.GetLogger("Main");
  39. BeginLog(logger, appPaths);
  40. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  41. if (PerformUpdateIfNeeded(appPaths, logger))
  42. {
  43. logger.Info("Exiting to perform application update.");
  44. return;
  45. }
  46. try
  47. {
  48. RunApplication(appPaths, logManager, options);
  49. }
  50. finally
  51. {
  52. logger.Info("Shutting down");
  53. _appHost.Dispose();
  54. }
  55. }
  56. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  57. {
  58. if (string.IsNullOrEmpty(programDataPath))
  59. {
  60. return new ServerApplicationPaths(applicationPath);
  61. }
  62. return new ServerApplicationPaths(programDataPath, applicationPath);
  63. }
  64. /// <summary>
  65. /// Determines whether this instance [can self restart].
  66. /// </summary>
  67. /// <returns><c>true</c> if this instance [can self restart]; otherwise, <c>false</c>.</returns>
  68. public static bool CanSelfRestart
  69. {
  70. get
  71. {
  72. return false;
  73. }
  74. }
  75. /// <summary>
  76. /// Gets a value indicating whether this instance can self update.
  77. /// </summary>
  78. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  79. public static bool CanSelfUpdate
  80. {
  81. get
  82. {
  83. return false;
  84. }
  85. }
  86. private static RemoteCertificateValidationCallback _ignoreCertificates = new RemoteCertificateValidationCallback(delegate { return true; });
  87. private static TaskCompletionSource<bool> _applicationTaskCompletionSource = new TaskCompletionSource<bool>();
  88. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options)
  89. {
  90. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  91. // Allow all https requests
  92. ServicePointManager.ServerCertificateValidationCallback = _ignoreCertificates;
  93. var fileSystem = new CommonFileSystem(logManager.GetLogger("FileSystem"), false, true);
  94. _appHost = new ApplicationHost(appPaths, logManager, false, false, options, fileSystem, "MBServer.Mono", false);
  95. if (options.ContainsOption("-v")) {
  96. Console.WriteLine (_appHost.ApplicationVersion.ToString());
  97. return;
  98. }
  99. Console.WriteLine ("appHost.Init");
  100. var initProgress = new Progress<double>();
  101. var task = _appHost.Init(initProgress);
  102. Task.WaitAll (task);
  103. Console.WriteLine ("Running startup tasks");
  104. task = _appHost.RunStartupTasks();
  105. Task.WaitAll (task);
  106. task = _applicationTaskCompletionSource.Task;
  107. Task.WaitAll (task);
  108. }
  109. /// <summary>
  110. /// Handles the SessionEnding event of the SystemEvents control.
  111. /// </summary>
  112. /// <param name="sender">The source of the event.</param>
  113. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  114. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  115. {
  116. if (e.Reason == SessionEndReasons.SystemShutdown)
  117. {
  118. Shutdown();
  119. }
  120. }
  121. /// <summary>
  122. /// Begins the log.
  123. /// </summary>
  124. /// <param name="logger">The logger.</param>
  125. private static void BeginLog(ILogger logger, IApplicationPaths appPaths)
  126. {
  127. logger.Info("Media Browser Server started");
  128. ApplicationHost.LogEnvironmentInfo(logger, appPaths);
  129. }
  130. /// <summary>
  131. /// Handles the UnhandledException event of the CurrentDomain control.
  132. /// </summary>
  133. /// <param name="sender">The source of the event.</param>
  134. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  135. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  136. {
  137. var exception = (Exception)e.ExceptionObject;
  138. LogUnhandledException(exception);
  139. if (!Debugger.IsAttached)
  140. {
  141. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  142. }
  143. }
  144. private static void LogUnhandledException(Exception ex)
  145. {
  146. _logger.ErrorException("UnhandledException", ex);
  147. _appHost.LogManager.Flush ();
  148. var path = Path.Combine(_appHost.ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "crash_" + Guid.NewGuid() + ".txt");
  149. var builder = LogHelper.GetLogMessage(ex);
  150. Console.WriteLine ("UnhandledException");
  151. Console.WriteLine (builder.ToString());
  152. File.WriteAllText(path, builder.ToString());
  153. }
  154. /// <summary>
  155. /// Performs the update if needed.
  156. /// </summary>
  157. /// <param name="appPaths">The app paths.</param>
  158. /// <param name="logger">The logger.</param>
  159. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  160. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  161. {
  162. return false;
  163. }
  164. public static void Shutdown()
  165. {
  166. _applicationTaskCompletionSource.SetResult (true);
  167. }
  168. public static void Restart()
  169. {
  170. // Second instance will start first, so dispose so that the http ports will be available to the new instance
  171. _appHost.Dispose();
  172. // Right now this method will just shutdown, but not restart
  173. Shutdown ();
  174. }
  175. // Return the running process path
  176. #if MONOMKBUNDLE
  177. public static string GetExecutablePath()
  178. {
  179. var builder = new StringBuilder (8192);
  180. if (Syscall.readlink("/proc/self/exe", builder) >= 0)
  181. return builder.ToString ();
  182. else
  183. return null;
  184. }
  185. #endif
  186. }
  187. class NoCheckCertificatePolicy : ICertificatePolicy
  188. {
  189. public bool CheckValidationResult (ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  190. {
  191. return true;
  192. }
  193. }
  194. }