MainStartup.cs 20 KB

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