Files
NginxMan/NginxManager.cs
T

518 lines
16 KiB
C#

using System.Diagnostics;
using System.Text;
using System.Text.Json;
namespace NginxMan;
public sealed class NginxManager
{
private const string ConfigFileName = "nginxman.json";
private readonly string _baseDirectory;
private readonly string _dataDirectory;
private readonly string _configPath;
private NginxManagerConfig _config;
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
private static readonly UTF8Encoding Utf8WithoutBom = new(false);
public NginxManager(string baseDirectory)
{
_baseDirectory = baseDirectory;
_dataDirectory = Path.Combine(_baseDirectory, "data");
Directory.CreateDirectory(_dataDirectory);
WebPortal.ExtractTo(_dataDirectory);
_configPath = Path.Combine(_dataDirectory, ConfigFileName);
MoveLegacyConfigIfNeeded();
_config = LoadOrCreateConfig();
ConfigureBundledNginx();
SaveConfig();
RenderConfig();
}
public string ConfigPath => _configPath;
public IReadOnlyList<RouteEntry> Routes => _config.Routes.AsReadOnly();
public string PortalDomain => _config.PortalDomain;
public int PortalListenPort => _config.PortalListenPort;
public string NginxExePath
{
get => _config.NginxExePath;
set
{
_config.NginxExePath = value;
SaveConfig();
}
}
public bool IsRunning => Process.GetProcessesByName("nginx").Any();
public void UpdatePortalSettings(string domain, int listenPort)
{
domain = NormalizeOptionalDomain(domain);
listenPort = NormalizePort(listenPort, "入口页监听端口");
if (!string.IsNullOrWhiteSpace(domain) &&
_config.Routes.Any(route =>
route.Domain.Equals(domain, StringComparison.OrdinalIgnoreCase) &&
route.ListenPort == listenPort))
{
throw new InvalidOperationException("入口页域名和端口不能与现有代理映射完全相同。");
}
_config.PortalDomain = domain;
_config.PortalListenPort = listenPort;
SaveConfig();
}
public void AddOrUpdateRoute(
string domain,
string upstream,
int listenPort,
string websiteName,
string description)
{
domain = NormalizeDomain(domain);
upstream = NormalizeUpstream(upstream);
listenPort = NormalizePort(listenPort, "监听端口");
websiteName = NormalizeRequiredText(websiteName, "网站名称");
description = NormalizeRequiredText(description, "网站简介");
EnsureRouteDoesNotConflictWithPortal(domain, listenPort);
var index = _config.Routes.FindIndex(x => x.Domain.Equals(domain, StringComparison.OrdinalIgnoreCase));
if (index >= 0)
{
_config.Routes[index] = new RouteEntry
{
Domain = domain,
Upstream = upstream,
ListenPort = listenPort,
WebsiteName = websiteName,
Description = description
};
}
else
{
_config.Routes.Add(new RouteEntry
{
Domain = domain,
Upstream = upstream,
ListenPort = listenPort,
WebsiteName = websiteName,
Description = description
});
}
SaveConfig();
}
public bool UpdateRoute(
string oldDomain,
string newDomain,
string upstream,
int listenPort,
string websiteName,
string description)
{
oldDomain = NormalizeDomain(oldDomain);
newDomain = NormalizeDomain(newDomain);
upstream = NormalizeUpstream(upstream);
listenPort = NormalizePort(listenPort, "监听端口");
websiteName = NormalizeRequiredText(websiteName, "网站名称");
description = NormalizeRequiredText(description, "网站简介");
EnsureRouteDoesNotConflictWithPortal(newDomain, listenPort);
var oldIndex = _config.Routes.FindIndex(x => x.Domain.Equals(oldDomain, StringComparison.OrdinalIgnoreCase));
if (oldIndex < 0)
{
return false;
}
if (!oldDomain.Equals(newDomain, StringComparison.OrdinalIgnoreCase))
{
var duplicate = _config.Routes.Any(
x => x.Domain.Equals(newDomain, StringComparison.OrdinalIgnoreCase) &&
!x.Domain.Equals(oldDomain, StringComparison.OrdinalIgnoreCase));
if (duplicate)
{
throw new InvalidOperationException($"域名已存在: {newDomain}");
}
}
_config.Routes[oldIndex] = new RouteEntry
{
Domain = newDomain,
Upstream = upstream,
ListenPort = listenPort,
WebsiteName = websiteName,
Description = description
};
SaveConfig();
return true;
}
public bool RemoveRoute(string domain)
{
domain = NormalizeDomain(domain);
var removed = _config.Routes.RemoveAll(x => x.Domain.Equals(domain, StringComparison.OrdinalIgnoreCase));
if (removed <= 0)
{
return false;
}
SaveConfig();
return true;
}
public string RenderConfig()
{
var confPath = ResolvePath(_config.NginxConfPath);
EnsureDirectory(Path.GetDirectoryName(confPath));
var accessLog = ResolvePath(_config.AccessLogPath);
var errorLog = ResolvePath(_config.ErrorLogPath);
EnsureDirectory(Path.GetDirectoryName(accessLog));
EnsureDirectory(Path.GetDirectoryName(errorLog));
var content = BuildNginxConfContent(accessLog, errorLog);
File.WriteAllText(confPath, content, Utf8WithoutBom);
return confPath;
}
public int Start()
{
var conf = RenderConfig();
return RunNginx($"-c \"{conf}\"", allowPersistentProcess: true);
}
public int Reload()
{
var conf = RenderConfig();
return RunNginx($"-c \"{conf}\" -s reload");
}
public int Stop()
{
return RunNginx("-s stop");
}
public void SaveConfig()
{
File.WriteAllText(_configPath, JsonSerializer.Serialize(_config, JsonOptions), Encoding.UTF8);
WebPortal.RenderTo(_dataDirectory, _config.Routes);
}
private NginxManagerConfig LoadOrCreateConfig()
{
if (!File.Exists(_configPath))
{
return DefaultConfig();
}
try
{
var json = File.ReadAllText(_configPath, Encoding.UTF8);
var config = JsonSerializer.Deserialize<NginxManagerConfig>(json, JsonOptions);
if (config is null)
{
return DefaultConfig();
}
config.Routes ??= [];
if (config.PortalListenPort is < 1 or > 65535)
{
config.PortalListenPort = 80;
}
NormalizeDataPaths(config);
NormalizeRouteMetadata(config.Routes);
return config;
}
catch
{
return DefaultConfig();
}
}
private int RunNginx(string arguments, bool allowPersistentProcess = false)
{
var exe = ResolvePath(_config.NginxExePath);
if (!File.Exists(exe))
{
throw new FileNotFoundException($"未找到 nginx.exe: {exe}。请先配置正确路径。");
}
var workingDirectory = Path.GetDirectoryName(exe) ?? _baseDirectory;
Directory.CreateDirectory(Path.Combine(workingDirectory, "logs"));
Directory.CreateDirectory(Path.Combine(workingDirectory, "temp"));
using var process = new Process();
process.StartInfo = new ProcessStartInfo
{
FileName = exe,
Arguments = arguments,
WorkingDirectory = workingDirectory,
UseShellExecute = false,
CreateNoWindow = true
};
process.Start();
if (!process.WaitForExit(10000))
{
if (allowPersistentProcess && IsRunning)
{
return 0;
}
throw new TimeoutException("Nginx 执行超时,请检查 data\\logs\\error.log。");
}
if (process.ExitCode != 0)
{
throw new InvalidOperationException(
$"Nginx 执行失败,退出码: {process.ExitCode}\n请检查 data\\logs\\error.log。");
}
return process.ExitCode;
}
private string BuildNginxConfContent(string accessLog, string errorLog)
{
var nginxAccessLog = accessLog.Replace('\\', '/');
var nginxErrorLog = errorLog.Replace('\\', '/');
var sb = new StringBuilder();
sb.AppendLine("worker_processes 1;");
sb.AppendLine("events { worker_connections 1024; }");
sb.AppendLine("http {");
sb.AppendLine(" default_type application/octet-stream;");
sb.AppendLine(" sendfile on;");
sb.AppendLine($" access_log {nginxAccessLog};");
sb.AppendLine($" error_log {nginxErrorLog} warn;");
sb.AppendLine(" keepalive_timeout 65;");
sb.AppendLine();
if (!string.IsNullOrWhiteSpace(_config.PortalDomain))
{
var portalRoot = Path.Combine(_dataDirectory, "www").Replace('\\', '/');
sb.AppendLine(" server {");
sb.AppendLine($" listen {_config.PortalListenPort};");
sb.AppendLine($" server_name {_config.PortalDomain};");
sb.AppendLine($" root \"{portalRoot}\";");
sb.AppendLine(" index index.html;");
sb.AppendLine(" location / {");
sb.AppendLine(" try_files $uri $uri/ /index.html;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
}
foreach (var route in _config.Routes)
{
sb.AppendLine(" server {");
sb.AppendLine($" listen {route.ListenPort};");
sb.AppendLine($" server_name {route.Domain};");
sb.AppendLine(" location / {");
sb.AppendLine($" proxy_pass {route.Upstream};");
sb.AppendLine(" proxy_set_header Host $host;");
sb.AppendLine(" proxy_set_header X-Real-IP $remote_addr;");
sb.AppendLine(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;");
sb.AppendLine(" proxy_set_header X-Forwarded-Proto $scheme;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
}
sb.AppendLine("}");
return sb.ToString();
}
private static NginxManagerConfig DefaultConfig() => new()
{
NginxExePath = Path.Combine("data", "nginx", "nginx.exe"),
NginxConfPath = Path.Combine("data", "nginx.conf"),
AccessLogPath = Path.Combine("data", "logs", "access.log"),
ErrorLogPath = Path.Combine("data", "logs", "error.log"),
PortalDomain = string.Empty,
PortalListenPort = 80,
Routes = []
};
private void ConfigureBundledNginx()
{
var bundledExePath = BundledNginx.ExtractTo(_dataDirectory);
if (bundledExePath is null ||
!string.Equals(_config.NginxExePath, "nginx.exe", StringComparison.OrdinalIgnoreCase))
{
return;
}
_config.NginxExePath = Path.GetRelativePath(_baseDirectory, bundledExePath);
}
private void MoveLegacyConfigIfNeeded()
{
var legacyConfigPath = Path.Combine(_baseDirectory, ConfigFileName);
if (!File.Exists(_configPath) && File.Exists(legacyConfigPath))
{
File.Move(legacyConfigPath, _configPath);
}
}
private static void NormalizeDataPaths(NginxManagerConfig config)
{
if (IsLegacyPath(config.NginxConfPath, "nginx.conf"))
{
config.NginxConfPath = Path.Combine("data", "nginx.conf");
}
if (IsLegacyPath(config.AccessLogPath, Path.Combine("logs", "access.log")))
{
config.AccessLogPath = Path.Combine("data", "logs", "access.log");
}
if (IsLegacyPath(config.ErrorLogPath, Path.Combine("logs", "error.log")))
{
config.ErrorLogPath = Path.Combine("data", "logs", "error.log");
}
}
private static void NormalizeRouteMetadata(IEnumerable<RouteEntry> routes)
{
foreach (var route in routes)
{
if (string.IsNullOrWhiteSpace(route.WebsiteName))
{
route.WebsiteName = route.Domain;
}
if (string.IsNullOrWhiteSpace(route.Description))
{
route.Description = $"访问 {route.Domain} 服务。";
}
}
}
private static bool IsLegacyPath(string path, string expectedPath) =>
string.Equals(
path.Replace('/', '\\'),
expectedPath.Replace('/', '\\'),
StringComparison.OrdinalIgnoreCase);
private string ResolvePath(string path)
{
if (Path.IsPathFullyQualified(path))
{
return Path.GetFullPath(path);
}
return Path.GetFullPath(Path.Combine(_baseDirectory, path));
}
private static void EnsureDirectory(string? directory)
{
if (string.IsNullOrWhiteSpace(directory))
{
return;
}
Directory.CreateDirectory(directory);
}
private static string NormalizeDomain(string domain)
{
if (string.IsNullOrWhiteSpace(domain))
{
throw new ArgumentException("域名不能为空");
}
domain = domain.Trim().TrimEnd('.');
if (domain.Contains("://", StringComparison.Ordinal) || domain.Contains('/') ||
domain.Any(char.IsWhiteSpace) || Uri.CheckHostName(domain) == UriHostNameType.Unknown)
{
throw new ArgumentException("请输入有效域名,例如 app.example.com。");
}
return domain;
}
private static string NormalizeOptionalDomain(string domain) =>
string.IsNullOrWhiteSpace(domain) ? string.Empty : NormalizeDomain(domain);
private static int NormalizePort(int port, string fieldName)
{
if (port is < 1 or > 65535)
{
throw new ArgumentOutOfRangeException(nameof(port), $"{fieldName}必须在 1 到 65535 之间。");
}
return port;
}
private void EnsureRouteDoesNotConflictWithPortal(string domain, int listenPort)
{
if (!string.IsNullOrWhiteSpace(_config.PortalDomain) &&
_config.PortalDomain.Equals(domain, StringComparison.OrdinalIgnoreCase) &&
_config.PortalListenPort == listenPort)
{
throw new InvalidOperationException("代理映射不能与入口页使用相同的域名和监听端口。");
}
}
private static string NormalizeUpstream(string upstream)
{
if (string.IsNullOrWhiteSpace(upstream))
{
throw new ArgumentException("上游地址不能为空");
}
upstream = upstream.Trim();
if (upstream.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
upstream.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return upstream.TrimEnd('/');
}
return "http://" + upstream.TrimEnd('/');
}
private static string NormalizeRequiredText(string value, string fieldName)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException($"{fieldName}不能为空");
}
return value.Trim();
}
}
public sealed class NginxManagerConfig
{
public string NginxExePath { get; set; } = "nginx.exe";
public string NginxConfPath { get; set; } = "nginx.conf";
public string AccessLogPath { get; set; } = Path.Combine("logs", "access.log");
public string ErrorLogPath { get; set; } = Path.Combine("logs", "error.log");
public string PortalDomain { get; set; } = string.Empty;
public int PortalListenPort { get; set; } = 80;
public List<RouteEntry> Routes { get; set; } = [];
}
public sealed class RouteEntry
{
public string Domain { get; set; } = string.Empty;
public string Upstream { get; set; } = string.Empty;
public int ListenPort { get; set; } = 80;
public string WebsiteName { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}