MainStartup.cs 20 KB

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