feat(backup): 只读盘点真实批次、子库路径与容量
为什么:28189 验收里历史批次/子库路径/容量都没有真实接口,页面只能占位; 用户要求修实际接口而不是继续改文案,同时不得写主机或触发备份。 怎么改:新增 GET /api/v1/backup-schedule/inventory,只读盘点 statfs 实测容量、 st_blocks 实际占盘、全部批次与 MANIFEST 状态、每个子库完整主机路径。目录必须 只读挂载;用设备号区分挂载文件系统与容器根盘,同设备时不给主机容量。清单 missing/invalid、未接线、不可读分别展示。SSH 计划读回与盘点独立加载。 前端消费该接口:整盘色带、批次列表、子库路径复制、清单失败与容器根盘提示。 怎么验:Go 单测覆盖清单/占盘/符号链接/容器根盘;handler 契约;appconfig 接线校验; vitest 627 项、tsc、vite build、prettier 通过;本地页面夹具核对 8 批与路径复制, 1440/1024/768 无横向溢出。未连接真实主机、未执行备份、未改真实计划。
This commit is contained in:
@@ -68,6 +68,11 @@ type Config struct {
|
||||
BackupHostTarget string
|
||||
BackupHostScriptDir string
|
||||
BackupHostRoot string
|
||||
// BackupHostReadonlyRoot 是容器内只读挂载的 rds-logical 目录(批次/子库/实测容量)。
|
||||
// 留空即"未接线";它与上面的 SSH 计划读回是两条独立通道。
|
||||
BackupHostReadonlyRoot string
|
||||
BackupHostReadonlyHostPath string
|
||||
BackupHostReadonlySource string
|
||||
// 版本记录(「版本记录」页):**匿名只读**远端仓库的提交与 tag。来源留空即"未接线"
|
||||
// (页面降级展示,接口返回可用性=false)。只允许配置里批准的 origin 与仓库,
|
||||
// 不接受任何调用方传入的 URL;本功能**不使用凭据**。
|
||||
@@ -223,6 +228,9 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
|
||||
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
|
||||
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
|
||||
BackupHostReadonlyRoot: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_ROOT")),
|
||||
BackupHostReadonlyHostPath: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_HOST_PATH")),
|
||||
BackupHostReadonlySource: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_SOURCE")),
|
||||
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
|
||||
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
|
||||
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
|
||||
@@ -518,6 +526,25 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("TEST_AUTO_REVIEW_POLICY must be one of off, internal, all")
|
||||
}
|
||||
config.TestAutoReviewPolicy = string(normalizedPolicy)
|
||||
// 只读盘点接线与生产发布开关无关:测试栈也可能要先读通历史批次。
|
||||
if config.BackupHostReadonlyRoot != "" && !filepath.IsAbs(config.BackupHostReadonlyRoot) {
|
||||
return Config{}, errors.New("BACKUP_HOST_READONLY_ROOT must be an absolute path")
|
||||
}
|
||||
if config.BackupHostReadonlyHostPath != "" && !filepath.IsAbs(config.BackupHostReadonlyHostPath) {
|
||||
return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH must be an absolute path")
|
||||
}
|
||||
if config.BackupHostReadonlyRoot != "" && config.BackupHostReadonlyHostPath == "" {
|
||||
return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH is required when read-only root is set")
|
||||
}
|
||||
if config.BackupHostReadonlyRoot == "" &&
|
||||
(config.BackupHostReadonlyHostPath != "" || config.BackupHostReadonlySource != "") {
|
||||
return Config{}, errors.New("BACKUP_HOST_READONLY_ROOT is required when host path/source is set")
|
||||
}
|
||||
for _, value := range []string{config.BackupHostReadonlyHostPath, config.BackupHostReadonlySource} {
|
||||
if strings.ContainsAny(value, "\x00\r\n") {
|
||||
return Config{}, errors.New("backup inventory display path/source contains control characters")
|
||||
}
|
||||
}
|
||||
if config.ProductionReleaseRequestsEnabled {
|
||||
// 目标主机凭据要么都给要么都不给:只给一半会把"未接线"伪装成"已接线"。
|
||||
if (config.BackupHostSSHConfig == "") != (config.BackupHostTarget == "") {
|
||||
|
||||
@@ -53,6 +53,40 @@ func TestLoadUsesSafeDefaults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadValidatesBackupInventoryMount(t *testing.T) {
|
||||
base := map[string]string{"DATABASE_URL": "postgres://example"}
|
||||
load := func(extra map[string]string) (Config, error) {
|
||||
values := map[string]string{}
|
||||
for key, value := range base {
|
||||
values[key] = value
|
||||
}
|
||||
for key, value := range extra {
|
||||
values[key] = value
|
||||
}
|
||||
return Load(func(key string) string { return values[key] })
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_READONLY_ROOT": "relative/path"}); err == nil {
|
||||
t.Fatal("relative read-only root must be rejected")
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_READONLY_ROOT": "/var/lib/knowledge-governance/backup-host/rds-logical"}); err == nil {
|
||||
t.Fatal("read-only root without host path must be rejected (copy paths must not be guessed)")
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical"}); err == nil {
|
||||
t.Fatal("host path without read-only root must be rejected")
|
||||
}
|
||||
config, err := load(map[string]string{
|
||||
"BACKUP_HOST_READONLY_ROOT": "/var/lib/knowledge-governance/backup-host/rds-logical",
|
||||
"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
|
||||
"BACKUP_HOST_READONLY_SOURCE": "weknora-test:/srv/kb-backups/rds-logical",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("valid inventory mount rejected: %v", err)
|
||||
}
|
||||
if config.BackupHostReadonlyRoot == "" || config.BackupHostReadonlyHostPath == "" || config.BackupHostReadonlySource == "" {
|
||||
t.Fatalf("inventory mount fields lost: %#v", config)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRequiresDatabaseURL(t *testing.T) {
|
||||
if _, err := Load(func(string) string { return "" }); err == nil {
|
||||
t.Fatal("Load() error = nil, want missing DATABASE_URL error")
|
||||
|
||||
@@ -0,0 +1,592 @@
|
||||
// Package backupinventory 只读盘点备份执行主机上的 rds-logical 备份目录。
|
||||
//
|
||||
// 为什么不是再开一条 SSH 命令:盘点要列全部历史批次、子库目录和实际占盘,
|
||||
// 在主机上跑 find/du/df 既扩大远端命令面,也无法证明"读的是这块盘"。这里
|
||||
// 只接受一个**只读挂载**进来的目录,平台侧没有写路径;容量用 statfs 量,
|
||||
// 并比较挂载根与容器根的文件系统设备号,避免把容器根盘冒充主机磁盘。
|
||||
package backupinventory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultMaxBatches = 100
|
||||
defaultMaxFiles = 200_000
|
||||
defaultMaxManifestBytes = 8 << 20
|
||||
|
||||
// Linux statfs 的 ST_RDONLY;syscall 包没有导出这个名字。
|
||||
statReadOnly = 0x1
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
// Root 是容器内只读挂载点(如 /var/lib/knowledge-governance/backup-host/rds-logical)。
|
||||
// 留空即未接线;页面显示原因,不返回空表冒充"没有备份"。
|
||||
Root string
|
||||
// HostRoot 是给操作者复制/在主机上执行的路径(如 /srv/kb-backups/rds-logical)。
|
||||
HostRoot string
|
||||
// Source 是展示用的来源,如 weknora-test:/srv/kb-backups/rds-logical。
|
||||
Source string
|
||||
// MaxBatches/MaxFiles/MaxManifestBytes 防止一个异常目录把 API 拖死。
|
||||
MaxBatches int
|
||||
MaxFiles int
|
||||
MaxManifestBytes int64
|
||||
}
|
||||
|
||||
type statFS struct {
|
||||
Total uint64
|
||||
Free uint64
|
||||
Available uint64
|
||||
ReadOnly bool
|
||||
}
|
||||
|
||||
type ManifestState string
|
||||
|
||||
const (
|
||||
ManifestOK ManifestState = "ok"
|
||||
ManifestMissing ManifestState = "missing"
|
||||
ManifestInvalid ManifestState = "invalid"
|
||||
)
|
||||
|
||||
type MountInfo struct {
|
||||
ContainerRoot string `json:"container_root"`
|
||||
MountVerified bool `json:"mount_verified"`
|
||||
LivesOnContainerRoot bool `json:"lives_on_container_root"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
Evidence string `json:"evidence"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type Capacity struct {
|
||||
Measured bool `json:"measured"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
FreeBytes int64 `json:"free_bytes"`
|
||||
AvailableBytes int64 `json:"available_bytes"`
|
||||
UsedBytes int64 `json:"used_bytes"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type Database struct {
|
||||
Name string `json:"name"`
|
||||
DirName string `json:"dir_name"`
|
||||
Path string `json:"path"`
|
||||
HostPath string `json:"host_path"`
|
||||
Present bool `json:"present"`
|
||||
Failed bool `json:"failed"`
|
||||
InManifest bool `json:"in_manifest"`
|
||||
ApparentBytes int64 `json:"apparent_bytes"`
|
||||
ActualBytes int64 `json:"actual_bytes"`
|
||||
FileCount int `json:"file_count"`
|
||||
}
|
||||
|
||||
type Batch struct {
|
||||
Stamp string `json:"stamp"`
|
||||
Path string `json:"path"`
|
||||
HostPath string `json:"host_path"`
|
||||
ManifestState ManifestState `json:"manifest_state"`
|
||||
ManifestPath string `json:"manifest_path"`
|
||||
ManifestError string `json:"manifest_error,omitempty"`
|
||||
Kind string `json:"kind"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
StartedAt string `json:"started_at"`
|
||||
DurationSeconds int `json:"duration_seconds"`
|
||||
ManifestBytes int64 `json:"manifest_total_bytes"`
|
||||
ApparentBytes int64 `json:"apparent_bytes"`
|
||||
ActualBytes int64 `json:"actual_bytes"`
|
||||
FileCount int `json:"file_count"`
|
||||
SizesComplete bool `json:"sizes_complete"`
|
||||
SizesError string `json:"sizes_error,omitempty"`
|
||||
Databases []Database `json:"databases"`
|
||||
}
|
||||
|
||||
type Skipped struct {
|
||||
Name string `json:"name"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type Totals struct {
|
||||
BatchCount int `json:"batch_count"`
|
||||
DatabaseCount int `json:"database_count"`
|
||||
ApparentBytes int64 `json:"apparent_bytes"`
|
||||
ActualBytes int64 `json:"actual_bytes"`
|
||||
LatestStamp string `json:"latest_stamp"`
|
||||
LatestActualBytes int64 `json:"latest_actual_bytes"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
Wired bool `json:"wired"`
|
||||
Root string `json:"root"`
|
||||
HostRoot string `json:"host_root"`
|
||||
Source string `json:"source"`
|
||||
ObservedAt string `json:"observed_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Mount MountInfo `json:"mount"`
|
||||
Capacity Capacity `json:"capacity"`
|
||||
Batches []Batch `json:"batches"`
|
||||
Totals Totals `json:"totals"`
|
||||
IncompleteCount int `json:"incomplete_count"`
|
||||
Skipped []Skipped `json:"skipped"`
|
||||
Truncated bool `json:"truncated"`
|
||||
}
|
||||
|
||||
type Reader struct {
|
||||
config Config
|
||||
now func() time.Time
|
||||
statfs func(string) (statFS, error)
|
||||
device func(string) (uint64, error)
|
||||
}
|
||||
|
||||
func New(config Config) *Reader {
|
||||
if config.MaxBatches <= 0 {
|
||||
config.MaxBatches = defaultMaxBatches
|
||||
}
|
||||
if config.MaxFiles <= 0 {
|
||||
config.MaxFiles = defaultMaxFiles
|
||||
}
|
||||
if config.MaxManifestBytes <= 0 {
|
||||
config.MaxManifestBytes = defaultMaxManifestBytes
|
||||
}
|
||||
return &Reader{config: config, now: time.Now, statfs: defaultStatFS, device: defaultDevice}
|
||||
}
|
||||
|
||||
func (r *Reader) Available() bool {
|
||||
return r != nil && strings.TrimSpace(r.config.Root) != ""
|
||||
}
|
||||
|
||||
// Snapshot 永远返回可投影的结构:未接线、目录不可读、清单损坏都写在字段里,
|
||||
// 由页面区分,不把任一种情况变成 500 或"没有备份"。
|
||||
func (r *Reader) Snapshot(ctx context.Context) Snapshot {
|
||||
snapshot := Snapshot{
|
||||
Wired: r.Available(),
|
||||
HostRoot: r.config.HostRoot,
|
||||
Source: r.config.Source,
|
||||
Batches: []Batch{},
|
||||
Skipped: []Skipped{},
|
||||
}
|
||||
if r == nil || !r.Available() {
|
||||
snapshot.Error = "只读盘点未接线(BACKUP_HOST_READONLY_ROOT 未设置)"
|
||||
snapshot.ObservedAt = r.observedAt()
|
||||
return snapshot
|
||||
}
|
||||
snapshot.ObservedAt = r.observedAt()
|
||||
snapshot.Root = filepath.Clean(r.config.Root)
|
||||
resolved, err := filepath.EvalSymlinks(snapshot.Root)
|
||||
if err != nil {
|
||||
snapshot.Error = "只读挂载不可读:" + err.Error()
|
||||
snapshot.Capacity.Error = snapshot.Error
|
||||
return snapshot
|
||||
}
|
||||
info, err := os.Stat(resolved)
|
||||
if err != nil {
|
||||
snapshot.Error = "只读挂载不可读:" + err.Error()
|
||||
snapshot.Capacity.Error = snapshot.Error
|
||||
return snapshot
|
||||
}
|
||||
if !info.IsDir() {
|
||||
snapshot.Error = "只读挂载不是目录:" + resolved
|
||||
snapshot.Capacity.Error = snapshot.Error
|
||||
return snapshot
|
||||
}
|
||||
snapshot.Root = resolved
|
||||
snapshot.Mount = r.mountInfo(resolved)
|
||||
if !snapshot.Mount.MountVerified {
|
||||
reason := snapshot.Mount.Evidence
|
||||
if snapshot.Mount.Error != "" {
|
||||
reason = snapshot.Mount.Error
|
||||
}
|
||||
snapshot.Capacity = Capacity{Error: "无法证明只读目录位于独立挂载:" + reason}
|
||||
} else {
|
||||
snapshot.Capacity = r.capacity(resolved)
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(resolved)
|
||||
if err != nil {
|
||||
snapshot.Error = "无法列出备份目录:" + err.Error()
|
||||
return snapshot
|
||||
}
|
||||
dirs := make([]string, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
if strings.HasSuffix(name, ".incomplete") {
|
||||
snapshot.IncompleteCount++
|
||||
continue
|
||||
}
|
||||
if name == "" || strings.ContainsAny(name, `/\`) {
|
||||
snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "目录名不合法"})
|
||||
continue
|
||||
}
|
||||
if entry.Type()&os.ModeSymlink != 0 {
|
||||
snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "符号链接不跟随"})
|
||||
continue
|
||||
}
|
||||
if !entry.IsDir() {
|
||||
snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "不是批次目录"})
|
||||
continue
|
||||
}
|
||||
dirs = append(dirs, name)
|
||||
}
|
||||
sort.Sort(sort.Reverse(sort.StringSlice(dirs)))
|
||||
if len(dirs) > r.config.MaxBatches {
|
||||
dirs = dirs[:r.config.MaxBatches]
|
||||
snapshot.Truncated = true
|
||||
}
|
||||
for _, name := range dirs {
|
||||
if ctx.Err() != nil {
|
||||
snapshot.Error = "读取被取消:" + ctx.Err().Error()
|
||||
break
|
||||
}
|
||||
batch, reason, walkTruncated := r.readBatch(ctx, resolved, name)
|
||||
if reason != "" {
|
||||
snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: reason})
|
||||
continue
|
||||
}
|
||||
if walkTruncated {
|
||||
snapshot.Truncated = true
|
||||
}
|
||||
snapshot.Batches = append(snapshot.Batches, batch)
|
||||
snapshot.Totals.ApparentBytes += batch.ApparentBytes
|
||||
snapshot.Totals.ActualBytes += batch.ActualBytes
|
||||
snapshot.Totals.DatabaseCount += len(batch.Databases)
|
||||
}
|
||||
snapshot.Totals.BatchCount = len(snapshot.Batches)
|
||||
if len(snapshot.Batches) > 0 {
|
||||
snapshot.Totals.LatestStamp = snapshot.Batches[0].Stamp
|
||||
snapshot.Totals.LatestActualBytes = snapshot.Batches[0].ActualBytes
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func (r *Reader) observedAt() string {
|
||||
if r == nil || r.now == nil {
|
||||
return ""
|
||||
}
|
||||
return r.now().UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func (r *Reader) mountInfo(root string) MountInfo {
|
||||
info := MountInfo{ContainerRoot: "/"}
|
||||
rootDevice, err := r.device(root)
|
||||
if err != nil {
|
||||
info.Error = "无法读取挂载设备号:" + err.Error()
|
||||
info.Evidence = "无法证明挂载与容器根盘分离"
|
||||
return info
|
||||
}
|
||||
containerDevice, err := r.device("/")
|
||||
if err != nil {
|
||||
info.Error = "无法读取容器根盘设备号:" + err.Error()
|
||||
info.Evidence = "无法证明挂载与容器根盘分离"
|
||||
return info
|
||||
}
|
||||
info.LivesOnContainerRoot = rootDevice == containerDevice
|
||||
info.MountVerified = !info.LivesOnContainerRoot
|
||||
if stats, statErr := r.statfs(root); statErr == nil {
|
||||
info.ReadOnly = stats.ReadOnly
|
||||
}
|
||||
if info.MountVerified {
|
||||
info.Evidence = fmt.Sprintf("挂载设备 %d 与容器根盘 %d 不同:容量按挂载文件系统计量", rootDevice, containerDevice)
|
||||
} else {
|
||||
info.Evidence = fmt.Sprintf("挂载设备与容器根盘相同(%d):容量不代表备份主机磁盘", rootDevice)
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
func (r *Reader) capacity(root string) Capacity {
|
||||
stats, err := r.statfs(root)
|
||||
if err != nil {
|
||||
return Capacity{Error: "无法读取文件系统容量:" + err.Error()}
|
||||
}
|
||||
used := uint64(0)
|
||||
if stats.Total > stats.Free {
|
||||
used = stats.Total - stats.Free
|
||||
}
|
||||
return Capacity{
|
||||
Measured: true,
|
||||
TotalBytes: int64(stats.Total),
|
||||
FreeBytes: int64(stats.Free),
|
||||
AvailableBytes: int64(stats.Available),
|
||||
UsedBytes: int64(used),
|
||||
}
|
||||
}
|
||||
|
||||
type manifest struct {
|
||||
Kind string `json:"kind"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
StartedAt string `json:"started_at"`
|
||||
DurationSeconds int `json:"duration_seconds"`
|
||||
Databases []string `json:"databases"`
|
||||
FailedDatabases []string `json:"failed_databases"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
Files []struct {
|
||||
File string `json:"file"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
} `json:"files"`
|
||||
}
|
||||
|
||||
type sizes struct {
|
||||
apparent int64
|
||||
actual int64
|
||||
files int
|
||||
}
|
||||
|
||||
func (value *sizes) add(other sizes) {
|
||||
value.apparent += other.apparent
|
||||
value.actual += other.actual
|
||||
value.files += other.files
|
||||
}
|
||||
|
||||
func (r *Reader) readBatch(ctx context.Context, root, name string) (Batch, string, bool) {
|
||||
fullPath := filepath.Join(root, name)
|
||||
resolved, err := filepath.EvalSymlinks(fullPath)
|
||||
if err != nil {
|
||||
return Batch{}, "无法解析批次目录:" + err.Error(), false
|
||||
}
|
||||
if !within(root, resolved) {
|
||||
return Batch{}, "批次目录指向只读挂载之外", false
|
||||
}
|
||||
batch := Batch{
|
||||
Stamp: name,
|
||||
Path: resolved,
|
||||
HostPath: joinHostPath(r.config.HostRoot, name),
|
||||
ManifestPath: filepath.Join(resolved, "MANIFEST.json"),
|
||||
ManifestState: ManifestMissing,
|
||||
Databases: []Database{},
|
||||
SizesComplete: true,
|
||||
}
|
||||
|
||||
var parsed manifest
|
||||
state, manifestErr := readManifest(batch.ManifestPath, r.config.MaxManifestBytes, &parsed)
|
||||
batch.ManifestState = state
|
||||
batch.ManifestError = manifestErr
|
||||
if state == ManifestOK {
|
||||
batch.Kind = parsed.Kind
|
||||
batch.CreatedAt = parsed.CreatedAt
|
||||
batch.StartedAt = parsed.StartedAt
|
||||
batch.DurationSeconds = parsed.DurationSeconds
|
||||
batch.ManifestBytes = parsed.TotalBytes
|
||||
}
|
||||
|
||||
walked, byTop, walkErr, truncated := r.walkBatch(ctx, resolved)
|
||||
batch.ApparentBytes = walked.apparent
|
||||
batch.ActualBytes = walked.actual
|
||||
batch.FileCount = walked.files
|
||||
if walkErr != nil {
|
||||
batch.SizesComplete = false
|
||||
batch.SizesError = walkErr.Error()
|
||||
}
|
||||
if state == ManifestOK && parsed.TotalBytes > 0 {
|
||||
batch.ApparentBytes = parsed.TotalBytes
|
||||
}
|
||||
|
||||
manifestSizes := map[string]sizes{}
|
||||
if state == ManifestOK {
|
||||
for _, file := range parsed.Files {
|
||||
clean := path.Clean(filepath.ToSlash(file.File))
|
||||
if clean == "." || strings.HasPrefix(clean, "../") || path.IsAbs(clean) {
|
||||
continue
|
||||
}
|
||||
top := strings.SplitN(clean, "/", 2)[0]
|
||||
if !strings.HasSuffix(top, ".dir") {
|
||||
continue
|
||||
}
|
||||
entry := manifestSizes[top]
|
||||
entry.apparent += file.Bytes
|
||||
entry.files++
|
||||
manifestSizes[top] = entry
|
||||
}
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
failed := map[string]bool{}
|
||||
for _, db := range parsed.FailedDatabases {
|
||||
failed[db] = true
|
||||
}
|
||||
appendDatabase := func(db string) {
|
||||
if db == "" || seen[db] {
|
||||
return
|
||||
}
|
||||
seen[db] = true
|
||||
dirName := db + ".dir"
|
||||
containerDir := filepath.Join(resolved, dirName)
|
||||
info, statErr := os.Stat(containerDir)
|
||||
present := statErr == nil && info.IsDir()
|
||||
apparent := sizes{}
|
||||
if entry, ok := manifestSizes[dirName]; ok {
|
||||
apparent = entry
|
||||
} else if walkedEntry, ok := byTop[dirName]; ok {
|
||||
apparent = walkedEntry
|
||||
}
|
||||
batch.Databases = append(batch.Databases, Database{
|
||||
Name: db,
|
||||
DirName: dirName,
|
||||
Path: containerDir,
|
||||
HostPath: joinHostPath(batch.HostPath, dirName),
|
||||
Present: present,
|
||||
Failed: failed[db],
|
||||
InManifest: contains(parsed.Databases, db),
|
||||
ApparentBytes: apparent.apparent,
|
||||
ActualBytes: byTop[dirName].actual,
|
||||
FileCount: apparent.files,
|
||||
})
|
||||
}
|
||||
for _, db := range parsed.Databases {
|
||||
appendDatabase(db)
|
||||
}
|
||||
dirNames := make([]string, 0, len(byTop))
|
||||
for top := range byTop {
|
||||
if strings.HasSuffix(top, ".dir") {
|
||||
dirNames = append(dirNames, top)
|
||||
}
|
||||
}
|
||||
sort.Strings(dirNames)
|
||||
for _, top := range dirNames {
|
||||
appendDatabase(strings.TrimSuffix(top, ".dir"))
|
||||
}
|
||||
return batch, "", truncated
|
||||
}
|
||||
|
||||
func (r *Reader) walkBatch(ctx context.Context, batchPath string) (sizes, map[string]sizes, error, bool) {
|
||||
total := sizes{}
|
||||
byTop := map[string]sizes{}
|
||||
scanned := 0
|
||||
truncated := false
|
||||
err := filepath.WalkDir(batchPath, func(current string, entry fs.DirEntry, walkErr error) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if current == batchPath {
|
||||
return nil
|
||||
}
|
||||
if entry.Type()&os.ModeSymlink != 0 {
|
||||
if entry.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if scanned >= r.config.MaxFiles {
|
||||
truncated = true
|
||||
return errStopWalk
|
||||
}
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
relative, err := filepath.Rel(batchPath, current)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
top := strings.SplitN(filepath.ToSlash(relative), "/", 2)[0]
|
||||
fileSize := sizes{apparent: info.Size(), actual: actualBytes(info), files: 1}
|
||||
total.add(fileSize)
|
||||
entrySizes := byTop[top]
|
||||
entrySizes.add(fileSize)
|
||||
byTop[top] = entrySizes
|
||||
scanned++
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, errStopWalk) {
|
||||
err = nil
|
||||
}
|
||||
if err != nil {
|
||||
return total, byTop, err, truncated
|
||||
}
|
||||
return total, byTop, nil, truncated
|
||||
}
|
||||
|
||||
var errStopWalk = errors.New("file scan limit reached")
|
||||
|
||||
func readManifest(filename string, maxBytes int64, parsed *manifest) (ManifestState, string) {
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return ManifestMissing, ""
|
||||
}
|
||||
return ManifestInvalid, err.Error()
|
||||
}
|
||||
defer file.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(file, maxBytes+1))
|
||||
if err != nil {
|
||||
return ManifestInvalid, err.Error()
|
||||
}
|
||||
if int64(len(raw)) > maxBytes {
|
||||
return ManifestInvalid, fmt.Sprintf("清单超过 %d 字节读取上限", maxBytes)
|
||||
}
|
||||
if err := json.Unmarshal(raw, parsed); err != nil {
|
||||
return ManifestInvalid, "清单无法解析:" + err.Error()
|
||||
}
|
||||
return ManifestOK, ""
|
||||
}
|
||||
|
||||
func within(root, target string) bool {
|
||||
relative, err := filepath.Rel(root, target)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return relative != ".." && !strings.HasPrefix(relative, ".."+string(os.PathSeparator))
|
||||
}
|
||||
|
||||
func joinHostPath(root, name string) string {
|
||||
if strings.TrimSpace(root) == "" {
|
||||
return ""
|
||||
}
|
||||
return path.Join(filepath.ToSlash(root), name)
|
||||
}
|
||||
|
||||
func contains(list []string, value string) bool {
|
||||
for _, item := range list {
|
||||
if item == value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func actualBytes(info fs.FileInfo) int64 {
|
||||
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
|
||||
return int64(stat.Blocks) * 512
|
||||
}
|
||||
return info.Size()
|
||||
}
|
||||
|
||||
func defaultStatFS(root string) (statFS, error) {
|
||||
var stats syscall.Statfs_t
|
||||
if err := syscall.Statfs(root, &stats); err != nil {
|
||||
return statFS{}, err
|
||||
}
|
||||
blockSize := uint64(stats.Bsize)
|
||||
return statFS{
|
||||
Total: stats.Blocks * blockSize,
|
||||
Free: stats.Bfree * blockSize,
|
||||
Available: stats.Bavail * blockSize,
|
||||
ReadOnly: stats.Flags&statReadOnly != 0,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func defaultDevice(root string) (uint64, error) {
|
||||
info, err := os.Stat(root)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("无法读取 %s 的设备号", root)
|
||||
}
|
||||
return uint64(stat.Dev), nil
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package backupinventory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func writeFile(t *testing.T, filename string, content string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filename, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func actualOf(t *testing.T, filename string) int64 {
|
||||
t.Helper()
|
||||
info, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
t.Fatal("no stat")
|
||||
}
|
||||
return int64(stat.Blocks) * 512
|
||||
}
|
||||
|
||||
func fixtureRoot(t *testing.T) string {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
latest := filepath.Join(root, "20261118T193001Z")
|
||||
writeFile(t, filepath.Join(latest, "MANIFEST.json"), `{
|
||||
"kind": "rds-logical-backup",
|
||||
"created_at": "20261118T193001Z",
|
||||
"started_at": "20261118T192908Z",
|
||||
"duration_seconds": 53,
|
||||
"databases": ["weknora_v090prod", "weknora_test"],
|
||||
"failed_databases": ["weknora_test"],
|
||||
"total_bytes": 300,
|
||||
"files": [
|
||||
{"file": "weknora_v090prod.dir/toc.dat", "bytes": 100},
|
||||
{"file": "weknora_v090prod.dir/0001.dat.gz", "bytes": 150},
|
||||
{"file": "weknora_test.dir/toc.dat", "bytes": 50}
|
||||
]
|
||||
}`)
|
||||
writeFile(t, filepath.Join(latest, "weknora_v090prod.dir", "toc.dat"), strings.Repeat("a", 100))
|
||||
writeFile(t, filepath.Join(latest, "weknora_v090prod.dir", "0001.dat.gz"), strings.Repeat("b", 150))
|
||||
writeFile(t, filepath.Join(latest, "weknora_test.dir", "toc.dat"), strings.Repeat("c", 50))
|
||||
|
||||
invalid := filepath.Join(root, "20261117T193001Z")
|
||||
writeFile(t, filepath.Join(invalid, "MANIFEST.json"), "{not-json")
|
||||
writeFile(t, filepath.Join(invalid, "weknora_prod.dir", "toc.dat"), strings.Repeat("d", 20))
|
||||
|
||||
missing := filepath.Join(root, "20261116T193001Z")
|
||||
writeFile(t, filepath.Join(missing, "weknora_archive.dir", "toc.dat"), strings.Repeat("e", 30))
|
||||
|
||||
incomplete := filepath.Join(root, "20261115T193001Z.incomplete")
|
||||
writeFile(t, filepath.Join(incomplete, "MANIFEST.json"), `{}`)
|
||||
|
||||
return root
|
||||
}
|
||||
|
||||
func TestSnapshotReadsBatchesManifestsAndActualUsage(t *testing.T) {
|
||||
root := fixtureRoot(t)
|
||||
reader := New(Config{
|
||||
Root: root,
|
||||
HostRoot: "/srv/kb-backups/rds-logical",
|
||||
Source: "weknora-test:/srv/kb-backups/rds-logical",
|
||||
})
|
||||
reader.device = func(path string) (uint64, error) {
|
||||
if path == "/" {
|
||||
return 10, nil
|
||||
}
|
||||
return 20, nil
|
||||
}
|
||||
reader.statfs = func(string) (statFS, error) {
|
||||
return statFS{Total: 1000, Free: 400, Available: 350, ReadOnly: true}, nil
|
||||
}
|
||||
|
||||
snapshot := reader.Snapshot(context.Background())
|
||||
if !snapshot.Wired || snapshot.Error != "" {
|
||||
t.Fatalf("应读到接线目录: %+v", snapshot)
|
||||
}
|
||||
if !snapshot.Mount.MountVerified || snapshot.Mount.LivesOnContainerRoot || !snapshot.Mount.ReadOnly {
|
||||
t.Fatalf("挂载判定不对: %+v", snapshot.Mount)
|
||||
}
|
||||
if !snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 1000 || snapshot.Capacity.AvailableBytes != 350 {
|
||||
t.Fatalf("容量不对: %+v", snapshot.Capacity)
|
||||
}
|
||||
if len(snapshot.Batches) != 3 || snapshot.IncompleteCount != 1 {
|
||||
t.Fatalf("批次数量不对: %d incomplete=%d", len(snapshot.Batches), snapshot.IncompleteCount)
|
||||
}
|
||||
latest := snapshot.Batches[0]
|
||||
if latest.Stamp != "20261118T193001Z" || latest.ManifestState != ManifestOK {
|
||||
t.Fatalf("最近批次不对: %+v", latest)
|
||||
}
|
||||
if latest.CreatedAt != "20261118T193001Z" || latest.DurationSeconds != 53 || latest.ManifestBytes != 300 {
|
||||
t.Fatalf("清单字段不对: %+v", latest)
|
||||
}
|
||||
if latest.HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z" {
|
||||
t.Fatalf("批次主机路径不对: %q", latest.HostPath)
|
||||
}
|
||||
if len(latest.Databases) != 2 {
|
||||
t.Fatalf("子库数量不对: %+v", latest.Databases)
|
||||
}
|
||||
prod := latest.Databases[0]
|
||||
if prod.Name != "weknora_v090prod" || !prod.Present || prod.Failed || !prod.InManifest {
|
||||
t.Fatalf("子库状态不对: %+v", prod)
|
||||
}
|
||||
if prod.Path != filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir") {
|
||||
t.Fatalf("子库容器路径不对: %q", prod.Path)
|
||||
}
|
||||
if prod.HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
|
||||
t.Fatalf("子库主机路径不对: %q", prod.HostPath)
|
||||
}
|
||||
expectedActual := actualOf(t, filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir", "toc.dat")) +
|
||||
actualOf(t, filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir", "0001.dat.gz"))
|
||||
if prod.ActualBytes != expectedActual {
|
||||
t.Fatalf("子库实际占盘不对: got %d want %d", prod.ActualBytes, expectedActual)
|
||||
}
|
||||
if prod.ApparentBytes != 250 || prod.FileCount != 2 {
|
||||
t.Fatalf("子库清单体积不对: %+v", prod)
|
||||
}
|
||||
if !latest.Databases[1].Failed {
|
||||
t.Fatalf("失败库没有标记: %+v", latest.Databases[1])
|
||||
}
|
||||
|
||||
broken := snapshot.Batches[1]
|
||||
if broken.Stamp != "20261117T193001Z" || broken.ManifestState != ManifestInvalid || broken.ManifestError == "" {
|
||||
t.Fatalf("损坏清单没有如实标记: %+v", broken)
|
||||
}
|
||||
if len(broken.Databases) != 1 || broken.Databases[0].Name != "weknora_prod" || !broken.Databases[0].Present {
|
||||
t.Fatalf("清单损坏时仍应按目录列出子库: %+v", broken.Databases)
|
||||
}
|
||||
withoutManifest := snapshot.Batches[2]
|
||||
if withoutManifest.ManifestState != ManifestMissing {
|
||||
t.Fatalf("缺清单没有如实标记: %+v", withoutManifest)
|
||||
}
|
||||
if snapshot.Totals.BatchCount != 3 || snapshot.Totals.LatestStamp != "20261118T193001Z" {
|
||||
t.Fatalf("汇总不对: %+v", snapshot.Totals)
|
||||
}
|
||||
if snapshot.ObservedAt == "" || snapshot.Source != "weknora-test:/srv/kb-backups/rds-logical" {
|
||||
t.Fatalf("观测时间/来源不对: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotUnconfigured(t *testing.T) {
|
||||
snapshot := New(Config{}).Snapshot(context.Background())
|
||||
if snapshot.Wired || snapshot.Error == "" || len(snapshot.Batches) != 0 {
|
||||
t.Fatalf("未接线必须给出原因且不伪造批次: %+v", snapshot)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "未接线") {
|
||||
t.Fatalf("未接线原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotMissingRoot(t *testing.T) {
|
||||
reader := New(Config{Root: filepath.Join(t.TempDir(), "missing")})
|
||||
snapshot := reader.Snapshot(context.Background())
|
||||
if !snapshot.Wired || snapshot.Error == "" || snapshot.Capacity.Measured {
|
||||
t.Fatalf("目录不存在应报错且不报容量: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRefusesSymlinkBatches(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
writeFile(t, filepath.Join(outside, "MANIFEST.json"), `{"databases":["escaped"]}`)
|
||||
if err := os.Symlink(outside, filepath.Join(root, "20261118T193001Z")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snapshot := New(Config{Root: root}).Snapshot(context.Background())
|
||||
if len(snapshot.Batches) != 0 {
|
||||
t.Fatalf("符号链接批次不能跟随: %+v", snapshot.Batches)
|
||||
}
|
||||
if len(snapshot.Skipped) != 1 || !strings.Contains(snapshot.Skipped[0].Reason, "符号链接") {
|
||||
t.Fatalf("跳过原因不对: %+v", snapshot.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotDoesNotUseContainerRootCapacity(t *testing.T) {
|
||||
root := fixtureRoot(t)
|
||||
reader := New(Config{Root: root})
|
||||
reader.device = func(string) (uint64, error) { return 7, nil }
|
||||
reader.statfs = func(string) (statFS, error) {
|
||||
return statFS{Total: 999, Free: 1, Available: 1}, nil
|
||||
}
|
||||
snapshot := reader.Snapshot(context.Background())
|
||||
if snapshot.Mount.MountVerified || !snapshot.Mount.LivesOnContainerRoot {
|
||||
t.Fatalf("同设备必须判定为容器根盘: %+v", snapshot.Mount)
|
||||
}
|
||||
if snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 0 || snapshot.Capacity.Error == "" {
|
||||
t.Fatalf("容器根盘不能冒充主机容量: %+v", snapshot.Capacity)
|
||||
}
|
||||
if len(snapshot.Batches) != 3 {
|
||||
t.Fatalf("容量不可用不应影响批次读取: %+v", snapshot.Batches)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
)
|
||||
|
||||
// BackupInventoryReader 只读盘点备份主机目录。它与 SSH 主机计划读回完全独立:
|
||||
// 挂载没接线不应拖垮计划读回,计划读回失败也不应把历史批次说成"没有"。
|
||||
type BackupInventoryReader interface {
|
||||
Available() bool
|
||||
Snapshot(context.Context) backupinventory.Snapshot
|
||||
}
|
||||
|
||||
// handleBackupInventory 返回真实批次、子库路径与实测容量。
|
||||
// 未接线/目录不可读/清单损坏都作为 200 的字段返回,由页面区分原因;
|
||||
// 只有投影本身失败才 500。
|
||||
func (config Config) handleBackupInventory(w http.ResponseWriter, r *http.Request) {
|
||||
snapshot := config.BackupInventory.Snapshot(r.Context())
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": snapshot})
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
)
|
||||
|
||||
type fakeBackupInventory struct {
|
||||
snapshot backupinventory.Snapshot
|
||||
}
|
||||
|
||||
func (fake fakeBackupInventory) Available() bool { return fake.snapshot.Wired }
|
||||
|
||||
func (fake fakeBackupInventory) Snapshot(context.Context) backupinventory.Snapshot {
|
||||
return fake.snapshot
|
||||
}
|
||||
|
||||
func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
|
||||
config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
|
||||
Wired: true,
|
||||
Root: "/var/lib/knowledge-governance/backup-host/rds-logical",
|
||||
HostRoot: "/srv/kb-backups/rds-logical",
|
||||
Source: "weknora-test:/srv/kb-backups/rds-logical",
|
||||
Mount: backupinventory.MountInfo{
|
||||
MountVerified: true,
|
||||
ReadOnly: true,
|
||||
Evidence: "挂载设备 20 与容器根盘 10 不同",
|
||||
},
|
||||
Capacity: backupinventory.Capacity{Measured: true, TotalBytes: 100, FreeBytes: 40, AvailableBytes: 35, UsedBytes: 60},
|
||||
Batches: []backupinventory.Batch{{
|
||||
Stamp: "20261118T193001Z",
|
||||
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z",
|
||||
ManifestState: backupinventory.ManifestOK,
|
||||
ActualBytes: 1024,
|
||||
Databases: []backupinventory.Database{{
|
||||
Name: "weknora_v090prod",
|
||||
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
|
||||
Present: true,
|
||||
ActualBytes: 512,
|
||||
}},
|
||||
}},
|
||||
Totals: backupinventory.Totals{BatchCount: 1, LatestStamp: "20261118T193001Z"},
|
||||
}}}
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", recorder.Code)
|
||||
}
|
||||
var payload struct {
|
||||
Data backupinventory.Snapshot `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !payload.Data.Wired || !payload.Data.Mount.MountVerified || !payload.Data.Capacity.Measured {
|
||||
t.Fatalf("接线/挂载/容量字段丢失: %+v", payload.Data)
|
||||
}
|
||||
if len(payload.Data.Batches) != 1 ||
|
||||
payload.Data.Batches[0].Databases[0].HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
|
||||
t.Fatalf("批次/子库真实路径丢失: %+v", payload.Data.Batches)
|
||||
}
|
||||
if payload.Data.Batches[0].ActualBytes != 1024 {
|
||||
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) {
|
||||
config := Config{BackupInventory: backupinventory.New(backupinventory.Config{})}
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("未接线不应 500: %d", recorder.Code)
|
||||
}
|
||||
var payload struct {
|
||||
Data backupinventory.Snapshot `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Data.Wired || payload.Data.Error == "" || payload.Data.Batches == nil {
|
||||
t.Fatalf("未接线必须给原因且批次为空数组: %+v", payload.Data)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/backuphost"
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
@@ -198,10 +199,13 @@ type Config struct {
|
||||
// 它不是运行时开关:生产部署不设置它,那次探测仍然直连目标库逐表计数。
|
||||
LibraryScopeProbe func(ctx context.Context, scope string) (bool, map[string]int64, error)
|
||||
// LibraryRetentionVersions/Days 是保留策略;都为 0 = 未设置(不生成清理候选)。
|
||||
LibraryRetentionVersions int
|
||||
LibraryRetentionDays int
|
||||
BackupSchedule BackupScheduleStore
|
||||
BackupHost BackupHost
|
||||
LibraryRetentionVersions int
|
||||
LibraryRetentionDays int
|
||||
BackupSchedule BackupScheduleStore
|
||||
BackupHost BackupHost
|
||||
// BackupInventory 读的是只读挂载的 rds-logical 目录(批次/子库/实测容量)。
|
||||
// 与 BackupHost 的 SSH 计划读回分离,任一侧失败都不能影响另一侧。
|
||||
BackupInventory BackupInventoryReader
|
||||
BackupRuns *BackupRunTracker
|
||||
ProductionBindings ProductionBindingStore
|
||||
ProductionKnowledgeBases ProductionKnowledgeBaseLister
|
||||
@@ -251,6 +255,10 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
// 未挂载主机凭据:Available()=false,页面显示"未接线"而不是 500。
|
||||
config.BackupHost = backuphost.New(backuphost.Config{})
|
||||
}
|
||||
if config.BackupInventory == nil {
|
||||
// 未挂载只读备份目录:批次/容量显示"未接线",独立于 SSH 计划读回。
|
||||
config.BackupInventory = backupinventory.New(backupinventory.Config{})
|
||||
}
|
||||
for _, knowledgeBaseID := range []string{config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID} {
|
||||
if knowledgeBaseID != "" && !validCatalogID(knowledgeBaseID) {
|
||||
return nil, errors.New("routing knowledge base ID is invalid")
|
||||
@@ -431,6 +439,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
config.handleBackupScheduleHost(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/backup-schedule/inventory", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleBackupInventory(w, r)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/v1/backup-schedule", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.BackupSchedule == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "backup schedule storage unavailable"})
|
||||
|
||||
Reference in New Issue
Block a user