MainStartup.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. using CommonIO.Windows;
  21. using MediaBrowser.Server.Implementations.Logging;
  22. namespace MediaBrowser.ServerApplication
  23. {
  24. public class MainStartup
  25. {
  26. private static ApplicationHost _appHost;
  27. private static ILogger _logger;
  28. private static bool _isRunningAsService = false;
  29. /// <summary>
  30. /// Defines the entry point of the application.
  31. /// </summary>
  32. public static void Main()
  33. {
  34. var options = new StartupOptions();
  35. _isRunningAsService = options.ContainsOption("-service");
  36. var currentProcess = Process.GetCurrentProcess();
  37. var applicationPath = currentProcess.MainModule.FileName;
  38. var appPaths = CreateApplicationPaths(applicationPath, _isRunningAsService);
  39. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  40. logManager.ReloadLogger(LogSeverity.Debug);
  41. logManager.AddConsoleOutput();
  42. var logger = _logger = logManager.GetLogger("Main");
  43. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  44. // Install directly
  45. if (options.ContainsOption("-installservice"))
  46. {
  47. logger.Info("Performing service installation");
  48. InstallService(applicationPath, logger);
  49. return;
  50. }
  51. // Restart with admin rights, then install
  52. if (options.ContainsOption("-installserviceasadmin"))
  53. {
  54. logger.Info("Performing service installation");
  55. RunServiceInstallation(applicationPath);
  56. return;
  57. }
  58. // Uninstall directly
  59. if (options.ContainsOption("-uninstallservice"))
  60. {
  61. logger.Info("Performing service uninstallation");
  62. UninstallService(applicationPath, logger);
  63. return;
  64. }
  65. // Restart with admin rights, then uninstall
  66. if (options.ContainsOption("-uninstallserviceasadmin"))
  67. {
  68. logger.Info("Performing service uninstallation");
  69. RunServiceUninstallation(applicationPath);
  70. return;
  71. }
  72. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  73. RunServiceInstallationIfNeeded(applicationPath);
  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, options);
  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="applicationPath">The application path.</param>
  97. /// <param name="currentProcess">The current process.</param>
  98. /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
  99. private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
  100. {
  101. var filename = Path.GetFileName(applicationPath);
  102. var duplicate = Process.GetProcesses().FirstOrDefault(i =>
  103. {
  104. try
  105. {
  106. return string.Equals(filename, Path.GetFileName(i.MainModule.FileName)) && currentProcess.Id != i.Id;
  107. }
  108. catch (Exception)
  109. {
  110. return false;
  111. }
  112. });
  113. if (duplicate != null)
  114. {
  115. _logger.Info("Found a duplicate process. Giving it time to exit.");
  116. if (!duplicate.WaitForExit(10000))
  117. {
  118. _logger.Info("The duplicate process did not exit.");
  119. return true;
  120. }
  121. }
  122. return false;
  123. }
  124. /// <summary>
  125. /// Creates the application paths.
  126. /// </summary>
  127. /// <param name="applicationPath">The application path.</param>
  128. /// <param name="runAsService">if set to <c>true</c> [run as service].</param>
  129. /// <returns>ServerApplicationPaths.</returns>
  130. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService)
  131. {
  132. var resourcesPath = Path.GetDirectoryName(applicationPath);
  133. if (runAsService)
  134. {
  135. var systemPath = Path.GetDirectoryName(applicationPath);
  136. var programDataPath = Path.GetDirectoryName(systemPath);
  137. return new ServerApplicationPaths(programDataPath, applicationPath, resourcesPath);
  138. }
  139. return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), applicationPath, resourcesPath);
  140. }
  141. /// <summary>
  142. /// Gets a value indicating whether this instance can self restart.
  143. /// </summary>
  144. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  145. public static bool CanSelfRestart
  146. {
  147. get
  148. {
  149. return !_isRunningAsService;
  150. }
  151. }
  152. /// <summary>
  153. /// Gets a value indicating whether this instance can self update.
  154. /// </summary>
  155. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  156. public static bool CanSelfUpdate
  157. {
  158. get
  159. {
  160. return !_isRunningAsService;
  161. }
  162. }
  163. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  164. /// <summary>
  165. /// Runs the application.
  166. /// </summary>
  167. /// <param name="appPaths">The app paths.</param>
  168. /// <param name="logManager">The log manager.</param>
  169. /// <param name="runService">if set to <c>true</c> [run service].</param>
  170. /// <param name="options">The options.</param>
  171. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
  172. {
  173. var fileSystem = new WindowsFileSystem(new PatternsLogger(logManager.GetLogger("FileSystem")));
  174. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  175. var nativeApp = new WindowsApp(fileSystem)
  176. {
  177. IsRunningAsService = runService
  178. };
  179. _appHost = new ApplicationHost(appPaths,
  180. logManager,
  181. options,
  182. fileSystem,
  183. "MBServer",
  184. nativeApp);
  185. var initProgress = new Progress<double>();
  186. if (!runService)
  187. {
  188. if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  189. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  190. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  191. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  192. }
  193. var task = _appHost.Init(initProgress);
  194. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()));
  195. if (runService)
  196. {
  197. StartService(logManager);
  198. }
  199. else
  200. {
  201. Task.WaitAll(task);
  202. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  203. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  204. HideSplashScreen();
  205. ShowTrayIcon();
  206. task = ApplicationTaskCompletionSource.Task;
  207. Task.WaitAll(task);
  208. }
  209. }
  210. private static ServerNotifyIcon _serverNotifyIcon;
  211. private static void ShowTrayIcon()
  212. {
  213. //Application.EnableVisualStyles();
  214. //Application.SetCompatibleTextRenderingDefault(false);
  215. _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
  216. Application.Run();
  217. }
  218. private static SplashForm _splash;
  219. private static Thread _splashThread;
  220. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  221. {
  222. var thread = new Thread(() =>
  223. {
  224. _splash = new SplashForm(appVersion, progress);
  225. _splash.ShowDialog();
  226. });
  227. thread.SetApartmentState(ApartmentState.STA);
  228. thread.IsBackground = true;
  229. thread.Start();
  230. _splashThread = thread;
  231. }
  232. private static void HideSplashScreen()
  233. {
  234. if (_splash != null)
  235. {
  236. Action act = () =>
  237. {
  238. _splash.Close();
  239. _splashThread = null;
  240. };
  241. _splash.Invoke(act);
  242. }
  243. }
  244. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  245. {
  246. if (e.Reason == SessionSwitchReason.SessionLogon)
  247. {
  248. BrowserLauncher.OpenDashboard(_appHost, _logger);
  249. }
  250. }
  251. /// <summary>
  252. /// Starts the service.
  253. /// </summary>
  254. private static void StartService(ILogManager logManager)
  255. {
  256. var service = new BackgroundService(logManager.GetLogger("Service"));
  257. service.Disposed += service_Disposed;
  258. ServiceBase.Run(service);
  259. }
  260. /// <summary>
  261. /// Handles the Disposed event of the service control.
  262. /// </summary>
  263. /// <param name="sender">The source of the event.</param>
  264. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  265. static void service_Disposed(object sender, EventArgs e)
  266. {
  267. ApplicationTaskCompletionSource.SetResult(true);
  268. OnServiceShutdown();
  269. }
  270. private static void OnServiceShutdown()
  271. {
  272. _logger.Info("Shutting down");
  273. _appHost.Dispose();
  274. if (!_isRunningAsService)
  275. {
  276. SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
  277. }
  278. }
  279. /// <summary>
  280. /// Installs the service.
  281. /// </summary>
  282. private static void InstallService(string applicationPath, ILogger logger)
  283. {
  284. try
  285. {
  286. ManagedInstallerClass.InstallHelper(new[] { applicationPath });
  287. logger.Info("Service installation succeeded");
  288. }
  289. catch (Exception ex)
  290. {
  291. logger.ErrorException("Uninstall failed", ex);
  292. }
  293. }
  294. /// <summary>
  295. /// Uninstalls the service.
  296. /// </summary>
  297. private static void UninstallService(string applicationPath, ILogger logger)
  298. {
  299. try
  300. {
  301. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  302. logger.Info("Service uninstallation succeeded");
  303. }
  304. catch (Exception ex)
  305. {
  306. logger.ErrorException("Uninstall failed", ex);
  307. }
  308. }
  309. private static void RunServiceInstallationIfNeeded(string applicationPath)
  310. {
  311. var serviceName = BackgroundService.GetExistingServiceName();
  312. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
  313. if (ctl == null)
  314. {
  315. RunServiceInstallation(applicationPath);
  316. }
  317. }
  318. /// <summary>
  319. /// Runs the service installation.
  320. /// </summary>
  321. private static void RunServiceInstallation(string applicationPath)
  322. {
  323. var startInfo = new ProcessStartInfo
  324. {
  325. FileName = applicationPath,
  326. Arguments = "-installservice",
  327. CreateNoWindow = true,
  328. WindowStyle = ProcessWindowStyle.Hidden,
  329. Verb = "runas",
  330. ErrorDialog = false
  331. };
  332. using (var process = Process.Start(startInfo))
  333. {
  334. process.WaitForExit();
  335. }
  336. }
  337. /// <summary>
  338. /// Runs the service uninstallation.
  339. /// </summary>
  340. private static void RunServiceUninstallation(string applicationPath)
  341. {
  342. var startInfo = new ProcessStartInfo
  343. {
  344. FileName = applicationPath,
  345. Arguments = "-uninstallservice",
  346. CreateNoWindow = true,
  347. WindowStyle = ProcessWindowStyle.Hidden,
  348. Verb = "runas",
  349. ErrorDialog = false
  350. };
  351. using (var process = Process.Start(startInfo))
  352. {
  353. process.WaitForExit();
  354. }
  355. }
  356. /// <summary>
  357. /// Handles the SessionEnding event of the SystemEvents control.
  358. /// </summary>
  359. /// <param name="sender">The source of the event.</param>
  360. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  361. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  362. {
  363. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  364. {
  365. Shutdown();
  366. }
  367. }
  368. /// <summary>
  369. /// Handles the UnhandledException event of the CurrentDomain control.
  370. /// </summary>
  371. /// <param name="sender">The source of the event.</param>
  372. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  373. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  374. {
  375. var exception = (Exception)e.ExceptionObject;
  376. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception);
  377. if (!_isRunningAsService)
  378. {
  379. MessageBox.Show("Unhandled exception: " + exception.Message);
  380. }
  381. if (!Debugger.IsAttached)
  382. {
  383. Environment.Exit(Marshal.GetHRForException(exception));
  384. }
  385. }
  386. /// <summary>
  387. /// Performs the update if needed.
  388. /// </summary>
  389. /// <param name="appPaths">The app paths.</param>
  390. /// <param name="logger">The logger.</param>
  391. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  392. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  393. {
  394. // Look for the existence of an update archive
  395. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  396. if (File.Exists(updateArchive))
  397. {
  398. logger.Info("An update is available from {0}", updateArchive);
  399. // Update is there - execute update
  400. try
  401. {
  402. var serviceName = _isRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty;
  403. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  404. // And just let the app exit so it can update
  405. return true;
  406. }
  407. catch (Exception e)
  408. {
  409. logger.ErrorException("Error starting updater.", e);
  410. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  411. }
  412. }
  413. return false;
  414. }
  415. public static void Shutdown()
  416. {
  417. if (_isRunningAsService)
  418. {
  419. ShutdownWindowsService();
  420. }
  421. else
  422. {
  423. ShutdownWindowsApplication();
  424. }
  425. }
  426. public static void Restart()
  427. {
  428. _logger.Info("Disposing app host");
  429. _appHost.Dispose();
  430. if (!_isRunningAsService)
  431. {
  432. //_logger.Info("Hiding server notify icon");
  433. //_serverNotifyIcon.Visible = false;
  434. _logger.Info("Starting new instance");
  435. //Application.Restart();
  436. Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath);
  437. ShutdownWindowsApplication();
  438. }
  439. }
  440. private static void ShutdownWindowsApplication()
  441. {
  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.GetExistingServiceName());
  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. }