You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
2.4 KiB
102 lines
2.4 KiB
package core
|
|
|
|
import (
|
|
"aufs/proto/pb"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/shirou/gopsutil/v3/cpu"
|
|
"github.com/shirou/gopsutil/v3/disk"
|
|
"github.com/shirou/gopsutil/v3/mem"
|
|
"github.com/shirou/gopsutil/v3/net"
|
|
"github.com/shirou/gopsutil/v3/process"
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
// 返回json数据
|
|
type SysResp struct {
|
|
Status int `json:"status"`
|
|
Message string `json:"message"`
|
|
Data any `json:"data"`
|
|
}
|
|
|
|
// 系统监控
|
|
func SysMonitor(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// 磁盘容量信息
|
|
diskInfo, err := disk.Usage("/")
|
|
if err != nil {
|
|
log.Fatal("获取磁盘信息失败:", err)
|
|
return
|
|
}
|
|
// 磁盘空间占用
|
|
hdtval := fmt.Sprintf("%.2f GB", float64(diskInfo.Total)/1024/1024/1024)
|
|
hduval := fmt.Sprintf("%.2f GB", float64(diskInfo.Used)/1024/1024/1024)
|
|
|
|
// 获取CPU占用率 (需要等待1秒来计算)
|
|
cpuPercent, err := cpu.Percent(time.Second, false)
|
|
if err != nil {
|
|
log.Fatalf("获取CPU信息失败: %v", err)
|
|
return
|
|
}
|
|
cpuinfo := fmt.Sprintf(" %.2f%%", cpuPercent[0])
|
|
|
|
// 获取内存占用信息
|
|
memInfo, err := mem.VirtualMemory()
|
|
if err != nil {
|
|
log.Fatalf("获取内存信息失败: %v", err)
|
|
return
|
|
|
|
}
|
|
|
|
// 获取网络流量信息
|
|
netIO, err := net.IOCounters(false)
|
|
if err != nil {
|
|
log.Fatalf("获取网络信息失败: %v", err)
|
|
return
|
|
}
|
|
|
|
// 获取系统进程信息 (只获取前5个进程)
|
|
processes, err := process.Processes()
|
|
if err != nil {
|
|
log.Fatalf("获取进程信息失败: %v", err)
|
|
return
|
|
}
|
|
// 统计运行中的进程数量
|
|
procnum := int32(len(processes))
|
|
|
|
//生成proto的内容
|
|
hdinfo, err := proto.Marshal(&pb.Hdinfo{
|
|
Hdstat: fmt.Sprintf("%v / %v", hduval, hdtval),
|
|
Procout: fmt.Sprintf(" %d", procnum),
|
|
Cpustat: cpuinfo,
|
|
Memstat: fmt.Sprintf(" %.2f%%", memInfo.UsedPercent),
|
|
Netstat: fmt.Sprintf(" %.2f MB", float64(netIO[0].BytesRecv)/1024/1024),
|
|
})
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
|
|
// ver:0821
|
|
// 输出proto
|
|
encdata := base64.StdEncoding.EncodeToString(hdinfo)
|
|
// w.Header().Set("content-type", "application/x-protobuf")
|
|
// w.Write([]byte(encdata))
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
// 生成json数据
|
|
sysresp := SysResp{
|
|
Status: 0,
|
|
Message: "success",
|
|
Data: encdata,
|
|
}
|
|
|
|
// 增加跨域
|
|
uCorsHadler(w, r)
|
|
json.NewEncoder(w).Encode(sysresp)
|
|
}
|
|
|