Files
Zhero & Rin 144b49cb53
build / build (push) Successful in 3m22s
feat(backup): 配额改按备份根占用并在超限时清理最旧批次
- 采集器上报 backup_root/usage/quota(加性字段),API 用 BACKUP_HOST_ROOT 校验并分别降级占用/配额
- 页面配额行改为备份占用 X / 配额 50 GB,4 条告警改用备份口径,解除本页归档依赖
- logical-backup.sh 预检按字节清理(保留最新、空间不足零删除),dump 后复查保护新批次
- backup_layout 写入 KB_BACKUP_QUOTA_BYTES;--show 输出根占用;新增 prune 工具与自检
2026-11-25 22:46:32 +08:00

667 lines
24 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package backupinventory 读取**宿主采集器**产出的备份元数据快照。
//
// 为什么不在 API 里遍历备份目录:备份目录通常是 root:root 0700,API 容器用户
// 没有进入权限;容器里遍历只能得到 permission denied 的部分字节,绝不能把部分
// 计数当成实际占盘。这里只读宿主进程原子写出的 metadata.json,并校验 schema、
// 批次路径、主机根、时效与完整性。API 不接触备份目录,也不借用 SSH/容器特权。
package backupinventory
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path"
"sort"
"strings"
"time"
)
const (
SchemaVersion = 1
defaultMaxAge = 15 * time.Minute
defaultMaxBytes = 16 << 20
futureTolerance = 2 * time.Minute
measurementLabel = "host_collector"
)
type Config struct {
// MetadataPath 是 API 容器内挂载的 metadata.json(宿主采集器原子写出)。
MetadataPath string
// HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
HostRoot string
// BackupRoot 是宿主上的备份根(KB_BACKUP_ROOT),用于校验快照里的根占用范围。
// 它必须与 BACKUP_HOST_ROOT 同源;不同源时占用不可信,整份快照拒绝。
BackupRoot string
// Source 是展示来源;快照里的 source 非空时以快照为准。
Source string
// MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
MaxAge time.Duration
// MaxBytes 防止异常大文件拖死 API。
MaxBytes int64
}
type ManifestState string
const (
ManifestOK ManifestState = "ok"
ManifestMissing ManifestState = "missing"
ManifestInvalid ManifestState = "invalid"
)
type MetadataInfo struct {
Configured bool `json:"configured"`
Present bool `json:"present"`
Valid bool `json:"valid"`
Fresh bool `json:"fresh"`
Complete bool `json:"complete"`
Path string `json:"path"`
CollectedAt string `json:"collected_at"`
AgeSeconds int64 `json:"age_seconds"`
MaxAgeSeconds int64 `json:"max_age_seconds"`
SchemaVersion int `json:"schema_version"`
Generation string `json:"generation"`
Host string `json:"host"`
CollectorVersion string `json:"collector_version"`
Error string `json:"error"`
}
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"`
MountPoint string `json:"mount_point"`
Device string `json:"device"`
FSType string `json:"fs_type"`
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"`
}
// Usage 是**备份根累计占用**(配额约束的对象),不是 rds-logical 批次之和。
// Measured=false 时所有字节为 null:部分遍历永远不能当占盘。
type Usage struct {
Root string `json:"root"`
Measured bool `json:"measured"`
Complete bool `json:"complete"`
ActualBytes *int64 `json:"actual_bytes"`
ApparentBytes *int64 `json:"apparent_bytes"`
FileCount *int `json:"file_count"`
DirCount *int `json:"dir_count"`
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"`
ManifestTotalBytes *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"`
Complete bool `json:"complete"`
}
type Snapshot struct {
Wired bool `json:"wired"`
Metadata MetadataInfo `json:"metadata"`
Root string `json:"root"`
HostRoot string `json:"host_root"`
BackupRoot string `json:"backup_root"`
Source string `json:"source"`
ObservedAt string `json:"observed_at"`
Error string `json:"error,omitempty"`
Measurement string `json:"measurement"`
Mount MountInfo `json:"mount"`
Capacity Capacity `json:"capacity"`
Usage Usage `json:"usage"`
QuotaBytes *int64 `json:"quota_bytes"`
QuotaError string `json:"quota_error,omitempty"`
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
read func(string) ([]byte, error)
}
func New(config Config) *Reader {
if config.MaxAge <= 0 {
config.MaxAge = defaultMaxAge
}
if config.MaxBytes <= 0 {
config.MaxBytes = defaultMaxBytes
}
return &Reader{config: config, now: time.Now, read: os.ReadFile}
}
func (r *Reader) Available() bool {
return r != nil && strings.TrimSpace(r.config.MetadataPath) != ""
}
// ---- 宿主快照文件(collector 的输出;只读、字段可验证) ----
type metadata struct {
SchemaVersion int `json:"schema_version"`
CollectorVersion string `json:"collector_version"`
Generation string `json:"generation"`
CollectedAt string `json:"collected_at"`
Host string `json:"host"`
Source string `json:"source"`
Root string `json:"root"`
BackupRoot string `json:"backup_root"`
Usage metadataUsage `json:"usage"`
QuotaBytes *int64 `json:"quota_bytes"`
QuotaError string `json:"quota_error"`
Complete bool `json:"complete"`
Errors []string `json:"errors"`
Filesystem metadataFilesystem `json:"filesystem"`
IncompleteCount int `json:"incomplete_count"`
Skipped []Skipped `json:"skipped"`
Truncated bool `json:"truncated"`
Batches []metadataBatch `json:"batches"`
}
type metadataUsage struct {
Root string `json:"root"`
Complete bool `json:"complete"`
ActualBytes *int64 `json:"actual_bytes"`
ApparentBytes *int64 `json:"apparent_bytes"`
FileCount *int `json:"file_count"`
DirCount *int `json:"dir_count"`
Errors []string `json:"errors"`
}
type metadataFilesystem struct {
MountPoint string `json:"mount_point"`
MountSource string `json:"mount_source"`
FSType string `json:"fs_type"`
ReadOnly bool `json:"read_only"`
TotalBytes int64 `json:"total_bytes"`
FreeBytes int64 `json:"free_bytes"`
AvailableBytes int64 `json:"available_bytes"`
}
type metadataBatch struct {
Stamp string `json:"stamp"`
Path string `json:"path"`
ManifestState string `json:"manifest_state"`
ManifestError string `json:"manifest_error"`
Kind string `json:"kind"`
CreatedAt string `json:"created_at"`
StartedAt string `json:"started_at"`
DurationSeconds int `json:"duration_seconds"`
ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
Complete bool `json:"complete"`
Errors []string `json:"errors"`
ApparentBytes *int64 `json:"apparent_bytes"`
ActualBytes *int64 `json:"actual_bytes"`
FileCount *int `json:"file_count"`
Databases []metadataDatabase `json:"databases"`
}
type metadataDatabase struct {
Name string `json:"name"`
DirName string `json:"dir_name"`
Path string `json:"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"`
}
// Snapshot 只返回可验证的事实:陈旧/缺失/不完整一律不给批次字节与容量。
func (r *Reader) Snapshot(ctx context.Context) Snapshot {
snapshot := Snapshot{
Wired: r.Available(),
Measurement: measurementLabel,
Batches: []Batch{},
Skipped: []Skipped{},
ObservedAt: r.observedAt(),
Metadata: MetadataInfo{
Configured: r.Available(),
MaxAgeSeconds: int64(r.config.MaxAge / time.Second),
},
}
if r == nil || !r.Available() {
snapshot.Metadata.Error = "元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)"
snapshot.Error = snapshot.Metadata.Error
return snapshot
}
snapshot.Metadata.Path = r.config.MetadataPath
snapshot.HostRoot = r.config.HostRoot
snapshot.Source = r.config.Source
if ctx.Err() != nil {
snapshot.Metadata.Error = "读取被取消:" + ctx.Err().Error()
snapshot.Error = snapshot.Metadata.Error
return snapshot
}
raw, err := r.read(r.config.MetadataPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
snapshot.Metadata.Error = "宿主元数据快照不存在:需要先运行 collect_backup_metadata.py"
} else {
snapshot.Metadata.Error = "宿主元数据快照不可读:" + err.Error()
}
snapshot.Error = snapshot.Metadata.Error
return snapshot
}
snapshot.Metadata.Present = true
if int64(len(raw)) > r.config.MaxBytes {
return invalid(snapshot, fmt.Sprintf("元数据快照超过 %d 字节读取上限", r.config.MaxBytes))
}
var file metadata
if err := json.Unmarshal(raw, &file); err != nil {
return invalid(snapshot, "元数据快照无法解析:"+err.Error())
}
snapshot.Metadata.SchemaVersion = file.SchemaVersion
snapshot.Metadata.Generation = file.Generation
snapshot.Metadata.Host = file.Host
snapshot.Metadata.CollectorVersion = file.CollectorVersion
snapshot.Metadata.CollectedAt = file.CollectedAt
snapshot.Metadata.Complete = file.Complete
if file.Source != "" {
snapshot.Source = file.Source
}
if file.SchemaVersion != SchemaVersion {
return invalid(snapshot, fmt.Sprintf("元数据 schema_version=%d,API 只支持 %d", file.SchemaVersion, SchemaVersion))
}
collectedAt, err := time.Parse(time.RFC3339, file.CollectedAt)
if err != nil {
return invalid(snapshot, "元数据 collected_at 非法:"+file.CollectedAt)
}
age := r.now().UTC().Sub(collectedAt.UTC())
if age < -futureTolerance {
return invalid(snapshot, "元数据 collected_at 在未来,拒绝使用")
}
snapshot.Metadata.AgeSeconds = int64(age / time.Second)
if age > r.config.MaxAge {
snapshot.Metadata.Fresh = false
return invalid(snapshot, fmt.Sprintf("元数据已陈旧:采集于 %s,超过 %s", file.CollectedAt, r.config.MaxAge))
}
snapshot.Metadata.Fresh = true
if strings.TrimSpace(r.config.HostRoot) == "" {
return invalid(snapshot, "宿主根路径未配置:无法校验批次路径")
}
expectedRoot := path.Clean(strings.TrimSpace(r.config.HostRoot))
snapshot.HostRoot = expectedRoot
root := strings.TrimSpace(file.Root)
if !path.IsAbs(root) || path.Clean(root) != root {
return invalid(snapshot, "元数据 root 不是规范绝对路径:"+root)
}
if root != expectedRoot {
return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
}
snapshot.Root = root
backupRoot, usage, quotaBytes, quotaError, err := projectUsageAndQuota(r.config.BackupRoot, root, file)
if err != nil {
return invalid(snapshot, err.Error())
}
snapshot.BackupRoot = backupRoot
snapshot.Usage = usage
snapshot.QuotaBytes = quotaBytes
snapshot.QuotaError = quotaError
if err := validateBatches(root, file.Batches); err != nil {
return invalid(snapshot, err.Error())
}
snapshot.Metadata.Valid = true
snapshot.IncompleteCount = file.IncompleteCount
snapshot.Skipped = append(snapshot.Skipped, file.Skipped...)
snapshot.Truncated = file.Truncated
snapshot.Mount = MountInfo{
Evidence: "宿主采集器上报:" + file.Host,
MountPoint: file.Filesystem.MountPoint,
Device: file.Filesystem.MountSource,
FSType: file.Filesystem.FSType,
ReadOnly: file.Filesystem.ReadOnly,
}
if file.Filesystem.MountPoint == "" || !path.IsAbs(file.Filesystem.MountPoint) {
snapshot.Mount.Error = "宿主采集器没有给出文件系统挂载点"
} else if root != file.Filesystem.MountPoint && !strings.HasPrefix(root, strings.TrimSuffix(file.Filesystem.MountPoint, "/")+"/") {
snapshot.Mount.Error = "批次根不在采集器上报的挂载点下"
} else {
snapshot.Mount.MountVerified = true
snapshot.Mount.Evidence = fmt.Sprintf("宿主采集器:%s 挂在 %s(%s),API 不遍历备份目录",
file.Filesystem.MountSource, file.Filesystem.MountPoint, file.Filesystem.FSType)
}
// 快照不完整/截断:路径与清单状态可展示,但所有字节与容量一律未知,
// 绝不用部分 counts 或完整批次的局部字节拼总量。
complete := file.Complete && !file.Truncated && snapshot.Mount.MountVerified && allBatchesComplete(file.Batches)
if !complete {
snapshot.Metadata.Complete = false
snapshot.Metadata.Error = incompleteReason(file)
snapshot.Capacity = Capacity{Error: "采集快照不完整:容量与占盘未知"}
snapshot.Mount.MountVerified = false
snapshot.Mount.Error = "采集快照不完整,不能据此判定文件系统与占盘"
snapshot.Batches = projectBatches(root, file.Batches, false)
snapshot.Totals = totals(snapshot.Batches, false)
snapshot.Error = ""
return snapshot
}
snapshot.Metadata.Complete = true
snapshot.Capacity = projectCapacity(file.Filesystem)
snapshot.Batches = projectBatches(root, file.Batches, true)
snapshot.Totals = totals(snapshot.Batches, true)
return snapshot
}
func (r *Reader) observedAt() string {
if r == nil || r.now == nil {
return ""
}
return r.now().UTC().Format(time.RFC3339)
}
// projectUsageAndQuota 校验「备份根占用」与「配额」并把它们投影给页面。
//
// 三条独立边界:
// 1. 旧采集器没有 usage/quota —— 批次照旧可用,占用与配额显式「未上报」,绝不用批次和冒充;
// 2. 路径必须与部署配置的备份根完全一致,批次根必须在其下 —— 否则整份快照拒绝;
// 3. 遍历不完整/配额非法 —— 只把对应字段降为未知,不牵连批次表与磁盘容量。
func projectUsageAndQuota(configuredRoot, batchRoot string, file metadata) (string, Usage, *int64, string, error) {
expected := path.Clean(strings.TrimSpace(configuredRoot))
reported := strings.TrimSpace(file.Usage.Root)
declared := strings.TrimSpace(file.BackupRoot)
usageReported := reported != "" || declared != "" || file.Usage.Complete ||
file.Usage.ActualBytes != nil || len(file.Usage.Errors) > 0
if !usageReported {
quotaError := strings.TrimSpace(file.QuotaError)
if quotaError == "" {
quotaError = "采集器未上报备份配额(需要升级采集器)"
}
return expected, Usage{Error: "采集器未上报备份根占用(需要升级采集器)"}, nil, quotaError, nil
}
if expected == "" || !path.IsAbs(expected) {
return "", Usage{}, nil, "", errors.New("备份根未配置:无法校验快照里的根占用")
}
if reported != expected || declared != expected {
return "", Usage{}, nil, "", fmt.Errorf("快照 backup_root=%q/usage.root=%q 与配置 %q 不一致", declared, reported, expected)
}
if batchRoot != expected && !strings.HasPrefix(batchRoot, expected+"/") {
return "", Usage{}, nil, "", fmt.Errorf("批次根 %s 不在备份根 %s 下", batchRoot, expected)
}
usage := Usage{Root: reported, Complete: file.Usage.Complete}
if file.Usage.Complete && file.Usage.ActualBytes != nil {
usage.Measured = true
usage.ActualBytes = file.Usage.ActualBytes
usage.ApparentBytes = file.Usage.ApparentBytes
usage.FileCount = file.Usage.FileCount
usage.DirCount = file.Usage.DirCount
} else {
usage.Complete = false
usage.ActualBytes = nil
usage.ApparentBytes = nil
usage.FileCount = nil
usage.DirCount = nil
reasons := limit(file.Usage.Errors, 3)
if len(reasons) == 0 {
usage.Error = "备份根占用未知:采集器未给出完整字节"
} else {
usage.Error = "备份根占用未知:" + strings.Join(reasons, ";")
}
}
quota := file.QuotaBytes
quotaError := strings.TrimSpace(file.QuotaError)
if quota != nil && *quota <= 0 {
quota = nil
quotaError = fmt.Sprintf("备份配额必须为正整数:%d", *file.QuotaBytes)
}
if quota == nil && quotaError == "" {
quotaError = "采集器未上报备份配额(需要升级采集器)"
}
return expected, usage, quota, quotaError, nil
}
func invalid(snapshot Snapshot, reason string) Snapshot {
snapshot.Metadata.Valid = false
snapshot.Metadata.Complete = false
snapshot.Metadata.Error = reason
snapshot.Error = reason
snapshot.Batches = []Batch{}
snapshot.Capacity = Capacity{Error: reason}
snapshot.Totals = Totals{}
snapshot.Usage = Usage{Error: reason}
snapshot.QuotaBytes = nil
return snapshot
}
func incompleteReason(file metadata) string {
if len(file.Errors) > 0 {
return "采集不完整:" + strings.Join(limit(file.Errors, 3), ";")
}
for _, batch := range file.Batches {
if len(batch.Errors) > 0 {
return "采集不完整:" + strings.Join(limit(batch.Errors, 3), ";")
}
}
return "采集不完整:存在无法遍历/统计的目录,占盘与容量未知"
}
func limit(items []string, n int) []string {
if len(items) <= n {
return items
}
return items[:n]
}
func allBatchesComplete(batches []metadataBatch) bool {
for _, batch := range batches {
if !batch.Complete || batch.ActualBytes == nil || batch.ApparentBytes == nil || batch.FileCount == nil {
return false
}
for _, database := range batch.Databases {
if database.ActualBytes == nil || database.ApparentBytes == nil || database.FileCount == nil {
return false
}
}
}
return true
}
// 校验的是"快照里的路径能否被安全地当成这台主机的批次/子库":
// 根必须精确匹配配置,批次必须精确等于 root/<stamp>,子库必须精确等于
// batch/<name>.dir,且不允许重复、分隔符、.incomplete。
func validateBatches(root string, batches []metadataBatch) error {
seen := map[string]bool{}
for _, batch := range batches {
stamp := strings.TrimSpace(batch.Stamp)
if err := safeSegment(stamp); err != nil {
return fmt.Errorf("批次名不合法:%q(%v)", stamp, err)
}
if strings.HasSuffix(stamp, ".incomplete") {
return fmt.Errorf("批次 %q 是未完成目录,不应进入快照", stamp)
}
if seen[stamp] {
return fmt.Errorf("批次 %q 重复", stamp)
}
seen[stamp] = true
expected := path.Join(root, stamp)
if batch.Path != expected || !path.IsAbs(batch.Path) {
return fmt.Errorf("批次 %q 路径 %q 不等于 %q", stamp, batch.Path, expected)
}
switch ManifestState(batch.ManifestState) {
case ManifestOK, ManifestMissing, ManifestInvalid:
default:
return fmt.Errorf("批次 %q 的 manifest_state 不认识:%q", stamp, batch.ManifestState)
}
databaseSeen := map[string]bool{}
for _, database := range batch.Databases {
name := strings.TrimSpace(database.Name)
if err := safeSegment(name); err != nil {
return fmt.Errorf("批次 %q 子库名不合法:%q", stamp, name)
}
if databaseSeen[name] {
return fmt.Errorf("批次 %q 子库 %q 重复", stamp, name)
}
databaseSeen[name] = true
expectedDir := path.Join(expected, name+".dir")
if database.DirName != name+".dir" || database.Path != expectedDir || !path.IsAbs(database.Path) {
return fmt.Errorf("批次 %q 子库 %q 路径不合法:%q", stamp, name, database.Path)
}
}
}
return nil
}
func safeSegment(value string) error {
if value == "" || value == "." || value == ".." {
return errors.New("空值或相对路径")
}
for _, r := range value {
if r == '/' || r == '\\' || r == 0 || r == '\n' || r == '\r' {
return errors.New("包含路径分隔符或控制字符")
}
}
return nil
}
func projectBatches(root string, batches []metadataBatch, complete bool) []Batch {
result := make([]Batch, 0, len(batches))
for _, batch := range batches {
item := Batch{
Stamp: batch.Stamp,
Path: path.Join(root, batch.Stamp),
HostPath: path.Join(root, batch.Stamp),
ManifestState: ManifestState(batch.ManifestState),
ManifestPath: path.Join(root, batch.Stamp, "MANIFEST.json"),
ManifestError: batch.ManifestError,
Kind: batch.Kind,
CreatedAt: batch.CreatedAt,
StartedAt: batch.StartedAt,
DurationSeconds: batch.DurationSeconds,
SizesComplete: complete && batch.Complete,
Databases: []Database{},
}
if complete && batch.Complete {
item.ManifestTotalBytes = batch.ManifestTotalBytes
item.ApparentBytes = batch.ApparentBytes
item.ActualBytes = batch.ActualBytes
item.FileCount = batch.FileCount
}
for _, database := range batch.Databases {
entry := Database{
Name: database.Name,
DirName: database.DirName,
Path: path.Join(root, batch.Stamp, database.DirName),
HostPath: path.Join(root, batch.Stamp, database.DirName),
Present: database.Present,
Failed: database.Failed,
InManifest: database.InManifest,
}
if complete && batch.Complete {
entry.ApparentBytes = database.ApparentBytes
entry.ActualBytes = database.ActualBytes
entry.FileCount = database.FileCount
}
item.Databases = append(item.Databases, entry)
}
if !item.SizesComplete {
item.SizesError = "宿主采集器该项不完整,占盘未知"
}
result = append(result, item)
}
sort.Slice(result, func(i, j int) bool { return result[i].Stamp > result[j].Stamp })
return result
}
func totals(batches []Batch, complete bool) Totals {
result := Totals{BatchCount: len(batches), Complete: complete}
if len(batches) > 0 {
result.LatestStamp = batches[0].Stamp
}
for _, batch := range batches {
result.DatabaseCount += len(batch.Databases)
}
if !complete {
return result
}
var apparent, actual int64
for _, batch := range batches {
if batch.ApparentBytes != nil {
apparent += *batch.ApparentBytes
}
if batch.ActualBytes != nil {
actual += *batch.ActualBytes
}
}
result.ApparentBytes = &apparent
result.ActualBytes = &actual
if len(batches) > 0 {
result.LatestActualBytes = batches[0].ActualBytes
}
return result
}
func projectCapacity(filesystem metadataFilesystem) Capacity {
if filesystem.TotalBytes <= 0 {
return Capacity{Error: "宿主采集器没有给出文件系统容量"}
}
used := filesystem.TotalBytes - filesystem.FreeBytes
if used < 0 {
used = 0
}
return Capacity{
Measured: true,
TotalBytes: filesystem.TotalBytes,
FreeBytes: filesystem.FreeBytes,
AvailableBytes: filesystem.AvailableBytes,
UsedBytes: used,
}
}