chore: sync local updates

This commit is contained in:
2026-05-16 19:03:34 +08:00
parent 9c086c3301
commit 80cf54a201
89 changed files with 10622 additions and 2443 deletions

View File

@@ -0,0 +1,121 @@
# 萌芽监控面板 - 后端服务
## 概述
Linux 服务器监控后端服务,使用 Go 原生 net/http 库实现。
## 功能
- CPU 使用率和负载监控
- 内存使用情况
- 磁盘存储监控
- GPU 监控(支持 NVIDIA
- 操作系统信息
- 系统运行时间
## API 端点
### `GET /api/health`
健康检查端点
```json
{
"status": "ok",
"timestamp": "2025-12-10T10:00:00Z"
}
```
### `GET /api/metrics`
获取系统监控指标
```json
{
"data": {
"hostname": "server1",
"timestamp": "2025-12-10T10:00:00Z",
"cpu": {
"model": "Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz",
"cores": 8,
"usagePercent": 23.45,
"loadAverages": [1.2, 1.5, 1.8]
},
"memory": {
"totalBytes": 16777216000,
"usedBytes": 8388608000,
"freeBytes": 8388608000,
"usedPercent": 50.0
},
"storage": [{
"mount": "/",
"totalBytes": 107374182400,
"usedBytes": 53687091200,
"freeBytes": 53687091200,
"usedPercent": 50.0
}],
"gpu": [{
"name": "Tesla T4",
"memoryTotalMB": 15360,
"memoryUsedMB": 512,
"utilizationPercent": 15.0,
"status": "ok"
}],
"os": {
"kernel": "Linux version 5.15.0",
"distro": "Ubuntu 22.04 LTS",
"architecture": "amd64"
},
"uptimeSeconds": 864000.5
}
}
```
## 运行方式
### 开发环境
```bash
go run .
```
### 生产环境
#### 标准编译
```bash
# 编译
go build -o mengyamonitor-backend
# 运行
./mengyamonitor-backend
```
#### 兼容旧版本系统编译(推荐)
如果需要在 Debian 11 或其他旧版本系统上运行,使用静态链接编译:
```bash
# 禁用 CGO静态链接不依赖系统 GLIBC 版本)
export CGO_ENABLED=0
go build -ldflags="-s -w" -o mengyamonitor-backend .
# 或使用提供的脚本
chmod +x build.sh
./build.sh
```
这样可以避免 GLIBC 版本兼容性问题。详细说明请参考 [BUILD.md](./BUILD.md)。
### 环境变量
- `HOST`: 监听地址,默认 `0.0.0.0`
- `PORT`: 监听端口,默认 `9292`
示例:
```bash
PORT=8080 ./mengyamonitor-backend
```
## 部署到服务器
1. 将编译好的二进制文件上传到目标服务器
2. 赋予执行权限:`chmod +x mengyamonitor-backend`
3. 运行服务:`./mengyamonitor-backend`
4. 可选:使用 systemd 或 supervisor 管理服务进程
## 注意事项
- 仅支持 Linux 系统
- GPU 监控需要安装 nvidia-smi 工具
- 需要读取 /proc 文件系统的权限

View File

@@ -0,0 +1,40 @@
# Cross-compile Linux agent (amd64 + arm64). Same as build_linux.sh.
# Usage: cd mengyamonitor-backend-client; .\build_linux.ps1
$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
Set-Location $Root
$name = if ($env:BINARY_NAME) { $env:BINARY_NAME } else { "mengyamonitor-agent" }
$out = if ($env:OUT_DIR) { $env:OUT_DIR } else { "dist" }
New-Item -ItemType Directory -Force -Path (Join-Path $out "linux_amd64"), (Join-Path $out "linux_arm64") | Out-Null
$env:CGO_ENABLED = "0"
Write-Host "==> linux/amd64 -> $out/linux_amd64/$name"
$env:GOOS = "linux"
$env:GOARCH = "amd64"
try {
$destAmd = Join-Path (Join-Path $out "linux_amd64") $name
go build -trimpath -ldflags="-s -w" -o $destAmd .
}
finally {
Remove-Item Env:GOOS, Env:GOARCH -ErrorAction SilentlyContinue
}
Write-Host "==> linux/arm64 -> $out/linux_arm64/$name"
$env:GOOS = "linux"
$env:GOARCH = "arm64"
try {
$destArm = Join-Path (Join-Path $out "linux_arm64") $name
go build -trimpath -ldflags="-s -w" -o $destArm .
}
finally {
Remove-Item Env:GOOS, Env:GOARCH -ErrorAction SilentlyContinue
}
Write-Host "Done."
$p1 = Join-Path (Join-Path $out "linux_amd64") $name
$p2 = Join-Path (Join-Path $out "linux_arm64") $name
Get-Item -LiteralPath $p1, $p2 | Format-Table -Property FullName, Length

View File

@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# 一键交叉编译 Linux 采集端amd64 + arm64输出与 dist/install_mengyamonitor.sh 发布路径一致。
#
# 用法(在 mengyamonitor-backend-client 目录下):
# chmod +x build_linux.sh && ./build_linux.sh
#
# Windows: Git Bash 同上;或在项目目录执行: powershell -ExecutionPolicy Bypass -File .\build_linux.ps1
#
# 可选环境变量:
# BINARY_NAME 默认 mengyamonitor-agent
# OUT_DIR 默认 dist相对本脚本所在目录
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT"
NAME="${BINARY_NAME:-mengyamonitor-agent}"
OUT="${OUT_DIR:-dist}"
mkdir -p "$OUT/linux_amd64" "$OUT/linux_arm64"
export CGO_ENABLED=0
echo "==> linux/amd64 -> $OUT/linux_amd64/$NAME"
GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o "$OUT/linux_amd64/$NAME" .
echo "==> linux/arm64 -> $OUT/linux_arm64/$NAME"
GOOS=linux GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o "$OUT/linux_arm64/$NAME" .
echo "完成。产物:"
for arch in amd64 arm64; do
f="$OUT/linux_${arch}/$NAME"
if command -v ls >/dev/null 2>&1; then
ls -la "$f"
else
echo " $f"
fi
done

View File

@@ -0,0 +1,103 @@
package main
import (
"bufio"
"os"
"runtime"
"strconv"
"strings"
"time"
)
// CollectMetrics 收集所有系统监控指标
func CollectMetrics() (*Metrics, error) {
hostname, _ := os.Hostname()
cpuModel := firstMatchInFile("/proc/cpuinfo", "model name")
cpuUsage, err := readCPUUsage()
if err != nil {
return nil, err
}
cpuTemp := readCPUTemperature()
perCoreUsage := readPerCoreUsage()
mem, err := readMemory()
if err != nil {
return nil, err
}
storage, err := readAllStorage()
if err != nil {
return nil, err
}
gpu := readGPU()
network := readNetworkInterfaces()
systemStats := readSystemStats()
systemStats.DockerStats = readDockerStats()
osInfo := readOSInfo()
uptime := readUptime()
loads := readLoadAverages()
return &Metrics{
Hostname: hostname,
Timestamp: time.Now().UTC(),
CPU: CPUMetrics{
Model: cpuModel,
Cores: runtime.NumCPU(),
UsagePercent: round(cpuUsage, 2),
LoadAverages: loads,
Temperature: cpuTemp,
PerCoreUsage: perCoreUsage,
},
Memory: mem,
Storage: storage,
GPU: gpu,
Network: network,
System: systemStats,
OS: osInfo,
UptimeSeconds: uptime,
}, nil
}
func readOSInfo() OSInfo {
distro := readOSRelease()
kernel := strings.TrimSpace(readFirstLine("/proc/version"))
arch := runtime.GOARCH
return OSInfo{
Kernel: kernel,
Distro: distro,
Architecture: arch,
}
}
func readOSRelease() string {
f, err := os.Open("/etc/os-release")
if err != nil {
return runtime.GOOS
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "PRETTY_NAME=") {
return strings.Trim(line[len("PRETTY_NAME="):], "\"")
}
}
return runtime.GOOS
}
func readUptime() float64 {
line := readFirstLine("/proc/uptime")
fields := strings.Fields(line)
if len(fields) == 0 {
return 0
}
v, err := strconv.ParseFloat(fields[0], 64)
if err != nil {
return 0
}
return v
}

View File

@@ -0,0 +1,182 @@
package main
import (
"bufio"
"errors"
"os"
"strconv"
"strings"
"time"
)
// readCPUUsage 读取CPU整体使用率
func readCPUUsage() (float64, error) {
idle1, total1, err := readCPUTicks()
if err != nil {
return 0, err
}
time.Sleep(250 * time.Millisecond)
idle2, total2, err := readCPUTicks()
if err != nil {
return 0, err
}
if total2 == total1 {
return 0, errors.New("cpu totals unchanged")
}
idleDelta := float64(idle2 - idle1)
totalDelta := float64(total2 - total1)
usage := (1.0 - idleDelta/totalDelta) * 100
if usage < 0 {
usage = 0
}
return usage, nil
}
// readCPUTicks 读取CPU的idle和total ticks
func readCPUTicks() (idle, total uint64, err error) {
f, err := os.Open("/proc/stat")
if err != nil {
return 0, 0, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
if !scanner.Scan() {
return 0, 0, errors.New("failed to scan /proc/stat")
}
fields := strings.Fields(scanner.Text())
if len(fields) < 5 {
return 0, 0, errors.New("unexpected /proc/stat format")
}
// fields[0] is "cpu"
var vals []uint64
for _, f := range fields[1:] {
v, err := strconv.ParseUint(f, 10, 64)
if err != nil {
return 0, 0, err
}
vals = append(vals, v)
}
for _, v := range vals {
total += v
}
if len(vals) > 3 {
idle = vals[3] // idle time
// 注意:不包含 iowait因为 iowait 不算真正的空闲时间
// 如果系统有 iowait它会在 total 中,但不应该算作 idle
}
return idle, total, nil
}
// readPerCoreUsage 读取每个CPU核心的使用率
func readPerCoreUsage() []CoreUsage {
coreUsages := []CoreUsage{}
// 第一次读取
cores1 := readPerCoreTicks()
time.Sleep(100 * time.Millisecond) // 减少到100ms
// 第二次读取
cores2 := readPerCoreTicks()
for i := 0; i < len(cores1) && i < len(cores2); i++ {
idle1, total1 := cores1[i][0], cores1[i][1]
idle2, total2 := cores2[i][0], cores2[i][1]
if total2 == total1 {
continue
}
idleDelta := float64(idle2 - idle1)
totalDelta := float64(total2 - total1)
usage := (1.0 - idleDelta/totalDelta) * 100
if usage < 0 {
usage = 0
}
coreUsages = append(coreUsages, CoreUsage{
Core: i,
Percent: round(usage, 1),
})
}
return coreUsages
}
// readPerCoreTicks 读取每个CPU核心的ticks
func readPerCoreTicks() [][2]uint64 {
var result [][2]uint64
f, err := os.Open("/proc/stat")
if err != nil {
return result
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "cpu") {
continue
}
if strings.HasPrefix(line, "cpu ") {
continue // 跳过总的cpu行
}
fields := strings.Fields(line)
if len(fields) < 5 {
continue
}
var vals []uint64
for _, f := range fields[1:] {
v, err := strconv.ParseUint(f, 10, 64)
if err != nil {
break
}
vals = append(vals, v)
}
if len(vals) < 5 {
continue
}
var total, idle uint64
for _, v := range vals {
total += v
}
idle = vals[3] // idle time only, not including iowait
result = append(result, [2]uint64{idle, total})
}
return result
}
// readCPUTemperature 读取CPU温度
func readCPUTemperature() float64 {
// 尝试从常见位置读取温度
paths := []string{
"/sys/class/thermal/thermal_zone0/temp",
"/sys/class/hwmon/hwmon0/temp1_input",
"/sys/class/hwmon/hwmon1/temp1_input",
}
for _, path := range paths {
if temp := readTempFromFile(path); temp > 0 {
return temp
}
}
return 0
}
// readLoadAverages 读取系统负载平均值
func readLoadAverages() []float64 {
line := readFirstLine("/proc/loadavg")
fields := strings.Fields(line)
res := make([]float64, 0, 3)
for i := 0; i < len(fields) && i < 3; i++ {
v, err := strconv.ParseFloat(fields[i], 64)
if err == nil {
res = append(res, v)
}
}
return res
}

View File

@@ -0,0 +1,25 @@
package main
import "encoding/json"
// BuildDashboardPayloadJSON builds the same JSON shape the browser expects (including latency).
// collectorToCentralMs is 采集器到监控中心 TCP 建连毫秒数,失败传 -1。
func BuildDashboardPayloadJSON(collectorToCentralMs float64) ([]byte, error) {
m, err := CollectMetrics()
if err != nil {
return nil, err
}
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
var o map[string]any
if err := json.Unmarshal(b, &o); err != nil {
return nil, err
}
o["latency"] = map[string]any{
"clientToServer": collectorToCentralMs,
"external": readExternalLatencies(),
}
return json.Marshal(o)
}

View File

@@ -0,0 +1,78 @@
package main
import (
"context"
"os/exec"
"strings"
"time"
)
// readDockerStats 读取 Docker 统计信息(简化版)
func readDockerStats() DockerStats {
stats := DockerStats{
Available: false,
RunningNames: []string{},
StoppedNames: []string{},
ImageNames: []string{},
}
// 检查 docker 是否可用
if _, err := exec.LookPath("docker"); err != nil {
return stats
}
stats.Available = true
// 获取 Docker 版本
cmd := exec.Command("docker", "--version")
if out, err := cmd.Output(); err == nil {
stats.Version = strings.TrimSpace(string(out))
}
// 获取运行中的容器名
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd = exec.CommandContext(ctx, "docker", "ps", "--format", "{{.Names}}")
if out, err := cmd.Output(); err == nil {
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
stats.RunningNames = append(stats.RunningNames, line)
stats.Running++
}
}
}
// 获取停止的容器名
ctx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd = exec.CommandContext(ctx, "docker", "ps", "-a", "--filter", "status=exited", "--format", "{{.Names}}")
if out, err := cmd.Output(); err == nil {
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
stats.StoppedNames = append(stats.StoppedNames, line)
stats.Stopped++
}
}
}
// 获取镜像名只获取前20个避免数据过多
ctx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd = exec.CommandContext(ctx, "docker", "images", "--format", "{{.Repository}}:{{.Tag}}")
if out, err := cmd.Output(); err == nil {
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" && line != "<none>:<none>" {
stats.ImageNames = append(stats.ImageNames, line)
stats.ImageCount++
}
}
}
return stats
}

View File

@@ -0,0 +1,492 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.5
// protoc v5.28.3
// source: mengya/v1/agent.proto
package mengyav1
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type AgentMessage struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Types that are valid to be assigned to Payload:
//
// *AgentMessage_Hello
// *AgentMessage_Heartbeat
// *AgentMessage_Metrics
Payload isAgentMessage_Payload `protobuf_oneof:"payload"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AgentMessage) Reset() {
*x = AgentMessage{}
mi := &file_mengya_v1_agent_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AgentMessage) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AgentMessage) ProtoMessage() {}
func (x *AgentMessage) ProtoReflect() protoreflect.Message {
mi := &file_mengya_v1_agent_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AgentMessage.ProtoReflect.Descriptor instead.
func (*AgentMessage) Descriptor() ([]byte, []int) {
return file_mengya_v1_agent_proto_rawDescGZIP(), []int{0}
}
func (x *AgentMessage) GetPayload() isAgentMessage_Payload {
if x != nil {
return x.Payload
}
return nil
}
func (x *AgentMessage) GetHello() *Hello {
if x != nil {
if x, ok := x.Payload.(*AgentMessage_Hello); ok {
return x.Hello
}
}
return nil
}
func (x *AgentMessage) GetHeartbeat() *Heartbeat {
if x != nil {
if x, ok := x.Payload.(*AgentMessage_Heartbeat); ok {
return x.Heartbeat
}
}
return nil
}
func (x *AgentMessage) GetMetrics() *MetricsReport {
if x != nil {
if x, ok := x.Payload.(*AgentMessage_Metrics); ok {
return x.Metrics
}
}
return nil
}
type isAgentMessage_Payload interface {
isAgentMessage_Payload()
}
type AgentMessage_Hello struct {
Hello *Hello `protobuf:"bytes,1,opt,name=hello,proto3,oneof"`
}
type AgentMessage_Heartbeat struct {
Heartbeat *Heartbeat `protobuf:"bytes,2,opt,name=heartbeat,proto3,oneof"`
}
type AgentMessage_Metrics struct {
Metrics *MetricsReport `protobuf:"bytes,3,opt,name=metrics,proto3,oneof"`
}
func (*AgentMessage_Hello) isAgentMessage_Payload() {}
func (*AgentMessage_Heartbeat) isAgentMessage_Payload() {}
func (*AgentMessage_Metrics) isAgentMessage_Payload() {}
type Hello struct {
state protoimpl.MessageState `protogen:"open.v1"`
ServerId string `protobuf:"bytes,1,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"`
AgentKey string `protobuf:"bytes,2,opt,name=agent_key,json=agentKey,proto3" json:"agent_key,omitempty"`
Hostname string `protobuf:"bytes,3,opt,name=hostname,proto3" json:"hostname,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Hello) Reset() {
*x = Hello{}
mi := &file_mengya_v1_agent_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Hello) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Hello) ProtoMessage() {}
func (x *Hello) ProtoReflect() protoreflect.Message {
mi := &file_mengya_v1_agent_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Hello.ProtoReflect.Descriptor instead.
func (*Hello) Descriptor() ([]byte, []int) {
return file_mengya_v1_agent_proto_rawDescGZIP(), []int{1}
}
func (x *Hello) GetServerId() string {
if x != nil {
return x.ServerId
}
return ""
}
func (x *Hello) GetAgentKey() string {
if x != nil {
return x.AgentKey
}
return ""
}
func (x *Hello) GetHostname() string {
if x != nil {
return x.Hostname
}
return ""
}
type Heartbeat struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Heartbeat) Reset() {
*x = Heartbeat{}
mi := &file_mengya_v1_agent_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Heartbeat) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Heartbeat) ProtoMessage() {}
func (x *Heartbeat) ProtoReflect() protoreflect.Message {
mi := &file_mengya_v1_agent_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Heartbeat.ProtoReflect.Descriptor instead.
func (*Heartbeat) Descriptor() ([]byte, []int) {
return file_mengya_v1_agent_proto_rawDescGZIP(), []int{2}
}
type MetricsReport struct {
state protoimpl.MessageState `protogen:"open.v1"`
PayloadJson string `protobuf:"bytes,1,opt,name=payload_json,json=payloadJson,proto3" json:"payload_json,omitempty"`
CollectedAtUnixMs int64 `protobuf:"varint,2,opt,name=collected_at_unix_ms,json=collectedAtUnixMs,proto3" json:"collected_at_unix_ms,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *MetricsReport) Reset() {
*x = MetricsReport{}
mi := &file_mengya_v1_agent_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *MetricsReport) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*MetricsReport) ProtoMessage() {}
func (x *MetricsReport) ProtoReflect() protoreflect.Message {
mi := &file_mengya_v1_agent_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use MetricsReport.ProtoReflect.Descriptor instead.
func (*MetricsReport) Descriptor() ([]byte, []int) {
return file_mengya_v1_agent_proto_rawDescGZIP(), []int{3}
}
func (x *MetricsReport) GetPayloadJson() string {
if x != nil {
return x.PayloadJson
}
return ""
}
func (x *MetricsReport) GetCollectedAtUnixMs() int64 {
if x != nil {
return x.CollectedAtUnixMs
}
return 0
}
type ControlMessage struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Types that are valid to be assigned to Payload:
//
// *ControlMessage_Ack
Payload isControlMessage_Payload `protobuf_oneof:"payload"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ControlMessage) Reset() {
*x = ControlMessage{}
mi := &file_mengya_v1_agent_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ControlMessage) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ControlMessage) ProtoMessage() {}
func (x *ControlMessage) ProtoReflect() protoreflect.Message {
mi := &file_mengya_v1_agent_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ControlMessage.ProtoReflect.Descriptor instead.
func (*ControlMessage) Descriptor() ([]byte, []int) {
return file_mengya_v1_agent_proto_rawDescGZIP(), []int{4}
}
func (x *ControlMessage) GetPayload() isControlMessage_Payload {
if x != nil {
return x.Payload
}
return nil
}
func (x *ControlMessage) GetAck() *Ack {
if x != nil {
if x, ok := x.Payload.(*ControlMessage_Ack); ok {
return x.Ack
}
}
return nil
}
type isControlMessage_Payload interface {
isControlMessage_Payload()
}
type ControlMessage_Ack struct {
Ack *Ack `protobuf:"bytes,1,opt,name=ack,proto3,oneof"`
}
func (*ControlMessage_Ack) isControlMessage_Payload() {}
type Ack struct {
state protoimpl.MessageState `protogen:"open.v1"`
Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Ack) Reset() {
*x = Ack{}
mi := &file_mengya_v1_agent_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Ack) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Ack) ProtoMessage() {}
func (x *Ack) ProtoReflect() protoreflect.Message {
mi := &file_mengya_v1_agent_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Ack.ProtoReflect.Descriptor instead.
func (*Ack) Descriptor() ([]byte, []int) {
return file_mengya_v1_agent_proto_rawDescGZIP(), []int{5}
}
func (x *Ack) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
var File_mengya_v1_agent_proto protoreflect.FileDescriptor
var file_mengya_v1_agent_proto_rawDesc = string([]byte{
0x0a, 0x15, 0x6d, 0x65, 0x6e, 0x67, 0x79, 0x61, 0x2f, 0x76, 0x31, 0x2f, 0x61, 0x67, 0x65, 0x6e,
0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x09, 0x6d, 0x65, 0x6e, 0x67, 0x79, 0x61, 0x2e,
0x76, 0x31, 0x22, 0xaf, 0x01, 0x0a, 0x0c, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x4d, 0x65, 0x73, 0x73,
0x61, 0x67, 0x65, 0x12, 0x28, 0x0a, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x18, 0x01, 0x20, 0x01,
0x28, 0x0b, 0x32, 0x10, 0x2e, 0x6d, 0x65, 0x6e, 0x67, 0x79, 0x61, 0x2e, 0x76, 0x31, 0x2e, 0x48,
0x65, 0x6c, 0x6c, 0x6f, 0x48, 0x00, 0x52, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x34, 0x0a,
0x09, 0x68, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b,
0x32, 0x14, 0x2e, 0x6d, 0x65, 0x6e, 0x67, 0x79, 0x61, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61,
0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x48, 0x00, 0x52, 0x09, 0x68, 0x65, 0x61, 0x72, 0x74, 0x62,
0x65, 0x61, 0x74, 0x12, 0x34, 0x0a, 0x07, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x18, 0x03,
0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x6d, 0x65, 0x6e, 0x67, 0x79, 0x61, 0x2e, 0x76, 0x31,
0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x48, 0x00,
0x52, 0x07, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x42, 0x09, 0x0a, 0x07, 0x70, 0x61, 0x79,
0x6c, 0x6f, 0x61, 0x64, 0x22, 0x5d, 0x0a, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x1b, 0x0a,
0x09, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x52, 0x08, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x61, 0x67,
0x65, 0x6e, 0x74, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x61,
0x67, 0x65, 0x6e, 0x74, 0x4b, 0x65, 0x79, 0x12, 0x1a, 0x0a, 0x08, 0x68, 0x6f, 0x73, 0x74, 0x6e,
0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x68, 0x6f, 0x73, 0x74, 0x6e,
0x61, 0x6d, 0x65, 0x22, 0x0b, 0x0a, 0x09, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74,
0x22, 0x63, 0x0a, 0x0d, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x52, 0x65, 0x70, 0x6f, 0x72,
0x74, 0x12, 0x21, 0x0a, 0x0c, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x6a, 0x73, 0x6f,
0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64,
0x4a, 0x73, 0x6f, 0x6e, 0x12, 0x2f, 0x0a, 0x14, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x65,
0x64, 0x5f, 0x61, 0x74, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6d, 0x73, 0x18, 0x02, 0x20, 0x01,
0x28, 0x03, 0x52, 0x11, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x65, 0x64, 0x41, 0x74, 0x55,
0x6e, 0x69, 0x78, 0x4d, 0x73, 0x22, 0x3f, 0x0a, 0x0e, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c,
0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x22, 0x0a, 0x03, 0x61, 0x63, 0x6b, 0x18, 0x01,
0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x6d, 0x65, 0x6e, 0x67, 0x79, 0x61, 0x2e, 0x76, 0x31,
0x2e, 0x41, 0x63, 0x6b, 0x48, 0x00, 0x52, 0x03, 0x61, 0x63, 0x6b, 0x42, 0x09, 0x0a, 0x07, 0x70,
0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x22, 0x1f, 0x0a, 0x03, 0x41, 0x63, 0x6b, 0x12, 0x18, 0x0a,
0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07,
0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0x50, 0x0a, 0x0b, 0x41, 0x67, 0x65, 0x6e, 0x74,
0x49, 0x6e, 0x67, 0x65, 0x73, 0x74, 0x12, 0x41, 0x0a, 0x07, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63,
0x74, 0x12, 0x17, 0x2e, 0x6d, 0x65, 0x6e, 0x67, 0x79, 0x61, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x67,
0x65, 0x6e, 0x74, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x19, 0x2e, 0x6d, 0x65, 0x6e,
0x67, 0x79, 0x61, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x4d, 0x65,
0x73, 0x73, 0x61, 0x67, 0x65, 0x28, 0x01, 0x30, 0x01, 0x42, 0x3d, 0x5a, 0x3b, 0x6d, 0x65, 0x6e,
0x67, 0x79, 0x61, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x2d, 0x62, 0x61, 0x63, 0x6b, 0x65,
0x6e, 0x64, 0x2d, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e,
0x61, 0x6c, 0x2f, 0x67, 0x65, 0x6e, 0x2f, 0x6d, 0x65, 0x6e, 0x67, 0x79, 0x61, 0x76, 0x31, 0x3b,
0x6d, 0x65, 0x6e, 0x67, 0x79, 0x61, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
})
var (
file_mengya_v1_agent_proto_rawDescOnce sync.Once
file_mengya_v1_agent_proto_rawDescData []byte
)
func file_mengya_v1_agent_proto_rawDescGZIP() []byte {
file_mengya_v1_agent_proto_rawDescOnce.Do(func() {
file_mengya_v1_agent_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_mengya_v1_agent_proto_rawDesc), len(file_mengya_v1_agent_proto_rawDesc)))
})
return file_mengya_v1_agent_proto_rawDescData
}
var file_mengya_v1_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
var file_mengya_v1_agent_proto_goTypes = []any{
(*AgentMessage)(nil), // 0: mengya.v1.AgentMessage
(*Hello)(nil), // 1: mengya.v1.Hello
(*Heartbeat)(nil), // 2: mengya.v1.Heartbeat
(*MetricsReport)(nil), // 3: mengya.v1.MetricsReport
(*ControlMessage)(nil), // 4: mengya.v1.ControlMessage
(*Ack)(nil), // 5: mengya.v1.Ack
}
var file_mengya_v1_agent_proto_depIdxs = []int32{
1, // 0: mengya.v1.AgentMessage.hello:type_name -> mengya.v1.Hello
2, // 1: mengya.v1.AgentMessage.heartbeat:type_name -> mengya.v1.Heartbeat
3, // 2: mengya.v1.AgentMessage.metrics:type_name -> mengya.v1.MetricsReport
5, // 3: mengya.v1.ControlMessage.ack:type_name -> mengya.v1.Ack
0, // 4: mengya.v1.AgentIngest.Connect:input_type -> mengya.v1.AgentMessage
4, // 5: mengya.v1.AgentIngest.Connect:output_type -> mengya.v1.ControlMessage
5, // [5:6] is the sub-list for method output_type
4, // [4:5] is the sub-list for method input_type
4, // [4:4] is the sub-list for extension type_name
4, // [4:4] is the sub-list for extension extendee
0, // [0:4] is the sub-list for field type_name
}
func init() { file_mengya_v1_agent_proto_init() }
func file_mengya_v1_agent_proto_init() {
if File_mengya_v1_agent_proto != nil {
return
}
file_mengya_v1_agent_proto_msgTypes[0].OneofWrappers = []any{
(*AgentMessage_Hello)(nil),
(*AgentMessage_Heartbeat)(nil),
(*AgentMessage_Metrics)(nil),
}
file_mengya_v1_agent_proto_msgTypes[4].OneofWrappers = []any{
(*ControlMessage_Ack)(nil),
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_mengya_v1_agent_proto_rawDesc), len(file_mengya_v1_agent_proto_rawDesc)),
NumEnums: 0,
NumMessages: 6,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_mengya_v1_agent_proto_goTypes,
DependencyIndexes: file_mengya_v1_agent_proto_depIdxs,
MessageInfos: file_mengya_v1_agent_proto_msgTypes,
}.Build()
File_mengya_v1_agent_proto = out.File
file_mengya_v1_agent_proto_goTypes = nil
file_mengya_v1_agent_proto_depIdxs = nil
}

View File

@@ -0,0 +1,119 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v5.28.3
// source: mengya/v1/agent.proto
package mengyav1
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
AgentIngest_Connect_FullMethodName = "/mengya.v1.AgentIngest/Connect"
)
// AgentIngestClient is the client API for AgentIngest service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
//
// AgentIngest: 采集端出站连接,双向流上报指标。
type AgentIngestClient interface {
Connect(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[AgentMessage, ControlMessage], error)
}
type agentIngestClient struct {
cc grpc.ClientConnInterface
}
func NewAgentIngestClient(cc grpc.ClientConnInterface) AgentIngestClient {
return &agentIngestClient{cc}
}
func (c *agentIngestClient) Connect(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[AgentMessage, ControlMessage], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &AgentIngest_ServiceDesc.Streams[0], AgentIngest_Connect_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[AgentMessage, ControlMessage]{ClientStream: stream}
return x, nil
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type AgentIngest_ConnectClient = grpc.BidiStreamingClient[AgentMessage, ControlMessage]
// AgentIngestServer is the server API for AgentIngest service.
// All implementations must embed UnimplementedAgentIngestServer
// for forward compatibility.
//
// AgentIngest: 采集端出站连接,双向流上报指标。
type AgentIngestServer interface {
Connect(grpc.BidiStreamingServer[AgentMessage, ControlMessage]) error
mustEmbedUnimplementedAgentIngestServer()
}
// UnimplementedAgentIngestServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedAgentIngestServer struct{}
func (UnimplementedAgentIngestServer) Connect(grpc.BidiStreamingServer[AgentMessage, ControlMessage]) error {
return status.Errorf(codes.Unimplemented, "method Connect not implemented")
}
func (UnimplementedAgentIngestServer) mustEmbedUnimplementedAgentIngestServer() {}
func (UnimplementedAgentIngestServer) testEmbeddedByValue() {}
// UnsafeAgentIngestServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to AgentIngestServer will
// result in compilation errors.
type UnsafeAgentIngestServer interface {
mustEmbedUnimplementedAgentIngestServer()
}
func RegisterAgentIngestServer(s grpc.ServiceRegistrar, srv AgentIngestServer) {
// If the following call pancis, it indicates UnimplementedAgentIngestServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&AgentIngest_ServiceDesc, srv)
}
func _AgentIngest_Connect_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(AgentIngestServer).Connect(&grpc.GenericServerStream[AgentMessage, ControlMessage]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type AgentIngest_ConnectServer = grpc.BidiStreamingServer[AgentMessage, ControlMessage]
// AgentIngest_ServiceDesc is the grpc.ServiceDesc for AgentIngest service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var AgentIngest_ServiceDesc = grpc.ServiceDesc{
ServiceName: "mengya.v1.AgentIngest",
HandlerType: (*AgentIngestServer)(nil),
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{
{
StreamName: "Connect",
Handler: _AgentIngest_Connect_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "mengya/v1/agent.proto",
}

View File

@@ -0,0 +1,15 @@
module mengyamonitor-backend
go 1.22
require (
google.golang.org/grpc v1.70.0
google.golang.org/protobuf v1.35.2
)
require (
golang.org/x/net v0.32.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a // indirect
)

View File

@@ -0,0 +1,32 @@
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U=
go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg=
go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M=
go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8=
go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4=
go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU=
go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU=
go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ=
go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM=
go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8=
golang.org/x/net v0.32.0 h1:ZqPmj8Kzc+Y6e0+skZsuACbx+wzMgo5MQsJh9Qd6aYI=
golang.org/x/net v0.32.0/go.mod h1:CwU0IoeOlnQQWJ6ioyFrfRuomB8GKF6KbYXZVyeXNfs=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a h1:hgh8P4EuoxpsuKMXX/To36nOFD7vixReXgn8lPGnt+o=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a/go.mod h1:5uTbfoYQed2U9p3KIj2/Zzm02PYhndfdmML0qC3q3FU=
google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ=
google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw=
google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io=
google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=

View File

@@ -0,0 +1,48 @@
package main
import (
"os/exec"
"strconv"
"strings"
)
// readGPU 读取GPU信息
func readGPU() []GPUMetrics {
_, err := exec.LookPath("nvidia-smi")
if err != nil {
return []GPUMetrics{{Status: "not_available"}}
}
// Query GPU info including temperature
cmd := exec.Command("nvidia-smi", "--query-gpu=name,memory.total,memory.used,utilization.gpu,temperature.gpu", "--format=csv,noheader,nounits")
out, err := cmd.Output()
if err != nil {
return []GPUMetrics{{Status: "error", Name: "nvidia-smi", UtilizationPercent: 0}}
}
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
gpus := make([]GPUMetrics, 0, len(lines))
for _, line := range lines {
parts := strings.Split(line, ",")
for i := range parts {
parts[i] = strings.TrimSpace(parts[i])
}
if len(parts) < 5 {
continue
}
total, _ := strconv.ParseInt(parts[1], 10, 64)
used, _ := strconv.ParseInt(parts[2], 10, 64)
util, _ := strconv.ParseFloat(parts[3], 64)
temp, _ := strconv.ParseFloat(parts[4], 64)
gpus = append(gpus, GPUMetrics{
Name: parts[0],
MemoryTotalMB: total,
MemoryUsedMB: used,
UtilizationPercent: round(util, 2),
Temperature: temp,
Status: "ok",
})
}
if len(gpus) == 0 {
return []GPUMetrics{{Status: "not_available"}}
}
return gpus
}

View File

@@ -0,0 +1,96 @@
package main
import (
"context"
"io"
"log"
"os"
"time"
mengyav1 "mengyamonitor-backend/gen/mengyav1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func runGRPCLoop(addr, serverID, key string) {
backoff := time.Second
const maxBackoff = 30 * time.Second
for {
err := runGRPCSession(addr, serverID, key)
if err != nil {
log.Printf("grpc reporter: session ended: %v (reconnect in %v)", err, backoff)
time.Sleep(backoff)
if backoff < maxBackoff {
backoff *= 2
}
continue
}
backoff = time.Second
}
}
func runGRPCSession(addr, serverID, key string) error {
ctx := context.Background()
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return err
}
defer conn.Close()
cli := mengyav1.NewAgentIngestClient(conn)
stream, err := cli.Connect(ctx)
if err != nil {
return err
}
host, _ := os.Hostname()
if err := stream.Send(&mengyav1.AgentMessage{
Payload: &mengyav1.AgentMessage_Hello{
Hello: &mengyav1.Hello{ServerId: serverID, AgentKey: key, Hostname: host},
},
}); err != nil {
return err
}
errCh := make(chan error, 1)
go func() {
for {
_, err := stream.Recv()
if err != nil {
errCh <- err
return
}
}
}()
tick := time.NewTicker(2 * time.Second)
defer tick.Stop()
for {
select {
case err := <-errCh:
if err == io.EOF {
return nil
}
return err
case <-tick.C:
centralMs := measureCollectorToCentralTCP(addr, 3*time.Second)
payload, err := BuildDashboardPayloadJSON(centralMs)
if err != nil {
log.Printf("grpc reporter: collect: %v", err)
continue
}
if err := stream.Send(&mengyav1.AgentMessage{
Payload: &mengyav1.AgentMessage_Metrics{
Metrics: &mengyav1.MetricsReport{
PayloadJson: string(payload),
CollectedAtUnixMs: time.Now().UnixMilli(),
},
},
}); err != nil {
return err
}
}
}
}

View File

@@ -0,0 +1,78 @@
package main
import (
"fmt"
"net"
"strings"
"time"
)
// LatencyInfo 延迟信息(均由采集端在本机测量)
type LatencyInfo struct {
ClientToServer float64 `json:"clientToServer"` // 采集器 → 监控中心 gRPC 地址的 TCP 建连耗时ms失败为 -1
External map[string]string `json:"external"` // 采集器对外站点的 TCP 建连耗时(同 checkExternalLatency
}
// normalizeGRPCDialTarget strips common grpc-go target prefixes; expects host:port or [ipv6]:port.
func normalizeGRPCDialTarget(addr string) string {
a := strings.TrimSpace(addr)
a = strings.TrimPrefix(a, "dns:///")
a = strings.TrimPrefix(a, "dns://")
return strings.TrimSpace(a)
}
// measureCollectorToCentralTCP returns TCP connect time in ms to the central gRPC dial target, or -1 on failure.
func measureCollectorToCentralTCP(grpcAddr string, timeout time.Duration) float64 {
target := normalizeGRPCDialTarget(grpcAddr)
if target == "" || strings.HasPrefix(strings.ToLower(target), "unix:") {
return -1
}
start := time.Now()
conn, err := net.DialTimeout("tcp", target, timeout)
if err != nil {
return -1
}
_ = conn.Close()
return float64(time.Since(start).Microseconds()) / 1000.0
}
// checkExternalLatency 检测外部网站延迟
func checkExternalLatency(host string, timeout time.Duration) string {
start := time.Now()
// 尝试 TCP 连接 80 端口
conn, err := net.DialTimeout("tcp", host+":80", timeout)
if err != nil {
// 如果 80 端口失败,尝试 443 (HTTPS)
conn, err = net.DialTimeout("tcp", host+":443", timeout)
if err != nil {
return "超时"
}
}
defer conn.Close()
// 使用微秒换算,避免 Milliseconds() 截断成 0 ms 误导用户
ms := float64(time.Since(start).Microseconds()) / 1000.0
if ms < 1 {
return fmt.Sprintf("%.1f ms", ms)
}
return fmt.Sprintf("%.0f ms", ms)
}
// readExternalLatencies 读取外部网站延迟
func readExternalLatencies() map[string]string {
latencies := make(map[string]string)
timeout := 3 * time.Second
// 检测百度
latencies["baidu.com"] = checkExternalLatency("baidu.com", timeout)
// 检测谷歌
latencies["google.com"] = checkExternalLatency("google.com", timeout)
// 检测 GitHub
latencies["github.com"] = checkExternalLatency("github.com", timeout)
return latencies
}

View File

@@ -0,0 +1,17 @@
package main
import (
"log"
"os"
)
func main() {
addr := os.Getenv("CENTRAL_GRPC")
serverID := os.Getenv("SERVER_ID")
key := os.Getenv("AGENT_KEY")
if addr == "" || serverID == "" || key == "" {
log.Fatal("mengyamonitor agent requires CENTRAL_GRPC, SERVER_ID, and AGENT_KEY")
}
log.Printf("agent reporting via gRPC to %s (server_id=%s)", addr, serverID)
runGRPCLoop(addr, serverID, key)
}

View File

@@ -0,0 +1,127 @@
package main
import (
"bufio"
"os"
"sort"
"strconv"
"strings"
)
// readMemory 读取内存信息
func readMemory() (MemoryMetrics, error) {
totals := map[string]uint64{}
f, err := os.Open("/proc/meminfo")
if err != nil {
return MemoryMetrics{}, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
parts := strings.Split(line, ":")
if len(parts) < 2 {
continue
}
key := strings.TrimSpace(parts[0])
fields := strings.Fields(strings.TrimSpace(parts[1]))
if len(fields) == 0 {
continue
}
value, err := strconv.ParseUint(fields[0], 10, 64)
if err != nil {
continue
}
totals[key] = value * 1024 // kB to bytes
}
total := totals["MemTotal"]
// 优先使用 MemAvailableLinux 3.14+),如果没有则计算
var free uint64
if available, ok := totals["MemAvailable"]; ok && available > 0 {
free = available
} else {
// 回退到 MemFree + Buffers + Cached适用于较老的系统
free = totals["MemFree"]
if buffers, ok := totals["Buffers"]; ok {
free += buffers
}
if cached, ok := totals["Cached"]; ok {
free += cached
}
}
used := total - free
usedPercent := 0.0
if total > 0 {
usedPercent = (float64(used) / float64(total)) * 100
}
swapTotal := totals["SwapTotal"]
swapFree := totals["SwapFree"]
swapUsed := uint64(0)
if swapTotal >= swapFree {
swapUsed = swapTotal - swapFree
}
swapUsedPct := 0.0
if swapTotal > 0 {
swapUsedPct = (float64(swapUsed) / float64(swapTotal)) * 100
}
swapType := summarizeSwapTypes(swapTotal)
return MemoryMetrics{
TotalBytes: total,
UsedBytes: used,
FreeBytes: free,
UsedPercent: round(usedPercent, 2),
SwapTotalBytes: swapTotal,
SwapUsedBytes: swapUsed,
SwapFreeBytes: swapFree,
SwapUsedPercent: round(swapUsedPct, 2),
SwapType: swapType,
}, nil
}
// summarizeSwapTypes 根据 /proc/swaps 汇总交换区类型file / partition / zram 等);无 swap 时为「无」
func summarizeSwapTypes(swapTotalFromMeminfo uint64) string {
if swapTotalFromMeminfo == 0 {
return "无"
}
f, err := os.Open("/proc/swaps")
if err != nil {
return "未知"
}
defer f.Close()
scanner := bufio.NewScanner(f)
lineNum := 0
seen := map[string]struct{}{}
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
lineNum++
if lineNum == 1 || line == "" {
continue
}
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
filename := fields[0]
typ := fields[1]
if strings.Contains(strings.ToLower(filename), "zram") {
typ = "zram"
}
seen[typ] = struct{}{}
}
if len(seen) == 0 {
if swapTotalFromMeminfo > 0 {
return "未知"
}
return "无"
}
list := make([]string, 0, len(seen))
for t := range seen {
list = append(list, t)
}
sort.Strings(list)
return strings.Join(list, " + ")
}

View File

@@ -0,0 +1,112 @@
package main
import (
"os"
"os/exec"
"strconv"
"strings"
"time"
)
// readNetworkInterfaces 读取网络接口信息(包含瞬时流量速度) - 优化版:所有接口并行采样
func readNetworkInterfaces() []NetworkInterface {
interfaces := []NetworkInterface{}
// 读取网络接口列表
entries, err := os.ReadDir("/sys/class/net")
if err != nil {
return interfaces
}
// 收集要监控的接口名称
var validIfaces []string
for _, entry := range entries {
ifName := entry.Name()
if ifName == "lo" { // 跳过回环接口
continue
}
// 跳过 Docker 相关网络接口
if strings.HasPrefix(ifName, "docker") ||
strings.HasPrefix(ifName, "br-") ||
strings.HasPrefix(ifName, "wwan") ||
strings.HasPrefix(ifName, "nm-bridge") ||
strings.HasPrefix(ifName, "veth") {
continue
}
validIfaces = append(validIfaces, ifName)
}
// 第一次批量读取所有接口的流量
firstReadings := make(map[string][2]uint64) // [rx, tx]
for _, ifName := range validIfaces {
rxPath := "/sys/class/net/" + ifName + "/statistics/rx_bytes"
txPath := "/sys/class/net/" + ifName + "/statistics/tx_bytes"
var rxBytes, txBytes uint64
if rxStr := readFirstLine(rxPath); rxStr != "" {
rxBytes, _ = strconv.ParseUint(strings.TrimSpace(rxStr), 10, 64)
}
if txStr := readFirstLine(txPath); txStr != "" {
txBytes, _ = strconv.ParseUint(strings.TrimSpace(txStr), 10, 64)
}
firstReadings[ifName] = [2]uint64{rxBytes, txBytes}
}
// 等待500ms所有接口一起等待而不是每个接口单独等待
time.Sleep(500 * time.Millisecond)
// 第二次批量读取并构建结果
for _, ifName := range validIfaces {
iface := NetworkInterface{
Name: ifName,
}
// 读取 MAC 地址
macPath := "/sys/class/net/" + ifName + "/address"
iface.MACAddress = strings.TrimSpace(readFirstLine(macPath))
// 读取 IP 地址 (使用 ip addr show)
cmd := exec.Command("ip", "addr", "show", ifName)
if out, err := cmd.Output(); err == nil {
lines := strings.Split(string(out), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "inet ") {
fields := strings.Fields(line)
if len(fields) >= 2 {
iface.IPAddress = strings.Split(fields[1], "/")[0]
break
}
}
}
}
// 读取第二次流量统计
rxPath := "/sys/class/net/" + ifName + "/statistics/rx_bytes"
txPath := "/sys/class/net/" + ifName + "/statistics/tx_bytes"
var rxBytes2, txBytes2 uint64
if rxStr := readFirstLine(rxPath); rxStr != "" {
rxBytes2, _ = strconv.ParseUint(strings.TrimSpace(rxStr), 10, 64)
}
if txStr := readFirstLine(txPath); txStr != "" {
txBytes2, _ = strconv.ParseUint(strings.TrimSpace(txStr), 10, 64)
}
// 设置累计流量
iface.RxBytes = rxBytes2
iface.TxBytes = txBytes2
// 计算瞬时速度 (bytes/s乘以2因为采样间隔是0.5秒)
if first, ok := firstReadings[ifName]; ok {
iface.RxSpeed = float64(rxBytes2-first[0]) * 2
iface.TxSpeed = float64(txBytes2-first[1]) * 2
}
interfaces = append(interfaces, iface)
}
return interfaces
}

View File

@@ -0,0 +1,436 @@
package main
import (
"bufio"
"context"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
// readSystemStats 读取系统统计信息
func readSystemStats() SystemStats {
stats := SystemStats{}
// 读取进程数量
stats.ProcessCount = countProcesses()
stats.LoggedInUsers = countLoggedInSessions()
stats.TCPConnections = countTCPConnectionsFromProc()
// 读取已安装包数量和包管理器类型
stats.PackageCount, stats.PackageManager = countPackages()
// 读取系统温度
stats.Temperature = readSystemTemperature()
// 读取磁盘读写速度
stats.DiskReadSpeed, stats.DiskWriteSpeed = readDiskSpeed()
// 读取 Top 10 进程
stats.TopProcesses = readTopProcesses()
// 读取系统日志
stats.SystemLogs = readSystemLogs(10)
return stats
}
func countProcesses() int {
entries, err := os.ReadDir("/proc")
if err != nil {
return 0
}
count := 0
for _, entry := range entries {
if entry.IsDir() {
// 进程目录是数字命名的
if _, err := strconv.Atoi(entry.Name()); err == nil {
count++
}
}
}
return count
}
// countLoggedInSessions 当前登录会话数(与 who 输出行数一致:多个 SSH/终端各占一行)
func countLoggedInSessions() int {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "who")
out, err := cmd.Output()
if err != nil {
return 0
}
s := strings.TrimSpace(string(out))
if s == "" {
return 0
}
return len(strings.Split(s, "\n"))
}
// countTCPConnectionsFromProc 统计 /proc/net/tcp 与 tcp6 中的套接字条目数(内核导出的各行状态,非仅 ESTABLISHED
func countTCPConnectionsFromProc() int {
return countProcNetTCPFile("/proc/net/tcp") + countProcNetTCPFile("/proc/net/tcp6")
}
func countProcNetTCPFile(path string) int {
f, err := os.Open(path)
if err != nil {
return 0
}
defer f.Close()
scanner := bufio.NewScanner(f)
n := 0
header := true
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
if header {
header = false
continue
}
n++
}
return n
}
func countPackages() (int, string) {
// 尝试不同的包管理器
// dpkg (Debian/Ubuntu)
if _, err := exec.LookPath("dpkg"); err == nil {
cmd := exec.Command("dpkg", "-l")
out, err := cmd.Output()
if err == nil {
lines := strings.Split(string(out), "\n")
count := 0
for _, line := range lines {
if strings.HasPrefix(line, "ii ") {
count++
}
}
return count, "dpkg (apt)"
}
}
// rpm (RedHat/CentOS/Fedora)
if _, err := exec.LookPath("rpm"); err == nil {
cmd := exec.Command("rpm", "-qa")
out, err := cmd.Output()
if err == nil {
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
return len(lines), "rpm (yum/dnf)"
}
}
// pacman (Arch Linux)
if _, err := exec.LookPath("pacman"); err == nil {
cmd := exec.Command("pacman", "-Q")
out, err := cmd.Output()
if err == nil {
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
return len(lines), "pacman"
}
}
return 0, "unknown"
}
func readSystemTemperature() float64 {
var cpuTemp float64 = 0
var fallbackTemp float64 = 0
// 1. 优先读取 thermal_zone (通常是 CPU 温度)
thermalDir := "/sys/class/thermal"
entries, err := os.ReadDir(thermalDir)
if err == nil {
for _, entry := range entries {
if !strings.HasPrefix(entry.Name(), "thermal_zone") {
continue
}
tempPath := thermalDir + "/" + entry.Name() + "/temp"
if temp := readTempFromFile(tempPath); temp > 0 && temp > 20 && temp < 120 {
// thermal_zone0 通常是 CPU
if entry.Name() == "thermal_zone0" {
cpuTemp = temp
break
} else if fallbackTemp == 0 {
fallbackTemp = temp
}
}
}
}
// 2. 扫描所有 hwmon 设备,查找 CPU 温度
hwmonDir := "/sys/class/hwmon"
entries, err = os.ReadDir(hwmonDir)
if err == nil {
for _, entry := range entries {
hwmonPath := hwmonDir + "/" + entry.Name()
// 读取 name 文件,检查是否是 CPU 相关
namePath := hwmonPath + "/name"
name := strings.ToLower(strings.TrimSpace(readFirstLine(namePath)))
// 检查是否是 CPU 温度传感器
isCPU := strings.Contains(name, "cpu") ||
strings.Contains(name, "core") ||
strings.Contains(name, "k10temp") ||
strings.Contains(name, "coretemp") ||
strings.Contains(name, "zenpower")
// 尝试读取 temp1_input (通常是 CPU)
temp1Path := hwmonPath + "/temp1_input"
if temp := readTempFromFile(temp1Path); temp > 0 && temp > 20 && temp < 120 {
if isCPU {
cpuTemp = temp
break
} else if fallbackTemp == 0 {
fallbackTemp = temp
}
}
// 也尝试 temp2_input
temp2Path := hwmonPath + "/temp2_input"
if temp := readTempFromFile(temp2Path); temp > 0 && temp > 20 && temp < 120 {
if isCPU && cpuTemp == 0 {
cpuTemp = temp
} else if fallbackTemp == 0 {
fallbackTemp = temp
}
}
}
}
// 优先返回 CPU 温度,如果没有则返回其他温度
if cpuTemp > 0 {
return cpuTemp
}
return fallbackTemp
}
// readDiskSpeed 读取磁盘瞬时读写速度 (MB/s)
func readDiskSpeed() (float64, float64) {
// 第一次读取
readSectors1, writeSectors1 := getDiskSectors()
if readSectors1 == 0 && writeSectors1 == 0 {
return 0, 0
}
// 等待1秒
time.Sleep(1 * time.Second)
// 第二次读取
readSectors2, writeSectors2 := getDiskSectors()
// 计算差值(扇区数)
readDiff := readSectors2 - readSectors1
writeDiff := writeSectors2 - writeSectors1
// 扇区大小通常是 512 字节,转换为 MB/s
readSpeed := float64(readDiff) * 512 / 1024 / 1024
writeSpeed := float64(writeDiff) * 512 / 1024 / 1024
return round(readSpeed, 2), round(writeSpeed, 2)
}
func getDiskSectors() (uint64, uint64) {
f, err := os.Open("/proc/diskstats")
if err != nil {
return 0, 0
}
defer f.Close()
scanner := bufio.NewScanner(f)
var maxRead uint64 = 0
var mainDevice string
// 第一次遍历:找到读写量最大的主磁盘(通常是系统盘)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 14 {
continue
}
deviceName := fields[2]
// 跳过分区(分区名通常包含数字,如 sda1, vda1, nvme0n1p1
if strings.ContainsAny(deviceName, "0123456789") &&
!strings.HasPrefix(deviceName, "nvme") &&
!strings.HasPrefix(deviceName, "loop") {
continue
}
// 跳过虚拟设备
if strings.HasPrefix(deviceName, "loop") ||
strings.HasPrefix(deviceName, "ram") ||
strings.HasPrefix(deviceName, "zram") {
continue
}
readSectors, _ := strconv.ParseUint(fields[5], 10, 64)
// 选择读写量最大的作为主磁盘
if readSectors > maxRead {
maxRead = readSectors
mainDevice = deviceName
}
}
// 第二次遍历:读取主磁盘的数据
f.Close()
f, err = os.Open("/proc/diskstats")
if err != nil {
return 0, 0
}
scanner = bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 14 {
continue
}
if fields[2] == mainDevice {
readSectors, _ := strconv.ParseUint(fields[5], 10, 64)
writeSectors, _ := strconv.ParseUint(fields[9], 10, 64)
return readSectors, writeSectors
}
}
// 如果没找到,尝试常见的设备名(向后兼容)
f.Close()
f, err = os.Open("/proc/diskstats")
if err != nil {
return 0, 0
}
scanner = bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 14 {
continue
}
deviceName := fields[2]
if deviceName == "sda" || deviceName == "vda" || deviceName == "nvme0n1" {
readSectors, _ := strconv.ParseUint(fields[5], 10, 64)
writeSectors, _ := strconv.ParseUint(fields[9], 10, 64)
return readSectors, writeSectors
}
}
return 0, 0
}
// readTopProcesses 读取 Top 10 进程 (按 CPU 使用率)
func readTopProcesses() []ProcessInfo {
processes := []ProcessInfo{}
// 读取系统总内存
memInfo, _ := readMemory()
totalMemGB := float64(memInfo.TotalBytes) / 1024 / 1024 / 1024
// 使用 ps 命令获取进程信息,添加超时控制
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "ps", "aux", "--sort=-%cpu", "--no-headers")
out, err := cmd.Output()
if err != nil {
return processes
}
lines := strings.Split(string(out), "\n")
count := 0
for _, line := range lines {
if count >= 10 { // 只取前 10 个
break
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
fields := strings.Fields(line)
if len(fields) < 11 {
continue
}
pid, _ := strconv.Atoi(fields[1])
cpu, _ := strconv.ParseFloat(fields[2], 64)
mem, _ := strconv.ParseFloat(fields[3], 64)
// 计算内存MB数
memoryMB := (mem / 100) * totalMemGB * 1024
// 命令可能包含空格从第11个字段开始拼接
command := strings.Join(fields[10:], " ")
if len(command) > 50 {
command = command[:50] + "..."
}
processes = append(processes, ProcessInfo{
PID: pid,
Name: fields[10],
CPU: round(cpu, 1),
Memory: round(mem, 1),
MemoryMB: round(memoryMB, 1),
Command: command,
})
count++
}
return processes
}
// readSystemLogs 读取系统最新日志
func readSystemLogs(count int) []string {
logs := []string{}
// 尝试使用 journalctl 读取系统日志
if _, err := exec.LookPath("journalctl"); err == nil {
cmd := exec.Command("journalctl", "-n", strconv.Itoa(count), "--no-pager", "-o", "short")
out, err := cmd.Output()
if err == nil {
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
for _, line := range lines {
if line != "" {
logs = append(logs, line)
}
}
return logs
}
}
// 如果 journalctl 不可用,尝试读取 /var/log/syslog 或 /var/log/messages
logFiles := []string{"/var/log/syslog", "/var/log/messages"}
for _, logFile := range logFiles {
f, err := os.Open(logFile)
if err != nil {
continue
}
defer f.Close()
// 读取最后几行
var lines []string
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
// 取最后count行
start := len(lines) - count
if start < 0 {
start = 0
}
logs = lines[start:]
break
}
return logs
}

View File

@@ -0,0 +1,113 @@
//go:build linux
// +build linux
package main
import (
"bufio"
"os"
"strings"
"syscall"
)
func readStorage() ([]StorageMetrics, error) {
// For simplicity, report root mount. Can be extended to iterate mounts.
var stat syscall.Statfs_t
if err := syscall.Statfs("/", &stat); err != nil {
return nil, err
}
total := stat.Blocks * uint64(stat.Bsize)
free := stat.Bfree * uint64(stat.Bsize)
used := total - free
usedPercent := 0.0
if total > 0 {
usedPercent = (float64(used) / float64(total)) * 100
}
return []StorageMetrics{{
Mount: "/",
TotalBytes: total,
UsedBytes: used,
FreeBytes: free,
UsedPercent: round(usedPercent, 2),
}}, nil
}
// readAllStorage 读取所有挂载的存储设备
func readAllStorage() ([]StorageMetrics, error) {
storages := []StorageMetrics{}
// 读取 /proc/mounts 获取所有挂载点
f, err := os.Open("/proc/mounts")
if err != nil {
return readStorage() // 降级到只读根目录
}
defer f.Close()
scanner := bufio.NewScanner(f)
seen := make(map[string]bool)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 3 {
continue
}
device := fields[0]
mountPoint := fields[1]
fsType := fields[2]
// 跳过虚拟文件系统
if strings.HasPrefix(device, "/dev/") == false {
continue
}
// 跳过特殊文件系统类型
skipTypes := map[string]bool{
"tmpfs": true, "devtmpfs": true, "squashfs": true,
"overlay": true, "aufs": true, "proc": true,
"sysfs": true, "devpts": true, "cgroup": true,
}
if skipTypes[fsType] {
continue
}
// 避免重复挂载点
if seen[mountPoint] {
continue
}
seen[mountPoint] = true
// 获取该挂载点的统计信息
var stat syscall.Statfs_t
if err := syscall.Statfs(mountPoint, &stat); err != nil {
continue
}
total := stat.Blocks * uint64(stat.Bsize)
free := stat.Bfree * uint64(stat.Bsize)
used := total - free
usedPercent := 0.0
if total > 0 {
usedPercent = (float64(used) / float64(total)) * 100
}
// 只添加有容量的存储
if total > 0 {
storages = append(storages, StorageMetrics{
Mount: mountPoint,
TotalBytes: total,
UsedBytes: used,
FreeBytes: free,
UsedPercent: round(usedPercent, 2),
})
}
}
// 如果没有找到任何存储,至少返回根目录
if len(storages) == 0 {
return readStorage()
}
return storages, nil
}

View File

@@ -0,0 +1,14 @@
//go:build !linux
// +build !linux
package main
import "errors"
func readStorage() ([]StorageMetrics, error) {
return nil, errors.New("storage monitoring is only supported on Linux")
}
func readAllStorage() ([]StorageMetrics, error) {
return nil, errors.New("storage monitoring is only supported on Linux")
}

View File

@@ -0,0 +1,121 @@
package main
import "time"
// CPU相关信息
type CPUMetrics struct {
Model string `json:"model"`
Cores int `json:"cores"`
UsagePercent float64 `json:"usagePercent"`
LoadAverages []float64 `json:"loadAverages,omitempty"`
Temperature float64 `json:"temperature,omitempty"` // CPU温度(摄氏度)
PerCoreUsage []CoreUsage `json:"perCoreUsage,omitempty"` // 每个核心使用率
}
type CoreUsage struct {
Core int `json:"core"`
Percent float64 `json:"percent"`
}
// 内存相关信息
type MemoryMetrics struct {
TotalBytes uint64 `json:"totalBytes"`
UsedBytes uint64 `json:"usedBytes"`
FreeBytes uint64 `json:"freeBytes"`
UsedPercent float64 `json:"usedPercent"`
SwapTotalBytes uint64 `json:"swapTotalBytes"`
SwapUsedBytes uint64 `json:"swapUsedBytes"`
SwapFreeBytes uint64 `json:"swapFreeBytes"`
SwapUsedPercent float64 `json:"swapUsedPercent"`
SwapType string `json:"swapType"` // /proc/swaps 类型汇总,如 file、partition、zram无交换分区时为「无」
}
// 储存相关信息
type StorageMetrics struct {
Mount string `json:"mount"`
TotalBytes uint64 `json:"totalBytes"`
UsedBytes uint64 `json:"usedBytes"`
FreeBytes uint64 `json:"freeBytes"`
UsedPercent float64 `json:"usedPercent"`
}
// GPU相关信息
type GPUMetrics struct {
Name string `json:"name"`
MemoryTotalMB int64 `json:"memoryTotalMB"`
MemoryUsedMB int64 `json:"memoryUsedMB"`
UtilizationPercent float64 `json:"utilizationPercent"`
Temperature float64 `json:"temperature,omitempty"` // GPU温度(摄氏度)
Status string `json:"status"`
}
// 网络相关信息
type NetworkInterface struct {
Name string `json:"name"`
IPAddress string `json:"ipAddress"`
MACAddress string `json:"macAddress"`
RxBytes uint64 `json:"rxBytes"` // 接收字节数
TxBytes uint64 `json:"txBytes"` // 发送字节数
RxSpeed float64 `json:"rxSpeed"` // 接收速度 bytes/s
TxSpeed float64 `json:"txSpeed"` // 发送速度 bytes/s
}
// 系统状态相关信息
type SystemStats struct {
ProcessCount int `json:"processCount"` // 进程数量
LoggedInUsers int `json:"loggedInUsers"` // 当前登录会话数who 行数,与 ssh/tty 会话对应)
TCPConnections int `json:"tcpConnections"` // IPv4+IPv6 套接字行数(/proc/net/tcp + tcp6含各状态
PackageCount int `json:"packageCount"` // 已安装软件包数量
PackageManager string `json:"packageManager"` // 包管理器类型
Temperature float64 `json:"temperature,omitempty"` // 系统温度(摄氏度)
DiskReadSpeed float64 `json:"diskReadSpeed"` // 磁盘读取速度 MB/s
DiskWriteSpeed float64 `json:"diskWriteSpeed"` // 磁盘写入速度 MB/s
NetworkRxSpeed float64 `json:"networkRxSpeed"` // 网络下载速度 MB/s
NetworkTxSpeed float64 `json:"networkTxSpeed"` // 网络上传速度 MB/s
TopProcesses []ProcessInfo `json:"topProcesses"` // Top 10 进程
DockerStats DockerStats `json:"dockerStats"` // Docker 统计信息
SystemLogs []string `json:"systemLogs"` // 系统最新日志
}
// 服务器进程相关信息
type ProcessInfo struct {
PID int `json:"pid"`
Name string `json:"name"`
CPU float64 `json:"cpu"`
Memory float64 `json:"memory"`
MemoryMB float64 `json:"memoryMB"` // 内存占用MB
Command string `json:"command"`
}
// Docker相关信息简化版
type DockerStats struct {
Available bool `json:"available"` // Docker是否可用
Version string `json:"version"` // Docker版本
Running int `json:"running"` // 运行中的容器数
Stopped int `json:"stopped"` // 停止的容器数
ImageCount int `json:"imageCount"` // 镜像数量
RunningNames []string `json:"runningNames"` // 运行中的容器名列表
StoppedNames []string `json:"stoppedNames"` // 停止的容器名列表
ImageNames []string `json:"imageNames"` // 镜像名列表
}
// 操作系统相关信息
type OSInfo struct {
Kernel string `json:"kernel"`
Distro string `json:"distro"`
Architecture string `json:"architecture"`
}
// 所有注册指标
type Metrics struct {
Hostname string `json:"hostname"`
Timestamp time.Time `json:"timestamp"`
CPU CPUMetrics `json:"cpu"`
Memory MemoryMetrics `json:"memory"`
Storage []StorageMetrics `json:"storage"`
GPU []GPUMetrics `json:"gpu"`
Network []NetworkInterface `json:"network"`
System SystemStats `json:"system"`
OS OSInfo `json:"os"`
UptimeSeconds float64 `json:"uptimeSeconds"`
}

View File

@@ -0,0 +1,66 @@
package main
import (
"bufio"
"math"
"os"
"strconv"
"strings"
)
// round 将浮点数四舍五入到指定小数位
func round(v float64, places int) float64 {
factor := math.Pow(10, float64(places))
return math.Round(v*factor) / factor
}
// readFirstLine 读取文件的第一行
func readFirstLine(path string) string {
f, err := os.Open(path)
if err != nil {
return ""
}
defer f.Close()
scanner := bufio.NewScanner(f)
if scanner.Scan() {
return scanner.Text()
}
return ""
}
// firstMatchInFile 在文件中查找第一个匹配指定前缀的行,并返回冒号后的内容
func firstMatchInFile(path, prefix string) string {
f, err := os.Open(path)
if err != nil {
return ""
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(strings.TrimSpace(line), prefix) {
parts := strings.SplitN(line, ":", 2)
if len(parts) == 2 {
return strings.TrimSpace(parts[1])
}
}
}
return ""
}
// readTempFromFile 从文件读取温度值
func readTempFromFile(path string) float64 {
content := readFirstLine(path)
if content == "" {
return 0
}
val, err := strconv.ParseFloat(strings.TrimSpace(content), 64)
if err != nil {
return 0
}
// 温度通常以毫度为单位
if val > 1000 {
return round(val/1000, 1)
}
return round(val, 1)
}