Radarr/NzbDrone/Providers/IISProvider.cs

240 lines
8.0 KiB
C#
Raw Normal View History

2010-10-15 07:10:44 +00:00
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Remoting;
using System.Timers;
using System.Xml.Linq;
using System.Xml.XPath;
2010-10-15 07:10:44 +00:00
using NLog;
namespace NzbDrone.Providers
2010-10-15 07:10:44 +00:00
{
2011-10-07 03:37:41 +00:00
internal class IISProvider
2010-10-15 07:10:44 +00:00
{
private readonly ConfigProvider _configProvider;
2010-10-15 07:10:44 +00:00
private static readonly Logger IISLogger = LogManager.GetLogger("IISExpress");
2011-10-07 03:37:41 +00:00
private static readonly Logger Logger = LogManager.GetLogger("IISProvider");
private readonly string IISExe;
private readonly string IISConfigPath;
private static Timer _pingTimer;
private static int _pingFailCounter;
2011-10-07 03:37:41 +00:00
private static Process _iisProcess;
2010-10-15 07:10:44 +00:00
2011-10-07 03:37:41 +00:00
public IISProvider(ConfigProvider configProvider)
{
_configProvider = configProvider;
IISExe = Path.Combine(_configProvider.IISFolder, @"iisexpress.exe");
IISConfigPath = Path.Combine(_configProvider.IISFolder, "AppServer", "applicationhost.config");
}
internal string AppUrl
2010-10-15 07:10:44 +00:00
{
get { return string.Format("http://localhost:{0}/", _configProvider.Port); }
2010-10-15 07:10:44 +00:00
}
2011-10-07 03:37:41 +00:00
internal int IISProcessId
{
get
{
if (_iisProcess == null)
{
throw new InvalidOperationException("IIS Process isn't running yet.");
}
return _iisProcess.Id;
}
}
internal Process StartServer()
2010-10-15 07:10:44 +00:00
{
Logger.Info("Preparing IISExpress Server...");
2011-10-07 03:37:41 +00:00
_iisProcess = new Process();
2010-10-15 07:10:44 +00:00
2011-10-07 03:37:41 +00:00
_iisProcess.StartInfo.FileName = IISExe;
_iisProcess.StartInfo.Arguments = String.Format("/config:\"{0}\" /trace:i", IISConfigPath);//"/config:"""" /trace:i";
_iisProcess.StartInfo.WorkingDirectory = _configProvider.ApplicationRoot;
2010-10-15 07:10:44 +00:00
2011-10-07 03:37:41 +00:00
_iisProcess.StartInfo.UseShellExecute = false;
_iisProcess.StartInfo.RedirectStandardOutput = true;
_iisProcess.StartInfo.RedirectStandardError = true;
_iisProcess.StartInfo.CreateNoWindow = true;
2010-10-15 07:10:44 +00:00
2011-10-07 03:37:41 +00:00
_iisProcess.OutputDataReceived += (OnOutputDataReceived);
_iisProcess.ErrorDataReceived += (OnErrorDataReceived);
2010-10-15 07:10:44 +00:00
//Set Variables for the config file.
2011-10-07 03:37:41 +00:00
_iisProcess.StartInfo.EnvironmentVariables.Add("NZBDRONE_PATH", _configProvider.ApplicationRoot);
_iisProcess.StartInfo.EnvironmentVariables.Add("NZBDRONE_PID", Process.GetCurrentProcess().Id.ToString());
try
{
UpdateIISConfig();
}
catch (Exception e)
{
Logger.ErrorException("An error has occurred while trying to update the config file.", e);
}
2010-10-15 07:10:44 +00:00
2011-10-07 03:37:41 +00:00
Logger.Info("Starting process. [{0}]", _iisProcess.StartInfo.FileName);
2011-04-25 03:51:18 +00:00
2011-07-17 20:01:37 +00:00
2011-10-07 03:37:41 +00:00
_iisProcess.Start();
_iisProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
2010-10-15 07:10:44 +00:00
2011-10-07 03:37:41 +00:00
_iisProcess.BeginErrorReadLine();
_iisProcess.BeginOutputReadLine();
2011-04-22 06:46:26 +00:00
//Start Ping
2011-06-22 06:34:33 +00:00
_pingTimer = new Timer(300000) { AutoReset = true };
_pingTimer.Elapsed += (PingServer);
2011-04-22 06:46:26 +00:00
_pingTimer.Start();
2011-10-07 03:37:41 +00:00
return _iisProcess;
2010-10-15 07:10:44 +00:00
}
2011-04-25 03:51:18 +00:00
private static void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e == null || String.IsNullOrWhiteSpace(e.Data))
return;
IISLogger.Error(e.Data);
}
internal void StopServer()
{
2011-10-07 03:37:41 +00:00
KillProcess(_iisProcess);
2011-04-22 06:46:26 +00:00
Logger.Info("Finding orphaned IIS Processes.");
foreach (var process in Process.GetProcessesByName("IISExpress"))
{
string processPath = process.MainModule.FileName;
Logger.Info("[{0}]IIS Process found. Path:{1}", process.Id, processPath);
2011-04-25 03:51:18 +00:00
if (NormalizePath(processPath) == NormalizePath(IISExe))
2011-04-22 06:46:26 +00:00
{
Logger.Info("[{0}]Process is considered orphaned.", process.Id);
KillProcess(process);
}
else
{
Logger.Info("[{0}]Process has a different start-up path. skipping.", process.Id);
}
}
}
private void RestartServer()
2011-04-22 06:46:26 +00:00
{
_pingTimer.Stop();
Logger.Warn("Attempting to restart server.");
StopServer();
StartServer();
}
private void PingServer(object sender, ElapsedEventArgs e)
{
try
{
var response = new WebClient().DownloadString(AppUrl + "/health");
if (!response.Contains("OK"))
{
throw new ServerException("Health services responded with an invalid response.");
}
if (_pingFailCounter > 0)
{
Logger.Info("Application pool has been successfully recovered.");
}
_pingFailCounter = 0;
}
catch (Exception ex)
{
_pingFailCounter++;
Logger.ErrorException("Application pool is not responding. Count " + _pingFailCounter, ex);
2011-04-22 06:46:26 +00:00
if (_pingFailCounter > 2)
{
2011-04-22 06:46:26 +00:00
RestartServer();
}
}
}
private void OnOutputDataReceived(object s, DataReceivedEventArgs e)
{
if (e == null || String.IsNullOrWhiteSpace(e.Data) || e.Data.StartsWith("Request started:") ||
2011-04-10 02:44:01 +00:00
e.Data.StartsWith("Request ended:") || e.Data == ("IncrementMessages called"))
return;
if (e.Data.Contains(" NzbDrone."))
{
Console.WriteLine(e.Data);
return;
}
IISLogger.Trace(e.Data);
}
private void UpdateIISConfig()
2010-10-15 07:10:44 +00:00
{
string configPath = Path.Combine(_configProvider.IISFolder, @"AppServer\applicationhost.config");
Logger.Info(@"Server configuration file: {0}", configPath);
Logger.Info(@"Configuring server to: [http://localhost:{0}]", _configProvider.Port);
var configXml = XDocument.Load(configPath);
2011-04-10 02:44:01 +00:00
var bindings =
configXml.XPathSelectElement("configuration/system.applicationHost/sites").Elements("site").Where(
d => d.Attribute("name").Value.ToLowerInvariant() == "nzbdrone").First().Element("bindings");
bindings.Descendants().Remove();
bindings.Add(
2011-04-10 02:44:01 +00:00
new XElement("binding",
new XAttribute("protocol", "http"),
new XAttribute("bindingInformation", String.Format("*:{0}:localhost", _configProvider.Port))
2011-04-10 02:44:01 +00:00
));
bindings.Add(
new XElement("binding",
new XAttribute("protocol", "http"),
new XAttribute("bindingInformation", String.Format("*:{0}:", _configProvider.Port))
));
configXml.Save(configPath);
2010-10-15 07:10:44 +00:00
}
private void KillProcess(Process process)
2011-04-22 06:46:26 +00:00
{
if (process != null && !process.HasExited)
{
Logger.Info("[{0}]Killing process", process.Id);
process.Kill();
Logger.Info("[{0}]Waiting for exit", process.Id);
process.WaitForExit();
Logger.Info("[{0}]Process terminated successfully", process.Id);
}
}
public string NormalizePath(string path)
2010-10-15 07:10:44 +00:00
{
2011-04-25 03:51:18 +00:00
if (String.IsNullOrWhiteSpace(path))
throw new ArgumentException("Path can not be null or empty");
var info = new FileInfo(path);
if (info.FullName.StartsWith(@"\\")) //UNC
{
return info.FullName.TrimEnd('/', '\\', ' ');
}
return info.FullName.Trim('/', '\\', ' ').ToLower();
2010-10-15 07:10:44 +00:00
}
2010-10-15 07:10:44 +00:00
}
2011-04-10 02:44:01 +00:00
}