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
+115 -2
View File
@@ -28,10 +28,13 @@ public sealed class MainForm : Form
private Button _btnStart = null!;
private Button _btnReload = null!;
private Button _btnStop = null!;
private Button _btnBackup = null!;
private Button _btnImport = null!;
private Button _btnRefreshStatus = null!;
private Button _btnSavePortal = null!;
private string? _selectedDomain;
private bool _closingBackupCreated;
public MainForm(NginxManager manager)
{
@@ -79,6 +82,7 @@ public sealed class MainForm : Form
root.Controls.Add(CreateRouteListPanel(), 0, 2);
root.Controls.Add(CreateEditorPanel(), 0, 3);
Controls.Add(root);
FormClosing += OnFormClosingBackup;
}
private Control CreateHeaderPanel()
@@ -316,12 +320,16 @@ public sealed class MainForm : Form
_btnStart = CreateButton("启动代理", 110, Color.FromArgb(37, 123, 80), Color.White);
_btnReload = CreateButton("重新加载", 110);
_btnStop = CreateButton("停止代理", 110, Color.FromArgb(177, 53, 53), Color.White);
_btnBackup = CreateButton("手动备份", 110);
_btnImport = CreateButton("导入备份", 110);
_btnRender.Click += async (s, e) => await RenderOnlyAsync();
_btnStart.Click += async (s, e) => await RunNginxAsync("启动", _manager.Start, expectedRunning: true);
_btnReload.Click += async (s, e) => await RunNginxAsync("重新加载", _manager.Reload, expectedRunning: true);
_btnStop.Click += async (s, e) => await RunNginxAsync("停止", _manager.Stop, expectedRunning: false);
actions.Controls.AddRange([_btnRender, _btnStart, _btnReload, _btnStop]);
return CreateSectionPanel("Nginx 操作", actions);
_btnBackup.Click += (s, e) => ManualBackup();
_btnImport.Click += (s, e) => ImportBackup();
actions.Controls.AddRange([_btnRender, _btnStart, _btnReload, _btnStop, _btnBackup, _btnImport]);
return CreateSectionPanel("Nginx 与数据", actions);
}
private Control CreateSectionPanel(string title, Control content)
@@ -446,6 +454,8 @@ public sealed class MainForm : Form
_btnStart.Enabled = true;
_btnReload.Enabled = false;
_btnStop.Enabled = false;
_btnBackup.Enabled = true;
_btnImport.Enabled = true;
return;
}
@@ -458,6 +468,8 @@ public sealed class MainForm : Form
_btnStart.Enabled = !isRunning;
_btnReload.Enabled = isRunning;
_btnStop.Enabled = isRunning;
_btnBackup.Enabled = true;
_btnImport.Enabled = true;
}
private async Task RunNginxAsync(string actionName, Func<int> action, bool expectedRunning)
@@ -507,9 +519,110 @@ public sealed class MainForm : Form
_btnStart.Enabled = enabled;
_btnReload.Enabled = enabled;
_btnStop.Enabled = enabled;
_btnBackup.Enabled = enabled;
_btnImport.Enabled = enabled;
_btnRefreshStatus.Enabled = enabled;
}
private void ManualBackup()
{
try
{
var path = _manager.CreateManualBackup();
MessageBox.Show(
$"备份已完成:\n{path}\n\n备份目录最多保留最新 10 个文件。",
"NginxMan",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"备份失败:\n{ex.Message}", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ImportBackup()
{
using var dialog = new OpenFileDialog
{
Filter = "NginxMan 备份或配置 (*.zip;*.json)|*.zip;*.json|ZIP 备份包 (*.zip)|*.zip|JSON 配置 (*.json)|*.json",
CheckFileExists = true,
InitialDirectory = _manager.BackupDirectory,
RestoreDirectory = true
};
if (dialog.ShowDialog(this) != DialogResult.OK)
{
return;
}
var confirm = MessageBox.Show(
"导入会替换当前配置,并重新生成入口页与 Nginx 配置。\n\n程序会先自动创建一份“导入前”备份。是否继续?",
"确认导入",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
if (confirm != DialogResult.Yes)
{
return;
}
try
{
var wasRunning = _manager.IsRunning;
var result = _manager.ImportBackup(dialog.FileName);
RefreshBasicInfo();
LoadDataGrid();
ClearForm();
RefreshStatus();
var reloadTip = wasRunning
? "\n\nNginx 当前正在运行,请点击“重新加载”使导入的代理配置生效。"
: string.Empty;
MessageBox.Show(
$"导入完成,共恢复 {result.RouteCount} 条映射。\n导入前备份:\n{result.SafetyBackupPath}{reloadTip}",
"NginxMan",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"导入失败:\n{ex.Message}", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void OnFormClosingBackup(object? sender, FormClosingEventArgs e)
{
if (_closingBackupCreated)
{
return;
}
try
{
_manager.CreateAutomaticBackup();
_closingBackupCreated = true;
}
catch (Exception ex)
{
if (e.CloseReason is CloseReason.WindowsShutDown or CloseReason.TaskManagerClosing)
{
return;
}
var result = MessageBox.Show(
$"关闭前自动备份失败:\n{ex.Message}\n\n是否仍然关闭程序?",
"NginxMan",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button2);
if (result != DialogResult.Yes)
{
e.Cancel = true;
}
}
}
private async Task RenderOnlyAsync()
{
try
+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";
+38
View File
@@ -25,6 +25,9 @@ NginxMan 主要用于:
- **入口页生成**:根据所有代理映射自动生成 `data/www/index.html`。
- **网页模板**:入口页样式保存在 `data/www/index.template.html`,入口卡片由程序动态填充。
- **配置持久化**:设置保存在 `data/nginxman.json`,重启程序后继续使用。
- **手动备份**:可将当前配置和可编辑入口页模板保存为一个 ZIP 备份包。
- **关闭时备份**:正常关闭程序时,自动在 `data/backups` 中保存一份备份。
- **手动导入**:支持导入 NginxMan ZIP 备份包,也兼容直接导入旧的 `nginxman.json`。
- **自定义 Nginx**:既可以使用内置 Nginx,也可以在界面中选择其他 `nginx.exe`。
## 配置组成
@@ -138,6 +141,8 @@ app.example.com -> 服务器 IP
| 启动代理 | 生成配置并启动 Nginx |
| 重新加载 | 让正在运行的 Nginx 读取最新配置 |
| 停止代理 | 停止 Nginx |
| 手动备份 | 将当前配置与入口页模板打包到 `data/backups`,并只保留最新 10 份 |
| 导入备份 | 导入 ZIP 备份包或旧版 JSON 配置;导入前会自动备份当前数据 |
| 刷新状态 | 重新检查 Nginx 进程状态 |
| 打开配置文件 | 打开 `nginxman.json` |
| 打开文件夹 | 打开配置文件所在目录 |
@@ -155,6 +160,7 @@ bin\
├─ nginx.conf # 自动生成的 Nginx 配置
├─ nginx\ # 内置 Nginx 运行文件
├─ logs\ # 访问日志和错误日志
├─ backups\ # 手动、关闭时和导入前安全备份(最多 10 份)
└─ www\
├─ index.template.html # 可编辑的入口页模板
└─ index.html # 自动生成的入口页
@@ -162,6 +168,38 @@ bin\
升级或替换 `NginxMan.exe` 时,请保留 `bin/data` 目录,以免丢失用户配置、模板和日志。
## 备份与恢复
### 手动备份
点击“手动备份”,程序会在 `data/backups` 中创建以时间开头的文件,例如 `20260827-103015-123-manual.zip`。生成的 ZIP 备份包包含:
- `nginxman.json`:入口页设置、Nginx 路径和全部代理映射。
- `www/index.template.html`:当前可编辑的网站入口页模板。
运行日志、自动生成的 `nginx.conf`、`index.html` 和 Nginx 程序文件不会写入备份;这些内容可以由程序重新生成,或不属于用户配置。
### 关闭时自动备份
通过窗口关闭按钮、快捷键或正常退出程序时,NginxMan 会自动创建以时间开头的备份:
```text
data\backups\年年年年月月日日-时时分分秒秒-毫秒-auto-close.zip
```
文件名使用固定宽度时间格式,按名称排序即可直观看到备份先后。`data/backups` 中的手动备份、关闭备份和导入前备份合计最多保留最新 10 个,超过数量后自动删除最旧文件。自动备份失败时,正常交互关闭会提示是否仍然退出。系统关机过程中不会阻止 Windows 关闭。
### 手动导入
点击“导入备份”,可以选择:
- NginxMan 生成的 `.zip` 备份包;
- 旧版本或手工保存的 `nginxman.json`。
程序会先读取并校验全部配置。校验通过后,会在 `data/backups` 中创建 `年年年年月月日日-时时分分秒秒-毫秒-before-import.zip`,然后才替换当前配置、恢复备份包中的网页模板,并重新生成入口页和 Nginx 配置。损坏的 ZIP、无效 JSON、重复域名、错误端口或缺少入口占位符的网页模板不会覆盖现有数据。
如果导入时 Nginx 正在运行,导入完成后请点击“重新加载”,使新的代理配置生效。
## 配置文件示例
`data/nginxman.json` 的结构示例: