feat(backup): 系统设置里的存储与备份——定时时间与储存天数可配、下发到目标主机 cron

需求:整库逻辑备份做定时,但要在「系统设置 → 存储与备份」里设置定时时间与储存天数。

后端
- migration 000045 backup_schedule(单行:enabled/schedule_time/retention_days/retention_months/
  last_applied_*),store + 领域校验(HH:MM、1~365 天、0~24 月,非法值 400 且不落库不下发)
- internal/backuphost:通过 ssh 在目标主机上读回/下发计划并立即备份(未接线时 Available=false,
  页面降级提示;主机侧错误带输出回传)。最近一次只认有 MANIFEST.json 的完整目录,跳 *.incomplete
- 接口 GET/PUT /api/v1/backup-schedule、GET …/host、POST …/apply、POST …/run;
  写操作经 classifyRole 限管理员;run 为异步 202 + 在途单飞(http 写超时 30s,备份约 35s)
- openapi.yaml 补齐 5 条路由(契约测试要求每条都写 400/500)

主机侧
- scripts/install_backup_schedule.sh(幂等):写 /etc/knowledge-governance/backup-schedule.env 与
  /etc/cron.d/kb-logical-backup,参数校验,--show/--disable,最后一行 SCHEDULE_APPLIED 供平台核对
- logical-backup.sh 从该文件读保留策略;失败或被中断把目录改名 *.incomplete,不留'像成功'的半成品
- install --show 只回显计划行(原先把 SHELL=/PATH= 当计划显示)

前端
- web/src/backupSchedule.ts(严格解析:缺计划字段即报错,不把默认值伪装成设置)
- BackupScheduleSection:容器 + 纯视图(管理员表单/只读、已一致/待下发、在途轮询)

运行前提(已落实):运行镜像加 openssh-client,且容器 uid 1000 在 /etc/passwd 有名字
(否则 ssh 报 No user exists for uid 1000);凭据只读挂载 secrets/backup-host(git 忽略)

实测:主机 cron 每天 03:30 / 保留 7 天 / 每月 3 份;立即备份一次 34 秒 / 742.7 MiB / 失败 0;
Go 与前端测试全绿(170 vitest)。
This commit is contained in:
姚章浩
2026-10-09 13:50:23 +08:00
parent 4455d02262
commit 3f603aa293
25 changed files with 2353 additions and 11 deletions
+283
View File
@@ -0,0 +1,283 @@
// Package backuphost 在"目标库所在主机"上执行整库备份计划的下发、查询与立即执行。
//
// 为什么走 SSH 而不是平台自己连库:备份必须在数据面主机本地跑(同 VPC 直连 RDS、
// 内网写盘),平台的职责只是下发计划、读回结果。凭据是挂载进来的 0600 ssh 配置文件与
// 私钥(`secrets/backup-host/`),平台不保存任何主机密码。
package backuphost
import (
"context"
"encoding/json"
"errors"
"fmt"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
)
// ErrNotConfigured 表示没有挂载主机凭据(未接线):调用方据此降级展示,而不是报 500。
var ErrNotConfigured = errors.New("backup host is not configured")
// Config 描述如何连到目标库所在主机。
type Config struct {
// SSHConfig 是 `ssh -F` 用的配置文件路径(挂载进来的 0600 文件)。
SSHConfig string
// Target 是配置文件里的 Host 别名(如 weknora-test)。
Target string
// ScriptDir 是主机上备份脚本所在目录(install_backup_schedule.sh / logical-backup.sh)。
ScriptDir string
// Root 是主机上的备份根目录(与 backup_layout.sh 的契约一致,默认 /srv/kb-backups)。
Root string
// QueryTimeout 用于只读查询(查看计划、读最近一次结果)。
QueryTimeout time.Duration
// ApplyTimeout 用于下发计划。
ApplyTimeout time.Duration
// RunTimeout 用于"立即备份一次"(全库 pg_dump 约为分钟级)。
RunTimeout time.Duration
}
// ShowResult 是主机上当前的计划状态(页面"当前主机上的计划")。
type ShowResult struct {
ScheduleEnabled bool
ScheduleTime string
KeepDays int
KeepMonths int
CronLines []string
CronService string
ScriptPresent bool
Raw string
}
// ApplyResult 是下发结果,字段来自脚本最后一行 SCHEDULE_APPLIED。
type ApplyResult struct {
Enabled bool
Time string
Days int
Months int
NextRun string
CronFile string
Raw string
}
// RunResult 是一次整库备份的结果(来自主机上的 MANIFEST.json)。
type RunResult struct {
Stamp string
CreatedAt string
DurationSeconds int
TotalBytes int64
Databases []string
FailedDatabases []string
Raw string
}
// Runner 通过 ssh 执行主机侧脚本。exec 可注入,便于测试。
type Runner struct {
config Config
exec func(ctx context.Context, timeout time.Duration, remote string) (string, error)
}
// New 构造 Runner;config 为空时仍可用,只是 Available() 为 false。
func New(config Config) *Runner {
if config.QueryTimeout <= 0 {
config.QueryTimeout = 30 * time.Second
}
if config.ApplyTimeout <= 0 {
config.ApplyTimeout = 90 * time.Second
}
if config.RunTimeout <= 0 {
config.RunTimeout = 15 * time.Minute
}
if config.Root == "" {
config.Root = "/srv/kb-backups"
}
runner := &Runner{config: config}
runner.exec = runner.runRemote
return runner
}
// Available 报告主机凭据是否已接线。
func (r *Runner) Available() bool {
return r != nil && r.config.SSHConfig != "" && r.config.Target != "" && r.config.ScriptDir != ""
}
// Target 便于日志与页面显示连的是哪台主机。
func (r *Runner) Target() string {
if r == nil {
return ""
}
return r.config.Target
}
func (r *Runner) runRemote(ctx context.Context, timeout time.Duration, remote string) (string, error) {
if !r.Available() {
return "", ErrNotConfigured
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
command := exec.CommandContext(ctx, "ssh",
"-F", r.config.SSHConfig,
"-o", "BatchMode=yes",
"-o", "ConnectTimeout=10",
r.config.Target, remote)
output, err := command.CombinedOutput()
text := strings.TrimSpace(string(output))
if err != nil {
if ctx.Err() != nil {
return text, fmt.Errorf("ssh %s 超时(%s)", r.config.Target, timeout)
}
// 主机侧脚本会用退出码表达"参数非法/有库失败",把输出带回去便于页面展示。
return text, fmt.Errorf("ssh %s 执行失败: %s", r.config.Target, firstLines(text, 6))
}
return text, nil
}
var scheduleAppliedPattern = regexp.MustCompile(
`SCHEDULE_APPLIED enabled=(\d)(?: time=(\S+))?(?: days=(\d+))?(?: months=(\d+))?(?: next=(\S+))?(?: cron=(\S+))?`)
// Apply 下发计划(enabled=false 时关闭定时但保留已有备份)。
func (r *Runner) Apply(ctx context.Context, enabled bool, hhmm string, days, months int) (ApplyResult, error) {
if !r.Available() {
return ApplyResult{}, ErrNotConfigured
}
remote := fmt.Sprintf("bash %s/install_backup_schedule.sh --disable", r.config.ScriptDir)
if enabled {
remote = fmt.Sprintf("bash %s/install_backup_schedule.sh --time %s --days %d --months %d",
r.config.ScriptDir, hhmm, days, months)
}
output, err := r.exec(ctx, r.config.ApplyTimeout, remote)
if err != nil {
return ApplyResult{}.withRaw(output), err
}
result := ApplyResult{Raw: output}
match := scheduleAppliedPattern.FindStringSubmatch(output)
if match == nil {
return result, fmt.Errorf("下发结果无法识别(主机未按预期输出 SCHEDULE_APPLIED)")
}
result.Enabled = match[1] == "1"
result.Time = match[2]
result.Days = atoiOrZero(match[3])
result.Months = atoiOrZero(match[4])
result.NextRun = match[5]
result.CronFile = match[6]
return result, nil
}
func (result ApplyResult) withRaw(raw string) ApplyResult {
result.Raw = raw
return result
}
// Show 读回主机上的当前计划(参数文件 + cron 条目 + cron 服务状态)。
func (r *Runner) Show(ctx context.Context) (ShowResult, error) {
if !r.Available() {
return ShowResult{}, ErrNotConfigured
}
output, err := r.exec(ctx, r.config.QueryTimeout,
fmt.Sprintf("bash %s/install_backup_schedule.sh --show", r.config.ScriptDir))
if err != nil {
return ShowResult{Raw: output}, err
}
result := ShowResult{Raw: output}
for _, line := range strings.Split(output, "\n") {
switch {
case strings.HasPrefix(line, "备份脚本:"):
result.ScriptPresent = strings.Contains(line, "(存在)")
case strings.HasPrefix(line, "计划参数:"):
fields := parseKeyValues(strings.TrimPrefix(line, "计划参数:"))
result.ScheduleEnabled = fields["KB_BACKUP_SCHEDULE_ENABLED"] == "1"
result.ScheduleTime = fields["KB_BACKUP_SCHEDULE_TIME"]
result.KeepDays = atoiOrZero(fields["KB_BACKUP_KEEP_DAYS"])
result.KeepMonths = atoiOrZero(fields["KB_BACKUP_KEEP_MONTHS"])
case strings.HasPrefix(line, "cron 服务:"):
result.CronService = strings.TrimSpace(strings.TrimPrefix(line, "cron 服务:"))
case strings.HasPrefix(line, " "):
// 只收计划行:SHELL=/PATH= 这类环境行不是计划,回显出来会误导操作者。
if entry := strings.TrimSpace(line); entry != "" && !strings.HasPrefix(entry, "#") &&
!strings.Contains(entry, "=") {
result.CronLines = append(result.CronLines, entry)
}
}
}
return result, nil
}
// RunNow 立刻在主机上跑一次整库备份,并读回结果(页面"立即备份一次")。
func (r *Runner) RunNow(ctx context.Context) (RunResult, error) {
if !r.Available() {
return RunResult{}, ErrNotConfigured
}
if _, err := r.exec(ctx, r.config.RunTimeout,
fmt.Sprintf("bash %s/logical-backup.sh", r.config.ScriptDir)); err != nil {
return RunResult{}, err
}
return r.LastRun(ctx)
}
// LastRun 读回最近一次备份的清单摘要(时间/耗时/大小/失败的库)。
func (r *Runner) LastRun(ctx context.Context) (RunResult, error) {
if !r.Available() {
return RunResult{}, ErrNotConfigured
}
// 只认"有 MANIFEST.json 的完整目录":被中断的运行会被备份脚本改名成 *.incomplete,
// 这里再兜一层,避免把半成品当成"最近一次成功备份"。
remote := fmt.Sprintf(
`S=""; I=0; for d in $(ls -1t %s/rds-logical 2>/dev/null); do case "$d" in *.incomplete) I=$((I+1)); continue ;; esac; if [ -f "%s/rds-logical/$d/MANIFEST.json" ]; then S="$d"; break; fi; I=$((I+1)); done; echo "STAMP=$S"; echo "SKIPPED_INCOMPLETE=$I"; if [ -n "$S" ]; then cat "%s/rds-logical/$S/MANIFEST.json"; fi`,
r.config.Root, r.config.Root, r.config.Root)
output, err := r.exec(ctx, r.config.QueryTimeout, remote)
if err != nil {
return RunResult{Raw: output}, err
}
result := RunResult{Raw: output}
jsonStart := strings.Index(output, "{")
if strings.HasPrefix(output, "STAMP=") {
line := strings.SplitN(output, "\n", 2)[0]
result.Stamp = strings.TrimSpace(strings.TrimPrefix(line, "STAMP="))
}
if jsonStart < 0 {
return result, nil
}
var manifest struct {
CreatedAt string `json:"created_at"`
DurationSeconds int `json:"duration_seconds"`
TotalBytes int64 `json:"total_bytes"`
Databases []string `json:"databases"`
FailedDatabases []string `json:"failed_databases"`
}
if err := json.Unmarshal([]byte(output[jsonStart:]), &manifest); err != nil {
return result, fmt.Errorf("最近一次备份清单无法解析: %w", err)
}
result.CreatedAt = manifest.CreatedAt
result.DurationSeconds = manifest.DurationSeconds
result.TotalBytes = manifest.TotalBytes
result.Databases = manifest.Databases
result.FailedDatabases = manifest.FailedDatabases
return result, nil
}
func parseKeyValues(line string) map[string]string {
fields := map[string]string{}
for _, token := range strings.Fields(line) {
if key, value, found := strings.Cut(token, "="); found {
fields[key] = value
}
}
return fields
}
func atoiOrZero(text string) int {
value, err := strconv.Atoi(strings.TrimSpace(text))
if err != nil {
return 0
}
return value
}
func firstLines(text string, limit int) string {
lines := strings.Split(strings.TrimSpace(text), "\n")
if len(lines) > limit {
lines = lines[:limit]
}
return strings.Join(lines, " | ")
}
+210
View File
@@ -0,0 +1,210 @@
package backuphost
import (
"context"
"errors"
"strings"
"testing"
"time"
)
func testRunner(exec func(ctx context.Context, timeout time.Duration, remote string) (string, error)) *Runner {
runner := New(Config{
SSHConfig: "/run/backup-host/ssh_config",
Target: "weknora-test",
ScriptDir: "/opt/weknora-test",
Root: "/srv/kb-backups",
})
if exec != nil {
runner.exec = exec
}
return runner
}
func TestRunnerUnavailableWithoutCredentials(t *testing.T) {
runner := New(Config{})
if runner.Available() {
t.Fatal("没有凭据时不应判定为已接线")
}
for name, call := range map[string]func() error{
"Show": func() error { _, err := runner.Show(context.Background()); return err },
"Apply": func() error { _, err := runner.Apply(context.Background(), true, "03:30", 7, 3); return err },
"RunNow": func() error { _, err := runner.RunNow(context.Background()); return err },
} {
if err := call(); !errors.Is(err, ErrNotConfigured) {
t.Errorf("%s: 期望 ErrNotConfigured,得到 %v", name, err)
}
}
}
// 只给一半参数(缺 Target)也算未接线,避免"看起来接上了"。
func TestRunnerPartialConfigIsNotAvailable(t *testing.T) {
runner := New(Config{SSHConfig: "/run/backup-host/ssh_config"})
if runner.Available() {
t.Fatal("缺少 Target 时不应判定为已接线")
}
}
func TestRunnerApplyBuildsCommandAndParsesResult(t *testing.T) {
var seen string
runner := testRunner(func(_ context.Context, _ time.Duration, remote string) (string, error) {
seen = remote
return "计划已下发:每天 03:30(保留 7 天,另按自然月保留 3 份)\n" +
"SCHEDULE_APPLIED enabled=1 time=03:30 days=7 months=3 next=2026-10-10T03:30:00+0800 cron=/etc/cron.d/kb-logical-backup\n", nil
})
result, err := runner.Apply(context.Background(), true, "03:30", 7, 3)
if err != nil {
t.Fatal(err)
}
if seen != "bash /opt/weknora-test/install_backup_schedule.sh --time 03:30 --days 7 --months 3" {
t.Fatalf("下发的远端命令不对: %q", seen)
}
if !result.Enabled || result.Time != "03:30" || result.Days != 7 || result.Months != 3 {
t.Fatalf("结果解析不对: %+v", result)
}
if result.CronFile != "/etc/cron.d/kb-logical-backup" || result.NextRun != "2026-10-10T03:30:00+0800" {
t.Fatalf("cron/下次执行解析不对: %+v", result)
}
}
func TestRunnerApplyDisable(t *testing.T) {
var seen string
runner := testRunner(func(_ context.Context, _ time.Duration, remote string) (string, error) {
seen = remote
return "已关闭定时备份(已生成的备份保留)。\nSCHEDULE_APPLIED enabled=0\n", nil
})
result, err := runner.Apply(context.Background(), false, "03:30", 7, 3)
if err != nil {
t.Fatal(err)
}
if seen != "bash /opt/weknora-test/install_backup_schedule.sh --disable" {
t.Fatalf("关闭定时应调用 --disable: %q", seen)
}
if result.Enabled {
t.Fatal("关闭后 enabled 应为 false")
}
}
// 主机没按预期输出 SCHEDULE_APPLIED(例如脚本版本旧)时必须报错,绝不能默默当成功。
func TestRunnerApplyFailsWithoutMarker(t *testing.T) {
runner := testRunner(func(context.Context, time.Duration, string) (string, error) {
return "bash: /opt/weknora-test/install_backup_schedule.sh: No such file or directory\n", nil
})
if _, err := runner.Apply(context.Background(), true, "03:30", 7, 3); err == nil {
t.Fatal("缺少 SCHEDULE_APPLIED 应报错")
}
}
func TestRunnerShowParsesHostState(t *testing.T) {
runner := testRunner(func(context.Context, time.Duration, string) (string, error) {
return `备份脚本: /opt/weknora-test/logical-backup.sh (存在)
计划参数: KB_BACKUP_SCHEDULE_ENABLED=1 KB_BACKUP_SCHEDULE_TIME=03:30 KB_BACKUP_KEEP_DAYS=7 KB_BACKUP_KEEP_MONTHS=3 KB_BACKUP_SCRIPT=/opt/weknora-test/logical-backup.sh KB_BACKUP_LOG=/srv/kb-backups/logs/logical-backup.log
cron 条目:
30 03 * * * root /bin/bash /opt/weknora-test/logical-backup.sh >> /srv/kb-backups/logs/logical-backup.log 2>&1
cron 服务: active
备份根目录: /srv/kb-backups(758M 已用)
`, nil
})
show, err := runner.Show(context.Background())
if err != nil {
t.Fatal(err)
}
if !show.ScheduleEnabled || show.ScheduleTime != "03:30" || show.KeepDays != 7 || show.KeepMonths != 3 {
t.Fatalf("计划参数解析不对: %+v", show)
}
if len(show.CronLines) != 1 || !strings.Contains(show.CronLines[0], "logical-backup.sh") {
t.Fatalf("cron 条目解析不对: %+v", show.CronLines)
}
if show.CronService != "active" || !show.ScriptPresent {
t.Fatalf("服务/脚本状态解析不对: %+v", show)
}
}
// 未配置计划时主机输出"未配置/未安装",解析不能崩、也不能谎报为已启用。
func TestRunnerShowHandlesUnconfiguredHost(t *testing.T) {
runner := testRunner(func(context.Context, time.Duration, string) (string, error) {
return "备份脚本: /opt/weknora-test/logical-backup.sh (存在)\n计划参数: 未配置\ncron 条目: 未安装(定时关闭)\ncron 服务: active\n", nil
})
show, err := runner.Show(context.Background())
if err != nil {
t.Fatal(err)
}
if show.ScheduleEnabled || show.ScheduleTime != "" || len(show.CronLines) != 0 {
t.Fatalf("未配置主机不应解析成已启用: %+v", show)
}
}
func TestRunnerLastRunParsesManifest(t *testing.T) {
var seen string
runner := testRunner(func(_ context.Context, _ time.Duration, remote string) (string, error) {
seen = remote
return `STAMP=20261009T052909Z
{
"kind": "rds-logical-backup",
"created_at": "20261009T052909Z",
"duration_seconds": 33,
"databases": ["dobotai_prod", "weknora_test"],
"failed_databases": ["rdsadmin"],
"total_bytes": 778502144
}
`, nil
})
lastRun, err := runner.LastRun(context.Background())
if err != nil {
t.Fatal(err)
}
if !strings.Contains(seen, "/srv/kb-backups/rds-logical") {
t.Fatalf("应读取契约路径下的 rds-logical: %q", seen)
}
if lastRun.Stamp != "20261009T052909Z" || lastRun.DurationSeconds != 33 || lastRun.TotalBytes != 778502144 {
t.Fatalf("清单解析不对: %+v", lastRun)
}
if len(lastRun.FailedDatabases) != 1 || lastRun.FailedDatabases[0] != "rdsadmin" {
t.Fatalf("失败库解析不对: %+v", lastRun.FailedDatabases)
}
}
// 还没跑过备份:STAMP 为空且无清单,应得到空结果而不是错误。
func TestRunnerLastRunWithoutSnapshot(t *testing.T) {
runner := testRunner(func(context.Context, time.Duration, string) (string, error) {
return "STAMP=\n", nil
})
lastRun, err := runner.LastRun(context.Background())
if err != nil {
t.Fatal(err)
}
if lastRun.Stamp != "" || lastRun.DurationSeconds != 0 {
t.Fatalf("无备份时应为空结果: %+v", lastRun)
}
}
// 主机侧错误(ssh 失败、脚本非零退出)必须带着输出回传,页面才能显示原因。
func TestRunnerSurfacesHostFailure(t *testing.T) {
runner := testRunner(func(context.Context, time.Duration, string) (string, error) {
return "", errors.New("ssh weknora-test 执行失败: bash: install_backup_schedule.sh: No such file")
})
if _, err := runner.Show(context.Background()); err == nil || !strings.Contains(err.Error(), "No such file") {
t.Fatalf("应把主机侧失败原因带回来,得到 %v", err)
}
}
func TestRunnerRunNowReadsBackLastRun(t *testing.T) {
calls := 0
runner := testRunner(func(_ context.Context, _ time.Duration, remote string) (string, error) {
calls++
if strings.Contains(remote, "logical-backup.sh") && !strings.Contains(remote, "ls -1t") {
return "备份目标: /srv/kb-backups/rds-logical/20261009T060000Z\ndone: /srv/kb-backups/rds-logical/20261009T060000Z\n", nil
}
return "STAMP=20261009T060000Z\n{\"duration_seconds\": 34, \"total_bytes\": 800000000, \"failed_databases\": []}\n", nil
})
run, err := runner.RunNow(context.Background())
if err != nil {
t.Fatal(err)
}
if calls != 2 {
t.Fatalf("应立即执行一次并回读一次,实际调用 %d 次", calls)
}
if run.Stamp != "20261009T060000Z" || run.DurationSeconds != 34 || run.TotalBytes != 800000000 {
t.Fatalf("立即备份结果不对: %+v", run)
}
}