MainStartup.cs 13 KB

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