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:
@@ -0,0 +1,216 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { applyBackupSchedule, fetchBackupSchedule, fetchBackupScheduleHost, runBackupNow, saveBackupSchedule } from './backupSchedule'
|
||||
import type { BackupSchedule } from './backupSchedule'
|
||||
|
||||
export const formatBackupBytes = (bytes: number): string => {
|
||||
if (!bytes) return '—'
|
||||
const mib = bytes / (1024 * 1024)
|
||||
return mib >= 1024 ? `${(mib / 1024).toFixed(2)} GiB` : `${mib.toFixed(1)} MiB`
|
||||
}
|
||||
|
||||
export const formatBackupMoment = (value: string): string => {
|
||||
if (!value) return '—'
|
||||
const parsed = new Date(value)
|
||||
return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
|
||||
export const backupTimeValid = (value: string): boolean => /^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(value)
|
||||
export const backupDaysValid = (value: number): boolean => Number.isInteger(value) && value >= 1 && value <= 365
|
||||
export const backupMonthsValid = (value: number): boolean => Number.isInteger(value) && value >= 0 && value <= 24
|
||||
|
||||
export interface BackupScheduleViewProps {
|
||||
schedule: BackupSchedule
|
||||
isAdmin: boolean
|
||||
loading: boolean
|
||||
probing: boolean
|
||||
busy: 'save' | 'apply' | 'run' | null
|
||||
error: string | null
|
||||
message: string
|
||||
enabledDraft: boolean
|
||||
timeDraft: string
|
||||
daysDraft: string
|
||||
monthsDraft: string
|
||||
onEnabledChange: (next: boolean) => void
|
||||
onTimeChange: (next: string) => void
|
||||
onDaysChange: (next: string) => void
|
||||
onMonthsChange: (next: string) => void
|
||||
onSave: () => void
|
||||
onApply: () => void
|
||||
onRunNow: () => void
|
||||
onReload: () => void
|
||||
}
|
||||
|
||||
// 纯视图:所有状态由 props 驱动,便于在测试里直接渲染各种状态(管理员/只读、已一致/待下发、在途)。
|
||||
export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
const {
|
||||
schedule, isAdmin, loading, probing, busy, error, message,
|
||||
enabledDraft, timeDraft, daysDraft, monthsDraft,
|
||||
onEnabledChange, onTimeChange, onDaysChange, onMonthsChange, onSave, onApply, onRunNow, onReload,
|
||||
} = props
|
||||
const days = Number(daysDraft)
|
||||
const months = Number(monthsDraft)
|
||||
const valid = backupTimeValid(timeDraft) && backupDaysValid(days) && backupMonthsValid(months)
|
||||
const dirty = enabledDraft !== schedule.enabled || timeDraft !== schedule.schedule_time ||
|
||||
days !== schedule.retention_days || months !== schedule.retention_months
|
||||
const hostLine = !schedule.host_configured
|
||||
? '未接线(缺少主机凭据)'
|
||||
: schedule.host_reachable
|
||||
? `${schedule.host_target} · 已连接`
|
||||
: `${schedule.host_target} · 连接失败`
|
||||
|
||||
return <section className="settings-panel wide storage-settings-panel" id="settings-storage">
|
||||
<div className="settings-section-heading"><div>
|
||||
<h2>存储与备份</h2>
|
||||
<p>整库逻辑备份(pg_dump 目录格式)在<strong>目标库所在主机</strong>上本地执行:这里设置定时时间与储存天数,保存即下发到主机 cron,并可读回主机上生效的计划与最近一次结果。</p>
|
||||
</div><button onClick={onReload} disabled={loading || probing}>{loading || probing ? '读取中…' : '重新读取'}</button></div>
|
||||
{error ? <p className="error-message" role="alert">{error}</p> : null}
|
||||
<div className="storage-settings-grid">
|
||||
<dl>
|
||||
<dt>目标主机</dt><dd>{hostLine}</dd>
|
||||
<dt>主机 cron</dt><dd>{schedule.host_cron_service ? `服务 ${schedule.host_cron_service}` : '—'}{schedule.host_script_present ? '' : ' · 备份脚本缺失'}</dd>
|
||||
<dt>最近一次备份</dt><dd>{schedule.last_run_stamp || '—'}{schedule.last_run_created_at ? ` · ${formatBackupMoment(schedule.last_run_created_at)}` : ''}</dd>
|
||||
<dt>备份耗时 / 体积</dt><dd>{schedule.last_run_stamp ? `${schedule.last_run_duration_seconds} 秒 · ${formatBackupBytes(schedule.last_run_total_bytes)}` : '—'}</dd>
|
||||
</dl>
|
||||
<dl>
|
||||
<dt>覆盖的库</dt><dd>{schedule.last_run_databases.length ? schedule.last_run_databases.join('、') : '—'}</dd>
|
||||
<dt>失败的库</dt><dd>{schedule.last_run_failed_databases.length ? schedule.last_run_failed_databases.join('、') : '无'}</dd>
|
||||
<dt>主机上生效的计划</dt><dd>{schedule.host_schedule_enabled ? `每天 ${schedule.host_schedule_time} · 保留 ${schedule.host_keep_days} 天 · 每月 ${schedule.host_keep_months} 份` : schedule.host_configured ? '未启用定时' : '—'}</dd>
|
||||
<dt>与设置是否一致</dt><dd>{schedule.in_sync ? '已一致' : '待下发'}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
{schedule.host_error ? <p className="hint">主机探测:{schedule.host_error}</p> : null}
|
||||
{schedule.last_run_error ? <p className="hint">最近一次结果读取:{schedule.last_run_error}</p> : null}
|
||||
{schedule.host_cron_lines.length ? <p className="hint">主机 cron 条目:<code>{schedule.host_cron_lines.join(' ; ')}</code></p> : null}
|
||||
{schedule.last_applied_at ? <p className="hint">最后下发:{formatBackupMoment(schedule.last_applied_at)}{schedule.last_applied_summary ? ` · ${schedule.last_applied_summary}` : ''}</p> : null}
|
||||
<p className="hint">留档分层:PG 行级留档(发布前,含 ES 文档)+ ES 快照仓 + OSS 版本控制 + 本节的整库逻辑备份 + RDS 托管备份(控制台配置)。详见 <code>docs/PRODUCTION_BACKUP_RECOVERY.md</code>。</p>
|
||||
{isAdmin ? <div className="kb-binding-editor">
|
||||
<label>定时时间 <input type="time" value={timeDraft} onChange={(event) => onTimeChange(event.target.value)} aria-label="定时时间" /></label>
|
||||
<label>储存天数 <input type="number" min={1} max={365} value={daysDraft} onChange={(event) => onDaysChange(event.target.value)} aria-label="储存天数" /></label>
|
||||
<label>每月归档保留 <input type="number" min={0} max={24} value={monthsDraft} onChange={(event) => onMonthsChange(event.target.value)} aria-label="每月归档保留" /></label>
|
||||
<label className="checkbox-label"><input type="checkbox" checked={enabledDraft} onChange={(event) => onEnabledChange(event.target.checked)} /> 启用定时整库备份</label>
|
||||
{!valid ? <p className="error-message">定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。</p> : null}
|
||||
<button onClick={onSave} disabled={busy !== null || !valid || !dirty}>{busy === 'save' ? '正在保存并下发…' : '保存并下发到主机'}</button>
|
||||
<button onClick={onApply} disabled={busy !== null || !schedule.host_configured}>{busy === 'apply' ? '正在下发…' : '重新下发当前设置'}</button>
|
||||
<button onClick={onRunNow} disabled={busy !== null || !schedule.host_configured || schedule.running}>{schedule.running ? '备份进行中…' : '立即备份一次'}</button>
|
||||
{message ? <p className="success-message" role="status">{message}</p> : null}
|
||||
{schedule.running ? <p className="hint">正在备份({formatBackupMoment(schedule.running_started_at)} 开始),完成后自动刷新。</p> : null}
|
||||
{schedule.run_last_error && !schedule.running ? <p className="error-message">上一次立即备份失败:{schedule.run_last_error}</p> : null}
|
||||
</div> : <p className="hint">定时备份设置仅管理员可修改;当前设置:{schedule.enabled ? `每天 ${schedule.schedule_time} · 保留 ${schedule.retention_days} 天` : '未启用'}。</p>}
|
||||
</section>
|
||||
}
|
||||
|
||||
// 容器:读取 + 下发 + 在途轮询。真正执行备份的是目标库所在主机(同 VPC 直连 RDS)。
|
||||
export function BackupScheduleSection() {
|
||||
const auth = useOptionalAuth()
|
||||
const isAdmin = auth?.identity?.role === 'admin'
|
||||
const [schedule, setSchedule] = useState<BackupSchedule | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [probing, setProbing] = useState(false)
|
||||
const [busy, setBusy] = useState<'save' | 'apply' | 'run' | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [message, setMessage] = useState('')
|
||||
const [enabledDraft, setEnabledDraft] = useState(false)
|
||||
const [timeDraft, setTimeDraft] = useState('03:30')
|
||||
const [daysDraft, setDaysDraft] = useState('7')
|
||||
const [monthsDraft, setMonthsDraft] = useState('3')
|
||||
const polling = useRef<number | null>(null)
|
||||
|
||||
const adopt = useCallback((next: BackupSchedule) => {
|
||||
setSchedule(next)
|
||||
setEnabledDraft(next.enabled)
|
||||
setTimeDraft(next.schedule_time || '03:30')
|
||||
setDaysDraft(String(next.retention_days ?? 7))
|
||||
setMonthsDraft(String(next.retention_months ?? 3))
|
||||
}, [])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true); setError(null)
|
||||
try {
|
||||
adopt(await fetchBackupSchedule())
|
||||
setProbing(true)
|
||||
try {
|
||||
adopt(await fetchBackupScheduleHost())
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '读取目标主机上的备份状态失败')
|
||||
} finally { setProbing(false) }
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '读取备份计划失败')
|
||||
} finally { setLoading(false) }
|
||||
}, [adopt])
|
||||
|
||||
useEffect(() => { void load() }, [load])
|
||||
|
||||
// 立即备份约 30~60 秒:在途时轮询主机状态,直到 running 转假并出现新的最近一次结果。
|
||||
useEffect(() => {
|
||||
if (!schedule?.running) {
|
||||
if (polling.current !== null) { window.clearInterval(polling.current); polling.current = null }
|
||||
return
|
||||
}
|
||||
if (polling.current !== null) return
|
||||
polling.current = window.setInterval(() => {
|
||||
void fetchBackupScheduleHost().then(adopt).catch(() => undefined)
|
||||
}, 5000)
|
||||
return () => {
|
||||
if (polling.current !== null) { window.clearInterval(polling.current); polling.current = null }
|
||||
}
|
||||
}, [schedule?.running, adopt])
|
||||
|
||||
const save = async () => {
|
||||
setBusy('save'); setError(null); setMessage('')
|
||||
try {
|
||||
const next = await saveBackupSchedule({
|
||||
enabled: enabledDraft, schedule_time: timeDraft,
|
||||
retention_days: Number(daysDraft), retention_months: Number(monthsDraft), apply: true,
|
||||
})
|
||||
adopt(next)
|
||||
if (!next.host_configured) {
|
||||
setMessage('计划已保存。目标主机凭据未挂载,因此还不能下发到主机上的 cron。')
|
||||
} else if (next.applied) {
|
||||
setMessage(`计划已保存并下发:每天 ${next.schedule_time} 执行,保留 ${next.retention_days} 天(每月另留 ${next.retention_months} 份)。`)
|
||||
} else {
|
||||
setMessage(`计划已保存,但下发失败:${next.apply_error}`)
|
||||
}
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '保存备份计划失败') }
|
||||
finally { setBusy(null) }
|
||||
}
|
||||
|
||||
const apply = async () => {
|
||||
setBusy('apply'); setError(null); setMessage('')
|
||||
try {
|
||||
const next = await applyBackupSchedule()
|
||||
adopt(next)
|
||||
setMessage(next.applied ? '已按当前设置重新下发到目标主机。' : `下发失败:${next.apply_error}`)
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '下发备份计划失败') }
|
||||
finally { setBusy(null) }
|
||||
}
|
||||
|
||||
const runNow = async () => {
|
||||
setBusy('run'); setError(null); setMessage('')
|
||||
try {
|
||||
const start = await runBackupNow()
|
||||
setMessage(start.started ? '已在目标主机上开始备份(整库 pg_dump,约 30~60 秒),下方会自动刷新结果。' : '已有一个备份任务在执行中。')
|
||||
adopt(await fetchBackupScheduleHost())
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '触发备份失败') }
|
||||
finally { setBusy(null) }
|
||||
}
|
||||
|
||||
if (!schedule) {
|
||||
return <section className="settings-panel wide storage-settings-panel" id="settings-storage">
|
||||
<div className="settings-section-heading"><div><h2>存储与备份</h2></div></div>
|
||||
{error ? <p className="error-message" role="alert">{error}</p> : null}
|
||||
<p className="hint">{loading ? '正在读取备份计划…' : '备份计划暂不可用。'}</p>
|
||||
</section>
|
||||
}
|
||||
|
||||
return <BackupScheduleView
|
||||
schedule={schedule} isAdmin={isAdmin} loading={loading} probing={probing} busy={busy}
|
||||
error={error} message={message}
|
||||
enabledDraft={enabledDraft} timeDraft={timeDraft} daysDraft={daysDraft} monthsDraft={monthsDraft}
|
||||
onEnabledChange={setEnabledDraft} onTimeChange={setTimeDraft}
|
||||
onDaysChange={setDaysDraft} onMonthsChange={setMonthsDraft}
|
||||
onSave={() => void save()} onApply={() => void apply()} onRunNow={() => void runNow()}
|
||||
onReload={() => void load()}
|
||||
/>
|
||||
}
|
||||
Reference in New Issue
Block a user