2
0

MainStartup.cs 20 KB

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