MainStartup.cs 20 KB

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