MainStartup.cs 20 KB

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