MainStartup.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Constants;
  3. using MediaBrowser.Common.Implementations.Logging;
  4. using MediaBrowser.Common.Implementations.Updates;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Server.Implementations;
  7. using MediaBrowser.ServerApplication.Native;
  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.Windows;
  17. namespace MediaBrowser.ServerApplication
  18. {
  19. public class MainStartup
  20. {
  21. private static ApplicationHost _appHost;
  22. private static App _app;
  23. private static ILogger _logger;
  24. private static bool _isRunningAsService = false;
  25. /// <summary>
  26. /// Defines the entry point of the application.
  27. /// </summary>
  28. [STAThread]
  29. public static void Main()
  30. {
  31. var startFlag = Environment.GetCommandLineArgs().ElementAtOrDefault(1);
  32. _isRunningAsService = string.Equals(startFlag, "-service", StringComparison.OrdinalIgnoreCase);
  33. var appPaths = CreateApplicationPaths(_isRunningAsService);
  34. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  35. logManager.ReloadLogger(LogSeverity.Debug);
  36. var logger = _logger = logManager.GetLogger("Main");
  37. BeginLog(logger, appPaths);
  38. // Install directly
  39. if (string.Equals(startFlag, "-installservice", StringComparison.OrdinalIgnoreCase))
  40. {
  41. logger.Info("Performing service installation");
  42. InstallService(logger);
  43. return;
  44. }
  45. // Restart with admin rights, then install
  46. if (string.Equals(startFlag, "-installserviceasadmin", StringComparison.OrdinalIgnoreCase))
  47. {
  48. logger.Info("Performing service installation");
  49. RunServiceInstallation();
  50. return;
  51. }
  52. // Uninstall directly
  53. if (string.Equals(startFlag, "-uninstallservice", StringComparison.OrdinalIgnoreCase))
  54. {
  55. logger.Info("Performing service uninstallation");
  56. UninstallService(logger);
  57. return;
  58. }
  59. // Restart with admin rights, then uninstall
  60. if (string.Equals(startFlag, "-uninstallserviceasadmin", StringComparison.OrdinalIgnoreCase))
  61. {
  62. logger.Info("Performing service uninstallation");
  63. RunServiceUninstallation();
  64. return;
  65. }
  66. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  67. RunServiceInstallationIfNeeded();
  68. var currentProcess = Process.GetCurrentProcess();
  69. if (IsAlreadyRunning(currentProcess))
  70. {
  71. logger.Info("Shutting down because another instance of Media Browser Server is already running.");
  72. return;
  73. }
  74. if (PerformUpdateIfNeeded(appPaths, logger))
  75. {
  76. logger.Info("Exiting to perform application update.");
  77. return;
  78. }
  79. try
  80. {
  81. RunApplication(appPaths, logManager, _isRunningAsService);
  82. }
  83. finally
  84. {
  85. OnServiceShutdown();
  86. }
  87. }
  88. /// <summary>
  89. /// Determines whether [is already running] [the specified current process].
  90. /// </summary>
  91. /// <param name="currentProcess">The current process.</param>
  92. /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
  93. private static bool IsAlreadyRunning(Process currentProcess)
  94. {
  95. var runningPath = currentProcess.MainModule.FileName;
  96. var duplicate = Process.GetProcesses().FirstOrDefault(i =>
  97. {
  98. try
  99. {
  100. return string.Equals(runningPath, i.MainModule.FileName) && currentProcess.Id != i.Id;
  101. }
  102. catch (Exception)
  103. {
  104. return false;
  105. }
  106. });
  107. if (duplicate != null)
  108. {
  109. _logger.Info("Found a duplicate process. Giving it time to exit.");
  110. if (!duplicate.WaitForExit(5000))
  111. {
  112. _logger.Info("The duplicate process did not exit.");
  113. return true;
  114. }
  115. }
  116. return false;
  117. }
  118. /// <summary>
  119. /// Creates the application paths.
  120. /// </summary>
  121. /// <param name="runAsService">if set to <c>true</c> [run as service].</param>
  122. /// <returns>ServerApplicationPaths.</returns>
  123. private static ServerApplicationPaths CreateApplicationPaths(bool runAsService)
  124. {
  125. if (runAsService)
  126. {
  127. var systemPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
  128. var programDataPath = Path.GetDirectoryName(systemPath);
  129. return new ServerApplicationPaths(programDataPath);
  130. }
  131. var applicationPath = Process.GetCurrentProcess().MainModule.FileName;
  132. return new ServerApplicationPaths(applicationPath);
  133. }
  134. /// <summary>
  135. /// Gets a value indicating whether this instance can self restart.
  136. /// </summary>
  137. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  138. public static bool CanSelfRestart
  139. {
  140. get
  141. {
  142. return !_isRunningAsService;
  143. }
  144. }
  145. /// <summary>
  146. /// Gets a value indicating whether this instance can self update.
  147. /// </summary>
  148. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  149. public static bool CanSelfUpdate
  150. {
  151. get
  152. {
  153. return !_isRunningAsService;
  154. }
  155. }
  156. /// <summary>
  157. /// Begins the log.
  158. /// </summary>
  159. /// <param name="logger">The logger.</param>
  160. /// <param name="appPaths">The app paths.</param>
  161. private static void BeginLog(ILogger logger, IApplicationPaths appPaths)
  162. {
  163. logger.Info("Media Browser Server started");
  164. logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));
  165. logger.Info("Server: {0}", Environment.MachineName);
  166. logger.Info("Operating system: {0}", Environment.OSVersion.ToString());
  167. logger.Info("Program data path: {0}", appPaths.ProgramDataPath);
  168. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  169. logger.Info("Executable: {0}", runningPath);
  170. }
  171. /// <summary>
  172. /// Runs the application.
  173. /// </summary>
  174. /// <param name="appPaths">The app paths.</param>
  175. /// <param name="logManager">The log manager.</param>
  176. /// <param name="runService">if set to <c>true</c> [run service].</param>
  177. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService)
  178. {
  179. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  180. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  181. _appHost = new ApplicationHost(appPaths, logManager);
  182. _app = new App(_appHost, _appHost.LogManager.GetLogger("App"), runService);
  183. if (runService)
  184. {
  185. _app.AppStarted += (sender, args) => StartService(logManager);
  186. }
  187. else
  188. {
  189. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  190. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  191. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  192. }
  193. _app.Run();
  194. }
  195. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  196. {
  197. if (e.Reason == SessionSwitchReason.SessionLogon)
  198. {
  199. BrowserLauncher.OpenDashboard(_appHost.UserManager, _appHost.ServerConfigurationManager, _appHost, _logger);
  200. }
  201. }
  202. /// <summary>
  203. /// Starts the service.
  204. /// </summary>
  205. private static void StartService(ILogManager logManager)
  206. {
  207. var service = new BackgroundService(logManager.GetLogger("Service"));
  208. service.Disposed += service_Disposed;
  209. ServiceBase.Run(service);
  210. }
  211. /// <summary>
  212. /// Handles the Disposed event of the service control.
  213. /// </summary>
  214. /// <param name="sender">The source of the event.</param>
  215. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  216. static void service_Disposed(object sender, EventArgs e)
  217. {
  218. OnServiceShutdown();
  219. }
  220. private static void OnServiceShutdown()
  221. {
  222. _logger.Info("Shutting down");
  223. _appHost.Dispose();
  224. if (!_isRunningAsService)
  225. {
  226. SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
  227. }
  228. _app.Dispatcher.Invoke(_app.Shutdown);
  229. }
  230. /// <summary>
  231. /// Installs the service.
  232. /// </summary>
  233. private static void InstallService(ILogger logger)
  234. {
  235. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  236. try
  237. {
  238. ManagedInstallerClass.InstallHelper(new[] { runningPath });
  239. logger.Info("Service installation succeeded");
  240. }
  241. catch (Exception ex)
  242. {
  243. logger.ErrorException("Uninstall failed", ex);
  244. }
  245. }
  246. /// <summary>
  247. /// Uninstalls the service.
  248. /// </summary>
  249. private static void UninstallService(ILogger logger)
  250. {
  251. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  252. try
  253. {
  254. ManagedInstallerClass.InstallHelper(new[] { "/u", runningPath });
  255. logger.Info("Service uninstallation succeeded");
  256. }
  257. catch (Exception ex)
  258. {
  259. logger.ErrorException("Uninstall failed", ex);
  260. }
  261. }
  262. private static void RunServiceInstallationIfNeeded()
  263. {
  264. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == BackgroundService.Name);
  265. if (ctl == null)
  266. {
  267. RunServiceInstallation();
  268. }
  269. }
  270. /// <summary>
  271. /// Runs the service installation.
  272. /// </summary>
  273. private static void RunServiceInstallation()
  274. {
  275. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  276. var startInfo = new ProcessStartInfo
  277. {
  278. FileName = runningPath,
  279. Arguments = "-installservice",
  280. CreateNoWindow = true,
  281. WindowStyle = ProcessWindowStyle.Hidden,
  282. Verb = "runas",
  283. ErrorDialog = false
  284. };
  285. using (var process = Process.Start(startInfo))
  286. {
  287. process.WaitForExit();
  288. }
  289. }
  290. /// <summary>
  291. /// Runs the service uninstallation.
  292. /// </summary>
  293. private static void RunServiceUninstallation()
  294. {
  295. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  296. var startInfo = new ProcessStartInfo
  297. {
  298. FileName = runningPath,
  299. Arguments = "-uninstallservice",
  300. CreateNoWindow = true,
  301. WindowStyle = ProcessWindowStyle.Hidden,
  302. Verb = "runas",
  303. ErrorDialog = false
  304. };
  305. using (var process = Process.Start(startInfo))
  306. {
  307. process.WaitForExit();
  308. }
  309. }
  310. /// <summary>
  311. /// Handles the SessionEnding event of the SystemEvents control.
  312. /// </summary>
  313. /// <param name="sender">The source of the event.</param>
  314. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  315. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  316. {
  317. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  318. {
  319. Shutdown();
  320. }
  321. }
  322. /// <summary>
  323. /// Handles the UnhandledException event of the CurrentDomain control.
  324. /// </summary>
  325. /// <param name="sender">The source of the event.</param>
  326. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  327. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  328. {
  329. var exception = (Exception)e.ExceptionObject;
  330. LogUnhandledException(exception);
  331. _appHost.LogManager.Flush();
  332. if (!_isRunningAsService)
  333. {
  334. _app.OnUnhandledException(exception);
  335. }
  336. if (!Debugger.IsAttached)
  337. {
  338. Environment.Exit(Marshal.GetHRForException(exception));
  339. }
  340. }
  341. private static void LogUnhandledException(Exception ex)
  342. {
  343. _logger.ErrorException("UnhandledException", ex);
  344. var path = Path.Combine(_appHost.ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "unhandled_" + Guid.NewGuid() + ".txt");
  345. var builder = LogHelper.GetLogMessage(ex);
  346. File.WriteAllText(path, builder.ToString());
  347. }
  348. /// <summary>
  349. /// Performs the update if needed.
  350. /// </summary>
  351. /// <param name="appPaths">The app paths.</param>
  352. /// <param name="logger">The logger.</param>
  353. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  354. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  355. {
  356. // Look for the existence of an update archive
  357. var updateArchive = Path.Combine(appPaths.TempUpdatePath, Constants.MbServerPkgName + ".zip");
  358. if (File.Exists(updateArchive))
  359. {
  360. logger.Info("An update is available from {0}", updateArchive);
  361. // Update is there - execute update
  362. try
  363. {
  364. var serviceName = _isRunningAsService ? BackgroundService.Name : string.Empty;
  365. new ApplicationUpdater().UpdateApplication(MBApplication.MBServer, appPaths, updateArchive, logger, serviceName);
  366. // And just let the app exit so it can update
  367. return true;
  368. }
  369. catch (Exception e)
  370. {
  371. logger.ErrorException("Error starting updater.", e);
  372. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  373. }
  374. }
  375. return false;
  376. }
  377. public static void Shutdown()
  378. {
  379. if (_isRunningAsService)
  380. {
  381. ShutdownWindowsService();
  382. }
  383. else
  384. {
  385. ShutdownWindowsApplication();
  386. }
  387. }
  388. public static void Restart()
  389. {
  390. _logger.Info("Disposing app host");
  391. _appHost.Dispose();
  392. if (!_isRunningAsService)
  393. {
  394. _logger.Info("Executing windows forms restart");
  395. System.Windows.Forms.Application.Restart();
  396. ShutdownWindowsApplication();
  397. }
  398. }
  399. private static void ShutdownWindowsApplication()
  400. {
  401. _app.Dispatcher.Invoke(_app.Shutdown);
  402. }
  403. private static void ShutdownWindowsService()
  404. {
  405. _logger.Info("Stopping background service");
  406. var service = new ServiceController(BackgroundService.Name);
  407. service.Refresh();
  408. if (service.Status == ServiceControllerStatus.Running)
  409. {
  410. service.Stop();
  411. }
  412. }
  413. /// <summary>
  414. /// Sets the error mode.
  415. /// </summary>
  416. /// <param name="uMode">The u mode.</param>
  417. /// <returns>ErrorModes.</returns>
  418. [DllImport("kernel32.dll")]
  419. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  420. /// <summary>
  421. /// Enum ErrorModes
  422. /// </summary>
  423. [Flags]
  424. public enum ErrorModes : uint
  425. {
  426. /// <summary>
  427. /// The SYSTE m_ DEFAULT
  428. /// </summary>
  429. SYSTEM_DEFAULT = 0x0,
  430. /// <summary>
  431. /// The SE m_ FAILCRITICALERRORS
  432. /// </summary>
  433. SEM_FAILCRITICALERRORS = 0x0001,
  434. /// <summary>
  435. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  436. /// </summary>
  437. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  438. /// <summary>
  439. /// The SE m_ NOGPFAULTERRORBOX
  440. /// </summary>
  441. SEM_NOGPFAULTERRORBOX = 0x0002,
  442. /// <summary>
  443. /// The SE m_ NOOPENFILEERRORBOX
  444. /// </summary>
  445. SEM_NOOPENFILEERRORBOX = 0x8000
  446. }
  447. }
  448. }