Files
knowledge-governance/internal/backuphost/runner.go
T
姚章浩 5e1482e349
build / build (push) Successful in 1m40s
feat(library): 恢复验证成为可页面发起的真实作业
根因:生产可恢复性只有 PRODUCTION_BACKUP_RESTORE_VERIFIED 这个手填 env 开关,
页面没有任何入口去真跑一次恢复;CLI(librarydrill)又不是 worker 能复用的实现,
所以"已验证"既证明不了跑过、也证明不了跑的是当前目标。

改动:
- 共享实现 internal/libraryverify(维护隔离→捕获→基线校验→canary→恢复→复核→关窗口),
  cmd/librarydrill 改为薄封装,CLI 与 worker 只允许一份执行体。
- verify 成为独立业务作业:kind + VerifyStages(capture/verify/canary/restore/finalize),
  与 sync/restore/baseline 共用同一把写互斥;迁移 79 加 kind 约束、重建部分唯一索引、
  新建 library_restore_verifications(按 target_id 绑定,换库/索引/桶旧证据自动失效,
  同 target+scope+job 幂等)。
- worker:admitLibraryJob + runOwnedLibraryAttempt 之后调用共享实现,阶段实时写
  library_job_stages,结束后写真实终态;通过写 passed 证据,失败写 failed+原因(不伪成功);
  中断接管按同一作业 id 收掉维护窗口。
- API:POST/GET /api/v1/library/verifications(管理员;闸口关闭/维护中拒绝;返回完整
  整库目标、最近证据、失败原因),OpenAPI 同步。
- 闸口:同步/恢复/续作的证据判断改为读当前目标证据;历史 env 仅在证据缺失时兜底,
  证据存在时以证据为准。
- 页面:生产保护与恢复面板加「恢复验证」块(完整 KB/索引/桶、状态、最近证据、失败原因、
  管理员按钮、5s 轮询),作业类型补 verify 文案。

测试:make verify 16/16 全绿(go 1387 例 + web 454 例 + 契约/迁移/密钥/依赖锁定);
新增用例覆盖证据四条件、闸口证据优先、页面无证据/失败/通过三种呈现与管理员可见性。
2026-11-03 10:14:08 +08:00

355 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package backuphost 在"目标库所在主机"上执行整库备份计划的下发、查询与立即执行。
//
// 为什么走 SSH 而不是平台自己连库:备份必须在数据面主机本地跑(同 VPC 直连 RDS、
// 内网写盘),平台的职责只是下发计划、读回结果。凭据是挂载进来的 0600 ssh 配置文件与
// 私钥(`secrets/backup-host/`),平台不保存任何主机密码。
package backuphost
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"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, hostFailure(r.config.Target, text)
}
return text, nil
}
// hostFailure 把 ssh 的非零退出分成两类:连不上,和连上了但远端命令失败。
func hostFailure(target, text string) error {
if connectionFailurePattern.MatchString(text) {
return fmt.Errorf("目标主机 %s 不可达(%s);未执行任何主机侧脚本,脚本与计划状态未知",
target, firstLines(text, 3))
}
// 主机侧脚本会用退出码表达"参数非法/有库失败",把输出带回去便于页面展示。
return fmt.Errorf("已连上 %s,但主机侧命令失败: %s", target, firstLines(text, 6))
}
// connectionFailurePattern 是 OpenSSH 客户端在"根本没建立连接"时打的原文。
// 只有命中它才允许说"不可达";其余非零退出属于远端命令自己的失败。
var connectionFailurePattern = regexp.MustCompile(`(?i)ssh: connect to host|Operation timed out|Connection timed out|Connection refused|Connection reset by peer|No route to host|Network is unreachable|Could not resolve hostname|Host key verification failed|Permission denied|Connection closed by`)
// Endpoint 读回挂载的 ssh 配置里本别名真实拨号的 host:port。
// 页面必须能说清"现在连的是哪个地址"——只显示别名时,改错文件也看不出来。
func (r *Runner) Endpoint() string {
if r == nil || r.config.SSHConfig == "" || r.config.Target == "" {
return ""
}
raw, err := os.ReadFile(r.config.SSHConfig)
if err != nil {
return ""
}
host, port := sshConfigEndpoint(string(raw), r.config.Target)
if host == "" {
return ""
}
if port == "" {
port = "22"
}
return net.JoinHostPort(host, port)
}
// sshConfigEndpoint 解析 `Host <alias>` 段的 HostName/Port(首个匹配段生效)。
// 只做"页面显示用"的最小解析,不替代 ssh 自己的配置语义。
func sshConfigEndpoint(config, alias string) (string, string) {
host, port := "", ""
active := false
for _, line := range strings.Split(config, "\n") {
fields := strings.Fields(strings.TrimSpace(line))
if len(fields) == 0 || strings.HasPrefix(fields[0], "#") {
continue
}
key := strings.ToLower(fields[0])
if key == "host" {
active = false
for _, pattern := range fields[1:] {
if pattern == alias {
active = true
break
}
}
continue
}
if !active || len(fields) < 2 {
continue
}
switch key {
case "hostname":
host = strings.Trim(fields[1], `"`)
case "port":
port = strings.Trim(fields[1], `"`)
}
}
return host, port
}
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, " | ")
}