MainStartup.cs 13 KB

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