MainStartup.cs 18 KB

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