MainStartup.cs 20 KB

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