MainStartup.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 = Process.GetCurrentProcess().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 (Win32Exception)
  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. #if (RELEASE)
  130. var systemPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
  131. var programDataPath = Path.GetDirectoryName(systemPath);
  132. return new ServerApplicationPaths(programDataPath);
  133. #endif
  134. }
  135. return new ServerApplicationPaths();
  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 true;
  146. }
  147. }
  148. /// <summary>
  149. /// Begins the log.
  150. /// </summary>
  151. /// <param name="logger">The logger.</param>
  152. /// <param name="appPaths">The app paths.</param>
  153. private static void BeginLog(ILogger logger, IApplicationPaths appPaths)
  154. {
  155. logger.Info("Media Browser Server started");
  156. logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));
  157. logger.Info("Server: {0}", Environment.MachineName);
  158. logger.Info("Operating system: {0}", Environment.OSVersion.ToString());
  159. logger.Info("Program data path: {0}", appPaths.ProgramDataPath);
  160. }
  161. /// <summary>
  162. /// Runs the application.
  163. /// </summary>
  164. /// <param name="appPaths">The app paths.</param>
  165. /// <param name="logManager">The log manager.</param>
  166. /// <param name="runService">if set to <c>true</c> [run service].</param>
  167. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService)
  168. {
  169. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  170. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  171. MigrateShortcuts(appPaths.RootFolderPath);
  172. _appHost = new ApplicationHost(appPaths, logManager);
  173. _app = new App(_appHost, _appHost.LogManager.GetLogger("App"), runService);
  174. if (runService)
  175. {
  176. _app.AppStarted += (sender, args) => StartService(logManager);
  177. }
  178. else
  179. {
  180. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  181. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  182. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  183. }
  184. _app.Run();
  185. }
  186. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  187. {
  188. if (e.Reason == SessionSwitchReason.SessionLogon)
  189. {
  190. BrowserLauncher.OpenDashboard(_appHost.UserManager, _appHost.ServerConfigurationManager, _appHost, _logger);
  191. }
  192. }
  193. /// <summary>
  194. /// Starts the service.
  195. /// </summary>
  196. private static void StartService(ILogManager logManager)
  197. {
  198. var service = new BackgroundService(logManager.GetLogger("Service"));
  199. service.Disposed += service_Disposed;
  200. ServiceBase.Run(service);
  201. }
  202. /// <summary>
  203. /// Handles the Disposed event of the service control.
  204. /// </summary>
  205. /// <param name="sender">The source of the event.</param>
  206. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  207. static void service_Disposed(object sender, EventArgs e)
  208. {
  209. OnServiceShutdown();
  210. }
  211. private static void OnServiceShutdown()
  212. {
  213. _logger.Info("Shutting down");
  214. _appHost.Dispose();
  215. if (!_isRunningAsService)
  216. {
  217. SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
  218. }
  219. _app.Dispatcher.Invoke(_app.Shutdown);
  220. }
  221. /// <summary>
  222. /// Installs the service.
  223. /// </summary>
  224. private static void InstallService(ILogger logger)
  225. {
  226. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  227. try
  228. {
  229. ManagedInstallerClass.InstallHelper(new[] { runningPath });
  230. using (var process = Process.Start("cmd.exe", "/c sc failure " + BackgroundService.Name + " reset= 0 actions= restart/1000/restart/1000/restart/60000"))
  231. {
  232. process.WaitForExit();
  233. }
  234. logger.Info("Service installation succeeded");
  235. }
  236. catch (Exception ex)
  237. {
  238. logger.ErrorException("Uninstall failed", ex);
  239. }
  240. }
  241. /// <summary>
  242. /// Uninstalls the service.
  243. /// </summary>
  244. private static void UninstallService(ILogger logger)
  245. {
  246. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  247. try
  248. {
  249. ManagedInstallerClass.InstallHelper(new[] { "/u", runningPath });
  250. logger.Info("Service uninstallation succeeded");
  251. }
  252. catch (Exception ex)
  253. {
  254. logger.ErrorException("Uninstall failed", ex);
  255. }
  256. }
  257. private static void RunServiceInstallationIfNeeded()
  258. {
  259. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == BackgroundService.Name);
  260. if (ctl == null)
  261. {
  262. RunServiceInstallation();
  263. }
  264. }
  265. /// <summary>
  266. /// Runs the service installation.
  267. /// </summary>
  268. private static void RunServiceInstallation()
  269. {
  270. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  271. var startInfo = new ProcessStartInfo
  272. {
  273. FileName = runningPath,
  274. Arguments = "-installservice",
  275. CreateNoWindow = true,
  276. WindowStyle = ProcessWindowStyle.Hidden,
  277. Verb = "runas",
  278. ErrorDialog = false
  279. };
  280. using (var process = Process.Start(startInfo))
  281. {
  282. process.WaitForExit();
  283. }
  284. }
  285. /// <summary>
  286. /// Runs the service uninstallation.
  287. /// </summary>
  288. private static void RunServiceUninstallation()
  289. {
  290. var runningPath = Process.GetCurrentProcess().MainModule.FileName;
  291. var startInfo = new ProcessStartInfo
  292. {
  293. FileName = runningPath,
  294. Arguments = "-uninstallservice",
  295. CreateNoWindow = true,
  296. WindowStyle = ProcessWindowStyle.Hidden,
  297. Verb = "runas",
  298. ErrorDialog = false
  299. };
  300. using (var process = Process.Start(startInfo))
  301. {
  302. process.WaitForExit();
  303. }
  304. }
  305. /// <summary>
  306. /// Handles the SessionEnding event of the SystemEvents control.
  307. /// </summary>
  308. /// <param name="sender">The source of the event.</param>
  309. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  310. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  311. {
  312. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  313. {
  314. Shutdown();
  315. }
  316. }
  317. /// <summary>
  318. /// Handles the UnhandledException event of the CurrentDomain control.
  319. /// </summary>
  320. /// <param name="sender">The source of the event.</param>
  321. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  322. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  323. {
  324. var exception = (Exception)e.ExceptionObject;
  325. _logger.ErrorException("UnhandledException", exception);
  326. _appHost.LogManager.Flush();
  327. if (!_isRunningAsService)
  328. {
  329. _app.OnUnhandledException(exception);
  330. }
  331. if (!Debugger.IsAttached)
  332. {
  333. Environment.Exit(Marshal.GetHRForException(exception));
  334. }
  335. }
  336. /// <summary>
  337. /// Performs the update if needed.
  338. /// </summary>
  339. /// <param name="appPaths">The app paths.</param>
  340. /// <param name="logger">The logger.</param>
  341. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  342. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  343. {
  344. // Look for the existence of an update archive
  345. var updateArchive = Path.Combine(appPaths.TempUpdatePath, Constants.MbServerPkgName + ".zip");
  346. if (File.Exists(updateArchive))
  347. {
  348. logger.Info("An update is available from {0}", updateArchive);
  349. // Update is there - execute update
  350. try
  351. {
  352. var serviceName = _isRunningAsService ? BackgroundService.Name : string.Empty;
  353. new ApplicationUpdater().UpdateApplication(MBApplication.MBServer, appPaths, updateArchive, logger, serviceName);
  354. // And just let the app exit so it can update
  355. return true;
  356. }
  357. catch (Exception e)
  358. {
  359. logger.ErrorException("Error starting updater.", e);
  360. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  361. }
  362. }
  363. return false;
  364. }
  365. public static void Shutdown()
  366. {
  367. if (_isRunningAsService)
  368. {
  369. ShutdownWindowsService();
  370. }
  371. else
  372. {
  373. ShutdownWindowsApplication();
  374. }
  375. }
  376. public static void Restart()
  377. {
  378. _logger.Info("Disposing app host");
  379. _appHost.Dispose();
  380. if (!_isRunningAsService)
  381. {
  382. _logger.Info("Starting server application");
  383. RestartWindowsApplication();
  384. }
  385. else
  386. {
  387. _logger.Info("Calling Enviornment.Exit to tell Windows to restart the server.");
  388. Environment.Exit(1);
  389. }
  390. }
  391. private static void RestartWindowsApplication()
  392. {
  393. System.Windows.Forms.Application.Restart();
  394. }
  395. private static void ShutdownWindowsApplication()
  396. {
  397. _app.Dispatcher.Invoke(_app.Shutdown);
  398. }
  399. private static void ShutdownWindowsService()
  400. {
  401. _logger.Info("Stopping background service");
  402. var service = new ServiceController(BackgroundService.Name);
  403. service.Refresh();
  404. if (service.Status == ServiceControllerStatus.Running)
  405. {
  406. service.Stop();
  407. }
  408. }
  409. /// <summary>
  410. /// Sets the error mode.
  411. /// </summary>
  412. /// <param name="uMode">The u mode.</param>
  413. /// <returns>ErrorModes.</returns>
  414. [DllImport("kernel32.dll")]
  415. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  416. /// <summary>
  417. /// Enum ErrorModes
  418. /// </summary>
  419. [Flags]
  420. public enum ErrorModes : uint
  421. {
  422. /// <summary>
  423. /// The SYSTE m_ DEFAULT
  424. /// </summary>
  425. SYSTEM_DEFAULT = 0x0,
  426. /// <summary>
  427. /// The SE m_ FAILCRITICALERRORS
  428. /// </summary>
  429. SEM_FAILCRITICALERRORS = 0x0001,
  430. /// <summary>
  431. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  432. /// </summary>
  433. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  434. /// <summary>
  435. /// The SE m_ NOGPFAULTERRORBOX
  436. /// </summary>
  437. SEM_NOGPFAULTERRORBOX = 0x0002,
  438. /// <summary>
  439. /// The SE m_ NOOPENFILEERRORBOX
  440. /// </summary>
  441. SEM_NOOPENFILEERRORBOX = 0x8000
  442. }
  443. private static void MigrateShortcuts(string directory)
  444. {
  445. Directory.CreateDirectory(directory);
  446. foreach (var file in Directory.EnumerateFiles(directory, "*.lnk", SearchOption.AllDirectories).ToList())
  447. {
  448. MigrateShortcut(file);
  449. }
  450. }
  451. private static void MigrateShortcut(string file)
  452. {
  453. var newFile = Path.ChangeExtension(file, ".mblink");
  454. try
  455. {
  456. var resolvedPath = FileSystem.ResolveShortcut(file);
  457. if (!string.IsNullOrEmpty(resolvedPath))
  458. {
  459. FileSystem.CreateShortcut(newFile, resolvedPath);
  460. }
  461. }
  462. finally
  463. {
  464. File.Delete(file);
  465. }
  466. }
  467. }
  468. }