MainStartup.cs 18 KB

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