Program.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. // Allow this to be specified on the command line.
  41. var customProgramDataPath = ParseProgramDataPathFromCommandLine();
  42. var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);
  43. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  44. logManager.ReloadLogger(LogSeverity.Info);
  45. logManager.AddConsoleOutput();
  46. var logger = _logger = logManager.GetLogger("Main");
  47. BeginLog(logger);
  48. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  49. if (PerformUpdateIfNeeded(appPaths, logger))
  50. {
  51. logger.Info("Exiting to perform application update.");
  52. return;
  53. }
  54. try
  55. {
  56. RunApplication(appPaths, logManager);
  57. }
  58. finally
  59. {
  60. logger.Info("Shutting down");
  61. _appHost.Dispose();
  62. }
  63. }
  64. private static string ParseProgramDataPathFromCommandLine()
  65. {
  66. var commandArgs = Environment.GetCommandLineArgs().ToList();
  67. var programDataPathIndex = commandArgs.IndexOf("-programdata");
  68. if (programDataPathIndex != -1)
  69. {
  70. return commandArgs.ElementAtOrDefault(programDataPathIndex + 1);
  71. }
  72. return null;
  73. }
  74. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  75. {
  76. if (string.IsNullOrEmpty(programDataPath))
  77. {
  78. return new ServerApplicationPaths(applicationPath);
  79. }
  80. return new ServerApplicationPaths(programDataPath, applicationPath);
  81. }
  82. /// <summary>
  83. /// Determines whether this instance [can self restart].
  84. /// </summary>
  85. /// <returns><c>true</c> if this instance [can self restart]; otherwise, <c>false</c>.</returns>
  86. public static bool CanSelfRestart
  87. {
  88. get
  89. {
  90. return false;
  91. }
  92. }
  93. /// <summary>
  94. /// Gets a value indicating whether this instance can self update.
  95. /// </summary>
  96. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  97. public static bool CanSelfUpdate
  98. {
  99. get
  100. {
  101. return false;
  102. }
  103. }
  104. private static RemoteCertificateValidationCallback _ignoreCertificates = new RemoteCertificateValidationCallback(delegate { return true; });
  105. private static TaskCompletionSource<bool> _applicationTaskCompletionSource = new TaskCompletionSource<bool>();
  106. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager)
  107. {
  108. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  109. // Allow all https requests
  110. ServicePointManager.ServerCertificateValidationCallback = _ignoreCertificates;
  111. _appHost = new ApplicationHost(appPaths, logManager, false, false);
  112. Console.WriteLine ("appHost.Init");
  113. var initProgress = new Progress<double>();
  114. var task = _appHost.Init(initProgress);
  115. Task.WaitAll (task);
  116. Console.WriteLine ("Running startup tasks");
  117. task = _appHost.RunStartupTasks();
  118. Task.WaitAll (task);
  119. task = _applicationTaskCompletionSource.Task;
  120. Task.WaitAll (task);
  121. }
  122. /// <summary>
  123. /// Handles the SessionEnding event of the SystemEvents control.
  124. /// </summary>
  125. /// <param name="sender">The source of the event.</param>
  126. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  127. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  128. {
  129. if (e.Reason == SessionEndReasons.SystemShutdown)
  130. {
  131. Shutdown();
  132. }
  133. }
  134. /// <summary>
  135. /// Begins the log.
  136. /// </summary>
  137. /// <param name="logger">The logger.</param>
  138. private static void BeginLog(ILogger logger)
  139. {
  140. logger.Info("Media Browser Server started");
  141. logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));
  142. logger.Info("Server: {0}", Environment.MachineName);
  143. logger.Info("Operating system: {0}", Environment.OSVersion.ToString());
  144. }
  145. /// <summary>
  146. /// Handles the UnhandledException event of the CurrentDomain control.
  147. /// </summary>
  148. /// <param name="sender">The source of the event.</param>
  149. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  150. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  151. {
  152. var exception = (Exception)e.ExceptionObject;
  153. LogUnhandledException(exception);
  154. if (!Debugger.IsAttached)
  155. {
  156. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  157. }
  158. }
  159. private static void LogUnhandledException(Exception ex)
  160. {
  161. _logger.ErrorException("UnhandledException", ex);
  162. _appHost.LogManager.Flush ();
  163. var path = Path.Combine(_appHost.ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "crash_" + Guid.NewGuid() + ".txt");
  164. var builder = LogHelper.GetLogMessage(ex);
  165. Console.WriteLine ("UnhandledException");
  166. Console.WriteLine (builder.ToString());
  167. File.WriteAllText(path, builder.ToString());
  168. }
  169. /// <summary>
  170. /// Performs the update if needed.
  171. /// </summary>
  172. /// <param name="appPaths">The app paths.</param>
  173. /// <param name="logger">The logger.</param>
  174. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  175. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  176. {
  177. return false;
  178. }
  179. public static void Shutdown()
  180. {
  181. _applicationTaskCompletionSource.SetResult (true);
  182. }
  183. public static void Restart()
  184. {
  185. // Second instance will start first, so dispose so that the http ports will be available to the new instance
  186. _appHost.Dispose();
  187. // Right now this method will just shutdown, but not restart
  188. Shutdown ();
  189. }
  190. // Return the running process path
  191. #if MONOMKBUNDLE
  192. public static string GetExecutablePath()
  193. {
  194. var builder = new StringBuilder (8192);
  195. if (Syscall.readlink("/proc/self/exe", builder) >= 0)
  196. return builder.ToString ();
  197. else
  198. return null;
  199. }
  200. #endif
  201. }
  202. class NoCheckCertificatePolicy : ICertificatePolicy
  203. {
  204. public bool CheckValidationResult (ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  205. {
  206. return true;
  207. }
  208. }
  209. }