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