MainStartup.cs 19 KB

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