MainStartup.cs 19 KB

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