Add configuration backup and import

This commit is contained in:
2026-08-27 09:44:20 +08:00
parent 70da7ffda6
commit e202a1eae2
3 changed files with 453 additions and 6 deletions
+300 -4
View File
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.IO.Compression;
using System.Text;
using System.Text.Json;
@@ -7,6 +8,11 @@ namespace NginxMan;
public sealed class NginxManager
{
private const string ConfigFileName = "nginxman.json";
private const string BackupTemplateEntryName = "www/index.template.html";
private const string ServiceCardsToken = "{{NGINXMAN_SERVICE_CARDS}}";
private const long MaximumConfigImportBytes = 5 * 1024 * 1024;
private const long MaximumTemplateImportBytes = 10 * 1024 * 1024;
private const int MaximumManagedBackups = 10;
private readonly string _baseDirectory;
private readonly string _dataDirectory;
@@ -27,6 +33,7 @@ public sealed class NginxManager
_baseDirectory = baseDirectory;
_dataDirectory = Path.Combine(_baseDirectory, "data");
Directory.CreateDirectory(_dataDirectory);
Directory.CreateDirectory(BackupDirectory);
WebPortal.ExtractTo(_dataDirectory);
_configPath = Path.Combine(_dataDirectory, ConfigFileName);
MoveLegacyConfigIfNeeded();
@@ -38,6 +45,8 @@ public sealed class NginxManager
public string ConfigPath => _configPath;
public string BackupDirectory => Path.Combine(_dataDirectory, "backups");
public IReadOnlyList<RouteEntry> Routes => _config.Routes.AsReadOnly();
public string PortalDomain => _config.PortalDomain;
@@ -212,6 +221,129 @@ public sealed class NginxManager
WebPortal.RenderTo(_dataDirectory, _config.Routes);
}
public string CreateBackup(string destinationPath)
{
if (string.IsNullOrWhiteSpace(destinationPath))
{
throw new ArgumentException("备份文件路径不能为空。", nameof(destinationPath));
}
SaveConfig();
var fullDestinationPath = Path.GetFullPath(destinationPath);
EnsureDirectory(Path.GetDirectoryName(fullDestinationPath));
var temporaryPath = fullDestinationPath + ".tmp-" + Guid.NewGuid().ToString("N");
try
{
using (var archive = ZipFile.Open(temporaryPath, ZipArchiveMode.Create))
{
archive.CreateEntryFromFile(_configPath, ConfigFileName, CompressionLevel.Optimal);
var templatePath = GetTemplatePath();
if (File.Exists(templatePath))
{
archive.CreateEntryFromFile(
templatePath,
BackupTemplateEntryName,
CompressionLevel.Optimal);
}
}
File.Move(temporaryPath, fullDestinationPath, overwrite: true);
return fullDestinationPath;
}
finally
{
if (File.Exists(temporaryPath))
{
File.Delete(temporaryPath);
}
}
}
public string CreateAutomaticBackup() => CreateTimestampedBackup("auto-close");
public string CreateManualBackup() => CreateTimestampedBackup("manual");
public BackupImportResult ImportBackup(string sourcePath)
{
if (string.IsNullOrWhiteSpace(sourcePath))
{
throw new ArgumentException("导入文件路径不能为空。", nameof(sourcePath));
}
var fullSourcePath = Path.GetFullPath(sourcePath);
if (!File.Exists(fullSourcePath))
{
throw new FileNotFoundException("未找到要导入的备份文件。", fullSourcePath);
}
var imported = ReadImportFile(fullSourcePath);
var importedConfig = DeserializeAndValidateImportedConfig(imported.ConfigJson);
if (imported.Template is not null &&
!imported.Template.Contains(ServiceCardsToken, StringComparison.Ordinal))
{
throw new InvalidDataException($"备份中的网页模板缺少入口占位符 {ServiceCardsToken}。");
}
var safetyBackupPath = CreateTimestampedBackup("before-import");
var previousConfig = _config;
var templatePath = GetTemplatePath();
var previousTemplate = File.Exists(templatePath)
? File.ReadAllText(templatePath, Encoding.UTF8)
: null;
try
{
_config = importedConfig;
if (imported.Template is not null)
{
EnsureDirectory(Path.GetDirectoryName(templatePath));
File.WriteAllText(templatePath, imported.Template, Utf8WithoutBom);
}
SaveConfig();
RenderConfig();
return new BackupImportResult(
fullSourcePath,
safetyBackupPath,
_config.Routes.Count,
imported.Template is not null);
}
catch (Exception importException)
{
_config = previousConfig;
try
{
if (imported.Template is not null)
{
if (previousTemplate is null)
{
if (File.Exists(templatePath))
{
File.Delete(templatePath);
}
}
else
{
File.WriteAllText(templatePath, previousTemplate, Utf8WithoutBom);
}
}
SaveConfig();
RenderConfig();
}
catch
{
// The safety backup remains available even if restoring files fails.
}
throw new InvalidOperationException(
$"导入失败,原配置已保留。导入前备份位于:{safetyBackupPath}",
importException);
}
}
private NginxManagerConfig LoadOrCreateConfig()
{
if (!File.Exists(_configPath))
@@ -245,6 +377,154 @@ public sealed class NginxManager
}
}
private string CreateTimestampedBackup(string category)
{
Directory.CreateDirectory(BackupDirectory);
var fileName = $"{DateTime.Now:yyyyMMdd-HHmmss-fff}-{category}.zip";
var backupPath = CreateBackup(Path.Combine(BackupDirectory, fileName));
PruneManagedBackups();
return backupPath;
}
private void PruneManagedBackups()
{
var managedBackups = Directory
.EnumerateFiles(BackupDirectory, "*.zip", SearchOption.TopDirectoryOnly)
.Where(path =>
Path.GetFileName(path).EndsWith("-auto-close.zip", StringComparison.OrdinalIgnoreCase) ||
Path.GetFileName(path).EndsWith("-before-import.zip", StringComparison.OrdinalIgnoreCase) ||
Path.GetFileName(path).EndsWith("-manual.zip", StringComparison.OrdinalIgnoreCase))
.Select(path => new FileInfo(path))
.OrderByDescending(file => file.LastWriteTimeUtc)
.ThenByDescending(file => file.Name, StringComparer.OrdinalIgnoreCase)
.Skip(MaximumManagedBackups)
.ToArray();
foreach (var oldBackup in managedBackups)
{
oldBackup.Delete();
}
}
private ImportedBackup ReadImportFile(string sourcePath)
{
var extension = Path.GetExtension(sourcePath);
if (extension.Equals(".json", StringComparison.OrdinalIgnoreCase))
{
var fileInfo = new FileInfo(sourcePath);
if (fileInfo.Length > MaximumConfigImportBytes)
{
throw new InvalidDataException("配置文件过大,无法导入。");
}
return new ImportedBackup(File.ReadAllText(sourcePath, Encoding.UTF8), null);
}
if (!extension.Equals(".zip", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidDataException("仅支持导入 .zip 备份包或 .json 配置文件。");
}
using var archive = ZipFile.OpenRead(sourcePath);
var configEntries = archive.Entries
.Where(entry => entry.FullName.Equals(ConfigFileName, StringComparison.OrdinalIgnoreCase))
.ToArray();
if (configEntries.Length != 1)
{
throw new InvalidDataException($"备份包必须包含且只能包含一个 {ConfigFileName}。");
}
var templateEntries = archive.Entries
.Where(entry => entry.FullName.Replace('\\', '/').Equals(
BackupTemplateEntryName,
StringComparison.OrdinalIgnoreCase))
.ToArray();
if (templateEntries.Length > 1)
{
throw new InvalidDataException("备份包中包含重复的网页模板。");
}
var configJson = ReadArchiveTextEntry(
configEntries[0],
MaximumConfigImportBytes,
"配置文件");
var template = templateEntries.Length == 1
? ReadArchiveTextEntry(templateEntries[0], MaximumTemplateImportBytes, "网页模板")
: null;
return new ImportedBackup(configJson, template);
}
private static string ReadArchiveTextEntry(ZipArchiveEntry entry, long maximumBytes, string displayName)
{
if (entry.Length > maximumBytes)
{
throw new InvalidDataException($"备份包中的{displayName}过大,无法导入。");
}
using var stream = entry.Open();
using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
return reader.ReadToEnd();
}
private static NginxManagerConfig DeserializeAndValidateImportedConfig(string json)
{
NginxManagerConfig config;
try
{
config = JsonSerializer.Deserialize<NginxManagerConfig>(json, JsonOptions)
?? throw new InvalidDataException("配置文件内容为空。");
}
catch (JsonException ex)
{
throw new InvalidDataException("配置文件不是有效的 JSON。", ex);
}
var defaults = DefaultConfig();
config.NginxExePath = NormalizePathSetting(config.NginxExePath, defaults.NginxExePath);
config.NginxConfPath = NormalizePathSetting(config.NginxConfPath, defaults.NginxConfPath);
config.AccessLogPath = NormalizePathSetting(config.AccessLogPath, defaults.AccessLogPath);
config.ErrorLogPath = NormalizePathSetting(config.ErrorLogPath, defaults.ErrorLogPath);
config.PortalDomain = NormalizeOptionalDomain(config.PortalDomain ?? string.Empty);
config.PortalListenPort = NormalizePort(config.PortalListenPort, "入口页监听端口");
config.Routes ??= [];
NormalizeDataPaths(config);
NormalizeRouteMetadata(config.Routes);
var domains = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var route in config.Routes)
{
if (route is null)
{
throw new InvalidDataException("代理映射中包含空记录。");
}
route.Domain = NormalizeDomain(route.Domain);
route.Upstream = NormalizeUpstream(route.Upstream);
route.ListenPort = NormalizePort(route.ListenPort, "监听端口");
route.WebsiteName = NormalizeRequiredText(route.WebsiteName, "网站名称");
route.Description = NormalizeRequiredText(route.Description, "网站简介");
if (!domains.Add(route.Domain))
{
throw new InvalidDataException($"配置中存在重复域名:{route.Domain}");
}
if (!string.IsNullOrWhiteSpace(config.PortalDomain) &&
config.PortalDomain.Equals(route.Domain, StringComparison.OrdinalIgnoreCase) &&
config.PortalListenPort == route.ListenPort)
{
throw new InvalidDataException("入口页不能与代理映射使用相同的域名和监听端口。");
}
}
return config;
}
private static string NormalizePathSetting(string? path, string fallback) =>
string.IsNullOrWhiteSpace(path) ? fallback : path.Trim();
private string GetTemplatePath() => Path.Combine(_dataDirectory, "www", "index.template.html");
private int RunNginx(string arguments, bool allowPersistentProcess = false)
{
var exe = ResolvePath(_config.NginxExePath);
@@ -476,13 +756,21 @@ public sealed class NginxManager
}
upstream = upstream.Trim();
if (upstream.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
upstream.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
if (!upstream.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
!upstream.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return upstream.TrimEnd('/');
upstream = "http://" + upstream;
}
return "http://" + upstream.TrimEnd('/');
upstream = upstream.TrimEnd('/');
if (!Uri.TryCreate(upstream, UriKind.Absolute, out var uri) ||
(uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) ||
string.IsNullOrWhiteSpace(uri.Host))
{
throw new ArgumentException("上游接口必须是有效的 http:// 或 https:// 地址。");
}
return upstream;
}
private static string NormalizeRequiredText(string value, string fieldName)
@@ -496,6 +784,14 @@ public sealed class NginxManager
}
}
public sealed record BackupImportResult(
string SourcePath,
string SafetyBackupPath,
int RouteCount,
bool TemplateImported);
internal sealed record ImportedBackup(string ConfigJson, string? Template);
public sealed class NginxManagerConfig
{
public string NginxExePath { get; set; } = "nginx.exe";