初始化提交
This commit is contained in:
88
mengyamonitor-backend/BUILD.md
Normal file
88
mengyamonitor-backend/BUILD.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# 编译说明 - 兼容旧版本系统
|
||||
|
||||
## 问题说明
|
||||
|
||||
如果在 Debian 11 或其他旧版本系统上运行时出现 GLIBC 版本错误:
|
||||
```
|
||||
./mengyamonitor-backend: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.34' not found
|
||||
```
|
||||
|
||||
这是因为编译时使用了较新版本的 GLIBC,而目标系统的 GLIBC 版本较旧。
|
||||
|
||||
## 解决方案
|
||||
|
||||
### 方案 1:在目标系统上编译(推荐)
|
||||
|
||||
在 Debian 11 服务器上直接编译:
|
||||
|
||||
```bash
|
||||
cd mengyamonitor-backend
|
||||
|
||||
# 禁用 CGO,静态链接
|
||||
export CGO_ENABLED=0
|
||||
go build -ldflags="-s -w" -o mengyamonitor-backend .
|
||||
|
||||
# 或者使用提供的脚本
|
||||
chmod +x build.sh
|
||||
./build.sh
|
||||
```
|
||||
|
||||
### 方案 2:使用静态链接编译
|
||||
|
||||
在任何系统上编译,但使用静态链接:
|
||||
|
||||
```bash
|
||||
cd mengyamonitor-backend
|
||||
|
||||
# 禁用 CGO
|
||||
export CGO_ENABLED=0
|
||||
export GOOS=linux
|
||||
export GOARCH=amd64
|
||||
|
||||
# 编译(静态链接,不依赖系统库)
|
||||
go build -ldflags="-s -w" -o mengyamonitor-backend .
|
||||
```
|
||||
|
||||
### 方案 3:使用 Docker 编译
|
||||
|
||||
使用 Docker 在 Debian 11 环境中编译:
|
||||
|
||||
```bash
|
||||
# 使用 Debian 11 镜像编译
|
||||
docker run --rm -v $(pwd):/app -w /app golang:1.21-bullseye sh -c "
|
||||
export CGO_ENABLED=0
|
||||
go build -ldflags='-s -w' -o mengyamonitor-backend .
|
||||
"
|
||||
|
||||
# 或者使用多阶段构建
|
||||
docker build -t mengyamonitor-backend -f Dockerfile.build .
|
||||
```
|
||||
|
||||
## 验证编译结果
|
||||
|
||||
编译完成后,检查二进制文件:
|
||||
|
||||
```bash
|
||||
# 检查文件类型
|
||||
file mengyamonitor-backend
|
||||
|
||||
# 检查依赖(如果是静态链接,应该显示 "not a dynamic executable")
|
||||
ldd mengyamonitor-backend
|
||||
|
||||
# 检查 GLIBC 依赖(应该没有或很少)
|
||||
objdump -T mengyamonitor-backend | grep GLIBC
|
||||
```
|
||||
|
||||
## 编译参数说明
|
||||
|
||||
- `CGO_ENABLED=0`: 禁用 CGO,使用纯 Go 实现,不依赖系统 C 库
|
||||
- `-ldflags="-s -w"`: 减小二进制文件大小
|
||||
- `-s`: 省略符号表和调试信息
|
||||
- `-w`: 省略 DWARF 符号表
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. 禁用 CGO 后,某些需要 C 库的功能可能不可用,但本项目不依赖 CGO
|
||||
2. 静态链接的二进制文件会稍大一些,但兼容性更好
|
||||
3. 如果必须使用 CGO,需要在目标系统上编译,或使用相同 GLIBC 版本的系统编译
|
||||
|
||||
121
mengyamonitor-backend/README.md
Normal file
121
mengyamonitor-backend/README.md
Normal 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 文件系统的权限
|
||||
29
mengyamonitor-backend/build.sh
Normal file
29
mengyamonitor-backend/build.sh
Normal file
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# 编译脚本 - 兼容旧版本 GLIBC
|
||||
|
||||
echo "开始编译 mengyamonitor-backend..."
|
||||
|
||||
# 禁用 CGO,使用纯 Go 编译(不依赖系统 C 库)
|
||||
export CGO_ENABLED=0
|
||||
|
||||
# 设置目标平台
|
||||
export GOOS=linux
|
||||
export GOARCH=amd64
|
||||
|
||||
# 编译(静态链接)
|
||||
go build -ldflags="-s -w" -o mengyamonitor-backend .
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "编译成功!"
|
||||
echo "二进制文件: mengyamonitor-backend"
|
||||
echo ""
|
||||
echo "检查文件信息:"
|
||||
file mengyamonitor-backend
|
||||
echo ""
|
||||
echo "检查依赖库:"
|
||||
ldd mengyamonitor-backend 2>/dev/null || echo "静态链接,无外部依赖"
|
||||
else
|
||||
echo "编译失败!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
103
mengyamonitor-backend/collector.go
Normal file
103
mengyamonitor-backend/collector.go
Normal 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
|
||||
}
|
||||
182
mengyamonitor-backend/cpu.go
Normal file
182
mengyamonitor-backend/cpu.go
Normal 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
|
||||
}
|
||||
78
mengyamonitor-backend/docker.go
Normal file
78
mengyamonitor-backend/docker.go
Normal 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
|
||||
}
|
||||
3
mengyamonitor-backend/go.mod
Normal file
3
mengyamonitor-backend/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module mengyamonitor-backend
|
||||
|
||||
go 1.22
|
||||
48
mengyamonitor-backend/gpu.go
Normal file
48
mengyamonitor-backend/gpu.go
Normal 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
|
||||
}
|
||||
56
mengyamonitor-backend/latency.go
Normal file
56
mengyamonitor-backend/latency.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LatencyInfo 延迟信息
|
||||
type LatencyInfo struct {
|
||||
ClientToServer float64 `json:"clientToServer"` // 客户端到服务器延迟(ms),由前端计算
|
||||
External map[string]string `json:"external"` // 外部网站延迟
|
||||
}
|
||||
|
||||
// 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()
|
||||
|
||||
latency := time.Since(start).Milliseconds()
|
||||
|
||||
// 检查是否超时(超过超时时间的一半就认为可能有问题)
|
||||
if latency > timeout.Milliseconds()/2 {
|
||||
return "超时"
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%d ms", latency)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
265
mengyamonitor-backend/main.go
Normal file
265
mengyamonitor-backend/main.go
Normal file
@@ -0,0 +1,265 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
// envelope keeps JSON responses consistent.
|
||||
type envelope map[string]any
|
||||
|
||||
func main() {
|
||||
host := getenv("HOST", "0.0.0.0")
|
||||
port := getenv("PORT", "9292")
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/", rootHandler)
|
||||
mux.HandleFunc("/api/health", healthHandler)
|
||||
// 拆分的细粒度API端点
|
||||
mux.HandleFunc("/api/metrics/cpu", cpuMetricsHandler)
|
||||
mux.HandleFunc("/api/metrics/memory", memoryMetricsHandler)
|
||||
mux.HandleFunc("/api/metrics/storage", storageMetricsHandler)
|
||||
mux.HandleFunc("/api/metrics/gpu", gpuMetricsHandler)
|
||||
mux.HandleFunc("/api/metrics/network", networkMetricsHandler)
|
||||
mux.HandleFunc("/api/metrics/system", systemMetricsHandler)
|
||||
mux.HandleFunc("/api/metrics/docker", dockerMetricsHandler)
|
||||
mux.HandleFunc("/api/metrics/latency", latencyMetricsHandler)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: fmt.Sprintf("%s:%s", host, port),
|
||||
Handler: loggingMiddleware(corsMiddleware(mux)),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
|
||||
log.Printf("server starting on http://%s:%s", host, port)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("server error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func rootHandler(w http.ResponseWriter, r *http.Request) {
|
||||
respondJSON(w, http.StatusOK, envelope{
|
||||
"service": "萌芽监控面板 API",
|
||||
"version": "1.0.0",
|
||||
"endpoints": []map[string]string{
|
||||
{
|
||||
"path": "/",
|
||||
"description": "API 信息和可用端点列表",
|
||||
},
|
||||
{
|
||||
"path": "/api/health",
|
||||
"description": "健康检查",
|
||||
},
|
||||
{
|
||||
"path": "/api/metrics/cpu",
|
||||
"description": "获取 CPU 监控数据",
|
||||
},
|
||||
{
|
||||
"path": "/api/metrics/memory",
|
||||
"description": "获取内存监控数据",
|
||||
},
|
||||
{
|
||||
"path": "/api/metrics/storage",
|
||||
"description": "获取存储监控数据",
|
||||
},
|
||||
{
|
||||
"path": "/api/metrics/gpu",
|
||||
"description": "获取 GPU 监控数据",
|
||||
},
|
||||
{
|
||||
"path": "/api/metrics/network",
|
||||
"description": "获取网络接口监控数据",
|
||||
},
|
||||
{
|
||||
"path": "/api/metrics/system",
|
||||
"description": "获取系统统计信息(进程、包、磁盘速度等)",
|
||||
},
|
||||
{
|
||||
"path": "/api/metrics/docker",
|
||||
"description": "获取 Docker 容器监控数据",
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func healthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
respondJSON(w, http.StatusOK, envelope{
|
||||
"status": "ok",
|
||||
"timestamp": time.Now().UTC(),
|
||||
})
|
||||
}
|
||||
|
||||
// CPU监控数据
|
||||
func cpuMetricsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
cpuModel := firstMatchInFile("/proc/cpuinfo", "model name")
|
||||
cpuUsage, err := readCPUUsage()
|
||||
if err != nil {
|
||||
cpuUsage = 0
|
||||
}
|
||||
cpuTemp := readCPUTemperature()
|
||||
perCoreUsage := readPerCoreUsage()
|
||||
loads := readLoadAverages()
|
||||
|
||||
cores := runtime.NumCPU()
|
||||
respondJSON(w, http.StatusOK, envelope{
|
||||
"data": CPUMetrics{
|
||||
Model: cpuModel,
|
||||
Cores: cores,
|
||||
UsagePercent: round(cpuUsage, 2),
|
||||
LoadAverages: loads,
|
||||
Temperature: cpuTemp,
|
||||
PerCoreUsage: perCoreUsage,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 内存监控数据
|
||||
func memoryMetricsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
mem, err := readMemory()
|
||||
if err != nil {
|
||||
respondJSON(w, http.StatusInternalServerError, envelope{
|
||||
"error": "failed to read memory",
|
||||
})
|
||||
return
|
||||
}
|
||||
respondJSON(w, http.StatusOK, envelope{
|
||||
"data": mem,
|
||||
})
|
||||
}
|
||||
|
||||
// 存储监控数据
|
||||
func storageMetricsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
storage, err := readAllStorage()
|
||||
if err != nil {
|
||||
respondJSON(w, http.StatusInternalServerError, envelope{
|
||||
"error": "failed to read storage",
|
||||
})
|
||||
return
|
||||
}
|
||||
respondJSON(w, http.StatusOK, envelope{
|
||||
"data": storage,
|
||||
})
|
||||
}
|
||||
|
||||
// GPU监控数据
|
||||
func gpuMetricsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
gpu := readGPU()
|
||||
respondJSON(w, http.StatusOK, envelope{
|
||||
"data": gpu,
|
||||
})
|
||||
}
|
||||
|
||||
// 网络监控数据
|
||||
func networkMetricsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
network := readNetworkInterfaces()
|
||||
respondJSON(w, http.StatusOK, envelope{
|
||||
"data": network,
|
||||
})
|
||||
}
|
||||
|
||||
// 系统统计信息
|
||||
func systemMetricsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
stats := readSystemStats()
|
||||
|
||||
// 读取系统基本信息
|
||||
hostname, _ := os.Hostname()
|
||||
osInfo := readOSInfo()
|
||||
uptime := readUptime()
|
||||
|
||||
// 计算总网络速度(汇总所有接口)
|
||||
networkInterfaces := readNetworkInterfaces()
|
||||
var totalRxSpeed, totalTxSpeed float64
|
||||
for _, iface := range networkInterfaces {
|
||||
totalRxSpeed += iface.RxSpeed // bytes/s
|
||||
totalTxSpeed += iface.TxSpeed // bytes/s
|
||||
}
|
||||
// 转换为 MB/s
|
||||
stats.NetworkRxSpeed = round(totalRxSpeed/1024/1024, 2)
|
||||
stats.NetworkTxSpeed = round(totalTxSpeed/1024/1024, 2)
|
||||
|
||||
respondJSON(w, http.StatusOK, envelope{
|
||||
"data": map[string]interface{}{
|
||||
"hostname": hostname,
|
||||
"os": osInfo,
|
||||
"uptimeSeconds": uptime,
|
||||
"processCount": stats.ProcessCount,
|
||||
"packageCount": stats.PackageCount,
|
||||
"packageManager": stats.PackageManager,
|
||||
"temperature": stats.Temperature,
|
||||
"diskReadSpeed": stats.DiskReadSpeed,
|
||||
"diskWriteSpeed": stats.DiskWriteSpeed,
|
||||
"networkRxSpeed": stats.NetworkRxSpeed,
|
||||
"networkTxSpeed": stats.NetworkTxSpeed,
|
||||
"topProcesses": stats.TopProcesses,
|
||||
"systemLogs": stats.SystemLogs,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Docker监控数据
|
||||
func dockerMetricsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
docker := readDockerStats()
|
||||
respondJSON(w, http.StatusOK, envelope{
|
||||
"data": docker,
|
||||
})
|
||||
}
|
||||
|
||||
// 延迟监控数据
|
||||
func latencyMetricsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// 记录请求开始时间,用于计算客户端到服务器的延迟
|
||||
startTime := time.Now()
|
||||
|
||||
// 读取外部网站延迟
|
||||
externalLatencies := readExternalLatencies()
|
||||
|
||||
// 计算服务器处理时间(这个可以作为参考,实际客户端延迟由前端计算)
|
||||
serverProcessTime := time.Since(startTime).Milliseconds()
|
||||
|
||||
respondJSON(w, http.StatusOK, envelope{
|
||||
"data": map[string]interface{}{
|
||||
"serverProcessTime": serverProcessTime, // 服务器处理时间(参考)
|
||||
"external": externalLatencies,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func respondJSON(w http.ResponseWriter, status int, body envelope) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if err := json.NewEncoder(w).Encode(body); err != nil {
|
||||
log.Printf("write json error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
next.ServeHTTP(w, r)
|
||||
log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
|
||||
})
|
||||
}
|
||||
|
||||
func corsMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
64
mengyamonitor-backend/memory.go
Normal file
64
mengyamonitor-backend/memory.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"os"
|
||||
"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"]
|
||||
|
||||
// 优先使用 MemAvailable(Linux 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
|
||||
}
|
||||
return MemoryMetrics{
|
||||
TotalBytes: total,
|
||||
UsedBytes: used,
|
||||
FreeBytes: free,
|
||||
UsedPercent: round(usedPercent, 2),
|
||||
}, nil
|
||||
}
|
||||
110
mengyamonitor-backend/network.go
Normal file
110
mengyamonitor-backend/network.go
Normal file
@@ -0,0 +1,110 @@
|
||||
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, "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
|
||||
}
|
||||
390
mengyamonitor-backend/system.go
Normal file
390
mengyamonitor-backend/system.go
Normal file
@@ -0,0 +1,390 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// readSystemStats 读取系统统计信息
|
||||
func readSystemStats() SystemStats {
|
||||
stats := SystemStats{}
|
||||
|
||||
// 读取进程数量
|
||||
stats.ProcessCount = countProcesses()
|
||||
|
||||
// 读取已安装包数量和包管理器类型
|
||||
stats.PackageCount, stats.PackageManager = countPackages()
|
||||
|
||||
// 读取系统温度
|
||||
stats.Temperature = readSystemTemperature()
|
||||
|
||||
// 读取磁盘读写速度
|
||||
stats.DiskReadSpeed, stats.DiskWriteSpeed = readDiskSpeed()
|
||||
|
||||
// 读取 Top 5 进程
|
||||
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
|
||||
}
|
||||
|
||||
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 5 进程 (按 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 >= 5 { // 只取前5个
|
||||
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
|
||||
}
|
||||
113
mengyamonitor-backend/systeminfo_linux.go
Normal file
113
mengyamonitor-backend/systeminfo_linux.go
Normal 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
|
||||
}
|
||||
14
mengyamonitor-backend/systeminfo_other.go
Normal file
14
mengyamonitor-backend/systeminfo_other.go
Normal 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")
|
||||
}
|
||||
114
mengyamonitor-backend/types.go
Normal file
114
mengyamonitor-backend/types.go
Normal file
@@ -0,0 +1,114 @@
|
||||
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"`
|
||||
}
|
||||
|
||||
// 储存相关信息
|
||||
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"` // 进程数量
|
||||
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 5 进程
|
||||
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"`
|
||||
}
|
||||
66
mengyamonitor-backend/utils.go
Normal file
66
mengyamonitor-backend/utils.go
Normal 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)
|
||||
}
|
||||
Reference in New Issue
Block a user