MainStartup.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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 Emby.Drawing.ImageMagick;
  22. using ImageMagickSharp;
  23. using MediaBrowser.Common.Net;
  24. using MediaBrowser.Server.Implementations.Logging;
  25. namespace MediaBrowser.ServerApplication
  26. {
  27. public class MainStartup
  28. {
  29. private static ApplicationHost _appHost;
  30. private static ILogger _logger;
  31. private static bool _isRunningAsService = false;
  32. private static bool _appHostDisposed;
  33. [DllImport("kernel32.dll", SetLastError = true)]
  34. static extern bool SetDllDirectory(string lpPathName);
  35. /// <summary>
  36. /// Defines the entry point of the application.
  37. /// </summary>
  38. public static void Main()
  39. {
  40. var options = new StartupOptions();
  41. _isRunningAsService = options.ContainsOption("-service");
  42. var currentProcess = Process.GetCurrentProcess();
  43. var applicationPath = currentProcess.MainModule.FileName;
  44. var architecturePath = Path.Combine(Path.GetDirectoryName(applicationPath), Environment.Is64BitProcess ? "x64" : "x86");
  45. Wand.SetMagickCoderModulePath(architecturePath);
  46. var success = SetDllDirectory(architecturePath);
  47. var appPaths = CreateApplicationPaths(applicationPath, _isRunningAsService);
  48. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  49. logManager.ReloadLogger(LogSeverity.Debug);
  50. logManager.AddConsoleOutput();
  51. var logger = _logger = logManager.GetLogger("Main");
  52. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  53. // Install directly
  54. if (options.ContainsOption("-installservice"))
  55. {
  56. logger.Info("Performing service installation");
  57. InstallService(applicationPath, logger);
  58. return;
  59. }
  60. // Restart with admin rights, then install
  61. if (options.ContainsOption("-installserviceasadmin"))
  62. {
  63. logger.Info("Performing service installation");
  64. RunServiceInstallation(applicationPath);
  65. return;
  66. }
  67. // Uninstall directly
  68. if (options.ContainsOption("-uninstallservice"))
  69. {
  70. logger.Info("Performing service uninstallation");
  71. UninstallService(applicationPath, logger);
  72. return;
  73. }
  74. // Restart with admin rights, then uninstall
  75. if (options.ContainsOption("-uninstallserviceasadmin"))
  76. {
  77. logger.Info("Performing service uninstallation");
  78. RunServiceUninstallation(applicationPath);
  79. return;
  80. }
  81. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  82. RunServiceInstallationIfNeeded(applicationPath);
  83. if (IsAlreadyRunning(applicationPath, currentProcess))
  84. {
  85. logger.Info("Shutting down because another instance of Media Browser Server is already running.");
  86. return;
  87. }
  88. if (PerformUpdateIfNeeded(appPaths, logger))
  89. {
  90. logger.Info("Exiting to perform application update.");
  91. return;
  92. }
  93. try
  94. {
  95. RunApplication(appPaths, logManager, _isRunningAsService, options);
  96. }
  97. finally
  98. {
  99. OnServiceShutdown();
  100. }
  101. }
  102. /// <summary>
  103. /// Determines whether [is already running] [the specified current process].
  104. /// </summary>
  105. /// <param name="applicationPath">The application path.</param>
  106. /// <param name="currentProcess">The current process.</param>
  107. /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
  108. private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
  109. {
  110. var filename = Path.GetFileName(applicationPath);
  111. var duplicate = Process.GetProcesses().FirstOrDefault(i =>
  112. {
  113. try
  114. {
  115. return string.Equals(filename, Path.GetFileName(i.MainModule.FileName)) && currentProcess.Id != i.Id;
  116. }
  117. catch (Exception)
  118. {
  119. return false;
  120. }
  121. });
  122. if (duplicate != null)
  123. {
  124. _logger.Info("Found a duplicate process. Giving it time to exit.");
  125. if (!duplicate.WaitForExit(15000))
  126. {
  127. _logger.Info("The duplicate process did not exit.");
  128. return true;
  129. }
  130. }
  131. return false;
  132. }
  133. /// <summary>
  134. /// Creates the application paths.
  135. /// </summary>
  136. /// <param name="applicationPath">The application path.</param>
  137. /// <param name="runAsService">if set to <c>true</c> [run as service].</param>
  138. /// <returns>ServerApplicationPaths.</returns>
  139. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService)
  140. {
  141. var resourcesPath = Path.GetDirectoryName(applicationPath);
  142. if (runAsService)
  143. {
  144. var systemPath = Path.GetDirectoryName(applicationPath);
  145. var programDataPath = Path.GetDirectoryName(systemPath);
  146. return new ServerApplicationPaths(programDataPath, applicationPath, resourcesPath);
  147. }
  148. return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), applicationPath, resourcesPath);
  149. }
  150. /// <summary>
  151. /// Gets a value indicating whether this instance can self restart.
  152. /// </summary>
  153. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  154. public static bool CanSelfRestart
  155. {
  156. get
  157. {
  158. return !_isRunningAsService;
  159. }
  160. }
  161. /// <summary>
  162. /// Gets a value indicating whether this instance can self update.
  163. /// </summary>
  164. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  165. public static bool CanSelfUpdate
  166. {
  167. get
  168. {
  169. return !_isRunningAsService;
  170. }
  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. /// <param name="options">The options.</param>
  180. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
  181. {
  182. var fileSystem = new WindowsFileSystem(new PatternsLogger(logManager.GetLogger("FileSystem")));
  183. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  184. var nativeApp = new WindowsApp(fileSystem, _logger)
  185. {
  186. IsRunningAsService = runService
  187. };
  188. _appHost = new ApplicationHost(appPaths,
  189. logManager,
  190. options,
  191. fileSystem,
  192. "emby.windows.zip",
  193. nativeApp);
  194. var initProgress = new Progress<double>();
  195. if (!runService)
  196. {
  197. if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  198. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  199. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  200. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  201. }
  202. var task = _appHost.Init(initProgress);
  203. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()));
  204. if (runService)
  205. {
  206. StartService(logManager);
  207. }
  208. else
  209. {
  210. Task.WaitAll(task);
  211. task = InstallVcredistIfNeeded(_appHost, _logger);
  212. Task.WaitAll(task);
  213. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  214. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  215. HideSplashScreen();
  216. ShowTrayIcon();
  217. task = ApplicationTaskCompletionSource.Task;
  218. Task.WaitAll(task);
  219. }
  220. }
  221. private static ServerNotifyIcon _serverNotifyIcon;
  222. private static void ShowTrayIcon()
  223. {
  224. //Application.EnableVisualStyles();
  225. //Application.SetCompatibleTextRenderingDefault(false);
  226. _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
  227. Application.Run();
  228. }
  229. private static SplashForm _splash;
  230. private static Thread _splashThread;
  231. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  232. {
  233. var thread = new Thread(() =>
  234. {
  235. _splash = new SplashForm(appVersion, progress);
  236. _splash.ShowDialog();
  237. });
  238. thread.SetApartmentState(ApartmentState.STA);
  239. thread.IsBackground = true;
  240. thread.Start();
  241. _splashThread = thread;
  242. }
  243. private static void HideSplashScreen()
  244. {
  245. if (_splash != null)
  246. {
  247. Action act = () =>
  248. {
  249. _splash.Close();
  250. _splashThread = null;
  251. };
  252. _splash.Invoke(act);
  253. }
  254. }
  255. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  256. {
  257. if (e.Reason == SessionSwitchReason.SessionLogon)
  258. {
  259. BrowserLauncher.OpenDashboard(_appHost, _logger);
  260. }
  261. }
  262. /// <summary>
  263. /// Starts the service.
  264. /// </summary>
  265. private static void StartService(ILogManager logManager)
  266. {
  267. var service = new BackgroundService(logManager.GetLogger("Service"));
  268. service.Disposed += service_Disposed;
  269. ServiceBase.Run(service);
  270. }
  271. /// <summary>
  272. /// Handles the Disposed event of the service control.
  273. /// </summary>
  274. /// <param name="sender">The source of the event.</param>
  275. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  276. static void service_Disposed(object sender, EventArgs e)
  277. {
  278. ApplicationTaskCompletionSource.SetResult(true);
  279. OnServiceShutdown();
  280. }
  281. private static void OnServiceShutdown()
  282. {
  283. _logger.Info("Shutting down");
  284. DisposeAppHost();
  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 serviceName = BackgroundService.GetExistingServiceName();
  319. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
  320. if (ctl == null)
  321. {
  322. RunServiceInstallation(applicationPath);
  323. }
  324. }
  325. /// <summary>
  326. /// Runs the service installation.
  327. /// </summary>
  328. private static void RunServiceInstallation(string applicationPath)
  329. {
  330. var startInfo = new ProcessStartInfo
  331. {
  332. FileName = applicationPath,
  333. Arguments = "-installservice",
  334. CreateNoWindow = true,
  335. WindowStyle = ProcessWindowStyle.Hidden,
  336. Verb = "runas",
  337. ErrorDialog = false
  338. };
  339. using (var process = Process.Start(startInfo))
  340. {
  341. process.WaitForExit();
  342. }
  343. }
  344. /// <summary>
  345. /// Runs the service uninstallation.
  346. /// </summary>
  347. private static void RunServiceUninstallation(string applicationPath)
  348. {
  349. var startInfo = new ProcessStartInfo
  350. {
  351. FileName = applicationPath,
  352. Arguments = "-uninstallservice",
  353. CreateNoWindow = true,
  354. WindowStyle = ProcessWindowStyle.Hidden,
  355. Verb = "runas",
  356. ErrorDialog = false
  357. };
  358. using (var process = Process.Start(startInfo))
  359. {
  360. process.WaitForExit();
  361. }
  362. }
  363. /// <summary>
  364. /// Handles the SessionEnding event of the SystemEvents control.
  365. /// </summary>
  366. /// <param name="sender">The source of the event.</param>
  367. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  368. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  369. {
  370. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  371. {
  372. Shutdown();
  373. }
  374. }
  375. /// <summary>
  376. /// Handles the UnhandledException event of the CurrentDomain control.
  377. /// </summary>
  378. /// <param name="sender">The source of the event.</param>
  379. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  380. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  381. {
  382. var exception = (Exception)e.ExceptionObject;
  383. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception);
  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. /// <summary>
  394. /// Performs the update if needed.
  395. /// </summary>
  396. /// <param name="appPaths">The app paths.</param>
  397. /// <param name="logger">The logger.</param>
  398. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  399. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  400. {
  401. // Look for the existence of an update archive
  402. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  403. if (File.Exists(updateArchive))
  404. {
  405. logger.Info("An update is available from {0}", updateArchive);
  406. // Update is there - execute update
  407. try
  408. {
  409. var serviceName = _isRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty;
  410. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  411. // And just let the app exit so it can update
  412. return true;
  413. }
  414. catch (Exception e)
  415. {
  416. logger.ErrorException("Error starting updater.", e);
  417. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  418. }
  419. }
  420. return false;
  421. }
  422. public static void Shutdown()
  423. {
  424. if (_isRunningAsService)
  425. {
  426. ShutdownWindowsService();
  427. }
  428. else
  429. {
  430. DisposeAppHost();
  431. ShutdownWindowsApplication();
  432. }
  433. }
  434. public static void Restart()
  435. {
  436. DisposeAppHost();
  437. if (!_isRunningAsService)
  438. {
  439. //_logger.Info("Hiding server notify icon");
  440. //_serverNotifyIcon.Visible = false;
  441. _logger.Info("Starting new instance");
  442. //Application.Restart();
  443. Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath);
  444. ShutdownWindowsApplication();
  445. }
  446. }
  447. private static void DisposeAppHost()
  448. {
  449. if (!_appHostDisposed)
  450. {
  451. _logger.Info("Disposing app host");
  452. _appHostDisposed = true;
  453. _appHost.Dispose();
  454. }
  455. }
  456. private static void ShutdownWindowsApplication()
  457. {
  458. _logger.Info("Calling Application.Exit");
  459. Application.Exit();
  460. Environment.Exit(0);
  461. _logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
  462. ApplicationTaskCompletionSource.SetResult(true);
  463. }
  464. private static void ShutdownWindowsService()
  465. {
  466. _logger.Info("Stopping background service");
  467. var service = new ServiceController(BackgroundService.GetExistingServiceName());
  468. service.Refresh();
  469. if (service.Status == ServiceControllerStatus.Running)
  470. {
  471. service.Stop();
  472. }
  473. }
  474. private static async Task InstallVcredistIfNeeded(ApplicationHost appHost, ILogger logger)
  475. {
  476. try
  477. {
  478. var version = ImageMagickEncoder.GetVersion();
  479. return;
  480. }
  481. catch (Exception ex)
  482. {
  483. logger.ErrorException("Error loading ImageMagick", ex);
  484. }
  485. try
  486. {
  487. await InstallVcredist().ConfigureAwait(false);
  488. }
  489. catch (Exception ex)
  490. {
  491. logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
  492. }
  493. }
  494. private async static Task InstallVcredist()
  495. {
  496. var httpClient = _appHost.HttpClient;
  497. var tmp = await httpClient.GetTempFile(new HttpRequestOptions
  498. {
  499. Url = GetVcredistUrl(),
  500. Progress = new Progress<double>()
  501. }).ConfigureAwait(false);
  502. var exePath = Path.ChangeExtension(tmp, ".exe");
  503. File.Copy(tmp, exePath);
  504. var startInfo = new ProcessStartInfo
  505. {
  506. FileName = exePath,
  507. CreateNoWindow = true,
  508. WindowStyle = ProcessWindowStyle.Hidden,
  509. Verb = "runas",
  510. ErrorDialog = false
  511. };
  512. _logger.Info("Running {0}", startInfo.FileName);
  513. using (var process = Process.Start(startInfo))
  514. {
  515. process.WaitForExit();
  516. }
  517. }
  518. private static string GetVcredistUrl()
  519. {
  520. if (Environment.Is64BitProcess)
  521. {
  522. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x64.exe";
  523. }
  524. // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_arm.exe
  525. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x86.exe";
  526. }
  527. /// <summary>
  528. /// Sets the error mode.
  529. /// </summary>
  530. /// <param name="uMode">The u mode.</param>
  531. /// <returns>ErrorModes.</returns>
  532. [DllImport("kernel32.dll")]
  533. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  534. /// <summary>
  535. /// Enum ErrorModes
  536. /// </summary>
  537. [Flags]
  538. public enum ErrorModes : uint
  539. {
  540. /// <summary>
  541. /// The SYSTE m_ DEFAULT
  542. /// </summary>
  543. SYSTEM_DEFAULT = 0x0,
  544. /// <summary>
  545. /// The SE m_ FAILCRITICALERRORS
  546. /// </summary>
  547. SEM_FAILCRITICALERRORS = 0x0001,
  548. /// <summary>
  549. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  550. /// </summary>
  551. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  552. /// <summary>
  553. /// The SE m_ NOGPFAULTERRORBOX
  554. /// </summary>
  555. SEM_NOGPFAULTERRORBOX = 0x0002,
  556. /// <summary>
  557. /// The SE m_ NOOPENFILEERRORBOX
  558. /// </summary>
  559. SEM_NOOPENFILEERRORBOX = 0x8000
  560. }
  561. }
  562. }