MainStartup.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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. private static bool _appHostDisposed;
  30. [DllImport("kernel32.dll", SetLastError = true)]
  31. static extern bool SetDllDirectory(string lpPathName);
  32. /// <summary>
  33. /// Defines the entry point of the application.
  34. /// </summary>
  35. public static void Main()
  36. {
  37. var options = new StartupOptions();
  38. _isRunningAsService = options.ContainsOption("-service");
  39. var currentProcess = Process.GetCurrentProcess();
  40. var applicationPath = currentProcess.MainModule.FileName;
  41. var architecturePath = Path.Combine(Path.GetDirectoryName(applicationPath), Environment.Is64BitProcess ? "x64" : "x86");
  42. var success = SetDllDirectory(architecturePath);
  43. var appPaths = CreateApplicationPaths(applicationPath, _isRunningAsService);
  44. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  45. logManager.ReloadLogger(LogSeverity.Debug);
  46. logManager.AddConsoleOutput();
  47. var logger = _logger = logManager.GetLogger("Main");
  48. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  49. // Install directly
  50. if (options.ContainsOption("-installservice"))
  51. {
  52. logger.Info("Performing service installation");
  53. InstallService(applicationPath, logger);
  54. return;
  55. }
  56. // Restart with admin rights, then install
  57. if (options.ContainsOption("-installserviceasadmin"))
  58. {
  59. logger.Info("Performing service installation");
  60. RunServiceInstallation(applicationPath);
  61. return;
  62. }
  63. // Uninstall directly
  64. if (options.ContainsOption("-uninstallservice"))
  65. {
  66. logger.Info("Performing service uninstallation");
  67. UninstallService(applicationPath, logger);
  68. return;
  69. }
  70. // Restart with admin rights, then uninstall
  71. if (options.ContainsOption("-uninstallserviceasadmin"))
  72. {
  73. logger.Info("Performing service uninstallation");
  74. RunServiceUninstallation(applicationPath);
  75. return;
  76. }
  77. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  78. RunServiceInstallationIfNeeded(applicationPath);
  79. if (IsAlreadyRunning(applicationPath, currentProcess))
  80. {
  81. logger.Info("Shutting down because another instance of Media Browser Server is already running.");
  82. return;
  83. }
  84. if (PerformUpdateIfNeeded(appPaths, logger))
  85. {
  86. logger.Info("Exiting to perform application update.");
  87. return;
  88. }
  89. try
  90. {
  91. RunApplication(appPaths, logManager, _isRunningAsService, options);
  92. }
  93. finally
  94. {
  95. OnServiceShutdown();
  96. }
  97. }
  98. /// <summary>
  99. /// Determines whether [is already running] [the specified current process].
  100. /// </summary>
  101. /// <param name="applicationPath">The application path.</param>
  102. /// <param name="currentProcess">The current process.</param>
  103. /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
  104. private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
  105. {
  106. var filename = Path.GetFileName(applicationPath);
  107. var duplicate = Process.GetProcesses().FirstOrDefault(i =>
  108. {
  109. try
  110. {
  111. return string.Equals(filename, Path.GetFileName(i.MainModule.FileName)) && currentProcess.Id != i.Id;
  112. }
  113. catch (Exception)
  114. {
  115. return false;
  116. }
  117. });
  118. if (duplicate != null)
  119. {
  120. _logger.Info("Found a duplicate process. Giving it time to exit.");
  121. if (!duplicate.WaitForExit(10000))
  122. {
  123. _logger.Info("The duplicate process did not exit.");
  124. return true;
  125. }
  126. }
  127. return false;
  128. }
  129. /// <summary>
  130. /// Creates the application paths.
  131. /// </summary>
  132. /// <param name="applicationPath">The application path.</param>
  133. /// <param name="runAsService">if set to <c>true</c> [run as service].</param>
  134. /// <returns>ServerApplicationPaths.</returns>
  135. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService)
  136. {
  137. var resourcesPath = Path.GetDirectoryName(applicationPath);
  138. if (runAsService)
  139. {
  140. var systemPath = Path.GetDirectoryName(applicationPath);
  141. var programDataPath = Path.GetDirectoryName(systemPath);
  142. return new ServerApplicationPaths(programDataPath, applicationPath, resourcesPath);
  143. }
  144. return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), applicationPath, resourcesPath);
  145. }
  146. /// <summary>
  147. /// Gets a value indicating whether this instance can self restart.
  148. /// </summary>
  149. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  150. public static bool CanSelfRestart
  151. {
  152. get
  153. {
  154. return !_isRunningAsService;
  155. }
  156. }
  157. /// <summary>
  158. /// Gets a value indicating whether this instance can self update.
  159. /// </summary>
  160. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  161. public static bool CanSelfUpdate
  162. {
  163. get
  164. {
  165. return !_isRunningAsService;
  166. }
  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. /// <param name="options">The options.</param>
  176. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
  177. {
  178. var fileSystem = new WindowsFileSystem(new PatternsLogger(logManager.GetLogger("FileSystem")));
  179. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  180. var nativeApp = new WindowsApp(fileSystem)
  181. {
  182. IsRunningAsService = runService
  183. };
  184. _appHost = new ApplicationHost(appPaths,
  185. logManager,
  186. options,
  187. fileSystem,
  188. "MBServer",
  189. nativeApp);
  190. var initProgress = new Progress<double>();
  191. if (!runService)
  192. {
  193. if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  194. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  195. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  196. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  197. }
  198. var task = _appHost.Init(initProgress);
  199. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()));
  200. if (runService)
  201. {
  202. StartService(logManager);
  203. }
  204. else
  205. {
  206. Task.WaitAll(task);
  207. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  208. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  209. HideSplashScreen();
  210. ShowTrayIcon();
  211. task = ApplicationTaskCompletionSource.Task;
  212. Task.WaitAll(task);
  213. }
  214. }
  215. private static ServerNotifyIcon _serverNotifyIcon;
  216. private static void ShowTrayIcon()
  217. {
  218. //Application.EnableVisualStyles();
  219. //Application.SetCompatibleTextRenderingDefault(false);
  220. _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
  221. Application.Run();
  222. }
  223. private static SplashForm _splash;
  224. private static Thread _splashThread;
  225. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  226. {
  227. var thread = new Thread(() =>
  228. {
  229. _splash = new SplashForm(appVersion, progress);
  230. _splash.ShowDialog();
  231. });
  232. thread.SetApartmentState(ApartmentState.STA);
  233. thread.IsBackground = true;
  234. thread.Start();
  235. _splashThread = thread;
  236. }
  237. private static void HideSplashScreen()
  238. {
  239. if (_splash != null)
  240. {
  241. Action act = () =>
  242. {
  243. _splash.Close();
  244. _splashThread = null;
  245. };
  246. _splash.Invoke(act);
  247. }
  248. }
  249. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  250. {
  251. if (e.Reason == SessionSwitchReason.SessionLogon)
  252. {
  253. BrowserLauncher.OpenDashboard(_appHost, _logger);
  254. }
  255. }
  256. /// <summary>
  257. /// Starts the service.
  258. /// </summary>
  259. private static void StartService(ILogManager logManager)
  260. {
  261. var service = new BackgroundService(logManager.GetLogger("Service"));
  262. service.Disposed += service_Disposed;
  263. ServiceBase.Run(service);
  264. }
  265. /// <summary>
  266. /// Handles the Disposed event of the service control.
  267. /// </summary>
  268. /// <param name="sender">The source of the event.</param>
  269. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  270. static void service_Disposed(object sender, EventArgs e)
  271. {
  272. ApplicationTaskCompletionSource.SetResult(true);
  273. OnServiceShutdown();
  274. }
  275. private static void OnServiceShutdown()
  276. {
  277. _logger.Info("Shutting down");
  278. DisposeAppHost();
  279. }
  280. /// <summary>
  281. /// Installs the service.
  282. /// </summary>
  283. private static void InstallService(string applicationPath, ILogger logger)
  284. {
  285. try
  286. {
  287. ManagedInstallerClass.InstallHelper(new[] { applicationPath });
  288. logger.Info("Service installation succeeded");
  289. }
  290. catch (Exception ex)
  291. {
  292. logger.ErrorException("Uninstall failed", ex);
  293. }
  294. }
  295. /// <summary>
  296. /// Uninstalls the service.
  297. /// </summary>
  298. private static void UninstallService(string applicationPath, ILogger logger)
  299. {
  300. try
  301. {
  302. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  303. logger.Info("Service uninstallation succeeded");
  304. }
  305. catch (Exception ex)
  306. {
  307. logger.ErrorException("Uninstall failed", ex);
  308. }
  309. }
  310. private static void RunServiceInstallationIfNeeded(string applicationPath)
  311. {
  312. var serviceName = BackgroundService.GetExistingServiceName();
  313. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
  314. if (ctl == null)
  315. {
  316. RunServiceInstallation(applicationPath);
  317. }
  318. }
  319. /// <summary>
  320. /// Runs the service installation.
  321. /// </summary>
  322. private static void RunServiceInstallation(string applicationPath)
  323. {
  324. var startInfo = new ProcessStartInfo
  325. {
  326. FileName = applicationPath,
  327. Arguments = "-installservice",
  328. CreateNoWindow = true,
  329. WindowStyle = ProcessWindowStyle.Hidden,
  330. Verb = "runas",
  331. ErrorDialog = false
  332. };
  333. using (var process = Process.Start(startInfo))
  334. {
  335. process.WaitForExit();
  336. }
  337. }
  338. /// <summary>
  339. /// Runs the service uninstallation.
  340. /// </summary>
  341. private static void RunServiceUninstallation(string applicationPath)
  342. {
  343. var startInfo = new ProcessStartInfo
  344. {
  345. FileName = applicationPath,
  346. Arguments = "-uninstallservice",
  347. CreateNoWindow = true,
  348. WindowStyle = ProcessWindowStyle.Hidden,
  349. Verb = "runas",
  350. ErrorDialog = false
  351. };
  352. using (var process = Process.Start(startInfo))
  353. {
  354. process.WaitForExit();
  355. }
  356. }
  357. /// <summary>
  358. /// Handles the SessionEnding event of the SystemEvents control.
  359. /// </summary>
  360. /// <param name="sender">The source of the event.</param>
  361. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  362. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  363. {
  364. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  365. {
  366. Shutdown();
  367. }
  368. }
  369. /// <summary>
  370. /// Handles the UnhandledException event of the CurrentDomain control.
  371. /// </summary>
  372. /// <param name="sender">The source of the event.</param>
  373. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  374. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  375. {
  376. var exception = (Exception)e.ExceptionObject;
  377. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception);
  378. if (!_isRunningAsService)
  379. {
  380. MessageBox.Show("Unhandled exception: " + exception.Message);
  381. }
  382. if (!Debugger.IsAttached)
  383. {
  384. Environment.Exit(Marshal.GetHRForException(exception));
  385. }
  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.GetExistingServiceName() : 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. DisposeAppHost();
  425. ShutdownWindowsApplication();
  426. }
  427. }
  428. public static void Restart()
  429. {
  430. DisposeAppHost();
  431. if (!_isRunningAsService)
  432. {
  433. //_logger.Info("Hiding server notify icon");
  434. //_serverNotifyIcon.Visible = false;
  435. _logger.Info("Starting new instance");
  436. //Application.Restart();
  437. Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath);
  438. ShutdownWindowsApplication();
  439. }
  440. }
  441. private static void DisposeAppHost()
  442. {
  443. if (!_appHostDisposed)
  444. {
  445. _logger.Info("Disposing app host");
  446. _appHostDisposed = true;
  447. _appHost.Dispose();
  448. }
  449. }
  450. private static void ShutdownWindowsApplication()
  451. {
  452. _logger.Info("Calling Application.Exit");
  453. Application.Exit();
  454. Environment.Exit(0);
  455. _logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
  456. ApplicationTaskCompletionSource.SetResult(true);
  457. }
  458. private static void ShutdownWindowsService()
  459. {
  460. _logger.Info("Stopping background service");
  461. var service = new ServiceController(BackgroundService.GetExistingServiceName());
  462. service.Refresh();
  463. if (service.Status == ServiceControllerStatus.Running)
  464. {
  465. service.Stop();
  466. }
  467. }
  468. /// <summary>
  469. /// Sets the error mode.
  470. /// </summary>
  471. /// <param name="uMode">The u mode.</param>
  472. /// <returns>ErrorModes.</returns>
  473. [DllImport("kernel32.dll")]
  474. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  475. /// <summary>
  476. /// Enum ErrorModes
  477. /// </summary>
  478. [Flags]
  479. public enum ErrorModes : uint
  480. {
  481. /// <summary>
  482. /// The SYSTE m_ DEFAULT
  483. /// </summary>
  484. SYSTEM_DEFAULT = 0x0,
  485. /// <summary>
  486. /// The SE m_ FAILCRITICALERRORS
  487. /// </summary>
  488. SEM_FAILCRITICALERRORS = 0x0001,
  489. /// <summary>
  490. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  491. /// </summary>
  492. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  493. /// <summary>
  494. /// The SE m_ NOGPFAULTERRORBOX
  495. /// </summary>
  496. SEM_NOGPFAULTERRORBOX = 0x0002,
  497. /// <summary>
  498. /// The SE m_ NOOPENFILEERRORBOX
  499. /// </summary>
  500. SEM_NOOPENFILEERRORBOX = 0x8000
  501. }
  502. }
  503. }