MainStartup.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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 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="runAsService">if set to <c>true</c> [run as service].</param>
  126. /// <returns>ServerApplicationPaths.</returns>
  127. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService)
  128. {
  129. if (runAsService)
  130. {
  131. var systemPath = Path.GetDirectoryName(applicationPath);
  132. var programDataPath = Path.GetDirectoryName(systemPath);
  133. return new ServerApplicationPaths(programDataPath, applicationPath);
  134. }
  135. return new ServerApplicationPaths(applicationPath);
  136. }
  137. /// <summary>
  138. /// Gets a value indicating whether this instance can self restart.
  139. /// </summary>
  140. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  141. public static bool CanSelfRestart
  142. {
  143. get
  144. {
  145. return !_isRunningAsService;
  146. }
  147. }
  148. /// <summary>
  149. /// Gets a value indicating whether this instance can self update.
  150. /// </summary>
  151. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  152. public static bool CanSelfUpdate
  153. {
  154. get
  155. {
  156. return !_isRunningAsService;
  157. }
  158. }
  159. /// <summary>
  160. /// Begins the log.
  161. /// </summary>
  162. /// <param name="logger">The logger.</param>
  163. /// <param name="appPaths">The app paths.</param>
  164. private static void BeginLog(ILogger logger, IApplicationPaths appPaths)
  165. {
  166. logger.Info("Media Browser Server started");
  167. logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));
  168. logger.Info("Server: {0}", Environment.MachineName);
  169. logger.Info("Operating system: {0}", Environment.OSVersion.ToString());
  170. logger.Info("Program data path: {0}", appPaths.ProgramDataPath);
  171. logger.Info("Application Path: {0}", appPaths.ApplicationPath);
  172. }
  173. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  174. /// <summary>
  175. /// Runs the application.
  176. /// </summary>
  177. /// <param name="appPaths">The app paths.</param>
  178. /// <param name="logManager">The log manager.</param>
  179. /// <param name="runService">if set to <c>true</c> [run service].</param>
  180. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService)
  181. {
  182. _appHost = new ApplicationHost(appPaths, logManager, runService);
  183. var initProgress = new Progress<double>();
  184. if (!runService)
  185. {
  186. ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  187. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  188. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  189. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  190. }
  191. var task = _appHost.Init(initProgress);
  192. Task.WaitAll(task);
  193. task = _appHost.RunStartupTasks();
  194. Task.WaitAll(task);
  195. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  196. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  197. if (runService)
  198. {
  199. StartService(logManager);
  200. }
  201. else
  202. {
  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.UserManager, _appHost.LibraryManager, _appHost.JsonSerializer, _appHost.ItemRepository, _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.UserManager, _appHost.ServerConfigurationManager, _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. LogUnhandledException(exception);
  375. _appHost.LogManager.Flush();
  376. if (!_isRunningAsService)
  377. {
  378. MessageBox.Show("Unhandled exception: " + exception.Message);
  379. }
  380. if (!Debugger.IsAttached)
  381. {
  382. Environment.Exit(Marshal.GetHRForException(exception));
  383. }
  384. }
  385. private static void LogUnhandledException(Exception ex)
  386. {
  387. _logger.ErrorException("UnhandledException", ex);
  388. var path = Path.Combine(_appHost.ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "unhandled_" + Guid.NewGuid() + ".txt");
  389. Directory.CreateDirectory(Path.GetDirectoryName(path));
  390. var builder = LogHelper.GetLogMessage(ex);
  391. File.WriteAllText(path, builder.ToString());
  392. }
  393. /// <summary>
  394. /// Performs the update if needed.
  395. /// </summary>
  396. /// <param name="appPaths">The app paths.</param>
  397. /// <param name="logger">The logger.</param>
  398. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  399. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  400. {
  401. // Look for the existence of an update archive
  402. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  403. if (File.Exists(updateArchive))
  404. {
  405. logger.Info("An update is available from {0}", updateArchive);
  406. // Update is there - execute update
  407. try
  408. {
  409. var serviceName = _isRunningAsService ? BackgroundService.Name : string.Empty;
  410. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  411. // And just let the app exit so it can update
  412. return true;
  413. }
  414. catch (Exception e)
  415. {
  416. logger.ErrorException("Error starting updater.", e);
  417. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  418. }
  419. }
  420. return false;
  421. }
  422. public static void Shutdown()
  423. {
  424. if (_isRunningAsService)
  425. {
  426. ShutdownWindowsService();
  427. }
  428. else
  429. {
  430. ShutdownWindowsApplication();
  431. }
  432. }
  433. public static void Restart()
  434. {
  435. _logger.Info("Disposing app host");
  436. _appHost.Dispose();
  437. if (!_isRunningAsService)
  438. {
  439. _logger.Info("Executing windows forms restart");
  440. _serverNotifyIcon.Visible = false;
  441. Application.Restart();
  442. ShutdownWindowsApplication();
  443. }
  444. }
  445. private static void ShutdownWindowsApplication()
  446. {
  447. _serverNotifyIcon.Visible = false;
  448. Application.Exit();
  449. ApplicationTaskCompletionSource.SetResult(true);
  450. }
  451. private static void ShutdownWindowsService()
  452. {
  453. _logger.Info("Stopping background service");
  454. var service = new ServiceController(BackgroundService.Name);
  455. service.Refresh();
  456. if (service.Status == ServiceControllerStatus.Running)
  457. {
  458. service.Stop();
  459. }
  460. }
  461. /// <summary>
  462. /// Sets the error mode.
  463. /// </summary>
  464. /// <param name="uMode">The u mode.</param>
  465. /// <returns>ErrorModes.</returns>
  466. [DllImport("kernel32.dll")]
  467. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  468. /// <summary>
  469. /// Enum ErrorModes
  470. /// </summary>
  471. [Flags]
  472. public enum ErrorModes : uint
  473. {
  474. /// <summary>
  475. /// The SYSTE m_ DEFAULT
  476. /// </summary>
  477. SYSTEM_DEFAULT = 0x0,
  478. /// <summary>
  479. /// The SE m_ FAILCRITICALERRORS
  480. /// </summary>
  481. SEM_FAILCRITICALERRORS = 0x0001,
  482. /// <summary>
  483. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  484. /// </summary>
  485. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  486. /// <summary>
  487. /// The SE m_ NOGPFAULTERRORBOX
  488. /// </summary>
  489. SEM_NOGPFAULTERRORBOX = 0x0002,
  490. /// <summary>
  491. /// The SE m_ NOOPENFILEERRORBOX
  492. /// </summary>
  493. SEM_NOOPENFILEERRORBOX = 0x8000
  494. }
  495. }
  496. }