Files
aiops/agent/collector/swap.go
T
Logan.Li e0d652d211 feat: 完善堡垒机与 Agent 智能运维能力
- 支持 Windows Agent 构建、安装脚本和统一上报协议

- 增强 RDP 剪贴板、虚拟盘和文件传输能力

- 新增 AIOps 上下文工具、告警 RCA trace 落库和回放接口

- 重构 docs 模块文档并补充终端、堡垒机、监控、AI Agent 设计
2026-07-05 23:49:36 +08:00

79 lines
1.6 KiB
Go

//go:build !windows
// Package collector — Swap 采集器
// 从 /proc/meminfo 读取 SwapTotal / SwapFree
// 仅当系统有 swap 分区时返回有效数据
//
// 署名 Logan.Li
package collector
import (
"bufio"
"os"
"strings"
"ezops/agent/model"
)
// SwapCollector 交换分区采集器
type SwapCollector struct{}
// NewSwapCollector 创建 Swap 采集器
func NewSwapCollector() *SwapCollector {
return &SwapCollector{}
}
// Collect 读取 swap 指标
func (s *SwapCollector) Collect() (*model.SwapStat, error) {
f, err := os.Open("/proc/meminfo")
if err != nil {
return nil, err
}
defer f.Close()
var swapTotal, swapFree uint64
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
// Line format: "SwapTotal: 0 kB"
key := strings.TrimSuffix(fields[0], ":")
switch key {
case "SwapTotal":
swapTotal, _ = parseUint64(fields[1])
case "SwapFree":
swapFree, _ = parseUint64(fields[1])
}
}
// No swap configured — return nil (caller should omit from report)
if swapTotal == 0 {
return nil, nil
}
used := swapTotal - swapFree
stat := &model.SwapStat{
TotalGB: float64(swapTotal) / (1024.0 * 1024.0),
UsedGB: float64(used) / (1024.0 * 1024.0),
}
if swapTotal > 0 {
stat.UsagePercent = float64(used) / float64(swapTotal) * 100.0
}
return stat, nil
}
// parseUint64 parses a uint64 or returns 0
func parseUint64(s string) (uint64, error) {
var v uint64
for _, c := range s {
if c < '0' || c > '9' {
break
}
v = v*10 + uint64(c-'0')
}
return v, nil
}