MainStartup.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Implementations.Logging;
  3. using MediaBrowser.Model.Logging;
  4. using MediaBrowser.Server.Implementations;
  5. using MediaBrowser.ServerApplication.Native;
  6. using MediaBrowser.ServerApplication.Splash;
  7. using MediaBrowser.ServerApplication.Updates;
  8. using Microsoft.Win32;
  9. using System;
  10. using System.Configuration.Install;
  11. using System.Diagnostics;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Runtime.InteropServices;
  15. using System.ServiceProcess;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using System.Windows.Forms;
  19. namespace MediaBrowser.ServerApplication
  20. {
  21. public class MainStartup
  22. {
  23. private static ApplicationHost _appHost;
  24. private static ILogger _logger;
  25. private static bool _isRunningAsService = false;
  26. /// <summary>
  27. /// Defines the entry point of the application.
  28. /// </summary>
  29. public static void Main()
  30. {
  31. var startFlag = Environment.GetCommandLineArgs().ElementAtOrDefault(1);
  32. _isRunningAsService = string.Equals(startFlag, "-service", StringComparison.OrdinalIgnoreCase);
  33. var applicationPath = Process.GetCurrentProcess().MainModule.FileName;
  34. var appPaths = CreateApplicationPaths(applicationPath, _isRunningAsService);
  35. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  36. logManager.ReloadLogger(LogSeverity.Debug);
  37. logManager.AddConsoleOutput();
  38. var logger = _logger = logManager.GetLogger("Main");
  39. BeginLog(logger, appPaths);
  40. // Install directly
  41. if (string.Equals(startFlag, "-installservice", StringComparison.OrdinalIgnoreCase))
  42. {
  43. logger.Info("Performing service installation");
  44. InstallService(applicationPath, logger);
  45. return;
  46. }
  47. // Restart with admin rights, then install
  48. if (string.Equals(startFlag, "-installserviceasadmin", StringComparison.OrdinalIgnoreCase))
  49. {
  50. logger.Info("Performing service installation");
  51. RunServiceInstallation(applicationPath);
  52. return;
  53. }
  54. // Uninstall directly
  55. if (string.Equals(startFlag, "-uninstallservice", StringComparison.OrdinalIgnoreCase))
  56. {
  57. logger.Info("Performing service uninstallation");
  58. UninstallService(applicationPath, logger);
  59. return;
  60. }
  61. // Restart with admin rights, then uninstall
  62. if (string.Equals(startFlag, "-uninstallserviceasadmin", StringComparison.OrdinalIgnoreCase))
  63. {
  64. logger.Info("Performing service uninstallation");
  65. RunServiceUninstallation(applicationPath);
  66. return;
  67. }
  68. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  69. RunServiceInstallationIfNeeded(applicationPath);
  70. var currentProcess = Process.GetCurrentProcess();
  71. if (IsAlreadyRunning(applicationPath, currentProcess))
  72. {
  73. logger.Info("Shutting down because another instance of Media Browser Server is already running.");
  74. return;
  75. }
  76. if (PerformUpdateIfNeeded(appPaths, logger))
  77. {
  78. logger.Info("Exiting to perform application update.");
  79. return;
  80. }
  81. try
  82. {
  83. RunApplication(appPaths, logManager, _isRunningAsService);
  84. }
  85. finally
  86. {
  87. OnServiceShutdown();
  88. }
  89. }
  90. /// <summary>
  91. /// Determines whether [is already running] [the specified current process].
  92. /// </summary>
  93. /// <param name="applicationPath">The application path.</param>
  94. /// <param name="currentProcess">The current process.</param>
  95. /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
  96. private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
  97. {
  98. var filename = Path.GetFileName(applicationPath);
  99. var duplicate = Process.GetProcesses().FirstOrDefault(i =>
  100. {
  101. try
  102. {
  103. return string.Equals(filename, Path.GetFileName(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.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, "MBServer" + ".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("Hiding server notify icon");
  439. _serverNotifyIcon.Visible = false;
  440. _logger.Info("Executing windows forms restart");
  441. //Application.Restart();
  442. Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath);
  443. _logger.Info("Calling Application.Exit");
  444. Environment.Exit(0);
  445. }
  446. }
  447. private static void ShutdownWindowsApplication()
  448. {
  449. _logger.Info("Hiding server notify icon");
  450. _serverNotifyIcon.Visible = false;
  451. _logger.Info("Calling Application.Exit");
  452. Application.Exit();
  453. _logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
  454. ApplicationTaskCompletionSource.SetResult(true);
  455. }
  456. private static void ShutdownWindowsService()
  457. {
  458. _logger.Info("Stopping background service");
  459. var service = new ServiceController(BackgroundService.Name);
  460. service.Refresh();
  461. if (service.Status == ServiceControllerStatus.Running)
  462. {
  463. service.Stop();
  464. }
  465. }
  466. /// <summary>
  467. /// Sets the error mode.
  468. /// </summary>
  469. /// <param name="uMode">The u mode.</param>
  470. /// <returns>ErrorModes.</returns>
  471. [DllImport("kernel32.dll")]
  472. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  473. /// <summary>
  474. /// Enum ErrorModes
  475. /// </summary>
  476. [Flags]
  477. public enum ErrorModes : uint
  478. {
  479. /// <summary>
  480. /// The SYSTE m_ DEFAULT
  481. /// </summary>
  482. SYSTEM_DEFAULT = 0x0,
  483. /// <summary>
  484. /// The SE m_ FAILCRITICALERRORS
  485. /// </summary>
  486. SEM_FAILCRITICALERRORS = 0x0001,
  487. /// <summary>
  488. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  489. /// </summary>
  490. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  491. /// <summary>
  492. /// The SE m_ NOGPFAULTERRORBOX
  493. /// </summary>
  494. SEM_NOGPFAULTERRORBOX = 0x0002,
  495. /// <summary>
  496. /// The SE m_ NOOPENFILEERRORBOX
  497. /// </summary>
  498. SEM_NOOPENFILEERRORBOX = 0x8000
  499. }
  500. }
  501. }