MainStartup.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. using MediaBrowser.Common.Constants;
  2. using MediaBrowser.Common.Implementations.Logging;
  3. using MediaBrowser.Common.Implementations.Updates;
  4. using MediaBrowser.Controller.IO;
  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.Runtime.InteropServices;
  16. using System.ServiceProcess;
  17. using System.Windows;
  18. namespace MediaBrowser.ServerApplication
  19. {
  20. public class MainStartup
  21. {
  22. private static ApplicationHost _appHost;
  23. private static App _app;
  24. private static ILogger _logger;
  25. private static bool _isRestarting = false;
  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);
  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. /// Begins the log.
  139. /// </summary>
  140. /// <param name="logger">The logger.</param>
  141. private static void BeginLog(ILogger logger)
  142. {
  143. logger.Info("Media Browser Server started");
  144. logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));
  145. logger.Info("Server: {0}", Environment.MachineName);
  146. logger.Info("Operating system: {0}", Environment.OSVersion.ToString());
  147. }
  148. /// <summary>
  149. /// Runs the application.
  150. /// </summary>
  151. /// <param name="appPaths">The app paths.</param>
  152. /// <param name="logManager">The log manager.</param>
  153. /// <param name="runService">if set to <c>true</c> [run service].</param>
  154. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService)
  155. {
  156. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  157. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  158. MigrateShortcuts(appPaths.RootFolderPath);
  159. _appHost = new ApplicationHost(appPaths, logManager);
  160. _app = new App(_appHost, _appHost.LogManager.GetLogger("App"), runService);
  161. if (runService)
  162. {
  163. _app.AppStarted += (sender, args) => StartService(logManager);
  164. }
  165. else
  166. {
  167. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  168. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  169. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  170. }
  171. _app.Run();
  172. }
  173. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  174. {
  175. if (e.Reason == SessionSwitchReason.SessionLogon)
  176. {
  177. BrowserLauncher.OpenDashboard(_appHost.UserManager, _appHost.ServerConfigurationManager, _appHost, _logger);
  178. }
  179. }
  180. /// <summary>
  181. /// Starts the service.
  182. /// </summary>
  183. private static void StartService(ILogManager logManager)
  184. {
  185. var service = new BackgroundService(logManager.GetLogger("Service"));
  186. service.Disposed += service_Disposed;
  187. ServiceBase.Run(service);
  188. }
  189. /// <summary>
  190. /// Handles the Disposed event of the service control.
  191. /// </summary>
  192. /// <param name="sender">The source of the event.</param>
  193. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  194. static void service_Disposed(object sender, EventArgs e)
  195. {
  196. OnServiceShutdown();
  197. }
  198. private static void OnServiceShutdown()
  199. {
  200. _logger.Info("Shutting down");
  201. _appHost.Dispose();
  202. if (!_isRunningAsService)
  203. {
  204. SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
  205. }
  206. if (_isRestarting)
  207. {
  208. Process.Start("cmd", "/c net start " + BackgroundService.Name);
  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. _appHost.LogManager.Flush();
  315. if (!_isRunningAsService)
  316. {
  317. _app.OnUnhandledException(exception);
  318. }
  319. if (!Debugger.IsAttached)
  320. {
  321. Environment.Exit(Marshal.GetHRForException(exception));
  322. }
  323. }
  324. /// <summary>
  325. /// Performs the update if needed.
  326. /// </summary>
  327. /// <param name="appPaths">The app paths.</param>
  328. /// <param name="logger">The logger.</param>
  329. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  330. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  331. {
  332. // Look for the existence of an update archive
  333. var updateArchive = Path.Combine(appPaths.TempUpdatePath, Constants.MbServerPkgName + ".zip");
  334. if (File.Exists(updateArchive))
  335. {
  336. logger.Info("An update is available from {0}", updateArchive);
  337. // Update is there - execute update
  338. try
  339. {
  340. var serviceName = _isRunningAsService ? BackgroundService.Name : string.Empty;
  341. new ApplicationUpdater().UpdateApplication(MBApplication.MBServer, appPaths, updateArchive, logger, serviceName);
  342. // And just let the app exit so it can update
  343. return true;
  344. }
  345. catch (Exception e)
  346. {
  347. logger.ErrorException("Error starting updater.", e);
  348. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  349. }
  350. }
  351. return false;
  352. }
  353. public static void Shutdown()
  354. {
  355. if (_isRunningAsService)
  356. {
  357. ShutdownWindowsService();
  358. }
  359. else
  360. {
  361. ShutdownWindowsApplication();
  362. }
  363. }
  364. public static void Restart()
  365. {
  366. _logger.Info("Disposing app host");
  367. _appHost.Dispose();
  368. _logger.Info("Starting new instance of server");
  369. RestartInternal();
  370. _logger.Info("Shutting down existing instance of server.");
  371. Shutdown();
  372. }
  373. private static void RestartInternal()
  374. {
  375. if (!_isRunningAsService)
  376. {
  377. _logger.Info("Starting server application");
  378. RestartWindowsApplication();
  379. }
  380. else
  381. {
  382. _logger.Info("Starting windows service");
  383. RestartWindowsService();
  384. }
  385. }
  386. private static void RestartWindowsApplication()
  387. {
  388. System.Windows.Forms.Application.Restart();
  389. }
  390. private static void RestartWindowsService()
  391. {
  392. _isRestarting = true;
  393. }
  394. private static void ShutdownWindowsApplication()
  395. {
  396. _app.Dispatcher.Invoke(_app.Shutdown);
  397. }
  398. private static void ShutdownWindowsService()
  399. {
  400. _logger.Info("Stopping background service");
  401. var service = new ServiceController(BackgroundService.Name);
  402. service.Refresh();
  403. if (service.Status == ServiceControllerStatus.Running)
  404. {
  405. service.Stop();
  406. }
  407. }
  408. /// <summary>
  409. /// Sets the error mode.
  410. /// </summary>
  411. /// <param name="uMode">The u mode.</param>
  412. /// <returns>ErrorModes.</returns>
  413. [DllImport("kernel32.dll")]
  414. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  415. /// <summary>
  416. /// Enum ErrorModes
  417. /// </summary>
  418. [Flags]
  419. public enum ErrorModes : uint
  420. {
  421. /// <summary>
  422. /// The SYSTE m_ DEFAULT
  423. /// </summary>
  424. SYSTEM_DEFAULT = 0x0,
  425. /// <summary>
  426. /// The SE m_ FAILCRITICALERRORS
  427. /// </summary>
  428. SEM_FAILCRITICALERRORS = 0x0001,
  429. /// <summary>
  430. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  431. /// </summary>
  432. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  433. /// <summary>
  434. /// The SE m_ NOGPFAULTERRORBOX
  435. /// </summary>
  436. SEM_NOGPFAULTERRORBOX = 0x0002,
  437. /// <summary>
  438. /// The SE m_ NOOPENFILEERRORBOX
  439. /// </summary>
  440. SEM_NOOPENFILEERRORBOX = 0x8000
  441. }
  442. private static void MigrateShortcuts(string directory)
  443. {
  444. Directory.CreateDirectory(directory);
  445. foreach (var file in Directory.EnumerateFiles(directory, "*.lnk", SearchOption.AllDirectories).ToList())
  446. {
  447. MigrateShortcut(file);
  448. }
  449. }
  450. private static void MigrateShortcut(string file)
  451. {
  452. var newFile = Path.ChangeExtension(file, ".mblink");
  453. try
  454. {
  455. var resolvedPath = FileSystem.ResolveShortcut(file);
  456. if (!string.IsNullOrEmpty(resolvedPath))
  457. {
  458. FileSystem.CreateShortcut(newFile, resolvedPath);
  459. }
  460. }
  461. finally
  462. {
  463. File.Delete(file);
  464. }
  465. }
  466. }
  467. }