MainStartup.cs 20 KB

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