2
0

MainStartup.cs 17 KB

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