feat: 后端由 Spring Boot 重写为 Go

- backend: 使用 Go + gopsutil 重写,接口 GET /api/system/stats 结构与前端保持一致
- 内存占用从 ~178MiB 降至 ~4MiB,镜像从 200MB+ 降至 15MB
- Dockerfile 改为多阶段构建,运行镜像使用 distroless
- 前端 os.javaVersion 字段改为 os.goVersion,标签由 Java 改为 Go
- docker-compose: 为 backend 与 frontend 增加 mem_limit
This commit is contained in:
xiaozhou233 committed 2026-10-06 13:38:25 +08:00
1 parent cfa4f4745c
commit 5b3f40fc7b
22 files changed
+437 -674

No files matched your search

+5 -7
View File
@@ -1,7 +1,5 @@
.gradle
build/
.idea
*.iml
bin/
out/
.vscode
.git
.gitignore
*.md
Dockerfile
.dockerignore
-3
View File
@@ -1,3 +0,0 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary
+7 -36
View File
@@ -1,37 +1,8 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
# 编译产物
/server
server
server.exe
*.exe
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
# Go 工作区
/vendor/
+13 -9
View File
@@ -1,17 +1,21 @@
# ---- 构建阶段 ----
FROM gradle:9.5.1-jdk17 AS build
WORKDIR /workspace
FROM golang:1.26-alpine AS build
WORKDIR /src
# 先只拷贝依赖清单,让 Docker 缓存生效:只要依赖没变就不重复下载。
COPY go.mod go.sum ./
RUN go mod download
# 再拷贝源码并编译成静态二进制。
COPY . .
RUN gradle bootJar --no-daemon
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/server .
# ---- 运行阶段 ----
FROM eclipse-temurin:17-jre
WORKDIR /app
# distroless 里没有 shell/包管理器,只放二进制,镜像极小、攻击面也小。
FROM gcr.io/distroless/static-debian12:nonroot
RUN groupadd --system app && useradd --system --gid app app
COPY --from=build /workspace/build/libs/*.jar /app/server.jar
USER app
COPY --from=build /out/server /server
EXPOSE 9018
ENTRYPOINT ["java", "-jar", "/app/server.jar"]
ENTRYPOINT ["/server"]
-33
View File
@@ -1,33 +0,0 @@
plugins {
id 'java'
id 'org.springframework.boot' version '4.1.0'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'cn.xiaozhou233.workstation'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
testCompileOnly 'org.projectlombok:lombok'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testAnnotationProcessor 'org.projectlombok:lombok'
}
tasks.named('test') {
useJUnitPlatform()
}
+16
View File
@@ -0,0 +1,16 @@
module workstation-server
go 1.26.0
require github.com/shirou/gopsutil/v4 v4.26.9
require (
github.com/ebitengine/purego v0.11.1 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 // indirect
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/sys v0.48.0 // indirect
)
+28
View File
@@ -0,0 +1,28 @@
github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0=
github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 h1:jL3a8soXdzuTCcRnKhOmtcsVOObdDTFf4O2B403HPRU=
github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/shirou/gopsutil/v4 v4.26.9 h1:CaBo/hBFqvlJoLvAQEKdHdf5GD97/MN2ACfyv63+2Ig=
github.com/shirou/gopsutil/v4 v4.26.9/go.mod h1:nKH+8wX2zxr/mDbsR+AAy6Qd2z4ZOQ7wfQaEp+yrYmg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU=
github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=
github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
Binary file not shown.
-9
View File
@@ -1,9 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-248
View File
@@ -1,248 +0,0 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
-82
View File
@@ -1,82 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute Gradle
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+364
View File
@@ -0,0 +1,364 @@
// JuiceWorkStation 后端
//
// 这是原 Spring Boot 版本的 Go 重写,对外接口与 JSON 结构保持一致:
//
// GET /api/system/stats 返回系统状态 JSON
// 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("/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)
}
}
-1
View File
@@ -1 +0,0 @@
rootProject.name = 'server'
@@ -1,13 +0,0 @@
package cn.xiaozhou233.workstation.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
@@ -1,17 +0,0 @@
package cn.xiaozhou233.workstation.server.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*");
}
}
@@ -1,24 +0,0 @@
package cn.xiaozhou233.workstation.server.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.xiaozhou233.workstation.server.dto.SystemStats;
import cn.xiaozhou233.workstation.server.service.SystemInfoService;
@RestController
@RequestMapping("/api/system")
public class SystemInfoController {
private final SystemInfoService systemInfoService;
public SystemInfoController(SystemInfoService systemInfoService) {
this.systemInfoService = systemInfoService;
}
@GetMapping("/stats")
public SystemStats getSystemStats() {
return systemInfoService.getSystemStats();
}
}
@@ -1,27 +0,0 @@
package cn.xiaozhou233.workstation.server.dto;
import java.util.List;
public record SystemStats(
CpuStats cpu,
MemoryStats memory,
List<DiskStats> disks,
List<NetworkStats> networks,
OsStats os) {
public record CpuStats(String model, int cores, double usagePercent, double processUsagePercent) {
}
public record MemoryStats(long total, long used, long free, double usagePercent, long swapTotal, long swapUsed) {
}
public record DiskStats(String name, long total, long used, long free, double usagePercent, boolean readOnly) {
}
public record NetworkStats(String name, String displayName, boolean up, int mtu, List<String> addresses) {
}
public record OsStats(String name, String version, String arch, String javaVersion, String hostname,
long uptimeSeconds) {
}
}
@@ -1,144 +0,0 @@
package cn.xiaozhou233.workstation.server.service;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import org.springframework.stereotype.Service;
import com.sun.management.OperatingSystemMXBean;
import cn.xiaozhou233.workstation.server.dto.SystemStats;
import cn.xiaozhou233.workstation.server.dto.SystemStats.CpuStats;
import cn.xiaozhou233.workstation.server.dto.SystemStats.DiskStats;
import cn.xiaozhou233.workstation.server.dto.SystemStats.MemoryStats;
import cn.xiaozhou233.workstation.server.dto.SystemStats.NetworkStats;
import cn.xiaozhou233.workstation.server.dto.SystemStats.OsStats;
@Service
public class SystemInfoService {
private final OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
OperatingSystemMXBean.class);
public SystemStats getSystemStats() {
return new SystemStats(
getCpuStats(),
getMemoryStats(),
getDiskStats(),
getNetworkStats(),
getOsStats());
}
private CpuStats getCpuStats() {
double usage = Math.max(0, osBean.getCpuLoad() * 100);
double processUsage = Math.max(0, osBean.getProcessCpuLoad() * 100);
return new CpuStats(
detectCpuModel(),
osBean.getAvailableProcessors(),
round(usage),
round(processUsage));
}
private MemoryStats getMemoryStats() {
long total = osBean.getTotalMemorySize();
long free = osBean.getFreeMemorySize();
long used = total - free;
return new MemoryStats(
total,
used,
free,
round(total == 0 ? 0 : (double) used / total * 100),
osBean.getTotalSwapSpaceSize(),
osBean.getTotalSwapSpaceSize() - osBean.getFreeSwapSpaceSize());
}
private List<DiskStats> getDiskStats() {
List<DiskStats> disks = new ArrayList<>();
for (File root : File.listRoots()) {
long total = root.getTotalSpace();
long free = root.getUsableSpace();
long used = total - free;
disks.add(new DiskStats(
root.getPath(),
total,
used,
free,
round(total == 0 ? 0 : (double) used / total * 100),
!root.canWrite()));
}
return disks;
}
private List<NetworkStats> getNetworkStats() {
List<NetworkStats> networks = new ArrayList<>();
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface ni : Collections.list(interfaces)) {
if (ni.isLoopback() || !ni.isUp()) {
continue;
}
List<String> addresses = new ArrayList<>();
ni.getInterfaceAddresses().forEach(addr -> {
if (addr.getAddress() != null) {
addresses.add(addr.getAddress().getHostAddress());
}
});
networks.add(new NetworkStats(
ni.getName(),
ni.getDisplayName(),
ni.isUp(),
ni.getMTU(),
addresses));
}
} catch (Exception e) {
throw new RuntimeException("Failed to collect network info", e);
}
return networks;
}
private OsStats getOsStats() {
String hostname;
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
hostname = System.getenv("COMPUTERNAME");
}
return new OsStats(
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"),
System.getProperty("java.version"),
hostname,
ManagementFactory.getRuntimeMXBean().getUptime() / 1000);
}
private String detectCpuModel() {
String model = System.getenv("PROCESSOR_IDENTIFIER");
if (model != null && !model.isBlank()) {
return model;
}
try {
java.nio.file.Path cpuInfo = java.nio.file.Path.of("/proc/cpuinfo");
if (java.nio.file.Files.exists(cpuInfo)) {
for (String line : java.nio.file.Files.readAllLines(cpuInfo)) {
if (line.startsWith("model name")) {
return line.substring(line.indexOf(':') + 1).trim();
}
}
}
} catch (Exception ignored) {
// fall through
}
return "Unknown";
}
private double round(double value) {
return Math.round(value * 10) / 10.0;
}
}
@@ -1,6 +0,0 @@
server:
port: 9018
spring:
application:
name: server
@@ -1,13 +0,0 @@
package cn.xiaozhou233.workstation.server;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ServerApplicationTests {
@Test
void contextLoads() {
}
}
+2 -2
View File
@@ -18,7 +18,7 @@ interface OsStats {
name: string
version: string
arch: string
javaVersion: string
goVersion: string
uptimeSeconds: number
}
@@ -152,7 +152,7 @@ export default function Home() {
<span className="text-sm text-slate-500">
{stats.os.name} {stats.os.version} · {stats.os.arch}
</span>
<span className="text-sm text-slate-500">Java {stats.os.javaVersion}</span>
<span className="text-sm text-slate-500">Go {stats.os.goVersion}</span>
</div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 lg:divide-x lg:divide-slate-100">
+2
View File
@@ -7,6 +7,7 @@ services:
restart: unless-stopped
expose:
- "9018"
mem_limit: 128m
frontend:
build:
@@ -19,6 +20,7 @@ services:
image: workstation-dashboard:${BUILD_NUMBER:-latest}
container_name: workstation-dashboard
restart: unless-stopped
mem_limit: 128m
depends_on:
- backend
ports: