2
0

MainStartup.cs 20 KB

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