MainStartup.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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.IO;
  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. BeginLog(logger, appPaths);
  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="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. ApplicationHost.LogEnvironmentInfo(logger, appPaths);
  168. }
  169. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  170. /// <summary>
  171. /// Runs the application.
  172. /// </summary>
  173. /// <param name="appPaths">The app paths.</param>
  174. /// <param name="logManager">The log manager.</param>
  175. /// <param name="runService">if set to <c>true</c> [run service].</param>
  176. /// <param name="options">The options.</param>
  177. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
  178. {
  179. var fileSystem = new NativeFileSystem(logManager.GetLogger("FileSystem"), false);
  180. _appHost = new ApplicationHost(appPaths,
  181. logManager,
  182. true,
  183. runService,
  184. options,
  185. fileSystem,
  186. "MBServer",
  187. true);
  188. var initProgress = new Progress<double>();
  189. if (!runService)
  190. {
  191. if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  192. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  193. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  194. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  195. }
  196. var task = _appHost.Init(initProgress);
  197. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()));
  198. if (runService)
  199. {
  200. StartService(logManager);
  201. }
  202. else
  203. {
  204. Task.WaitAll(task);
  205. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  206. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  207. HideSplashScreen();
  208. ShowTrayIcon();
  209. task = ApplicationTaskCompletionSource.Task;
  210. Task.WaitAll(task);
  211. }
  212. }
  213. private static ServerNotifyIcon _serverNotifyIcon;
  214. private static void ShowTrayIcon()
  215. {
  216. //Application.EnableVisualStyles();
  217. //Application.SetCompatibleTextRenderingDefault(false);
  218. _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.UserManager, _appHost.LibraryManager, _appHost.JsonSerializer, _appHost.LocalizationManager, _appHost.UserViewManager);
  219. Application.Run();
  220. }
  221. private static SplashForm _splash;
  222. private static Thread _splashThread;
  223. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  224. {
  225. var thread = new Thread(() =>
  226. {
  227. _splash = new SplashForm(appVersion, progress);
  228. _splash.ShowDialog();
  229. });
  230. thread.SetApartmentState(ApartmentState.STA);
  231. thread.IsBackground = true;
  232. thread.Start();
  233. _splashThread = thread;
  234. }
  235. private static void HideSplashScreen()
  236. {
  237. if (_splash != null)
  238. {
  239. Action act = () =>
  240. {
  241. _splash.Close();
  242. _splashThread = null;
  243. };
  244. _splash.Invoke(act);
  245. }
  246. }
  247. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  248. {
  249. if (e.Reason == SessionSwitchReason.SessionLogon)
  250. {
  251. BrowserLauncher.OpenDashboard(_appHost, _logger);
  252. }
  253. }
  254. /// <summary>
  255. /// Starts the service.
  256. /// </summary>
  257. private static void StartService(ILogManager logManager)
  258. {
  259. var service = new BackgroundService(logManager.GetLogger("Service"));
  260. service.Disposed += service_Disposed;
  261. ServiceBase.Run(service);
  262. }
  263. /// <summary>
  264. /// Handles the Disposed event of the service control.
  265. /// </summary>
  266. /// <param name="sender">The source of the event.</param>
  267. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  268. static void service_Disposed(object sender, EventArgs e)
  269. {
  270. ApplicationTaskCompletionSource.SetResult(true);
  271. OnServiceShutdown();
  272. }
  273. private static void OnServiceShutdown()
  274. {
  275. _logger.Info("Shutting down");
  276. _appHost.Dispose();
  277. if (!_isRunningAsService)
  278. {
  279. SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
  280. }
  281. }
  282. /// <summary>
  283. /// Installs the service.
  284. /// </summary>
  285. private static void InstallService(string applicationPath, ILogger logger)
  286. {
  287. try
  288. {
  289. ManagedInstallerClass.InstallHelper(new[] { applicationPath });
  290. logger.Info("Service installation succeeded");
  291. }
  292. catch (Exception ex)
  293. {
  294. logger.ErrorException("Uninstall failed", ex);
  295. }
  296. }
  297. /// <summary>
  298. /// Uninstalls the service.
  299. /// </summary>
  300. private static void UninstallService(string applicationPath, ILogger logger)
  301. {
  302. try
  303. {
  304. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  305. logger.Info("Service uninstallation succeeded");
  306. }
  307. catch (Exception ex)
  308. {
  309. logger.ErrorException("Uninstall failed", ex);
  310. }
  311. }
  312. private static void RunServiceInstallationIfNeeded(string applicationPath)
  313. {
  314. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == BackgroundService.Name);
  315. if (ctl == null)
  316. {
  317. RunServiceInstallation(applicationPath);
  318. }
  319. }
  320. /// <summary>
  321. /// Runs the service installation.
  322. /// </summary>
  323. private static void RunServiceInstallation(string applicationPath)
  324. {
  325. var startInfo = new ProcessStartInfo
  326. {
  327. FileName = applicationPath,
  328. Arguments = "-installservice",
  329. CreateNoWindow = true,
  330. WindowStyle = ProcessWindowStyle.Hidden,
  331. Verb = "runas",
  332. ErrorDialog = false
  333. };
  334. using (var process = Process.Start(startInfo))
  335. {
  336. process.WaitForExit();
  337. }
  338. }
  339. /// <summary>
  340. /// Runs the service uninstallation.
  341. /// </summary>
  342. private static void RunServiceUninstallation(string applicationPath)
  343. {
  344. var startInfo = new ProcessStartInfo
  345. {
  346. FileName = applicationPath,
  347. Arguments = "-uninstallservice",
  348. CreateNoWindow = true,
  349. WindowStyle = ProcessWindowStyle.Hidden,
  350. Verb = "runas",
  351. ErrorDialog = false
  352. };
  353. using (var process = Process.Start(startInfo))
  354. {
  355. process.WaitForExit();
  356. }
  357. }
  358. /// <summary>
  359. /// Handles the SessionEnding event of the SystemEvents control.
  360. /// </summary>
  361. /// <param name="sender">The source of the event.</param>
  362. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  363. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  364. {
  365. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  366. {
  367. Shutdown();
  368. }
  369. }
  370. /// <summary>
  371. /// Handles the UnhandledException event of the CurrentDomain control.
  372. /// </summary>
  373. /// <param name="sender">The source of the event.</param>
  374. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  375. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  376. {
  377. var exception = (Exception)e.ExceptionObject;
  378. LogUnhandledException(exception);
  379. _appHost.LogManager.Flush();
  380. if (!_isRunningAsService)
  381. {
  382. MessageBox.Show("Unhandled exception: " + exception.Message);
  383. }
  384. if (!Debugger.IsAttached)
  385. {
  386. Environment.Exit(Marshal.GetHRForException(exception));
  387. }
  388. }
  389. private static void LogUnhandledException(Exception ex)
  390. {
  391. _logger.ErrorException("UnhandledException", ex);
  392. var path = Path.Combine(_appHost.ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "unhandled_" + Guid.NewGuid() + ".txt");
  393. Directory.CreateDirectory(Path.GetDirectoryName(path));
  394. var builder = LogHelper.GetLogMessage(ex);
  395. File.WriteAllText(path, builder.ToString());
  396. }
  397. /// <summary>
  398. /// Performs the update if needed.
  399. /// </summary>
  400. /// <param name="appPaths">The app paths.</param>
  401. /// <param name="logger">The logger.</param>
  402. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  403. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  404. {
  405. // Look for the existence of an update archive
  406. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  407. if (File.Exists(updateArchive))
  408. {
  409. logger.Info("An update is available from {0}", updateArchive);
  410. // Update is there - execute update
  411. try
  412. {
  413. var serviceName = _isRunningAsService ? BackgroundService.Name : string.Empty;
  414. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  415. // And just let the app exit so it can update
  416. return true;
  417. }
  418. catch (Exception e)
  419. {
  420. logger.ErrorException("Error starting updater.", e);
  421. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  422. }
  423. }
  424. return false;
  425. }
  426. public static void Shutdown()
  427. {
  428. if (_isRunningAsService)
  429. {
  430. ShutdownWindowsService();
  431. }
  432. else
  433. {
  434. ShutdownWindowsApplication();
  435. }
  436. }
  437. public static void Restart()
  438. {
  439. _logger.Info("Disposing app host");
  440. _appHost.Dispose();
  441. if (!_isRunningAsService)
  442. {
  443. _logger.Info("Hiding server notify icon");
  444. _serverNotifyIcon.Visible = false;
  445. _logger.Info("Executing windows forms restart");
  446. //Application.Restart();
  447. Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath);
  448. _logger.Info("Calling Application.Exit");
  449. Environment.Exit(0);
  450. }
  451. }
  452. private static void ShutdownWindowsApplication()
  453. {
  454. _logger.Info("Hiding server notify icon");
  455. _serverNotifyIcon.Visible = false;
  456. _logger.Info("Calling Application.Exit");
  457. Application.Exit();
  458. _logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
  459. ApplicationTaskCompletionSource.SetResult(true);
  460. }
  461. private static void ShutdownWindowsService()
  462. {
  463. _logger.Info("Stopping background service");
  464. var service = new ServiceController(BackgroundService.Name);
  465. service.Refresh();
  466. if (service.Status == ServiceControllerStatus.Running)
  467. {
  468. service.Stop();
  469. }
  470. }
  471. /// <summary>
  472. /// Sets the error mode.
  473. /// </summary>
  474. /// <param name="uMode">The u mode.</param>
  475. /// <returns>ErrorModes.</returns>
  476. [DllImport("kernel32.dll")]
  477. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  478. /// <summary>
  479. /// Enum ErrorModes
  480. /// </summary>
  481. [Flags]
  482. public enum ErrorModes : uint
  483. {
  484. /// <summary>
  485. /// The SYSTE m_ DEFAULT
  486. /// </summary>
  487. SYSTEM_DEFAULT = 0x0,
  488. /// <summary>
  489. /// The SE m_ FAILCRITICALERRORS
  490. /// </summary>
  491. SEM_FAILCRITICALERRORS = 0x0001,
  492. /// <summary>
  493. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  494. /// </summary>
  495. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  496. /// <summary>
  497. /// The SE m_ NOGPFAULTERRORBOX
  498. /// </summary>
  499. SEM_NOGPFAULTERRORBOX = 0x0002,
  500. /// <summary>
  501. /// The SE m_ NOOPENFILEERRORBOX
  502. /// </summary>
  503. SEM_NOOPENFILEERRORBOX = 0x8000
  504. }
  505. }
  506. }