MainStartup.cs 15 KB

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