MainStartup.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 Microsoft.Win32;
  7. using System;
  8. using System.Configuration.Install;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Linq;
  12. using System.ServiceProcess;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using System.Windows;
  16. namespace MediaBrowser.ServerApplication
  17. {
  18. public class MainStartup
  19. {
  20. /// <summary>
  21. /// The single instance mutex
  22. /// </summary>
  23. private static Mutex _singleInstanceMutex;
  24. private static ApplicationHost _appHost;
  25. private static App _app;
  26. /// <summary>
  27. /// Defines the entry point of the application.
  28. /// </summary>
  29. [STAThread]
  30. public static void Main()
  31. {
  32. var startFlag = Environment.GetCommandLineArgs().ElementAtOrDefault(1);
  33. var runService = string.Equals(startFlag, "-service", StringComparison.OrdinalIgnoreCase);
  34. var appPaths = CreateApplicationPaths(runService);
  35. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  36. logManager.ReloadLogger(LogSeverity.Info);
  37. var logger = logManager.GetLogger("Main");
  38. BeginLog(logger);
  39. // Install directly
  40. if (string.Equals(startFlag, "-installservice", StringComparison.OrdinalIgnoreCase))
  41. {
  42. logger.Info("Performing service installation");
  43. InstallService(logger);
  44. return;
  45. }
  46. // Restart with admin rights, then install
  47. if (string.Equals(startFlag, "-installserviceasadmin", StringComparison.OrdinalIgnoreCase))
  48. {
  49. logger.Info("Performing service installation");
  50. RunServiceInstallation();
  51. return;
  52. }
  53. // Uninstall directly
  54. if (string.Equals(startFlag, "-uninstallservice", StringComparison.OrdinalIgnoreCase))
  55. {
  56. logger.Info("Performing service uninstallation");
  57. UninstallService(logger);
  58. return;
  59. }
  60. // Restart with admin rights, then uninstall
  61. if (string.Equals(startFlag, "-uninstallserviceasadmin", StringComparison.OrdinalIgnoreCase))
  62. {
  63. logger.Info("Performing service uninstallation");
  64. RunServiceUninstallation();
  65. return;
  66. }
  67. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  68. bool createdNew;
  69. var runningPath = Process.GetCurrentProcess().MainModule.FileName.Replace(Path.DirectorySeparatorChar.ToString(), string.Empty);
  70. _singleInstanceMutex = new Mutex(true, @"Local\" + runningPath, out createdNew);
  71. if (!createdNew)
  72. {
  73. _singleInstanceMutex = null;
  74. logger.Info("Shutting down because another instance of Media Browser Server is already running.");
  75. return;
  76. }
  77. if (PerformUpdateIfNeeded(appPaths, logger))
  78. {
  79. logger.Info("Exiting to perform application update.");
  80. return;
  81. }
  82. try
  83. {
  84. RunApplication(appPaths, logManager, runService);
  85. }
  86. finally
  87. {
  88. logger.Info("Shutting down");
  89. ReleaseMutex(logger);
  90. _appHost.Dispose();
  91. }
  92. }
  93. /// <summary>
  94. /// Creates the application paths.
  95. /// </summary>
  96. /// <param name="runAsService">if set to <c>true</c> [run as service].</param>
  97. /// <returns>ServerApplicationPaths.</returns>
  98. private static ServerApplicationPaths CreateApplicationPaths(bool runAsService)
  99. {
  100. if (runAsService)
  101. {
  102. #if (RELEASE)
  103. var systemPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
  104. var programDataPath = Path.GetDirectoryName(systemPath);
  105. return new ServerApplicationPaths(programDataPath);
  106. #endif
  107. }
  108. return new ServerApplicationPaths();
  109. }
  110. /// <summary>
  111. /// Begins the log.
  112. /// </summary>
  113. /// <param name="logger">The logger.</param>
  114. private static void BeginLog(ILogger logger)
  115. {
  116. logger.Info("Media Browser Server started");
  117. logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));
  118. logger.Info("Server: {0}", Environment.MachineName);
  119. logger.Info("Operating system: {0}", Environment.OSVersion.ToString());
  120. }
  121. /// <summary>
  122. /// Runs the application.
  123. /// </summary>
  124. /// <param name="appPaths">The app paths.</param>
  125. /// <param name="logManager">The log manager.</param>
  126. /// <param name="runService">if set to <c>true</c> [run service].</param>
  127. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService)
  128. {
  129. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  130. var commandLineArgs = Environment.GetCommandLineArgs();
  131. _appHost = new ApplicationHost(appPaths, logManager);
  132. _app = new App(_appHost, _appHost.LogManager.GetLogger("App"), runService);
  133. if (runService)
  134. {
  135. _app.AppStarted += (sender, args) => StartService(logManager);
  136. }
  137. _app.Run();
  138. }
  139. /// <summary>
  140. /// Starts the service.
  141. /// </summary>
  142. private static void StartService(ILogManager logManager)
  143. {
  144. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == BackgroundService.Name);
  145. if (ctl == null)
  146. {
  147. RunServiceInstallation();
  148. }
  149. var service = new BackgroundService(logManager.GetLogger("Service"));
  150. service.Disposed += service_Disposed;
  151. ServiceBase.Run(service);
  152. }
  153. /// <summary>
  154. /// Handles the Disposed event of the service control.
  155. /// </summary>
  156. /// <param name="sender">The source of the event.</param>
  157. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  158. static async void service_Disposed(object sender, EventArgs e)
  159. {
  160. await _appHost.Shutdown();
  161. }
  162. /// <summary>
  163. /// Installs the service.
  164. /// </summary>
  165. private static void InstallService(ILogger logger)
  166. {
  167. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  168. try
  169. {
  170. ManagedInstallerClass.InstallHelper(new[] { runningPath });
  171. logger.Info("Service installation succeeded");
  172. }
  173. catch (Exception ex)
  174. {
  175. logger.ErrorException("Uninstall failed", ex);
  176. }
  177. }
  178. /// <summary>
  179. /// Uninstalls the service.
  180. /// </summary>
  181. private static void UninstallService(ILogger logger)
  182. {
  183. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  184. try
  185. {
  186. ManagedInstallerClass.InstallHelper(new[] { "/u", runningPath });
  187. logger.Info("Service uninstallation succeeded");
  188. }
  189. catch (Exception ex)
  190. {
  191. logger.ErrorException("Uninstall failed", ex);
  192. }
  193. }
  194. /// <summary>
  195. /// Runs the service installation.
  196. /// </summary>
  197. private static void RunServiceInstallation()
  198. {
  199. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  200. var startInfo = new ProcessStartInfo
  201. {
  202. FileName = runningPath,
  203. Arguments = "-installservice",
  204. CreateNoWindow = true,
  205. WindowStyle = ProcessWindowStyle.Hidden,
  206. Verb = "runas",
  207. ErrorDialog = false
  208. };
  209. using (var process = Process.Start(startInfo))
  210. {
  211. process.WaitForExit();
  212. }
  213. }
  214. /// <summary>
  215. /// Runs the service uninstallation.
  216. /// </summary>
  217. private static void RunServiceUninstallation()
  218. {
  219. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  220. var startInfo = new ProcessStartInfo
  221. {
  222. FileName = runningPath,
  223. Arguments = "-uninstallservice",
  224. CreateNoWindow = true,
  225. WindowStyle = ProcessWindowStyle.Hidden,
  226. Verb = "runas",
  227. ErrorDialog = false
  228. };
  229. using (var process = Process.Start(startInfo))
  230. {
  231. process.WaitForExit();
  232. }
  233. }
  234. /// <summary>
  235. /// Handles the SessionEnding event of the SystemEvents control.
  236. /// </summary>
  237. /// <param name="sender">The source of the event.</param>
  238. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  239. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  240. {
  241. // Try to shutdown gracefully
  242. var task = _appHost.Shutdown();
  243. Task.WaitAll(task);
  244. }
  245. /// <summary>
  246. /// Handles the UnhandledException event of the CurrentDomain control.
  247. /// </summary>
  248. /// <param name="sender">The source of the event.</param>
  249. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  250. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  251. {
  252. var exception = (Exception)e.ExceptionObject;
  253. _app.OnUnhandledException(exception);
  254. if (!Debugger.IsAttached)
  255. {
  256. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  257. }
  258. }
  259. /// <summary>
  260. /// Releases the mutex.
  261. /// </summary>
  262. internal static void ReleaseMutex(ILogger logger)
  263. {
  264. if (_singleInstanceMutex == null)
  265. {
  266. return;
  267. }
  268. logger.Debug("Releasing mutex");
  269. _singleInstanceMutex.ReleaseMutex();
  270. _singleInstanceMutex.Close();
  271. _singleInstanceMutex.Dispose();
  272. _singleInstanceMutex = null;
  273. }
  274. /// <summary>
  275. /// Performs the update if needed.
  276. /// </summary>
  277. /// <param name="appPaths">The app paths.</param>
  278. /// <param name="logger">The logger.</param>
  279. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  280. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  281. {
  282. // Look for the existence of an update archive
  283. var updateArchive = Path.Combine(appPaths.TempUpdatePath, Constants.MbServerPkgName + ".zip");
  284. if (File.Exists(updateArchive))
  285. {
  286. logger.Info("An update is available from {0}", updateArchive);
  287. // Update is there - execute update
  288. try
  289. {
  290. new ApplicationUpdater().UpdateApplication(MBApplication.MBServer, appPaths, updateArchive);
  291. // And just let the app exit so it can update
  292. return true;
  293. }
  294. catch (Exception e)
  295. {
  296. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  297. }
  298. }
  299. return false;
  300. }
  301. }
  302. }