MainStartup.cs 18 KB

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