Program.cs 6.8 KB

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