Program.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Constants;
  3. using MediaBrowser.Common.Implementations.Logging;
  4. using MediaBrowser.Common.Implementations.Updates;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Server.Implementations;
  7. using MediaBrowser.ServerApplication;
  8. using MediaBrowser.ServerApplication.Native;
  9. using MediaBrowser.ServerApplication.IO;
  10. using Microsoft.Win32;
  11. using System;
  12. using System.Diagnostics;
  13. using System.IO;
  14. using System.Threading;
  15. using System.Windows;
  16. using System.Net;
  17. using System.Net.Security;
  18. using System.Security.Cryptography.X509Certificates;
  19. using System.Threading.Tasks;
  20. using System.Reflection;
  21. using System.Linq;
  22. // MONOMKBUNDLE: For the embedded version, mkbundle tool
  23. #if MONOMKBUNDLE
  24. using Mono.Unix;
  25. using Mono.Unix.Native;
  26. using System.Text;
  27. #endif
  28. namespace MediaBrowser.Server.Mono
  29. {
  30. public class MainClass
  31. {
  32. private static ApplicationHost _appHost;
  33. private static ILogger _logger;
  34. public static void Main (string[] args)
  35. {
  36. //GetEntryAssembly is empty when running from a mkbundle package
  37. #if MONOMKBUNDLE
  38. var applicationPath = GetExecutablePath();
  39. #else
  40. var applicationPath = Assembly.GetEntryAssembly ().Location;
  41. #endif
  42. var options = new StartupOptions();
  43. // Allow this to be specified on the command line.
  44. var customProgramDataPath = options.GetOption("-programdata");
  45. var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);
  46. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  47. logManager.ReloadLogger(LogSeverity.Info);
  48. logManager.AddConsoleOutput();
  49. var logger = _logger = logManager.GetLogger("Main");
  50. BeginLog(logger, appPaths);
  51. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  52. if (PerformUpdateIfNeeded(appPaths, logger))
  53. {
  54. logger.Info("Exiting to perform application update.");
  55. return;
  56. }
  57. try
  58. {
  59. RunApplication(appPaths, logManager, options);
  60. }
  61. finally
  62. {
  63. logger.Info("Shutting down");
  64. _appHost.Dispose();
  65. }
  66. }
  67. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  68. {
  69. if (string.IsNullOrEmpty(programDataPath))
  70. {
  71. return new ServerApplicationPaths(applicationPath);
  72. }
  73. return new ServerApplicationPaths(programDataPath, applicationPath);
  74. }
  75. /// <summary>
  76. /// Determines whether this instance [can self restart].
  77. /// </summary>
  78. /// <returns><c>true</c> if this instance [can self restart]; otherwise, <c>false</c>.</returns>
  79. public static bool CanSelfRestart
  80. {
  81. get
  82. {
  83. return false;
  84. }
  85. }
  86. /// <summary>
  87. /// Gets a value indicating whether this instance can self update.
  88. /// </summary>
  89. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  90. public static bool CanSelfUpdate
  91. {
  92. get
  93. {
  94. return false;
  95. }
  96. }
  97. private static RemoteCertificateValidationCallback _ignoreCertificates = new RemoteCertificateValidationCallback(delegate { return true; });
  98. private static TaskCompletionSource<bool> _applicationTaskCompletionSource = new TaskCompletionSource<bool>();
  99. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options)
  100. {
  101. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  102. // Allow all https requests
  103. ServicePointManager.ServerCertificateValidationCallback = _ignoreCertificates;
  104. _appHost = new ApplicationHost(appPaths, logManager, false, false, options);
  105. Console.WriteLine ("appHost.Init");
  106. var initProgress = new Progress<double>();
  107. var task = _appHost.Init(initProgress);
  108. Task.WaitAll (task);
  109. Console.WriteLine ("Running startup tasks");
  110. task = _appHost.RunStartupTasks();
  111. Task.WaitAll (task);
  112. task = _applicationTaskCompletionSource.Task;
  113. Task.WaitAll (task);
  114. }
  115. /// <summary>
  116. /// Handles the SessionEnding event of the SystemEvents control.
  117. /// </summary>
  118. /// <param name="sender">The source of the event.</param>
  119. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  120. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  121. {
  122. if (e.Reason == SessionEndReasons.SystemShutdown)
  123. {
  124. Shutdown();
  125. }
  126. }
  127. /// <summary>
  128. /// Begins the log.
  129. /// </summary>
  130. /// <param name="logger">The logger.</param>
  131. private static void BeginLog(ILogger logger, IApplicationPaths appPaths)
  132. {
  133. logger.Info("Media Browser Server started");
  134. ApplicationHost.LogEnvironmentInfo(logger, appPaths);
  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. }