MainStartup.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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. logger.Info("Media Browser Server started");
  168. ApplicationHost.LogEnvironmentInfo(logger, appPaths);
  169. }
  170. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  171. /// <summary>
  172. /// Runs the application.
  173. /// </summary>
  174. /// <param name="appPaths">The app paths.</param>
  175. /// <param name="logManager">The log manager.</param>
  176. /// <param name="runService">if set to <c>true</c> [run service].</param>
  177. /// <param name="options">The options.</param>
  178. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
  179. {
  180. var fileSystem = new NativeFileSystem(logManager.GetLogger("FileSystem"), false);
  181. var nativeApp = new WindowsApp
  182. {
  183. IsRunningAsService = runService
  184. };
  185. _appHost = new ApplicationHost(appPaths,
  186. logManager,
  187. options,
  188. fileSystem,
  189. "MBServer",
  190. true,
  191. nativeApp);
  192. var initProgress = new Progress<double>();
  193. if (!runService)
  194. {
  195. if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  196. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  197. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  198. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  199. }
  200. var task = _appHost.Init(initProgress);
  201. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()));
  202. if (runService)
  203. {
  204. StartService(logManager);
  205. }
  206. else
  207. {
  208. Task.WaitAll(task);
  209. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  210. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  211. HideSplashScreen();
  212. ShowTrayIcon();
  213. task = ApplicationTaskCompletionSource.Task;
  214. Task.WaitAll(task);
  215. }
  216. }
  217. private static ServerNotifyIcon _serverNotifyIcon;
  218. private static void ShowTrayIcon()
  219. {
  220. //Application.EnableVisualStyles();
  221. //Application.SetCompatibleTextRenderingDefault(false);
  222. _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
  223. Application.Run();
  224. }
  225. private static SplashForm _splash;
  226. private static Thread _splashThread;
  227. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  228. {
  229. var thread = new Thread(() =>
  230. {
  231. _splash = new SplashForm(appVersion, progress);
  232. _splash.ShowDialog();
  233. });
  234. thread.SetApartmentState(ApartmentState.STA);
  235. thread.IsBackground = true;
  236. thread.Start();
  237. _splashThread = thread;
  238. }
  239. private static void HideSplashScreen()
  240. {
  241. if (_splash != null)
  242. {
  243. Action act = () =>
  244. {
  245. _splash.Close();
  246. _splashThread = null;
  247. };
  248. _splash.Invoke(act);
  249. }
  250. }
  251. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  252. {
  253. if (e.Reason == SessionSwitchReason.SessionLogon)
  254. {
  255. BrowserLauncher.OpenDashboard(_appHost, _logger);
  256. }
  257. }
  258. /// <summary>
  259. /// Starts the service.
  260. /// </summary>
  261. private static void StartService(ILogManager logManager)
  262. {
  263. var service = new BackgroundService(logManager.GetLogger("Service"));
  264. service.Disposed += service_Disposed;
  265. ServiceBase.Run(service);
  266. }
  267. /// <summary>
  268. /// Handles the Disposed event of the service control.
  269. /// </summary>
  270. /// <param name="sender">The source of the event.</param>
  271. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  272. static void service_Disposed(object sender, EventArgs e)
  273. {
  274. ApplicationTaskCompletionSource.SetResult(true);
  275. OnServiceShutdown();
  276. }
  277. private static void OnServiceShutdown()
  278. {
  279. _logger.Info("Shutting down");
  280. _appHost.Dispose();
  281. if (!_isRunningAsService)
  282. {
  283. SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
  284. }
  285. }
  286. /// <summary>
  287. /// Installs the service.
  288. /// </summary>
  289. private static void InstallService(string applicationPath, ILogger logger)
  290. {
  291. try
  292. {
  293. ManagedInstallerClass.InstallHelper(new[] { applicationPath });
  294. logger.Info("Service installation succeeded");
  295. }
  296. catch (Exception ex)
  297. {
  298. logger.ErrorException("Uninstall failed", ex);
  299. }
  300. }
  301. /// <summary>
  302. /// Uninstalls the service.
  303. /// </summary>
  304. private static void UninstallService(string applicationPath, ILogger logger)
  305. {
  306. try
  307. {
  308. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  309. logger.Info("Service uninstallation succeeded");
  310. }
  311. catch (Exception ex)
  312. {
  313. logger.ErrorException("Uninstall failed", ex);
  314. }
  315. }
  316. private static void RunServiceInstallationIfNeeded(string applicationPath)
  317. {
  318. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == BackgroundService.Name);
  319. if (ctl == null)
  320. {
  321. RunServiceInstallation(applicationPath);
  322. }
  323. }
  324. /// <summary>
  325. /// Runs the service installation.
  326. /// </summary>
  327. private static void RunServiceInstallation(string applicationPath)
  328. {
  329. var startInfo = new ProcessStartInfo
  330. {
  331. FileName = applicationPath,
  332. Arguments = "-installservice",
  333. CreateNoWindow = true,
  334. WindowStyle = ProcessWindowStyle.Hidden,
  335. Verb = "runas",
  336. ErrorDialog = false
  337. };
  338. using (var process = Process.Start(startInfo))
  339. {
  340. process.WaitForExit();
  341. }
  342. }
  343. /// <summary>
  344. /// Runs the service uninstallation.
  345. /// </summary>
  346. private static void RunServiceUninstallation(string applicationPath)
  347. {
  348. var startInfo = new ProcessStartInfo
  349. {
  350. FileName = applicationPath,
  351. Arguments = "-uninstallservice",
  352. CreateNoWindow = true,
  353. WindowStyle = ProcessWindowStyle.Hidden,
  354. Verb = "runas",
  355. ErrorDialog = false
  356. };
  357. using (var process = Process.Start(startInfo))
  358. {
  359. process.WaitForExit();
  360. }
  361. }
  362. /// <summary>
  363. /// Handles the SessionEnding event of the SystemEvents control.
  364. /// </summary>
  365. /// <param name="sender">The source of the event.</param>
  366. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  367. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  368. {
  369. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  370. {
  371. Shutdown();
  372. }
  373. }
  374. /// <summary>
  375. /// Handles the UnhandledException event of the CurrentDomain control.
  376. /// </summary>
  377. /// <param name="sender">The source of the event.</param>
  378. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  379. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  380. {
  381. var exception = (Exception)e.ExceptionObject;
  382. LogUnhandledException(exception);
  383. _appHost.LogManager.Flush();
  384. if (!_isRunningAsService)
  385. {
  386. MessageBox.Show("Unhandled exception: " + exception.Message);
  387. }
  388. if (!Debugger.IsAttached)
  389. {
  390. Environment.Exit(Marshal.GetHRForException(exception));
  391. }
  392. }
  393. private static void LogUnhandledException(Exception ex)
  394. {
  395. _logger.ErrorException("UnhandledException", ex);
  396. var path = Path.Combine(_appHost.ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "unhandled_" + Guid.NewGuid() + ".txt");
  397. Directory.CreateDirectory(Path.GetDirectoryName(path));
  398. var builder = LogHelper.GetLogMessage(ex);
  399. File.WriteAllText(path, builder.ToString());
  400. }
  401. /// <summary>
  402. /// Performs the update if needed.
  403. /// </summary>
  404. /// <param name="appPaths">The app paths.</param>
  405. /// <param name="logger">The logger.</param>
  406. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  407. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  408. {
  409. // Look for the existence of an update archive
  410. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  411. if (File.Exists(updateArchive))
  412. {
  413. logger.Info("An update is available from {0}", updateArchive);
  414. // Update is there - execute update
  415. try
  416. {
  417. var serviceName = _isRunningAsService ? BackgroundService.Name : string.Empty;
  418. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  419. // And just let the app exit so it can update
  420. return true;
  421. }
  422. catch (Exception e)
  423. {
  424. logger.ErrorException("Error starting updater.", e);
  425. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  426. }
  427. }
  428. return false;
  429. }
  430. public static void Shutdown()
  431. {
  432. if (_isRunningAsService)
  433. {
  434. ShutdownWindowsService();
  435. }
  436. else
  437. {
  438. ShutdownWindowsApplication();
  439. }
  440. }
  441. public static void Restart()
  442. {
  443. _logger.Info("Disposing app host");
  444. _appHost.Dispose();
  445. if (!_isRunningAsService)
  446. {
  447. _logger.Info("Hiding server notify icon");
  448. _serverNotifyIcon.Visible = false;
  449. _logger.Info("Executing windows forms restart");
  450. //Application.Restart();
  451. Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath);
  452. _logger.Info("Calling Application.Exit");
  453. Environment.Exit(0);
  454. }
  455. }
  456. private static void ShutdownWindowsApplication()
  457. {
  458. _logger.Info("Hiding server notify icon");
  459. _serverNotifyIcon.Visible = false;
  460. _logger.Info("Calling Application.Exit");
  461. Application.Exit();
  462. _logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
  463. ApplicationTaskCompletionSource.SetResult(true);
  464. }
  465. private static void ShutdownWindowsService()
  466. {
  467. _logger.Info("Stopping background service");
  468. var service = new ServiceController(BackgroundService.Name);
  469. service.Refresh();
  470. if (service.Status == ServiceControllerStatus.Running)
  471. {
  472. service.Stop();
  473. }
  474. }
  475. /// <summary>
  476. /// Sets the error mode.
  477. /// </summary>
  478. /// <param name="uMode">The u mode.</param>
  479. /// <returns>ErrorModes.</returns>
  480. [DllImport("kernel32.dll")]
  481. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  482. /// <summary>
  483. /// Enum ErrorModes
  484. /// </summary>
  485. [Flags]
  486. public enum ErrorModes : uint
  487. {
  488. /// <summary>
  489. /// The SYSTE m_ DEFAULT
  490. /// </summary>
  491. SYSTEM_DEFAULT = 0x0,
  492. /// <summary>
  493. /// The SE m_ FAILCRITICALERRORS
  494. /// </summary>
  495. SEM_FAILCRITICALERRORS = 0x0001,
  496. /// <summary>
  497. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  498. /// </summary>
  499. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  500. /// <summary>
  501. /// The SE m_ NOGPFAULTERRORBOX
  502. /// </summary>
  503. SEM_NOGPFAULTERRORBOX = 0x0002,
  504. /// <summary>
  505. /// The SE m_ NOOPENFILEERRORBOX
  506. /// </summary>
  507. SEM_NOOPENFILEERRORBOX = 0x8000
  508. }
  509. }
  510. }