jellyfin-server/MediaBrowser.ServerApplication/MainStartup.cs

560 lines
18 KiB
C#
Raw Normal View History

2013-09-28 18:07:30 +00:00
using System.Runtime.InteropServices;
using MediaBrowser.Common.Constants;
2013-09-21 01:04:14 +00:00
using MediaBrowser.Common.Implementations.Logging;
using MediaBrowser.Common.Implementations.Updates;
2013-10-01 20:20:48 +00:00
using MediaBrowser.Controller.IO;
2013-09-21 01:04:14 +00:00
using MediaBrowser.Model.Logging;
using MediaBrowser.Server.Implementations;
2013-09-28 18:07:30 +00:00
using MediaBrowser.ServerApplication.Native;
2013-09-21 01:04:14 +00:00
using Microsoft.Win32;
using System;
2013-09-27 21:09:21 +00:00
using System.ComponentModel;
2013-09-21 01:04:14 +00:00
using System.Configuration.Install;
using System.Diagnostics;
using System.IO;
2013-09-21 01:04:14 +00:00
using System.Linq;
using System.ServiceProcess;
using System.Windows;
namespace MediaBrowser.ServerApplication
{
public class MainStartup
{
2013-09-21 01:04:14 +00:00
private static ApplicationHost _appHost;
private static App _app;
2013-09-21 21:00:12 +00:00
private static ILogger _logger;
2013-09-27 21:09:21 +00:00
private static bool _isRestarting = false;
private static bool _isRunningAsService = false;
/// <summary>
/// Defines the entry point of the application.
/// </summary>
[STAThread]
public static void Main()
{
2013-09-21 01:04:14 +00:00
var startFlag = Environment.GetCommandLineArgs().ElementAtOrDefault(1);
2013-09-27 21:09:21 +00:00
_isRunningAsService = string.Equals(startFlag, "-service", StringComparison.OrdinalIgnoreCase);
2013-09-21 01:04:14 +00:00
2013-09-27 21:09:21 +00:00
var appPaths = CreateApplicationPaths(_isRunningAsService);
2013-09-21 01:04:14 +00:00
var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
logManager.ReloadLogger(LogSeverity.Info);
2013-09-21 21:00:12 +00:00
var logger = _logger = logManager.GetLogger("Main");
2013-09-21 01:04:14 +00:00
BeginLog(logger);
// Install directly
if (string.Equals(startFlag, "-installservice", StringComparison.OrdinalIgnoreCase))
{
logger.Info("Performing service installation");
InstallService(logger);
return;
}
// Restart with admin rights, then install
2013-09-21 01:15:19 +00:00
if (string.Equals(startFlag, "-installserviceasadmin", StringComparison.OrdinalIgnoreCase))
2013-09-21 01:04:14 +00:00
{
logger.Info("Performing service installation");
RunServiceInstallation();
return;
}
// Uninstall directly
if (string.Equals(startFlag, "-uninstallservice", StringComparison.OrdinalIgnoreCase))
{
logger.Info("Performing service uninstallation");
UninstallService(logger);
return;
}
// Restart with admin rights, then uninstall
2013-09-21 01:15:19 +00:00
if (string.Equals(startFlag, "-uninstallserviceasadmin", StringComparison.OrdinalIgnoreCase))
2013-09-21 01:04:14 +00:00
{
logger.Info("Performing service uninstallation");
RunServiceUninstallation();
return;
}
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
2013-09-27 21:09:21 +00:00
RunServiceInstallationIfNeeded();
2013-09-27 21:09:21 +00:00
var currentProcess = Process.GetCurrentProcess();
2013-09-27 21:09:21 +00:00
if (IsAlreadyRunning(currentProcess))
{
2013-09-21 01:04:14 +00:00
logger.Info("Shutting down because another instance of Media Browser Server is already running.");
return;
}
2013-09-21 01:04:14 +00:00
if (PerformUpdateIfNeeded(appPaths, logger))
{
2013-09-21 01:04:14 +00:00
logger.Info("Exiting to perform application update.");
return;
}
2013-09-21 01:04:14 +00:00
try
{
2013-09-27 21:09:21 +00:00
RunApplication(appPaths, logManager, _isRunningAsService);
}
2013-09-21 01:04:14 +00:00
finally
{
2013-09-27 21:09:21 +00:00
OnServiceShutdown();
}
}
2013-09-27 21:09:21 +00:00
/// <summary>
/// Determines whether [is already running] [the specified current process].
/// </summary>
/// <param name="currentProcess">The current process.</param>
/// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
private static bool IsAlreadyRunning(Process currentProcess)
{
var runningPath = Process.GetCurrentProcess().MainModule.FileName;
2013-09-21 01:04:14 +00:00
2013-09-27 21:09:21 +00:00
var duplicate = Process.GetProcesses().FirstOrDefault(i =>
{
try
{
return string.Equals(runningPath, i.MainModule.FileName) && currentProcess.Id != i.Id;
}
catch (Win32Exception)
{
return false;
}
});
if (duplicate != null)
{
_logger.Info("Found a duplicate process. Giving it time to exit.");
if (!duplicate.WaitForExit(5000))
{
_logger.Info("The duplicate process did not exit.");
return true;
}
2013-09-21 01:04:14 +00:00
}
2013-09-27 21:09:21 +00:00
return false;
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Creates the application paths.
/// </summary>
/// <param name="runAsService">if set to <c>true</c> [run as service].</param>
/// <returns>ServerApplicationPaths.</returns>
private static ServerApplicationPaths CreateApplicationPaths(bool runAsService)
{
if (runAsService)
{
#if (RELEASE)
var systemPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
var programDataPath = Path.GetDirectoryName(systemPath);
return new ServerApplicationPaths(programDataPath);
#endif
}
return new ServerApplicationPaths();
}
/// <summary>
/// Begins the log.
/// </summary>
/// <param name="logger">The logger.</param>
private static void BeginLog(ILogger logger)
{
logger.Info("Media Browser Server started");
logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));
logger.Info("Server: {0}", Environment.MachineName);
logger.Info("Operating system: {0}", Environment.OSVersion.ToString());
}
/// <summary>
/// Runs the application.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="logManager">The log manager.</param>
/// <param name="runService">if set to <c>true</c> [run service].</param>
private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService)
{
SystemEvents.SessionEnding += SystemEvents_SessionEnding;
2013-09-28 18:07:30 +00:00
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
2013-09-21 01:04:14 +00:00
2013-10-01 20:20:48 +00:00
MigrateShortcuts(appPaths.RootFolderPath);
2013-09-21 01:04:14 +00:00
_appHost = new ApplicationHost(appPaths, logManager);
_app = new App(_appHost, _appHost.LogManager.GetLogger("App"), runService);
if (runService)
{
2013-09-21 01:04:14 +00:00
_app.AppStarted += (sender, args) => StartService(logManager);
}
2013-09-28 18:07:30 +00:00
else
{
// Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
}
2013-09-21 01:04:14 +00:00
_app.Run();
}
2013-09-28 18:07:30 +00:00
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLogon)
{
BrowserLauncher.OpenDashboard(_appHost.UserManager, _appHost.ServerConfigurationManager, _appHost, _logger);
}
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Starts the service.
/// </summary>
private static void StartService(ILogManager logManager)
{
var service = new BackgroundService(logManager.GetLogger("Service"));
service.Disposed += service_Disposed;
ServiceBase.Run(service);
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Handles the Disposed event of the service control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
2013-09-27 21:09:21 +00:00
static void service_Disposed(object sender, EventArgs e)
{
OnServiceShutdown();
}
private static void OnServiceShutdown()
{
2013-09-27 21:09:21 +00:00
_logger.Info("Shutting down");
_appHost.Dispose();
2013-09-28 18:07:30 +00:00
if (!_isRunningAsService)
{
SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
}
2013-09-27 21:09:21 +00:00
if (_isRestarting)
{
using (var process = Process.Start("cmd", "/c net start " + BackgroundService.Name))
{
}
_logger.Info("New service process started");
}
_app.Dispatcher.Invoke(_app.Shutdown);
2013-09-21 01:04:14 +00:00
}
/// <summary>
/// Installs the service.
/// </summary>
private static void InstallService(ILogger logger)
{
var runningPath = Process.GetCurrentProcess().MainModule.FileName;
try
{
2013-09-21 01:04:14 +00:00
ManagedInstallerClass.InstallHelper(new[] { runningPath });
logger.Info("Service installation succeeded");
}
catch (Exception ex)
{
logger.ErrorException("Uninstall failed", ex);
}
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Uninstalls the service.
/// </summary>
private static void UninstallService(ILogger logger)
{
2013-09-21 01:04:14 +00:00
var runningPath = Process.GetCurrentProcess().MainModule.FileName;
2013-09-21 01:04:14 +00:00
try
{
ManagedInstallerClass.InstallHelper(new[] { "/u", runningPath });
2013-09-21 01:04:14 +00:00
logger.Info("Service uninstallation succeeded");
}
catch (Exception ex)
{
logger.ErrorException("Uninstall failed", ex);
}
}
2013-09-27 21:09:21 +00:00
private static void RunServiceInstallationIfNeeded()
{
var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == BackgroundService.Name);
if (ctl == null)
{
RunServiceInstallation();
}
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Runs the service installation.
/// </summary>
private static void RunServiceInstallation()
{
2013-09-21 01:04:14 +00:00
var runningPath = Process.GetCurrentProcess().MainModule.FileName;
var startInfo = new ProcessStartInfo
{
FileName = runningPath,
Arguments = "-installservice",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas",
ErrorDialog = false
};
2013-09-21 01:04:14 +00:00
using (var process = Process.Start(startInfo))
{
process.WaitForExit();
}
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Runs the service uninstallation.
/// </summary>
private static void RunServiceUninstallation()
{
2013-09-21 01:04:14 +00:00
var runningPath = Process.GetCurrentProcess().MainModule.FileName;
2013-09-21 01:04:14 +00:00
var startInfo = new ProcessStartInfo
{
2013-09-21 01:04:14 +00:00
FileName = runningPath,
Arguments = "-uninstallservice",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas",
ErrorDialog = false
};
using (var process = Process.Start(startInfo))
{
process.WaitForExit();
}
2013-09-21 01:04:14 +00:00
}
/// <summary>
/// Handles the SessionEnding event of the SystemEvents control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
2013-09-27 21:09:21 +00:00
if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
2013-09-21 21:00:12 +00:00
{
Shutdown();
}
2013-09-21 01:04:14 +00:00
}
/// <summary>
/// Handles the UnhandledException event of the CurrentDomain control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = (Exception)e.ExceptionObject;
2013-09-27 12:24:28 +00:00
_logger.ErrorException("UnhandledException", exception);
2013-09-26 21:20:26 +00:00
2013-09-27 21:09:21 +00:00
if (!_isRunningAsService)
2013-09-21 21:00:12 +00:00
{
_app.OnUnhandledException(exception);
}
if (!Debugger.IsAttached)
{
Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
}
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Performs the update if needed.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="logger">The logger.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
{
// Look for the existence of an update archive
var updateArchive = Path.Combine(appPaths.TempUpdatePath, Constants.MbServerPkgName + ".zip");
if (File.Exists(updateArchive))
{
logger.Info("An update is available from {0}", updateArchive);
// Update is there - execute update
try
{
new ApplicationUpdater().UpdateApplication(MBApplication.MBServer, appPaths, updateArchive);
// And just let the app exit so it can update
return true;
}
catch (Exception e)
{
MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
}
}
return false;
}
2013-09-21 21:00:12 +00:00
public static void Shutdown()
{
2013-09-27 21:09:21 +00:00
if (_isRunningAsService)
2013-09-21 21:00:12 +00:00
{
2013-09-27 21:09:21 +00:00
ShutdownWindowsService();
2013-09-21 21:00:12 +00:00
}
else
{
2013-09-27 21:09:21 +00:00
ShutdownWindowsApplication();
2013-09-21 21:00:12 +00:00
}
}
public static void Restart()
{
2013-09-27 21:09:21 +00:00
_logger.Info("Disposing app host");
2013-09-21 21:00:12 +00:00
_appHost.Dispose();
2013-09-27 21:09:21 +00:00
_logger.Info("Starting new instance of server");
2013-09-21 21:00:12 +00:00
RestartInternal();
2013-09-27 21:09:21 +00:00
_logger.Info("Shutting down existing instance of server.");
Shutdown();
2013-09-21 21:00:12 +00:00
}
private static void RestartInternal()
{
2013-09-27 21:09:21 +00:00
if (!_isRunningAsService)
2013-09-21 21:00:12 +00:00
{
2013-09-27 21:09:21 +00:00
_logger.Info("Starting server application");
RestartWindowsApplication();
2013-09-21 21:00:12 +00:00
}
else
{
2013-09-27 21:09:21 +00:00
_logger.Info("Starting windows service");
RestartWindowsService();
}
}
private static void RestartWindowsApplication()
{
System.Windows.Forms.Application.Restart();
}
private static void RestartWindowsService()
{
_isRestarting = true;
}
private static void ShutdownWindowsApplication()
{
_app.Dispatcher.Invoke(_app.Shutdown);
}
private static void ShutdownWindowsService()
{
_logger.Info("Stopping background service");
var service = new ServiceController(BackgroundService.Name);
service.Refresh();
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
2013-09-21 21:00:12 +00:00
}
}
2013-09-28 18:07:30 +00:00
/// <summary>
/// Sets the error mode.
/// </summary>
/// <param name="uMode">The u mode.</param>
/// <returns>ErrorModes.</returns>
[DllImport("kernel32.dll")]
static extern ErrorModes SetErrorMode(ErrorModes uMode);
/// <summary>
/// Enum ErrorModes
/// </summary>
[Flags]
public enum ErrorModes : uint
{
/// <summary>
/// The SYSTE m_ DEFAULT
/// </summary>
SYSTEM_DEFAULT = 0x0,
/// <summary>
/// The SE m_ FAILCRITICALERRORS
/// </summary>
SEM_FAILCRITICALERRORS = 0x0001,
/// <summary>
/// The SE m_ NOALIGNMENTFAULTEXCEPT
/// </summary>
SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
/// <summary>
/// The SE m_ NOGPFAULTERRORBOX
/// </summary>
SEM_NOGPFAULTERRORBOX = 0x0002,
/// <summary>
/// The SE m_ NOOPENFILEERRORBOX
/// </summary>
SEM_NOOPENFILEERRORBOX = 0x8000
}
2013-10-01 20:20:48 +00:00
private static void MigrateShortcuts(string directory)
{
Directory.CreateDirectory(directory);
foreach (var file in Directory.EnumerateFiles(directory, "*.lnk", SearchOption.AllDirectories).ToList())
{
MigrateShortcut(file);
}
}
private static void MigrateShortcut(string file)
{
var newFile = Path.ChangeExtension(file, ".mblink");
try
{
var resolvedPath = FileSystem.ResolveShortcut(file);
if (!string.IsNullOrEmpty(resolvedPath))
{
FileSystem.CreateShortcut(newFile, resolvedPath);
}
}
finally
{
File.Delete(file);
}
}
}
}