2
0

MainStartup.cs 18 KB

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