MainStartup.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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.Native;
  8. using Microsoft.Win32;
  9. using System;
  10. using System.Configuration.Install;
  11. using System.Diagnostics;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Runtime.InteropServices;
  15. using System.ServiceProcess;
  16. using System.Windows;
  17. namespace MediaBrowser.ServerApplication
  18. {
  19. public class MainStartup
  20. {
  21. private static ApplicationHost _appHost;
  22. private static App _app;
  23. private static ILogger _logger;
  24. private static bool _isRunningAsService = false;
  25. /// <summary>
  26. /// Defines the entry point of the application.
  27. /// </summary>
  28. [STAThread]
  29. public static void Main()
  30. {
  31. var startFlag = Environment.GetCommandLineArgs().ElementAtOrDefault(1);
  32. _isRunningAsService = string.Equals(startFlag, "-service", StringComparison.OrdinalIgnoreCase);
  33. var applicationPath = Process.GetCurrentProcess().MainModule.FileName;
  34. var appPaths = CreateApplicationPaths(applicationPath, _isRunningAsService);
  35. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  36. logManager.ReloadLogger(LogSeverity.Debug);
  37. var logger = _logger = logManager.GetLogger("Main");
  38. BeginLog(logger, appPaths);
  39. // Install directly
  40. if (string.Equals(startFlag, "-installservice", StringComparison.OrdinalIgnoreCase))
  41. {
  42. logger.Info("Performing service installation");
  43. InstallService(applicationPath, 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(applicationPath);
  51. return;
  52. }
  53. // Uninstall directly
  54. if (string.Equals(startFlag, "-uninstallservice", StringComparison.OrdinalIgnoreCase))
  55. {
  56. logger.Info("Performing service uninstallation");
  57. UninstallService(applicationPath, 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(applicationPath);
  65. return;
  66. }
  67. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  68. RunServiceInstallationIfNeeded(applicationPath);
  69. var currentProcess = Process.GetCurrentProcess();
  70. if (IsAlreadyRunning(applicationPath, currentProcess))
  71. {
  72. logger.Info("Shutting down because another instance of Media Browser Server is already running.");
  73. return;
  74. }
  75. if (PerformUpdateIfNeeded(appPaths, logger))
  76. {
  77. logger.Info("Exiting to perform application update.");
  78. return;
  79. }
  80. try
  81. {
  82. RunApplication(appPaths, logManager, _isRunningAsService);
  83. }
  84. finally
  85. {
  86. OnServiceShutdown();
  87. }
  88. }
  89. /// <summary>
  90. /// Determines whether [is already running] [the specified current process].
  91. /// </summary>
  92. /// <param name="currentProcess">The current process.</param>
  93. /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
  94. private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
  95. {
  96. var duplicate = Process.GetProcesses().FirstOrDefault(i =>
  97. {
  98. try
  99. {
  100. return string.Equals(applicationPath, i.MainModule.FileName) && currentProcess.Id != i.Id;
  101. }
  102. catch (Exception)
  103. {
  104. return false;
  105. }
  106. });
  107. if (duplicate != null)
  108. {
  109. _logger.Info("Found a duplicate process. Giving it time to exit.");
  110. if (!duplicate.WaitForExit(5000))
  111. {
  112. _logger.Info("The duplicate process did not exit.");
  113. return true;
  114. }
  115. }
  116. return false;
  117. }
  118. /// <summary>
  119. /// Creates the application paths.
  120. /// </summary>
  121. /// <param name="runAsService">if set to <c>true</c> [run as service].</param>
  122. /// <returns>ServerApplicationPaths.</returns>
  123. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService)
  124. {
  125. if (runAsService)
  126. {
  127. var systemPath = Path.GetDirectoryName(applicationPath);
  128. var programDataPath = Path.GetDirectoryName(systemPath);
  129. return new ServerApplicationPaths(programDataPath, applicationPath);
  130. }
  131. return new ServerApplicationPaths(applicationPath);
  132. }
  133. /// <summary>
  134. /// Gets a value indicating whether this instance can self restart.
  135. /// </summary>
  136. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  137. public static bool CanSelfRestart
  138. {
  139. get
  140. {
  141. return !_isRunningAsService;
  142. }
  143. }
  144. /// <summary>
  145. /// Gets a value indicating whether this instance can self update.
  146. /// </summary>
  147. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  148. public static bool CanSelfUpdate
  149. {
  150. get
  151. {
  152. return !_isRunningAsService;
  153. }
  154. }
  155. /// <summary>
  156. /// Begins the log.
  157. /// </summary>
  158. /// <param name="logger">The logger.</param>
  159. /// <param name="appPaths">The app paths.</param>
  160. private static void BeginLog(ILogger logger, IApplicationPaths appPaths)
  161. {
  162. logger.Info("Media Browser Server started");
  163. logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));
  164. logger.Info("Server: {0}", Environment.MachineName);
  165. logger.Info("Operating system: {0}", Environment.OSVersion.ToString());
  166. logger.Info("Program data path: {0}", appPaths.ProgramDataPath);
  167. logger.Info("Application Path: {0}", appPaths.ApplicationPath);
  168. }
  169. /// <summary>
  170. /// Runs the application.
  171. /// </summary>
  172. /// <param name="appPaths">The app paths.</param>
  173. /// <param name="logManager">The log manager.</param>
  174. /// <param name="runService">if set to <c>true</c> [run service].</param>
  175. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService)
  176. {
  177. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  178. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  179. _appHost = new ApplicationHost(appPaths, logManager);
  180. _app = new App(_appHost, _appHost.LogManager.GetLogger("App"), runService);
  181. if (runService)
  182. {
  183. _app.AppStarted += (sender, args) => StartService(logManager);
  184. }
  185. else
  186. {
  187. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  188. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  189. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  190. }
  191. _app.Run();
  192. }
  193. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  194. {
  195. if (e.Reason == SessionSwitchReason.SessionLogon)
  196. {
  197. BrowserLauncher.OpenDashboard(_appHost.UserManager, _appHost.ServerConfigurationManager, _appHost, _logger);
  198. }
  199. }
  200. /// <summary>
  201. /// Starts the service.
  202. /// </summary>
  203. private static void StartService(ILogManager logManager)
  204. {
  205. var service = new BackgroundService(logManager.GetLogger("Service"));
  206. service.Disposed += service_Disposed;
  207. ServiceBase.Run(service);
  208. }
  209. /// <summary>
  210. /// Handles the Disposed event of the service control.
  211. /// </summary>
  212. /// <param name="sender">The source of the event.</param>
  213. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  214. static void service_Disposed(object sender, EventArgs e)
  215. {
  216. OnServiceShutdown();
  217. }
  218. private static void OnServiceShutdown()
  219. {
  220. _logger.Info("Shutting down");
  221. _appHost.Dispose();
  222. if (!_isRunningAsService)
  223. {
  224. SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
  225. }
  226. _app.Dispatcher.Invoke(_app.Shutdown);
  227. }
  228. /// <summary>
  229. /// Installs the service.
  230. /// </summary>
  231. private static void InstallService(string applicationPath, ILogger logger)
  232. {
  233. try
  234. {
  235. ManagedInstallerClass.InstallHelper(new[] { applicationPath });
  236. logger.Info("Service installation succeeded");
  237. }
  238. catch (Exception ex)
  239. {
  240. logger.ErrorException("Uninstall failed", ex);
  241. }
  242. }
  243. /// <summary>
  244. /// Uninstalls the service.
  245. /// </summary>
  246. private static void UninstallService(string applicationPath, ILogger logger)
  247. {
  248. try
  249. {
  250. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  251. logger.Info("Service uninstallation succeeded");
  252. }
  253. catch (Exception ex)
  254. {
  255. logger.ErrorException("Uninstall failed", ex);
  256. }
  257. }
  258. private static void RunServiceInstallationIfNeeded(string applicationPath)
  259. {
  260. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == BackgroundService.Name);
  261. if (ctl == null)
  262. {
  263. RunServiceInstallation(applicationPath);
  264. }
  265. }
  266. /// <summary>
  267. /// Runs the service installation.
  268. /// </summary>
  269. private static void RunServiceInstallation(string applicationPath)
  270. {
  271. var startInfo = new ProcessStartInfo
  272. {
  273. FileName = applicationPath,
  274. Arguments = "-installservice",
  275. CreateNoWindow = true,
  276. WindowStyle = ProcessWindowStyle.Hidden,
  277. Verb = "runas",
  278. ErrorDialog = false
  279. };
  280. using (var process = Process.Start(startInfo))
  281. {
  282. process.WaitForExit();
  283. }
  284. }
  285. /// <summary>
  286. /// Runs the service uninstallation.
  287. /// </summary>
  288. private static void RunServiceUninstallation(string applicationPath)
  289. {
  290. var startInfo = new ProcessStartInfo
  291. {
  292. FileName = applicationPath,
  293. Arguments = "-uninstallservice",
  294. CreateNoWindow = true,
  295. WindowStyle = ProcessWindowStyle.Hidden,
  296. Verb = "runas",
  297. ErrorDialog = false
  298. };
  299. using (var process = Process.Start(startInfo))
  300. {
  301. process.WaitForExit();
  302. }
  303. }
  304. /// <summary>
  305. /// Handles the SessionEnding event of the SystemEvents control.
  306. /// </summary>
  307. /// <param name="sender">The source of the event.</param>
  308. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  309. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  310. {
  311. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  312. {
  313. Shutdown();
  314. }
  315. }
  316. /// <summary>
  317. /// Handles the UnhandledException event of the CurrentDomain control.
  318. /// </summary>
  319. /// <param name="sender">The source of the event.</param>
  320. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  321. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  322. {
  323. var exception = (Exception)e.ExceptionObject;
  324. LogUnhandledException(exception);
  325. _appHost.LogManager.Flush();
  326. if (!_isRunningAsService)
  327. {
  328. _app.OnUnhandledException(exception);
  329. }
  330. if (!Debugger.IsAttached)
  331. {
  332. Environment.Exit(Marshal.GetHRForException(exception));
  333. }
  334. }
  335. private static void LogUnhandledException(Exception ex)
  336. {
  337. _logger.ErrorException("UnhandledException", ex);
  338. var path = Path.Combine(_appHost.ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "unhandled_" + Guid.NewGuid() + ".txt");
  339. var builder = LogHelper.GetLogMessage(ex);
  340. File.WriteAllText(path, builder.ToString());
  341. }
  342. /// <summary>
  343. /// Performs the update if needed.
  344. /// </summary>
  345. /// <param name="appPaths">The app paths.</param>
  346. /// <param name="logger">The logger.</param>
  347. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  348. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  349. {
  350. // Look for the existence of an update archive
  351. var updateArchive = Path.Combine(appPaths.TempUpdatePath, Constants.MbServerPkgName + ".zip");
  352. if (File.Exists(updateArchive))
  353. {
  354. logger.Info("An update is available from {0}", updateArchive);
  355. // Update is there - execute update
  356. try
  357. {
  358. var serviceName = _isRunningAsService ? BackgroundService.Name : string.Empty;
  359. new ApplicationUpdater().UpdateApplication(MBApplication.MBServer, appPaths, updateArchive, logger, serviceName);
  360. // And just let the app exit so it can update
  361. return true;
  362. }
  363. catch (Exception e)
  364. {
  365. logger.ErrorException("Error starting updater.", e);
  366. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  367. }
  368. }
  369. return false;
  370. }
  371. public static void Shutdown()
  372. {
  373. if (_isRunningAsService)
  374. {
  375. ShutdownWindowsService();
  376. }
  377. else
  378. {
  379. ShutdownWindowsApplication();
  380. }
  381. }
  382. public static void Restart()
  383. {
  384. _logger.Info("Disposing app host");
  385. _appHost.Dispose();
  386. if (!_isRunningAsService)
  387. {
  388. _logger.Info("Executing windows forms restart");
  389. System.Windows.Forms.Application.Restart();
  390. ShutdownWindowsApplication();
  391. }
  392. }
  393. private static void ShutdownWindowsApplication()
  394. {
  395. _app.Dispatcher.Invoke(_app.Shutdown);
  396. }
  397. private static void ShutdownWindowsService()
  398. {
  399. _logger.Info("Stopping background service");
  400. var service = new ServiceController(BackgroundService.Name);
  401. service.Refresh();
  402. if (service.Status == ServiceControllerStatus.Running)
  403. {
  404. service.Stop();
  405. }
  406. }
  407. /// <summary>
  408. /// Sets the error mode.
  409. /// </summary>
  410. /// <param name="uMode">The u mode.</param>
  411. /// <returns>ErrorModes.</returns>
  412. [DllImport("kernel32.dll")]
  413. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  414. /// <summary>
  415. /// Enum ErrorModes
  416. /// </summary>
  417. [Flags]
  418. public enum ErrorModes : uint
  419. {
  420. /// <summary>
  421. /// The SYSTE m_ DEFAULT
  422. /// </summary>
  423. SYSTEM_DEFAULT = 0x0,
  424. /// <summary>
  425. /// The SE m_ FAILCRITICALERRORS
  426. /// </summary>
  427. SEM_FAILCRITICALERRORS = 0x0001,
  428. /// <summary>
  429. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  430. /// </summary>
  431. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  432. /// <summary>
  433. /// The SE m_ NOGPFAULTERRORBOX
  434. /// </summary>
  435. SEM_NOGPFAULTERRORBOX = 0x0002,
  436. /// <summary>
  437. /// The SE m_ NOOPENFILEERRORBOX
  438. /// </summary>
  439. SEM_NOOPENFILEERRORBOX = 0x8000
  440. }
  441. }
  442. }