1428 lines
62 KiB
TypeScript
1428 lines
62 KiB
TypeScript
import { useCallback, useEffect, useRef, useState } from 'react'
|
||
|
||
import { useOptionalAuth } from './auth'
|
||
import {
|
||
applyBackupSchedule,
|
||
fetchBackupSchedule,
|
||
fetchBackupScheduleHost,
|
||
runBackupNow,
|
||
saveBackupSchedule,
|
||
} from './backupSchedule'
|
||
import type { BackupSchedule } from './backupSchedule'
|
||
import { fetchBackupInventory } from './backupInventory'
|
||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||
import './storageBackup.css'
|
||
|
||
export const formatBackupBytes = (bytes: number | null | undefined): string => {
|
||
if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return '—'
|
||
if (bytes === 0) return '0 B'
|
||
if (bytes < 1024) return `${bytes} B`
|
||
const mib = bytes / (1024 * 1024)
|
||
if (mib >= 1024) return `${(mib / 1024).toFixed(2)} GiB`
|
||
// 小文件不能舍成 0.0 MiB;不足 0.05 MiB 用 KiB,其余保留一位 MiB。
|
||
if (mib < 0.05) return `${(bytes / 1024).toFixed(1)} KiB`
|
||
return `${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 })
|
||
}
|
||
|
||
// 清单里的 created_at 就是目录戳(如 20261009T060736Z),同值时不再重复显示一遍。
|
||
export const runMoment = (schedule: { last_run_stamp: string; last_run_created_at: string }): string => {
|
||
const createdAt = schedule.last_run_created_at.trim()
|
||
if (!createdAt || createdAt === schedule.last_run_stamp.trim()) return ''
|
||
return formatBackupMoment(createdAt)
|
||
}
|
||
|
||
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
|
||
|
||
const GIB = 1024 * 1024 * 1024
|
||
|
||
// 整盘读数是"主机 + 卷 + 备份目录"三件事实的组合,当前后端没有对应接口:
|
||
// 页面只保留原型位置并写明原因,不在产品里填任何示例容量。测试夹具通过这个
|
||
// 只读结构验证色带与告警的完整分支,生产容器恒传 null。
|
||
export interface StorageDiskObservation {
|
||
total_bytes: number
|
||
free_bytes: number
|
||
// 与策略目录同一卷上的备份占用
|
||
backup_bytes: number
|
||
// 其他磁盘上历史备份的占用(合计口径也要吃总配额)
|
||
other_volume_backup_bytes: number
|
||
quota_bytes: number
|
||
reserve_bytes: number
|
||
// 下次任务预计新增;未知时必须为空,不能拿上一次体积冒充
|
||
estimate_bytes: number | null
|
||
sampled_at: string
|
||
}
|
||
|
||
export type StorageAlertCode = 'disk_low' | 'quota_low' | 'both_low' | 'quota_over_physical'
|
||
|
||
export interface StorageAlert {
|
||
code: StorageAlertCode
|
||
label: string
|
||
active: boolean
|
||
known: boolean
|
||
detail: string
|
||
}
|
||
|
||
export interface StorageUsage {
|
||
total: number
|
||
free: number
|
||
system_other: number
|
||
backup: number
|
||
quota_free: number
|
||
beyond_quota_free: number
|
||
budget: number
|
||
used_total: number
|
||
allowance: number
|
||
writable: number
|
||
}
|
||
|
||
export function storageUsage(observation: StorageDiskObservation): StorageUsage {
|
||
const total = Math.max(0, observation.total_bytes)
|
||
const free = Math.max(0, observation.free_bytes)
|
||
const backup = Math.max(0, observation.backup_bytes)
|
||
const otherBackups = Math.max(0, observation.other_volume_backup_bytes)
|
||
const reserve = Math.max(0, observation.reserve_bytes)
|
||
const budget = Math.max(0, observation.quota_bytes)
|
||
const usedTotal = backup + otherBackups
|
||
const allowance = Math.max(0, budget - usedTotal)
|
||
const writable = Math.max(0, free - reserve)
|
||
const systemOther = Math.max(0, total - free - backup)
|
||
const onOtherVolumes = Math.max(0, usedTotal - backup)
|
||
const localQuota = Math.max(0, budget - onOtherVolumes)
|
||
const inQuota = Math.min(backup, localQuota)
|
||
// 配额允许但盘上画不下的部分不进入色带,避免把配额当成物理空间。
|
||
const quotaFree = Math.min(free, allowance)
|
||
return {
|
||
total,
|
||
free,
|
||
system_other: systemOther,
|
||
backup: inQuota,
|
||
quota_free: quotaFree,
|
||
beyond_quota_free: Math.max(0, free - quotaFree),
|
||
budget,
|
||
used_total: usedTotal,
|
||
allowance,
|
||
writable,
|
||
}
|
||
}
|
||
|
||
// 四种告警与原型一致;读数缺失时每条都只能是"无法判定",不能默认正常。
|
||
export function storageAlerts(observation: StorageDiskObservation | null): StorageAlert[] {
|
||
if (!observation) {
|
||
return [
|
||
{ code: 'disk_low', label: '磁盘不足', active: false, known: false, detail: '尚未读取宿主快照' },
|
||
{ code: 'quota_low', label: '配额不足', active: false, known: false, detail: '缺备份占用量与配额读数' },
|
||
{ code: 'both_low', label: '磁盘与配额同时不足', active: false, known: false, detail: '尚未读取宿主快照' },
|
||
{
|
||
code: 'quota_over_physical',
|
||
label: '配额超出物理空闲',
|
||
active: false,
|
||
known: false,
|
||
detail: '尚未读取宿主快照',
|
||
},
|
||
]
|
||
}
|
||
const usage = storageUsage(observation)
|
||
const estimate = observation.estimate_bytes
|
||
if (estimate === null) {
|
||
return [
|
||
{
|
||
code: 'disk_low',
|
||
label: '磁盘不足',
|
||
active: false,
|
||
known: false,
|
||
detail: '缺下次新增体积,不能判定是否装得下',
|
||
},
|
||
{
|
||
code: 'quota_low',
|
||
label: '配额不足',
|
||
active: false,
|
||
known: false,
|
||
detail: '缺下次新增体积,不能判定配额是否够',
|
||
},
|
||
{ code: 'both_low', label: '磁盘与配额同时不足', active: false, known: false, detail: '缺下次新增体积' },
|
||
{
|
||
code: 'quota_over_physical',
|
||
label: '配额超出物理空闲',
|
||
active: usage.allowance > usage.free,
|
||
known: true,
|
||
detail: `配额余量 ${formatGib(usage.allowance)} GiB,盘上实际空闲 ${formatGib(usage.free)} GiB`,
|
||
},
|
||
]
|
||
}
|
||
const diskLow = usage.writable < estimate
|
||
const quotaLow = usage.allowance < estimate
|
||
return [
|
||
{
|
||
code: 'disk_low',
|
||
label: '磁盘不足',
|
||
active: diskLow,
|
||
known: true,
|
||
detail: diskLow
|
||
? `扣除预留后可写 ${formatGib(usage.writable)} GiB,本次预计新增 ${formatGib(estimate)} GiB,差 ${formatGib(estimate - usage.writable)} GiB`
|
||
: `扣除预留后可写 ${formatGib(usage.writable)} GiB,够本次 ${formatGib(estimate)} GiB`,
|
||
},
|
||
{
|
||
code: 'quota_low',
|
||
label: '配额不足',
|
||
active: quotaLow,
|
||
known: true,
|
||
detail: quotaLow
|
||
? `配额余量 ${formatGib(usage.allowance)} GiB,本次预计新增 ${formatGib(estimate)} GiB,差 ${formatGib(estimate - usage.allowance)} GiB`
|
||
: `配额余量 ${formatGib(usage.allowance)} GiB,够本次 ${formatGib(estimate)} GiB`,
|
||
},
|
||
{
|
||
code: 'both_low',
|
||
label: '磁盘与配额同时不足',
|
||
active: diskLow && quotaLow,
|
||
known: true,
|
||
detail: diskLow && quotaLow ? '两项都不够,本次备份会失败' : '未同时触发',
|
||
},
|
||
{
|
||
code: 'quota_over_physical',
|
||
label: '配额超出物理空闲',
|
||
active: usage.allowance > usage.free,
|
||
known: true,
|
||
detail:
|
||
usage.allowance > usage.free
|
||
? `配额还允许 ${formatGib(usage.allowance)} GiB,但盘上只剩 ${formatGib(usage.free)} GiB;超出部分画不进磁盘`
|
||
: '配额余量未超过物理空闲',
|
||
},
|
||
]
|
||
}
|
||
|
||
const formatGib = (bytes: number): string => String(Number((bytes / GIB).toFixed(2)))
|
||
const percent = (part: number, total: number): string => (total > 0 ? `${(100 * part) / total}%` : '0%')
|
||
|
||
export const storageAlertSummary = (alerts: StorageAlert[]): string => {
|
||
const unknown = alerts.filter((item) => !item.known)
|
||
const quotaOnly = ['quota_low', 'both_low', 'quota_over_physical']
|
||
if (unknown.length === alerts.length) return '无法判定(缺读数与配额字段)'
|
||
if (unknown.length && unknown.every((item) => item.code === 'disk_low' || quotaOnly.includes(item.code))) {
|
||
const disk = alerts.find((item) => item.code === 'disk_low')
|
||
return disk?.known ? '磁盘项正常 · 配额字段未接线' : '磁盘项无法判定 · 配额字段未接线'
|
||
}
|
||
if (unknown.length) return `部分无法判定(${unknown.map((item) => item.label).join('、')})`
|
||
const active = alerts.filter((item) => item.active)
|
||
return active.length ? active.map((item) => item.label).join('、') : '四项均正常'
|
||
}
|
||
|
||
export interface InventoryUsage {
|
||
total: number
|
||
used: number
|
||
free: number
|
||
backup: number
|
||
system_other: number
|
||
}
|
||
|
||
// 完整新鲜的宿主快照 + 实测容量 + 采集器给出的文件系统,才画整盘图。
|
||
// 备份实际占盘取快照的总实际分配,不是 MANIFEST 表观字节,也不接受部分字节。
|
||
export function inventoryUsage(inventory: BackupInventory | null): InventoryUsage | null {
|
||
if (
|
||
!inventory ||
|
||
!inventory.wired ||
|
||
!inventory.metadata.present ||
|
||
!inventory.metadata.valid ||
|
||
!inventory.metadata.fresh ||
|
||
!inventory.metadata.complete ||
|
||
!inventory.mount.mount_verified ||
|
||
!inventory.capacity.measured ||
|
||
inventory.capacity.total_bytes <= 0 ||
|
||
inventory.totals.actual_bytes === null ||
|
||
inventory.totals.actual_bytes === undefined
|
||
) {
|
||
return null
|
||
}
|
||
if (inventory.batches.some((batch) => !batch.sizes_complete || batch.actual_bytes === null)) {
|
||
return null
|
||
}
|
||
const total = inventory.capacity.total_bytes
|
||
const used = Math.max(0, inventory.capacity.used_bytes)
|
||
const backup = Math.max(0, inventory.totals.actual_bytes)
|
||
return {
|
||
total,
|
||
used,
|
||
free: Math.max(0, inventory.capacity.available_bytes),
|
||
backup,
|
||
system_other: Math.max(0, used - backup),
|
||
}
|
||
}
|
||
|
||
// 配额与策略预留在后端仍是缺字段,不能因为容量读到了就假装能判定配额;
|
||
// 磁盘告警只拿"最近一批实际占盘"做参考,并注明不含预留。
|
||
export function inventoryAlerts(inventory: BackupInventory | null): StorageAlert[] {
|
||
const usage = inventoryUsage(inventory)
|
||
const latest = inventory?.batches[0]
|
||
const capacityKnown = Boolean(usage)
|
||
const latestBytes = latest?.actual_bytes ?? null
|
||
const diskKnown =
|
||
capacityKnown && latest !== undefined && latest.sizes_complete && latestBytes !== null && latestBytes !== undefined
|
||
const diskActive = diskKnown && latestBytes! > usage!.free
|
||
const diskDetail = !inventory
|
||
? '尚未读取宿主元数据快照'
|
||
: !inventory.wired
|
||
? '元数据快照未接线'
|
||
: !inventory.metadata.present
|
||
? '元数据快照缺失'
|
||
: !inventory.metadata.valid
|
||
? inventory.metadata.error || '元数据快照无效'
|
||
: !inventory.metadata.fresh
|
||
? '元数据快照已陈旧'
|
||
: !inventory.metadata.complete
|
||
? '元数据快照不完整:占盘与容量未知'
|
||
: !inventory.mount.mount_verified
|
||
? '宿主采集器未给出可用文件系统'
|
||
: !inventory.capacity.measured
|
||
? inventory.capacity.error || '未读到文件系统容量'
|
||
: latestBytes === null || latestBytes === undefined
|
||
? '容量已读到,但缺最近批次实际占盘;不能判定是否装得下'
|
||
: `剩余可用 ${formatGib(usage!.free)} GiB,最近一批实际占盘 ${formatGib(latestBytes)} GiB(参考值,不含策略预留)`
|
||
return [
|
||
{
|
||
code: 'disk_low',
|
||
label: '磁盘不足',
|
||
active: diskActive,
|
||
known: diskKnown,
|
||
detail: diskDetail,
|
||
},
|
||
{
|
||
code: 'quota_low',
|
||
label: '配额不足',
|
||
active: false,
|
||
known: false,
|
||
detail: '仅缺备份总配额字段,无法判定',
|
||
},
|
||
{
|
||
code: 'both_low',
|
||
label: '磁盘与配额同时不足',
|
||
active: false,
|
||
known: false,
|
||
detail: '仅缺配额字段,无法同时判定',
|
||
},
|
||
{
|
||
code: 'quota_over_physical',
|
||
label: '配额超出物理空闲',
|
||
active: false,
|
||
known: false,
|
||
detail: '仅缺配额字段,无法判定',
|
||
},
|
||
]
|
||
}
|
||
|
||
export async function copyBackupPath(value: string, button?: HTMLButtonElement | null): Promise<boolean> {
|
||
if (!value) return false
|
||
try {
|
||
await navigator.clipboard.writeText(value)
|
||
if (button) button.textContent = '已复制'
|
||
return true
|
||
} catch {
|
||
// 内网 http 页面没有 clipboard API 权限时退回选中,不谎报“已复制”。
|
||
const area = document.createElement('textarea')
|
||
area.value = value
|
||
area.setAttribute('readonly', '')
|
||
area.style.position = 'fixed'
|
||
area.style.opacity = '0'
|
||
document.body.append(area)
|
||
area.focus()
|
||
area.select()
|
||
const copied = document.execCommand('copy')
|
||
area.remove()
|
||
if (button) button.textContent = copied ? '已复制' : '路径已选中,可复制'
|
||
return copied
|
||
}
|
||
}
|
||
|
||
const manifestLabel = (batch: BackupInventoryBatch): string =>
|
||
batch.manifest_state === 'ok' ? '清单完整' : batch.manifest_state === 'missing' ? '清单缺失' : '清单损坏'
|
||
|
||
export type InventorySnapshotState =
|
||
'loading' | 'unconfigured' | 'missing' | 'stale' | 'invalid' | 'incomplete' | 'ready'
|
||
|
||
// 快照状态必须由接口字段判定,不能因为 fresh=false 就一律说“未接线”:
|
||
// 过期、缺失、无效、未配置是四种不同事实,目录/历史/容量都不能互相代替。
|
||
export function inventorySnapshotState(inventory: BackupInventory | null): InventorySnapshotState {
|
||
if (!inventory) return 'loading'
|
||
if (!inventory.wired || !inventory.metadata.configured) return 'unconfigured'
|
||
if (!inventory.metadata.present) return 'missing'
|
||
const age = inventory.metadata.age_seconds
|
||
const maxAge = inventory.metadata.max_age_seconds
|
||
const staleByAge = maxAge > 0 && age > maxAge
|
||
if (!inventory.metadata.fresh && (staleByAge || inventory.metadata.error.includes('陈旧'))) return 'stale'
|
||
if (!inventory.metadata.valid) return 'invalid'
|
||
if (!inventory.metadata.fresh) return 'stale'
|
||
if (!inventory.metadata.complete) return 'incomplete'
|
||
return 'ready'
|
||
}
|
||
|
||
const inventoryStateLabel = (state: InventorySnapshotState): string => {
|
||
switch (state) {
|
||
case 'unconfigured':
|
||
return '元数据快照未接线'
|
||
case 'missing':
|
||
return '元数据快照缺失'
|
||
case 'stale':
|
||
return '元数据快照已过期'
|
||
case 'invalid':
|
||
return '元数据快照无效'
|
||
case 'incomplete':
|
||
return '元数据快照不完整'
|
||
case 'ready':
|
||
return '元数据快照有效'
|
||
default:
|
||
return '元数据读取中'
|
||
}
|
||
}
|
||
|
||
// 备份执行主机上的整库逻辑备份(全部业务库一次 pg_dump)。
|
||
// 页面只展示接口真实给出的读数;目录、配额、预留、子库路径、历史批次与恢复
|
||
// 验证在后端契约里还没有字段,保留原型位置并写明"未接线"。
|
||
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
|
||
// 仅测试夹具提供;生产容器不传,磁盘区改用真实盘点的容量。
|
||
disk?: StorageDiskObservation | null
|
||
inventory?: BackupInventory | null
|
||
inventoryLoading?: boolean
|
||
inventoryError?: string | null
|
||
onReloadInventory?: () => void
|
||
}
|
||
|
||
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,
|
||
disk = null,
|
||
inventory = null,
|
||
inventoryLoading = false,
|
||
inventoryError = null,
|
||
onReloadInventory,
|
||
} = 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_checked_at || schedule.host_error
|
||
? `${schedule.host_target} · 连接失败`
|
||
: `${schedule.host_target} · 尚未探测`
|
||
// 未探测与探测失败必须分开:只读计划先返回时 reachable=false 不代表连不上。
|
||
const hostProbePending =
|
||
schedule.host_configured && !schedule.host_reachable && !schedule.host_checked_at && !schedule.host_error
|
||
const syncLine = !schedule.host_configured
|
||
? '无法比对(未读取主机计划)'
|
||
: hostProbePending
|
||
? '尚未比对'
|
||
: !schedule.host_reachable
|
||
? '无法比对(主机不可达)'
|
||
: schedule.in_sync
|
||
? '已一致'
|
||
: '待下发'
|
||
// 只有真的连上并读回主机状态时,才能说脚本在不在;连不上是"未知"。
|
||
const scriptLine = !schedule.host_reachable
|
||
? '未知(未连上主机,未执行主机侧脚本)'
|
||
: schedule.host_script_present
|
||
? '存在'
|
||
: '缺失'
|
||
const databaseCount = schedule.last_run_databases.length
|
||
const failedCount = schedule.last_run_failed_databases.length
|
||
const hasLastRun = Boolean(schedule.last_run_stamp)
|
||
const runFailed = failedCount > 0 || Boolean(schedule.last_run_error)
|
||
const usage = disk ? storageUsage(disk) : null
|
||
const alerts = disk ? storageAlerts(disk) : inventoryAlerts(inventory)
|
||
const snapshotState = inventorySnapshotState(inventory)
|
||
const snapshotLabel = inventory
|
||
? inventoryStateLabel(snapshotState)
|
||
: inventoryError
|
||
? '元数据快照读取失败'
|
||
: inventoryLoading
|
||
? '元数据读取中'
|
||
: '元数据快照未读取'
|
||
const snapshotPathsTrusted = snapshotState === 'ready' || snapshotState === 'incomplete'
|
||
const sshFallbackReason = snapshotPathsTrusted ? '元数据快照无批次' : snapshotLabel
|
||
const latestBatch: BackupInventoryBatch | null = snapshotPathsTrusted ? (inventory?.batches[0] ?? null) : null
|
||
const inventoryFigure = inventoryUsage(inventory)
|
||
const inventoryReady = snapshotPathsTrusted
|
||
const readyInventory = snapshotPathsTrusted ? inventory : null
|
||
const inventoryDatabases = latestBatch?.databases.map((item) => item.name) ?? []
|
||
const scopeDatabases = inventoryDatabases.length ? inventoryDatabases : schedule.last_run_databases
|
||
const scopeDatabaseCount = scopeDatabases.length
|
||
const scopeFailed = latestBatch ? latestBatch.databases.filter((item) => item.failed).length : failedCount
|
||
const hasScopeBatch = Boolean(latestBatch) || hasLastRun
|
||
|
||
return (
|
||
<section className="settings-panel wide storage-settings-panel" id="settings-storage">
|
||
<div className="settings-section-heading">
|
||
<div>
|
||
<h2>存储与备份</h2>
|
||
<p>
|
||
本页管的是<strong>数据库整库逻辑备份</strong>(pg_dump 目录格式,在备份执行主机本地写盘);
|
||
下方「归档占用」是版本快照的归档文件,两者不是同一种数据,体积不能相加。
|
||
</p>
|
||
</div>
|
||
<button onClick={onReload} disabled={loading || probing}>
|
||
{loading || probing ? '读取中…' : '刷新计划与快照'}
|
||
</button>
|
||
</div>
|
||
{error ? (
|
||
<p className="error-message" role="alert">
|
||
{error}
|
||
</p>
|
||
) : null}
|
||
|
||
<section className="storage-block" aria-labelledby="storage-scope-heading">
|
||
<div className="storage-block-heading">
|
||
<h3 id="storage-scope-heading">范围与读写方向</h3>
|
||
<span className={`storage-chip ${schedule.host_configured ? 'ok' : 'off'}`}>
|
||
{schedule.host_configured ? '平台已接主机凭据' : '平台未接主机凭据'}
|
||
</span>
|
||
<span className={`storage-chip ${inventoryReady ? 'ok' : 'off'}`}>
|
||
{inventoryLoading && !inventory
|
||
? '元数据读取中'
|
||
: snapshotState === 'ready'
|
||
? '元数据快照有效'
|
||
: snapshotState === 'incomplete'
|
||
? '元数据快照不完整'
|
||
: snapshotLabel}
|
||
</span>
|
||
</div>
|
||
<dl className="storage-facts">
|
||
<dt>读取源</dt>
|
||
<dd>
|
||
{inventory?.source
|
||
? `${inventory.source}${snapshotState === 'stale' ? '(快照已过期)' : ''}`
|
||
: `备份执行主机 ${schedule.host_target || '(未配置)'} 本机直连 RDS`}
|
||
{scopeDatabaseCount ? ` · 最近批次含 ${scopeDatabaseCount} 个数据库` : ' · 数据库清单未读到'}
|
||
</dd>
|
||
<dt>采集时间</dt>
|
||
<dd>
|
||
{inventory?.metadata.present
|
||
? `${formatBackupMoment(inventory.metadata.collected_at)}(快照) · 年龄 ${inventory.metadata.age_seconds} 秒 / 上限 ${inventory.metadata.max_age_seconds} 秒 · ${
|
||
snapshotState === 'stale' ? '已过期' : inventory.metadata.fresh ? '新鲜' : '不可用'
|
||
}`
|
||
: `—(${snapshotLabel})`}
|
||
</dd>
|
||
<dt>读回时间</dt>
|
||
<dd>{inventory?.observed_at ? `${formatBackupMoment(inventory.observed_at)}(API 读回)` : '—'}</dd>
|
||
<dt>写入方向</dt>
|
||
<dd>
|
||
{snapshotPathsTrusted && inventory?.host_root
|
||
? inventory.host_root
|
||
: snapshotState === 'stale'
|
||
? `—(${snapshotLabel}:不展示旧目录路径)`
|
||
: `—(${snapshotLabel})`}
|
||
<span className="storage-inline-note">
|
||
{snapshotPathsTrusted
|
||
? '宿主采集器快照(只读);平台没有写路径'
|
||
: `${snapshotLabel}:目录不可验证,不按设置推定`}
|
||
</span>
|
||
</dd>
|
||
<dt>执行范围</dt>
|
||
<dd>
|
||
{scopeDatabaseCount
|
||
? `整批 · ${scopeDatabaseCount} 个数据库(${scopeDatabases.join('、')})`
|
||
: '整批 · 数据库清单未读到,无法列出库名'}
|
||
</dd>
|
||
<dt>拨号地址</dt>
|
||
<dd>{schedule.host_endpoint || '—'}</dd>
|
||
</dl>
|
||
<div className="storage-block-actions">
|
||
<button type="button" disabled title="接口没有单库参数,单库范围未经证实">
|
||
仅备份该库(不可用)
|
||
</button>
|
||
<p className="hint">
|
||
<code>POST /api/v1/backup-schedule/run</code> 没有单库参数,一次就是该主机全部业务库的整批
|
||
pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复请复制「备份记录」里该库的
|
||
完整子目录(来自宿主元数据快照),不要自己拼路径。
|
||
</p>
|
||
</div>
|
||
</section>
|
||
|
||
<section className="storage-block" aria-labelledby="storage-run-heading">
|
||
<div className="storage-block-heading">
|
||
<h3 id="storage-run-heading">立即备份</h3>
|
||
<span
|
||
className={`storage-chip ${hasScopeBatch && scopeFailed === 0 ? 'ok' : hasScopeBatch ? 'warn' : 'off'}`}
|
||
>
|
||
{hasScopeBatch ? (scopeFailed > 0 ? '最近一批有失败' : '最近一批成功') : '尚无批次读数'}
|
||
</span>
|
||
</div>
|
||
<p>
|
||
{latestBatch
|
||
? `最近一批 ${latestBatch.stamp} · ${formatBackupMoment(latestBatch.created_at)} · ${scopeDatabaseCount} 个数据库 · 表观 ${formatBackupBytes(latestBatch.apparent_bytes)} · ${
|
||
latestBatch.actual_bytes === null
|
||
? '实际占盘未知(采集不完整)'
|
||
: `实际占盘 ${formatBackupBytes(latestBatch.actual_bytes)}`
|
||
} · ${latestBatch.duration_seconds} 秒`
|
||
: hasLastRun
|
||
? `SSH 读回最近一次 ${schedule.last_run_stamp} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)}(${sshFallbackReason},以下仅 SSH 读回结果)`
|
||
: '还没有从主机读到任何批次。'}
|
||
</p>
|
||
{schedule.running ? (
|
||
<div className="storage-progress" role="status">
|
||
<p className="storage-running">
|
||
正在备份({formatBackupMoment(schedule.running_started_at)} 开始,整批 {scopeDatabaseCount || '未知'}{' '}
|
||
个数据库)。 没有真实百分比接口,这里只报在途状态,完成后自动刷新。
|
||
</p>
|
||
<progress className="storage-progress-bar" aria-label="备份进行中,无百分比" />
|
||
</div>
|
||
) : null}
|
||
{schedule.run_last_error && !schedule.running ? (
|
||
<p className="error-message">上一次立即备份失败:{schedule.run_last_error}</p>
|
||
) : null}
|
||
{isAdmin ? (
|
||
<div className="storage-block-actions">
|
||
<button
|
||
className="primary"
|
||
onClick={onRunNow}
|
||
disabled={busy !== null || !schedule.host_configured || schedule.running}
|
||
>
|
||
{schedule.running
|
||
? '备份进行中…'
|
||
: busy === 'run'
|
||
? '正在触发…'
|
||
: `立即备份一次(整批${databaseCount ? ` ${databaseCount} 个数据库` : ''})`}
|
||
</button>
|
||
<span className="hint">触发的是该主机全部业务库的整批备份,不是 scope 快照,也不是单库。</span>
|
||
</div>
|
||
) : (
|
||
<p className="hint">立即备份仅管理员可触发;当前为只读。</p>
|
||
)}
|
||
</section>
|
||
|
||
<section
|
||
className={`storage-block storage-disk ${alerts.some((item) => item.known && item.active) ? 'storage-disk-low' : ''}`}
|
||
aria-labelledby="storage-disk-heading"
|
||
>
|
||
<div className="storage-block-heading">
|
||
<h3 id="storage-disk-heading">整盘占用与告警</h3>
|
||
<span className="storage-chip off">
|
||
{usage ? '已读到主机读数' : inventoryFigure ? '宿主采集器实测' : '占盘未知'}
|
||
</span>
|
||
</div>
|
||
{usage && disk ? (
|
||
<>
|
||
<div
|
||
className="storage-disk-track"
|
||
role="img"
|
||
aria-label={`整盘 ${formatGib(usage.total)} GiB:系统其他占用 ${formatGib(usage.system_other)} GiB、备份已用 ${formatGib(usage.backup)} GiB、配额内空闲 ${formatGib(usage.quota_free)} GiB、配额外空闲 ${formatGib(usage.beyond_quota_free)} GiB`}
|
||
>
|
||
<div className="storage-disk-other" style={{ width: percent(usage.system_other, usage.total) }} />
|
||
<div
|
||
className="storage-disk-zone"
|
||
style={{ width: percent(usage.backup + usage.quota_free, usage.total) }}
|
||
>
|
||
<div
|
||
className="storage-disk-used"
|
||
style={{ width: percent(usage.backup, usage.backup + usage.quota_free) }}
|
||
/>
|
||
</div>
|
||
<div className="storage-disk-blank" style={{ width: percent(usage.beyond_quota_free, usage.total) }} />
|
||
</div>
|
||
<div className="storage-disk-legend">
|
||
<span>
|
||
<i className="storage-dot other" />
|
||
系统其他占用 {formatGib(usage.system_other)} GiB
|
||
</span>
|
||
<span>
|
||
<i className="storage-dot used" />
|
||
备份已用 {formatGib(usage.backup)} GiB
|
||
</span>
|
||
<span>
|
||
<i className="storage-dot zone" />
|
||
配额内空闲 {formatGib(usage.quota_free)} GiB
|
||
</span>
|
||
<span>
|
||
<i className="storage-dot blank" />
|
||
配额外空闲 {formatGib(usage.beyond_quota_free)} GiB
|
||
</span>
|
||
</div>
|
||
<p className="storage-metric">
|
||
备份已用 {formatGib(usage.used_total)} / {formatGib(usage.budget)} GiB(
|
||
{usage.budget > 0 ? `${((100 * usage.used_total) / usage.budget).toFixed(2)}%` : '—'})· 总配额占当前整盘{' '}
|
||
{usage.total > 0 ? `${((100 * usage.budget) / usage.total).toFixed(2)}%` : '—'}
|
||
</p>
|
||
<small>
|
||
读数采集于 {formatBackupMoment(disk.sampled_at)} · 本盘实际空闲 {formatGib(usage.free)} GiB,系统预留{' '}
|
||
{formatGib(disk.reserve_bytes)} GiB
|
||
{disk.other_volume_backup_bytes > 0
|
||
? ` · 其他磁盘的历史备份占用总配额 ${formatGib(disk.other_volume_backup_bytes)} GiB`
|
||
: ''}
|
||
</small>
|
||
</>
|
||
) : inventoryFigure && inventory ? (
|
||
<>
|
||
<div
|
||
className="storage-disk-track"
|
||
role="img"
|
||
aria-label={`挂载盘 ${formatGib(inventoryFigure.total)} GiB:系统其他占用 ${formatGib(inventoryFigure.system_other)} GiB、备份实际占盘 ${formatGib(inventoryFigure.backup)} GiB、可用 ${formatGib(inventoryFigure.free)} GiB`}
|
||
>
|
||
<div
|
||
className="storage-disk-other"
|
||
style={{ width: percent(inventoryFigure.system_other, inventoryFigure.total) }}
|
||
/>
|
||
<div
|
||
className="storage-disk-used"
|
||
style={{ width: percent(inventoryFigure.backup, inventoryFigure.total) }}
|
||
/>
|
||
<div
|
||
className="storage-disk-blank"
|
||
style={{
|
||
width: percent(
|
||
Math.max(0, inventoryFigure.total - inventoryFigure.used - inventoryFigure.free),
|
||
inventoryFigure.total
|
||
),
|
||
}}
|
||
/>
|
||
</div>
|
||
<div className="storage-disk-legend">
|
||
<span>
|
||
<i className="storage-dot other" />
|
||
系统其他占用 {formatGib(inventoryFigure.system_other)} GiB
|
||
</span>
|
||
<span>
|
||
<i className="storage-dot used" />
|
||
备份实际占盘 {formatGib(inventoryFigure.backup)} GiB
|
||
</span>
|
||
<span>
|
||
<i className="storage-dot blank" />
|
||
可用 {formatGib(inventoryFigure.free)} GiB
|
||
</span>
|
||
<span>
|
||
<i className="storage-dot zone" />
|
||
配额内/外 —(无配额字段)
|
||
</span>
|
||
</div>
|
||
<p className="storage-metric">
|
||
备份实际占盘 {formatGib(inventoryFigure.backup)} / 整盘 {formatGib(inventoryFigure.total)} GiB(
|
||
{inventoryFigure.total > 0
|
||
? `${((100 * inventoryFigure.backup) / inventoryFigure.total).toFixed(2)}%`
|
||
: '—'}
|
||
)· 文件系统已用 {formatGib(inventoryFigure.used)} GiB · 可用 {formatGib(inventoryFigure.free)} GiB
|
||
</p>
|
||
<small>
|
||
{inventory.mount.evidence} · 挂载点 {inventory.mount.mount_point || '—'} · 采集于{' '}
|
||
{formatBackupMoment(inventory.metadata.collected_at)} · 读回于 {formatBackupMoment(inventory.observed_at)}
|
||
</small>
|
||
<p className="hint">
|
||
备份文件系统必须由备份主机可写;API 只读挂载元数据快照,不向该盘写入。空间预测仅以上次整批实际占盘
|
||
{latestBatch?.actual_bytes !== null && latestBatch?.actual_bytes !== undefined
|
||
? ` ${formatBackupBytes(latestBatch.actual_bytes)}`
|
||
: '(未读到)'}{' '}
|
||
作参考,不是接口预测,也不含策略预留。
|
||
</p>
|
||
</>
|
||
) : (
|
||
<>
|
||
<div
|
||
className="storage-disk-track storage-disk-track-unknown"
|
||
role="img"
|
||
aria-label="整盘占用未知:没有完整新鲜的宿主快照"
|
||
>
|
||
<span>{inventoryLoading ? '正在读取宿主元数据快照…' : '占盘未知 · 不使用部分字节'}</span>
|
||
</div>
|
||
<div className="storage-disk-legend">
|
||
{['系统其他占用', '备份实际占盘', '可用', '配额内/外'].map((label, index) => (
|
||
<span key={label}>
|
||
<i className={`storage-dot ${['other', 'used', 'blank', 'zone'][index]}`} />
|
||
{label} —
|
||
</span>
|
||
))}
|
||
</div>
|
||
<p className="storage-metric">
|
||
整盘总量 / 空闲 / 备份实际占盘:
|
||
{inventoryError || inventory?.metadata.error || inventory?.error || '未接线'}
|
||
</p>
|
||
</>
|
||
)}
|
||
<p className="hint">
|
||
容量与实际占盘来自宿主单项元数据采集器(stat/du 元数据,不读数据库内容);API 不遍历备份目录。
|
||
快照陈旧、缺失或不完整时,容量图与任何可写预测都不使用部分字节。配额与策略预留仍无后端字段;
|
||
容量可信时只对磁盘项判定,配额相关三项标注未接线。
|
||
</p>
|
||
<p className="storage-alert-summary">{storageAlertSummary(alerts)}</p>
|
||
<ul className="storage-alerts">
|
||
{alerts.map((alert) => (
|
||
<li key={alert.code} className={alert.known ? (alert.active ? 'alert-on' : 'alert-ok') : 'alert-unknown'}>
|
||
<strong>{alert.label}</strong>
|
||
<span>{alert.known ? (alert.active ? '触发' : '正常') : '无法判定'}</span>
|
||
<small>{alert.detail}</small>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</section>
|
||
|
||
<section className="storage-block" aria-labelledby="storage-policy-heading">
|
||
<div className="storage-block-heading">
|
||
<h3 id="storage-policy-heading">备份策略</h3>
|
||
<span className="hint">北京时间 · 主机读回</span>
|
||
</div>
|
||
<p className="storage-plan">
|
||
{!schedule.host_configured
|
||
? '平台未挂载主机凭据:无法读取当前主机计划,远端 cron 是否仍在执行未知(历史下发不能代替实时状态)。'
|
||
: hostProbePending
|
||
? '尚未探测当前主机计划:不能按设置或历史下发推定。'
|
||
: !schedule.host_reachable
|
||
? '主机连不上:以下"主机生效"状态未知,不能按设置推定。'
|
||
: schedule.host_schedule_enabled
|
||
? `主机生效:每天 ${schedule.host_schedule_time} · 保留 ${schedule.host_keep_days} 天 · 每月 ${schedule.host_keep_months} 份 · ${
|
||
schedule.in_sync ? '与设置已一致' : '与设置不一致(待下发)'
|
||
}`
|
||
: '主机生效:定时备份已关闭(已有备份保留)'}
|
||
{schedule.host_next_run ? ` · 下次 ${schedule.host_next_run}` : ' · 下一次实际执行未由主机返回'}
|
||
</p>
|
||
<p className="storage-plan">
|
||
编辑草稿:{enabledDraft ? `每天 ${timeDraft || '—'} · 保留 ${daysDraft || '—'} 天` : '定时备份关闭'} ·
|
||
每月归档 {monthsDraft || '—'} 份{dirty ? ' · 有未保存修改,主机仍按生效计划执行' : ' · 与已保存设置一致'}
|
||
</p>
|
||
{isAdmin ? (
|
||
<div className="storage-policy-editor">
|
||
<label>
|
||
备份主机上的目录
|
||
<input
|
||
type="text"
|
||
value={snapshotPathsTrusted ? (inventory?.host_root ?? '') : ''}
|
||
readOnly
|
||
disabled
|
||
placeholder={snapshotPathsTrusted ? '' : `${snapshotLabel}:目录不可验证`}
|
||
aria-label="备份主机上的目录(只读展示)"
|
||
/>
|
||
</label>
|
||
<div className="storage-block-actions">
|
||
<button type="button" disabled title="没有目录检查接口">
|
||
检查目录(不可用)
|
||
</button>
|
||
<span className="hint">
|
||
{snapshotPathsTrusted
|
||
? '目录来自宿主元数据快照,只读展示;修改目录需部署变更,平台没有写接口。'
|
||
: snapshotState === 'stale'
|
||
? '元数据快照已过期:目录不可验证,不沿用旧路径;等待宿主重新采集。'
|
||
: snapshotState === 'missing'
|
||
? '元数据快照缺失:目录不可验证,需先在备份主机运行采集器。'
|
||
: snapshotState === 'invalid'
|
||
? '元数据快照无效:目录不可验证,需检查快照内容。'
|
||
: snapshotState === 'loading'
|
||
? inventoryError
|
||
? '元数据快照读取失败:目录不可验证,请检查 API 到快照挂载的接线。'
|
||
: '尚未读取元数据快照:目录不可验证。'
|
||
: '元数据快照未接线:目录不可证明,不能按设置推定。'}
|
||
</span>
|
||
</div>
|
||
<label className="storage-checkbox">
|
||
<input
|
||
type="checkbox"
|
||
checked={enabledDraft}
|
||
onChange={(event) => onEnabledChange(event.target.checked)}
|
||
/>
|
||
启用定时备份
|
||
</label>
|
||
<div className="storage-policy-grid">
|
||
<label>
|
||
每日运行时间
|
||
<input
|
||
type="time"
|
||
value={timeDraft}
|
||
onChange={(event) => onTimeChange(event.target.value)}
|
||
aria-label="定时时间"
|
||
/>
|
||
</label>
|
||
<label>
|
||
备份总配额(GiB)
|
||
<input
|
||
type="number"
|
||
min={1}
|
||
value=""
|
||
disabled
|
||
readOnly
|
||
placeholder="接口未提供配额"
|
||
aria-label="备份总配额(未接线)"
|
||
/>
|
||
</label>
|
||
<label>
|
||
磁盘预留(GiB)
|
||
<input
|
||
type="number"
|
||
min={0}
|
||
value=""
|
||
disabled
|
||
readOnly
|
||
placeholder="接口未提供预留"
|
||
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>
|
||
</div>
|
||
<p className="hint">
|
||
保存只提交后端契约里的四项:启用、每日时间、储存天数、每月归档份数。目录、总配额、磁盘预留没有对应字段,
|
||
这里只占原型位置,不会被保存,也不会显示假的保存成功。
|
||
</p>
|
||
{!valid ? (
|
||
<p className="error-message">定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。</p>
|
||
) : null}
|
||
<div className="storage-block-actions">
|
||
<button onClick={onSave} disabled={busy !== null || !valid || !dirty}>
|
||
{busy === 'save' ? '正在保存并下发…' : '保存并下发到主机'}
|
||
</button>
|
||
<button onClick={onApply} disabled={busy !== null || !schedule.host_configured}>
|
||
{busy === 'apply' ? '正在下发…' : '重新下发当前设置'}
|
||
</button>
|
||
{message ? (
|
||
<span className="success-message" role="status">
|
||
{message}
|
||
</span>
|
||
) : null}
|
||
</div>
|
||
<p className="hint">
|
||
保存后从下次任务起使用新计划;历史文件保留在原路径。设置已保存但下发失败时,页面如实显示失败原因。
|
||
</p>
|
||
</div>
|
||
) : (
|
||
<p className="hint">
|
||
定时备份设置仅管理员可修改;当前设置:
|
||
{schedule.enabled ? `每天 ${schedule.schedule_time} · 保留 ${schedule.retention_days} 天` : '未启用'}。
|
||
</p>
|
||
)}
|
||
</section>
|
||
|
||
<section className="storage-block" aria-labelledby="storage-runs-heading">
|
||
<div className="storage-block-heading">
|
||
<h3 id="storage-runs-heading">备份记录</h3>
|
||
<span className="hint">
|
||
{readyInventory
|
||
? `${readyInventory.totals.batch_count} 批 · 元数据快照 · 实际占盘 ${formatBackupBytes(readyInventory.totals.actual_bytes)}`
|
||
: `${snapshotLabel} · 不展示旧批次`}
|
||
</span>
|
||
<button
|
||
type="button"
|
||
onClick={onReloadInventory}
|
||
disabled={inventoryLoading}
|
||
title="只重读 API 当前的 metadata.json 快照,不会让宿主重新采集"
|
||
>
|
||
{inventoryLoading ? '读取中…' : '重新盘点(仅重读快照)'}
|
||
</button>
|
||
</div>
|
||
{inventoryLoading && !inventory ? <p className="hint">正在读取宿主元数据快照…</p> : null}
|
||
{inventoryError ? (
|
||
<p className="error-message" role="alert">
|
||
快照请求失败:{inventoryError}。不能用 SSH 的“最近一次”代替历史;请检查 API 到快照挂载的接线。
|
||
</p>
|
||
) : null}
|
||
{inventory && snapshotState === 'unconfigured' ? (
|
||
<p className="hint">
|
||
元数据快照未接线:{inventory.metadata.error}。部署需在备份主机运行单次采集器并把输出目录只读挂进 API(见
|
||
docs/STORAGE_BACKUP_READONLY_API.md);未读到批次不等于没有备份。
|
||
</p>
|
||
) : null}
|
||
{inventory && snapshotState === 'missing' ? (
|
||
<p className="error-message" role="alert">
|
||
元数据快照缺失:{inventory.metadata.error || inventory.error || '快照文件不存在'}
|
||
。未读到批次不等于没有备份; 等待宿主采集器写出快照后重新盘点。
|
||
</p>
|
||
) : null}
|
||
{inventory && snapshotState === 'stale' ? (
|
||
<p className="error-message" role="alert">
|
||
元数据快照已过期:{inventory.metadata.error || '采集时间超过上限'}。旧批次、旧目录与旧容量都不再展示;
|
||
等待宿主重新采集后重新盘点。
|
||
</p>
|
||
) : null}
|
||
{inventory && snapshotState === 'invalid' ? (
|
||
<p className="error-message" role="alert">
|
||
元数据快照无效:{inventory.metadata.error || inventory.error || '快照无法通过校验'}
|
||
。不展示批次、路径或容量。
|
||
</p>
|
||
) : null}
|
||
{readyInventory ? (
|
||
<>
|
||
<p className="hint">
|
||
最近批次 {readyInventory.totals.latest_stamp || '—'} · 共 {readyInventory.totals.batch_count} 批 /{' '}
|
||
{readyInventory.totals.database_count} 个子库 ·{' '}
|
||
{readyInventory.metadata.complete && readyInventory.totals.actual_bytes !== null ? (
|
||
<>
|
||
表观 {formatBackupBytes(readyInventory.totals.apparent_bytes)} · 实际占盘{' '}
|
||
{formatBackupBytes(readyInventory.totals.actual_bytes)}。
|
||
</>
|
||
) : (
|
||
<>采集快照不完整:所有批次占盘与容量未知。</>
|
||
)}{' '}
|
||
路径来自宿主快照,不依赖 SSH 计划读回。
|
||
</p>
|
||
<p className="hint">
|
||
采集时间 {formatBackupMoment(readyInventory.metadata.collected_at)}(宿主快照) · 读回时间{' '}
|
||
{formatBackupMoment(readyInventory.observed_at)}(API) · 快照年龄 {readyInventory.metadata.age_seconds}{' '}
|
||
秒 / 上限 {readyInventory.metadata.max_age_seconds} 秒 · 新鲜度{' '}
|
||
{readyInventory.metadata.fresh ? '新鲜' : '已陈旧'} · 宿主 {readyInventory.metadata.host || '—'} · 快照{' '}
|
||
{readyInventory.metadata.generation || '—'}
|
||
</p>
|
||
{readyInventory.batches.length === 0 ? (
|
||
<p className="hint">
|
||
宿主快照可读,但没有批次目录(可能尚未执行,或采集到空目录);这不能证明备份成功或失败。
|
||
</p>
|
||
) : null}
|
||
{readyInventory.batches.map((batch, index) => {
|
||
const failedDatabases = batch.databases.filter((item) => item.failed)
|
||
const batchPath = batch.host_path || batch.path
|
||
return (
|
||
<details className="storage-batch" key={batch.stamp} open={index === 0}>
|
||
<summary>
|
||
<span>{batch.created_at || batch.stamp}</span>
|
||
<span>{batch.databases.length} 个数据库 · 整批</span>
|
||
<span className={`storage-manifest ${batch.manifest_state}`}>{manifestLabel(batch)}</span>
|
||
<strong className={failedDatabases.length || batch.manifest_state !== 'ok' ? 'off' : 'ok'}>
|
||
{failedDatabases.length
|
||
? `有失败 ${failedDatabases.length} 个`
|
||
: batch.actual_bytes === null
|
||
? '占盘未知(采集不完整)'
|
||
: `实际占盘 ${formatBackupBytes(batch.actual_bytes)}`}
|
||
</strong>
|
||
</summary>
|
||
<p>
|
||
批次戳 {batch.stamp} · 表观 {formatBackupBytes(batch.apparent_bytes)} · 实际占盘{' '}
|
||
{batch.actual_bytes === null ? '未知' : formatBackupBytes(batch.actual_bytes)} ·{' '}
|
||
{batch.file_count ?? '—'} 个文件
|
||
{batch.duration_seconds ? ` · 耗时 ${batch.duration_seconds} 秒` : ''}
|
||
{batch.kind ? ` · ${batch.kind}` : ''}
|
||
</p>
|
||
{batch.manifest_state === 'ok' ? null : (
|
||
<p className="error-message">
|
||
{batch.manifest_state === 'missing'
|
||
? '此批次没有 MANIFEST.json:完整性、耗时与库列表无法确认;占盘仅在快照完整时可信。'
|
||
: `此批次清单损坏:${batch.manifest_error || '无法解析'};库列表来自目录名,占盘仅在快照完整时可信。`}
|
||
</p>
|
||
)}
|
||
{!batch.sizes_complete ? (
|
||
<p className="error-message">
|
||
采集不完整:占盘未知({batch.sizes_error || '宿主采集器未给出完整统计'});不使用部分字节。
|
||
</p>
|
||
) : null}
|
||
<div className="storage-path-row">
|
||
<small>批次目录</small>
|
||
<code>{batchPath || '—'}</code>
|
||
<button
|
||
type="button"
|
||
disabled={!batch.host_path}
|
||
title={batch.host_path ? '复制完整主机路径' : '没有主机路径(快照未配置主机根)'}
|
||
onClick={(event) => void copyBackupPath(batch.host_path, event.currentTarget)}
|
||
>
|
||
复制目录
|
||
</button>
|
||
</div>
|
||
<ul className="storage-sublibraries">
|
||
{batch.databases.map((database) => (
|
||
<li key={database.dir_name}>
|
||
<code>{database.name}</code>
|
||
<span className={database.failed || !database.present ? 'off' : 'ok'}>
|
||
{database.failed ? '失败' : database.present ? '已写入' : '目录缺失'}
|
||
</span>
|
||
<small>
|
||
实际 {formatBackupBytes(database.actual_bytes)} · 表观{' '}
|
||
{formatBackupBytes(database.apparent_bytes)} · {database.file_count ?? '—'} 个文件
|
||
{database.in_manifest ? '' : ' · 不在清单库列表'}
|
||
</small>
|
||
<div className="storage-path-row storage-sublibrary-path">
|
||
<code>{database.host_path || database.path || '—'}</code>
|
||
<button
|
||
type="button"
|
||
disabled={!database.host_path}
|
||
title={database.host_path ? '复制子库完整路径' : '没有主机路径'}
|
||
onClick={(event) => void copyBackupPath(database.host_path, event.currentTarget)}
|
||
>
|
||
复制子库目录
|
||
</button>
|
||
</div>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
<p className="storage-verify">
|
||
恢复验证:未接线(没有数据库备份恢复验证接口,不能把“备份成功”当成“可恢复”)。
|
||
</p>
|
||
</details>
|
||
)
|
||
})}
|
||
{readyInventory.incomplete_count > 0 ? (
|
||
<p className="hint">
|
||
有 {readyInventory.incomplete_count} 个 <code>*.incomplete</code> 目录未计入批次(被中断的运行)。
|
||
</p>
|
||
) : null}
|
||
{readyInventory.skipped.length > 0 ? (
|
||
<p className="hint">
|
||
跳过 {readyInventory.skipped.length} 项:
|
||
{readyInventory.skipped.map((item) => `${item.name}(${item.reason})`).join(';')}
|
||
</p>
|
||
) : null}
|
||
{readyInventory.truncated ? (
|
||
<p className="hint">快照被截断:批次或文件超过采集上限,占盘未知(不使用部分结果)。</p>
|
||
) : null}
|
||
<p className="hint">
|
||
快照采集于 {formatBackupMoment(readyInventory.metadata.collected_at)} · 快照文件{' '}
|
||
{readyInventory.metadata.path || '—'} · 来源 {readyInventory.source || '—'}
|
||
</p>
|
||
</>
|
||
) : null}
|
||
{!inventory && !inventoryLoading && !inventoryError ? <p className="hint">尚未读取宿主元数据快照。</p> : null}
|
||
</section>
|
||
|
||
<section className="storage-block" aria-labelledby="storage-host-heading">
|
||
<div className="storage-block-heading">
|
||
<h3 id="storage-host-heading">主机状态(读回)</h3>
|
||
<span className="hint">
|
||
{!schedule.host_configured
|
||
? '未探测(平台未挂载主机凭据)'
|
||
: schedule.host_checked_at
|
||
? `读取于 ${formatBackupMoment(schedule.host_checked_at)}`
|
||
: '尚未探测'}
|
||
</span>
|
||
</div>
|
||
<div className="storage-settings-grid">
|
||
<dl>
|
||
<dt>目标主机</dt>
|
||
<dd>{hostLine}</dd>
|
||
<dt>拨号地址</dt>
|
||
<dd>{schedule.host_endpoint || '—'}</dd>
|
||
<dt>备份脚本</dt>
|
||
<dd>{scriptLine}</dd>
|
||
<dt>主机 cron</dt>
|
||
<dd>{schedule.host_cron_service ? `服务 ${schedule.host_cron_service}` : '—'}</dd>
|
||
<dt>下次计划(主机读回)</dt>
|
||
<dd>
|
||
{schedule.host_next_run
|
||
? schedule.host_next_run
|
||
: !schedule.host_configured
|
||
? '无法确认当前主机计划:平台未挂载主机凭据,远端 cron 可能仍在执行(历史下发不能代替实时状态)'
|
||
: hostProbePending
|
||
? '尚未探测主机,无法确认下一次执行'
|
||
: schedule.host_schedule_enabled
|
||
? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
|
||
: '未启用定时或未从主机读到计划'}
|
||
</dd>
|
||
</dl>
|
||
<dl>
|
||
<dt>SSH 最近一次结果(历史)</dt>
|
||
<dd>
|
||
{schedule.last_run_stamp || '—'}
|
||
{runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''}
|
||
{schedule.last_run_stamp ? (runFailed ? ' · 有失败/读取错误' : ' · 成功') : ''}
|
||
</dd>
|
||
<dt>最近一次成功</dt>
|
||
<dd>未从主机读取(不能用最近一次运行代替成功;历史批次以「备份记录」的元数据快照为准)</dd>
|
||
<dt>备份耗时 / 体积</dt>
|
||
<dd>
|
||
{schedule.last_run_stamp
|
||
? `${schedule.last_run_duration_seconds} 秒 · ${formatBackupBytes(schedule.last_run_total_bytes)}`
|
||
: '—'}
|
||
</dd>
|
||
<dt>与设置是否一致</dt>
|
||
<dd>{syncLine}</dd>
|
||
<dt>最后下发(历史)</dt>
|
||
<dd>
|
||
{schedule.last_applied_at
|
||
? `${formatBackupMoment(schedule.last_applied_at)}${schedule.last_applied_summary ? ` · ${schedule.last_applied_summary}` : ''} · 只记录当时下发结果,不能代表当前主机计划或执行状态`
|
||
: '—(没有历史下发记录;不能据设置推定主机计划)'}
|
||
</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.last_run_failed_databases.length ? (
|
||
<p className="hint">SSH 结果的失败库:{schedule.last_run_failed_databases.join('、')}</p>
|
||
) : null}
|
||
{schedule.host_cron_lines.length ? (
|
||
<p className="hint">
|
||
主机 cron 条目:<code>{schedule.host_cron_lines.join(' ; ')}</code>
|
||
</p>
|
||
) : null}
|
||
</section>
|
||
|
||
<p className="hint">
|
||
留档分层:PG 行级留档(发布前,含 ES 文档)+ ES 快照仓 + OSS 版本控制 + 本节的整库逻辑备份 + RDS
|
||
托管备份(控制台配置)。详见 <code>docs/PRODUCTION_BACKUP_RECOVERY.md</code>。
|
||
</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 [inventory, setInventory] = useState<BackupInventory | null>(null)
|
||
const [inventoryLoading, setInventoryLoading] = useState(true)
|
||
const [inventoryError, setInventoryError] = useState<string | null>(null)
|
||
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])
|
||
|
||
const loadInventory = useCallback(async () => {
|
||
setInventoryLoading(true)
|
||
setInventoryError(null)
|
||
try {
|
||
setInventory(await fetchBackupInventory())
|
||
} catch (cause) {
|
||
setInventoryError(cause instanceof Error ? cause.message : '读取只读备份盘点失败')
|
||
} finally {
|
||
setInventoryLoading(false)
|
||
}
|
||
}, [])
|
||
|
||
useEffect(() => {
|
||
void loadInventory()
|
||
}, [loadInventory])
|
||
|
||
useEffect(() => {
|
||
void load()
|
||
}, [load])
|
||
|
||
// 备份完成(running 转假)后再盘点一次,新批次才会出现在历史里;
|
||
// 运行中不反复扫目录,避免把主机 IO 当成轮询接口。
|
||
const wasRunning = useRef(false)
|
||
useEffect(() => {
|
||
if (schedule?.running) {
|
||
wasRunning.current = true
|
||
return
|
||
}
|
||
if (wasRunning.current) {
|
||
wasRunning.current = false
|
||
void loadInventory()
|
||
}
|
||
}, [schedule?.running, loadInventory])
|
||
|
||
// 立即备份约 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()
|
||
void loadInventory()
|
||
}}
|
||
inventory={inventory}
|
||
inventoryLoading={inventoryLoading}
|
||
inventoryError={inventoryError}
|
||
onReloadInventory={() => void loadInventory()}
|
||
// disk 不传:生产只认宿主元数据快照;disk 仅测试夹具用于验证告警分支。
|
||
/>
|
||
)
|
||
}
|