Files
JuiceWorkStation/backend/main.go
T
xiaozhou233 eaecdaf9f5 feat: 控制面板概览页新增 Docker 容器监控
后端新增 GET /api/docker/stats,走 Docker Engine API(unix socket)读取容器状态、CPU/内存/网络/磁盘与端口;前端 /dashboard 概览页展示汇总与容器列表,5 秒自动刷新;compose 只读挂载 docker.sock 并通过 group_add 注入宿主机 docker 组 GID。
2026-10-06 16:12:21 +08:00

367 lines
9.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// JuiceWorkStation 后端
//
// 这是原 Spring Boot 版本的 Go 重写,对外接口与 JSON 结构保持一致:
//
// GET /api/system/stats 返回系统状态 JSON
// GET /api/docker/stats 返回 Docker 容器监控 JSON(见 docker.go)
// GET /healthz 健康检查(给容器编排/探活用)
//
// 相比 Java 版,运行时只占十几 MB 内存,且不依赖 JVM。
package main
import (
"encoding/json"
"log"
"math"
"net/http"
"os"
"runtime"
"strings"
"sync"
"time"
"github.com/shirou/gopsutil/v4/cpu"
"github.com/shirou/gopsutil/v4/disk"
"github.com/shirou/gopsutil/v4/host"
"github.com/shirou/gopsutil/v4/mem"
psnet "github.com/shirou/gopsutil/v4/net"
"github.com/shirou/gopsutil/v4/process"
)
// listenAddr 是服务监听地址。和原来 Spring Boot 的 server.port 保持一致。
const listenAddr = ":9018"
// ---------------------------------------------------------------------------
// 对外 JSON 结构
//
// struct 后面的 `json:"xxx"` 是"标签",决定这个字段序列化出来的名字,
// 和前端 dashboard/src/pages/Home.tsx 里的 TS 接口一一对应。
// ---------------------------------------------------------------------------
type SystemStats struct {
CPU CpuStats `json:"cpu"`
Memory MemoryStats `json:"memory"`
Disks []DiskStats `json:"disks"`
Networks []NetworkStats `json:"networks"`
OS OsStats `json:"os"`
}
type CpuStats struct {
Model string `json:"model"`
Cores int `json:"cores"`
UsagePercent float64 `json:"usagePercent"`
ProcessUsagePercent float64 `json:"processUsagePercent"`
}
type MemoryStats struct {
Total uint64 `json:"total"`
Used uint64 `json:"used"`
Free uint64 `json:"free"`
UsagePercent float64 `json:"usagePercent"`
SwapTotal uint64 `json:"swapTotal"`
SwapUsed uint64 `json:"swapUsed"`
}
type DiskStats struct {
Name string `json:"name"`
Total uint64 `json:"total"`
Used uint64 `json:"used"`
Free uint64 `json:"free"`
UsagePercent float64 `json:"usagePercent"`
ReadOnly bool `json:"readOnly"`
}
type NetworkStats struct {
Name string `json:"name"`
DisplayName string `json:"displayName"`
Up bool `json:"up"`
MTU int `json:"mtu"`
Addresses []string `json:"addresses"`
}
type OsStats struct {
Name string `json:"name"`
Version string `json:"version"`
Arch string `json:"arch"`
GoVersion string `json:"goVersion"` // 原 Java 版的 javaVersion,改名为 Go 版本
Hostname string `json:"hostname"`
UptimeSeconds uint64 `json:"uptimeSeconds"`
}
// ---------------------------------------------------------------------------
// CPU 使用率采样
//
// CPU 使用率需要"两次采样求差"才能算出来(和原 Java 的 getCpuLoad 原理一样)。
// 这里用一个后台协程每秒采一次样,HTTP 处理函数只读取最新值,
// 这样请求不会被采样阻塞。
// ---------------------------------------------------------------------------
var (
sampleMu sync.RWMutex
sysCPUPercent float64
procCPUPercent float64
)
func startCPUSampler() {
// 当前进程对象,用于统计"本进程"CPU 占用。
proc, err := process.NewProcess(int32(os.Getpid()))
if err != nil {
log.Printf("无法获取当前进程信息: %v", err)
}
go func() {
for {
// cpu.Percent 传入 0 表示"与上一次调用相比", 不阻塞。
if v, err := cpu.Percent(0, false); err == nil && len(v) > 0 {
sampleMu.Lock()
sysCPUPercent = round1(v[0])
sampleMu.Unlock()
}
if proc != nil {
if v, err := proc.Percent(0); err == nil {
sampleMu.Lock()
procCPUPercent = round1(v)
sampleMu.Unlock()
}
}
time.Sleep(time.Second)
}
}()
}
// ---------------------------------------------------------------------------
// HTTP 处理
// ---------------------------------------------------------------------------
func handleSystemStats(w http.ResponseWriter, r *http.Request) {
stats := collectStats()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(stats); err != nil {
log.Printf("序列化响应失败: %v", err)
}
}
func handleHealthz(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}
// withCORS 允许跨域访问 /api,和原 Java 版 WebConfig 的行为保持一致。
// 如果确定只走 nginx 同源反代,可以把这段去掉以收紧安全策略。
func withCORS(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, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "*")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
// ---------------------------------------------------------------------------
// 采集各个子系统
// ---------------------------------------------------------------------------
func collectStats() SystemStats {
return SystemStats{
CPU: collectCPU(),
Memory: collectMemory(),
Disks: collectDisks(),
Networks: collectNetworks(),
OS: collectOS(),
}
}
func collectCPU() CpuStats {
model := "Unknown"
if infos, err := cpu.Info(); err == nil && len(infos) > 0 {
model = strings.TrimSpace(infos[0].ModelName)
}
// Counts(true) 返回逻辑核心数,等价于原 Java 的 getAvailableProcessors()。
cores, _ := cpu.Counts(true)
sampleMu.RLock()
sysP, procP := sysCPUPercent, procCPUPercent
sampleMu.RUnlock()
return CpuStats{
Model: model,
Cores: cores,
UsagePercent: sysP,
ProcessUsagePercent: procP,
}
}
func collectMemory() MemoryStats {
out := MemoryStats{}
if vm, err := mem.VirtualMemory(); err == nil {
out.Total = vm.Total
out.Used = vm.Used
out.Free = vm.Free
out.UsagePercent = round1(vm.UsedPercent)
}
if sw, err := mem.SwapMemory(); err == nil {
out.SwapTotal = sw.Total
out.SwapUsed = sw.Used
}
return out
}
func collectDisks() []DiskStats {
out := make([]DiskStats, 0)
// false 表示只取物理分区,忽略 tmpfs、proc 之类的虚拟文件系统。
parts, err := disk.Partitions(false)
if err != nil || len(parts) == 0 {
// 容器里的根文件系统通常是 overlay,会被上面的过滤掉,
// 这里回退到全部分区并只保留真实文件系统类型。
all, err2 := disk.Partitions(true)
if err2 != nil {
return out
}
parts = make([]disk.PartitionStat, 0, len(all))
for _, p := range all {
if isRealFS(p.Fstype) {
parts = append(parts, p)
}
}
}
seen := map[string]bool{}
for _, p := range parts {
if seen[p.Mountpoint] {
continue
}
// 跳过 /etc/hosts、/etc/hostname 这类"文件"挂载,它们和根是同一个文件系统。
if fi, err := os.Stat(p.Mountpoint); err != nil || !fi.IsDir() {
continue
}
seen[p.Mountpoint] = true
u, err := disk.Usage(p.Mountpoint)
if err != nil {
continue
}
out = append(out, DiskStats{
Name: p.Mountpoint,
Total: u.Total,
Used: u.Used,
Free: u.Free,
UsagePercent: round1(u.UsedPercent),
// 挂载选项里带 "ro" 就是只读。
ReadOnly: hasFlag(p.Opts, "ro"),
})
}
return out
}
// isRealFS 判断文件系统类型是否为"真实磁盘",用于过滤 tmpfs/proc/sysfs 等。
func isRealFS(fstype string) bool {
switch fstype {
case "ext2", "ext3", "ext4", "xfs", "btrfs", "zfs", "f2fs",
"overlay", "vfat", "exfat", "ntfs", "ntfs3", "fuseblk",
"apfs", "hfs", "hfsplus", "jfs", "reiserfs", "ufs":
return true
}
return false
}
func collectNetworks() []NetworkStats {
out := make([]NetworkStats, 0)
ifaces, err := psnet.Interfaces()
if err != nil {
return out
}
for _, ni := range ifaces {
if hasFlag(ni.Flags, "loopback") || !hasFlag(ni.Flags, "up") {
continue
}
addrs := make([]string, 0, len(ni.Addrs))
for _, a := range ni.Addrs {
if a.Addr != "" {
addrs = append(addrs, a.Addr)
}
}
out = append(out, NetworkStats{
Name: ni.Name,
DisplayName: ni.Name,
Up: true,
MTU: ni.MTU,
Addresses: addrs,
})
}
return out
}
func collectOS() OsStats {
out := OsStats{
Arch: runtime.GOARCH,
GoVersion: runtime.Version(),
}
if info, err := host.Info(); err == nil {
name := info.Platform
if name == "" {
name = info.OS
}
out.Name = name
out.Version = info.PlatformVersion
out.Hostname = info.Hostname
out.UptimeSeconds = info.Uptime
}
return out
}
// ---------------------------------------------------------------------------
// 工具函数
// ---------------------------------------------------------------------------
// round1 保留一位小数,和原 Java 版 round() 的行为一致。
func round1(v float64) float64 {
return math.Round(v*10) / 10
}
func hasFlag(flags []string, target string) bool {
for _, f := range flags {
if f == target {
return true
}
}
return false
}
func main() {
startCPUSampler()
mux := http.NewServeMux()
mux.HandleFunc("/api/system/stats", handleSystemStats)
mux.HandleFunc("/api/docker/stats", handleDockerStats)
mux.HandleFunc("/healthz", handleHealthz)
server := &http.Server{
Addr: listenAddr,
Handler: withCORS(mux),
ReadHeaderTimeout: 5 * time.Second,
}
log.Printf("workstation-server (Go %s) 启动,监听 %s", runtime.Version(), listenAddr)
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}