MainStartup.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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. //fileSystem.AddShortcutHandler(new LnkShortcutHandler(fileSystem));
  185. var nativeApp = new WindowsApp(fileSystem, _logger)
  186. {
  187. IsRunningAsService = runService
  188. };
  189. _appHost = new ApplicationHost(appPaths,
  190. logManager,
  191. options,
  192. fileSystem,
  193. "emby.windows.zip",
  194. nativeApp);
  195. var initProgress = new Progress<double>();
  196. if (!runService)
  197. {
  198. if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  199. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  200. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  201. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  202. }
  203. var task = _appHost.Init(initProgress);
  204. Task.WaitAll(task);
  205. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  206. if (runService)
  207. {
  208. StartService(logManager);
  209. }
  210. else
  211. {
  212. Task.WaitAll(task);
  213. task = InstallVcredist2013IfNeeded(_appHost, _logger);
  214. Task.WaitAll(task);
  215. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  216. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  217. HideSplashScreen();
  218. ShowTrayIcon();
  219. task = ApplicationTaskCompletionSource.Task;
  220. Task.WaitAll(task);
  221. }
  222. }
  223. private static ServerNotifyIcon _serverNotifyIcon;
  224. private static TaskScheduler _mainTaskScheduler;
  225. private static void ShowTrayIcon()
  226. {
  227. //Application.EnableVisualStyles();
  228. //Application.SetCompatibleTextRenderingDefault(false);
  229. _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
  230. _mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  231. Application.Run();
  232. }
  233. private static SplashForm _splash;
  234. private static Thread _splashThread;
  235. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  236. {
  237. var thread = new Thread(() =>
  238. {
  239. _splash = new SplashForm(appVersion, progress);
  240. _splash.ShowDialog();
  241. });
  242. thread.SetApartmentState(ApartmentState.STA);
  243. thread.IsBackground = true;
  244. thread.Start();
  245. _splashThread = thread;
  246. }
  247. private static void HideSplashScreen()
  248. {
  249. if (_splash != null)
  250. {
  251. Action act = () =>
  252. {
  253. _splash.Close();
  254. _splashThread = null;
  255. };
  256. _splash.Invoke(act);
  257. }
  258. }
  259. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  260. {
  261. if (e.Reason == SessionSwitchReason.SessionLogon)
  262. {
  263. BrowserLauncher.OpenDashboard(_appHost);
  264. }
  265. }
  266. public static void Invoke(Action action)
  267. {
  268. if (_isRunningAsService)
  269. {
  270. action();
  271. }
  272. else
  273. {
  274. Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, _mainTaskScheduler ?? TaskScheduler.Current);
  275. }
  276. }
  277. /// <summary>
  278. /// Starts the service.
  279. /// </summary>
  280. private static void StartService(ILogManager logManager)
  281. {
  282. var service = new BackgroundService(logManager.GetLogger("Service"));
  283. service.Disposed += service_Disposed;
  284. ServiceBase.Run(service);
  285. }
  286. /// <summary>
  287. /// Handles the Disposed event of the service control.
  288. /// </summary>
  289. /// <param name="sender">The source of the event.</param>
  290. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  291. static void service_Disposed(object sender, EventArgs e)
  292. {
  293. ApplicationTaskCompletionSource.SetResult(true);
  294. OnServiceShutdown();
  295. }
  296. private static void OnServiceShutdown()
  297. {
  298. _logger.Info("Shutting down");
  299. DisposeAppHost();
  300. }
  301. /// <summary>
  302. /// Installs the service.
  303. /// </summary>
  304. private static void InstallService(string applicationPath, ILogger logger)
  305. {
  306. try
  307. {
  308. ManagedInstallerClass.InstallHelper(new[] { applicationPath });
  309. logger.Info("Service installation succeeded");
  310. }
  311. catch (Exception ex)
  312. {
  313. logger.ErrorException("Uninstall failed", ex);
  314. }
  315. }
  316. /// <summary>
  317. /// Uninstalls the service.
  318. /// </summary>
  319. private static void UninstallService(string applicationPath, ILogger logger)
  320. {
  321. try
  322. {
  323. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  324. logger.Info("Service uninstallation succeeded");
  325. }
  326. catch (Exception ex)
  327. {
  328. logger.ErrorException("Uninstall failed", ex);
  329. }
  330. }
  331. private static void RunServiceInstallationIfNeeded(string applicationPath)
  332. {
  333. var serviceName = BackgroundService.GetExistingServiceName();
  334. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
  335. if (ctl == null)
  336. {
  337. RunServiceInstallation(applicationPath);
  338. }
  339. }
  340. /// <summary>
  341. /// Runs the service installation.
  342. /// </summary>
  343. private static void RunServiceInstallation(string applicationPath)
  344. {
  345. var startInfo = new ProcessStartInfo
  346. {
  347. FileName = applicationPath,
  348. Arguments = "-installservice",
  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. /// Runs the service uninstallation.
  361. /// </summary>
  362. private static void RunServiceUninstallation(string applicationPath)
  363. {
  364. var startInfo = new ProcessStartInfo
  365. {
  366. FileName = applicationPath,
  367. Arguments = "-uninstallservice",
  368. CreateNoWindow = true,
  369. WindowStyle = ProcessWindowStyle.Hidden,
  370. Verb = "runas",
  371. ErrorDialog = false
  372. };
  373. using (var process = Process.Start(startInfo))
  374. {
  375. process.WaitForExit();
  376. }
  377. }
  378. /// <summary>
  379. /// Handles the SessionEnding event of the SystemEvents control.
  380. /// </summary>
  381. /// <param name="sender">The source of the event.</param>
  382. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  383. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  384. {
  385. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  386. {
  387. Shutdown();
  388. }
  389. }
  390. /// <summary>
  391. /// Handles the UnhandledException event of the CurrentDomain control.
  392. /// </summary>
  393. /// <param name="sender">The source of the event.</param>
  394. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  395. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  396. {
  397. var exception = (Exception)e.ExceptionObject;
  398. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception);
  399. if (!_isRunningAsService)
  400. {
  401. MessageBox.Show("Unhandled exception: " + exception.Message);
  402. }
  403. if (!Debugger.IsAttached)
  404. {
  405. Environment.Exit(Marshal.GetHRForException(exception));
  406. }
  407. }
  408. /// <summary>
  409. /// Performs the update if needed.
  410. /// </summary>
  411. /// <param name="appPaths">The app paths.</param>
  412. /// <param name="logger">The logger.</param>
  413. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  414. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  415. {
  416. // Look for the existence of an update archive
  417. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  418. if (File.Exists(updateArchive))
  419. {
  420. logger.Info("An update is available from {0}", updateArchive);
  421. // Update is there - execute update
  422. try
  423. {
  424. var serviceName = _isRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty;
  425. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  426. // And just let the app exit so it can update
  427. return true;
  428. }
  429. catch (Exception e)
  430. {
  431. logger.ErrorException("Error starting updater.", e);
  432. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  433. }
  434. }
  435. return false;
  436. }
  437. public static void Shutdown()
  438. {
  439. if (_isRunningAsService)
  440. {
  441. ShutdownWindowsService();
  442. }
  443. else
  444. {
  445. DisposeAppHost();
  446. ShutdownWindowsApplication();
  447. }
  448. }
  449. public static void Restart()
  450. {
  451. DisposeAppHost();
  452. if (!_isRunningAsService)
  453. {
  454. //_logger.Info("Hiding server notify icon");
  455. //_serverNotifyIcon.Visible = false;
  456. _logger.Info("Starting new instance");
  457. //Application.Restart();
  458. Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath);
  459. ShutdownWindowsApplication();
  460. }
  461. }
  462. private static void DisposeAppHost()
  463. {
  464. if (!_appHostDisposed)
  465. {
  466. _logger.Info("Disposing app host");
  467. _appHostDisposed = true;
  468. _appHost.Dispose();
  469. }
  470. }
  471. private static void ShutdownWindowsApplication()
  472. {
  473. //_logger.Info("Calling Application.Exit");
  474. //Application.Exit();
  475. _logger.Info("Calling Environment.Exit");
  476. Environment.Exit(0);
  477. _logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
  478. ApplicationTaskCompletionSource.SetResult(true);
  479. }
  480. private static void ShutdownWindowsService()
  481. {
  482. _logger.Info("Stopping background service");
  483. var service = new ServiceController(BackgroundService.GetExistingServiceName());
  484. service.Refresh();
  485. if (service.Status == ServiceControllerStatus.Running)
  486. {
  487. service.Stop();
  488. }
  489. }
  490. private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger)
  491. {
  492. try
  493. {
  494. var version = ImageMagickEncoder.GetVersion();
  495. return;
  496. }
  497. catch (Exception ex)
  498. {
  499. logger.ErrorException("Error loading ImageMagick", ex);
  500. }
  501. try
  502. {
  503. await InstallVcredist2013().ConfigureAwait(false);
  504. }
  505. catch (Exception ex)
  506. {
  507. logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
  508. }
  509. }
  510. private async static Task InstallVcredist2013()
  511. {
  512. var httpClient = _appHost.HttpClient;
  513. var tmp = await httpClient.GetTempFile(new HttpRequestOptions
  514. {
  515. Url = GetVcredist2013Url(),
  516. Progress = new Progress<double>()
  517. }).ConfigureAwait(false);
  518. var exePath = Path.ChangeExtension(tmp, ".exe");
  519. File.Copy(tmp, exePath);
  520. var startInfo = new ProcessStartInfo
  521. {
  522. FileName = exePath,
  523. CreateNoWindow = true,
  524. WindowStyle = ProcessWindowStyle.Hidden,
  525. Verb = "runas",
  526. ErrorDialog = false
  527. };
  528. _logger.Info("Running {0}", startInfo.FileName);
  529. using (var process = Process.Start(startInfo))
  530. {
  531. process.WaitForExit();
  532. }
  533. }
  534. private static string GetVcredist2013Url()
  535. {
  536. if (Environment.Is64BitProcess)
  537. {
  538. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x64.exe";
  539. }
  540. // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_arm.exe
  541. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x86.exe";
  542. }
  543. /// <summary>
  544. /// Sets the error mode.
  545. /// </summary>
  546. /// <param name="uMode">The u mode.</param>
  547. /// <returns>ErrorModes.</returns>
  548. [DllImport("kernel32.dll")]
  549. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  550. /// <summary>
  551. /// Enum ErrorModes
  552. /// </summary>
  553. [Flags]
  554. public enum ErrorModes : uint
  555. {
  556. /// <summary>
  557. /// The SYSTE m_ DEFAULT
  558. /// </summary>
  559. SYSTEM_DEFAULT = 0x0,
  560. /// <summary>
  561. /// The SE m_ FAILCRITICALERRORS
  562. /// </summary>
  563. SEM_FAILCRITICALERRORS = 0x0001,
  564. /// <summary>
  565. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  566. /// </summary>
  567. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  568. /// <summary>
  569. /// The SE m_ NOGPFAULTERRORBOX
  570. /// </summary>
  571. SEM_NOGPFAULTERRORBOX = 0x0002,
  572. /// <summary>
  573. /// The SE m_ NOOPENFILEERRORBOX
  574. /// </summary>
  575. SEM_NOOPENFILEERRORBOX = 0x8000
  576. }
  577. }
  578. }