Program.cs 6.8 KB

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