Files
NginxMan/NginxManager.cs
T
2026-08-27 09:05:06 +08:00

486 lines
15 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();
}
public string ConfigPath => _configPath;
public IReadOnlyList<RouteEntry> Routes => _config.Routes.AsReadOnly();
public string NginxExePath
{
get => _config.NginxExePath;
set
{
_config.NginxExePath = value;
SaveConfig();
}
}
public bool IsRunning => Process.GetProcessesByName("nginx").Any();
public void AddOrUpdateRoute(
string domain,
string upstream,
int listenPort,
string websiteName,
string description)
{
domain = NormalizeDomain(domain);
upstream = NormalizeUpstream(upstream);
websiteName = NormalizeRequiredText(websiteName, "网站名称");
description = NormalizeRequiredText(description, "网站简介");
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);
websiteName = NormalizeRequiredText(websiteName, "网站名称");
description = NormalizeRequiredText(description, "网站简介");
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()
{
if (_config.Routes.Count == 0)
{
throw new InvalidOperationException("至少需要 1 条域名映射才能生成配置。");
}
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();
}
if (config.Routes is null || config.Routes.Count == 0)
{
config.Routes = DefaultConfig().Routes;
}
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();
var portalRoot = Path.Combine(_dataDirectory, "www").Replace('\\', '/');
sb.AppendLine(" server {");
sb.AppendLine(" listen 80;");
sb.AppendLine(" server_name www.m3frame.com;");
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"),
Routes =
[
new RouteEntry
{
Domain = "team.m3frame.com",
Upstream = "http://127.0.0.1:803",
ListenPort = 80,
WebsiteName = "Team Workspace",
Description = "团队协作、项目推进与知识沉淀,让成员始终连接在同一节奏。"
},
new RouteEntry
{
Domain = "git.m3frame.com",
Upstream = "http://127.0.0.1:3062",
ListenPort = 80,
WebsiteName = "Git Forge",
Description = "代码托管、版本审查与持续交付,把每一次提交变成可靠的软件。"
}
]
};
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.ToLowerInvariant() switch
{
"team.m3frame.com" => "Team Workspace",
"git.m3frame.com" => "Git Forge",
_ => route.Domain
};
}
if (string.IsNullOrWhiteSpace(route.Description))
{
route.Description = route.Domain.ToLowerInvariant() switch
{
"team.m3frame.com" => "团队协作、项目推进与知识沉淀,让成员始终连接在同一节奏。",
"git.m3frame.com" => "代码托管、版本审查与持续交付,把每一次提交变成可靠的软件。",
_ => $"访问 {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("域名不能为空");
}
return domain.Trim().TrimEnd('.');
}
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 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;
}