MainStartup.cs 19 KB

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