feat: Initialize backend with Spring Boot and Gradle
- Add Gradle wrapper files for project setup. - Create main application class for Spring Boot. - Implement CORS configuration for API. - Add system information controller and service to fetch system stats. - Define data transfer objects for system stats. - Configure application properties for server port and name. - Add unit test for application context loading. - Create example environment file for frontend API base URL.
This commit is contained in:
1 parent
d07ce0f427
commit
9dd1bc3cf9
18 files changed
+843
-69
No files matched your search
@@ -0,0 +1,3 @@
|
||||
/gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
@@ -0,0 +1,37 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### 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/
|
||||
@@ -0,0 +1,33 @@
|
||||
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()
|
||||
}
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,9 @@
|
||||
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
|
||||
Vendored
+248
@@ -0,0 +1,248 @@
|
||||
#!/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" "$@"
|
||||
Vendored
+82
@@ -0,0 +1,82 @@
|
||||
@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%
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = 'server'
|
||||
@@ -0,0 +1,13 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
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("*");
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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) {
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
server:
|
||||
port: 9018
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: server
|
||||
@@ -0,0 +1,13 @@
|
||||
package cn.xiaozhou233.workstation.server;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class ServerApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# 后端 API 基础地址
|
||||
# 开发环境留空即可(走 Vite 代理,避免 CORS);生产环境按需指定,例如 http://your-server:9018
|
||||
VITE_API_BASE_URL=
|
||||
+175
-69
@@ -1,62 +1,95 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
const features = [
|
||||
{
|
||||
title: '实时监控',
|
||||
description: '集中查看各服务器在线状态与 CPU、内存、磁盘使用情况,运行状况一目了然。',
|
||||
bg: 'bg-indigo-50 text-indigo-600',
|
||||
icon: (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="size-6">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M2.25 12.75V12A2.25 2.25 0 014.5 9.75h15A2.25 2.25 0 0121.75 12v.75m-8.69-6.44l-2.12-2.12a1.5 1.5 0 00-1.061-.44H4.5A2.25 2.25 0 002.25 6v12a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9a2.25 2.25 0 00-2.25-2.25h-5.379a1.5 1.5 0 01-1.06-.44z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '任务管理',
|
||||
description: '统一管理各服务器上的任务,创建、跟踪与批量执行尽在掌控。',
|
||||
bg: 'bg-emerald-50 text-emerald-600',
|
||||
icon: (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="size-6">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '自动化',
|
||||
description: '编排自动化流程与定时调度,让重复工作自动完成,释放人力。',
|
||||
bg: 'bg-amber-50 text-amber-600',
|
||||
icon: (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="size-6">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"
|
||||
/>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '日志中心',
|
||||
description: '统一收集与检索各服务器运行日志,问题定位更加高效。',
|
||||
bg: 'bg-rose-50 text-rose-600',
|
||||
icon: (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="size-6">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M6.75 7.5l3 2.25-3 2.25m4.5 0h3m-9 8.25h13.5A2.25 2.25 0 0021 18V6a2.25 2.25 0 00-2.25-2.25H5.25A2.25 2.25 0 003 6v12a2.25 2.25 0 002.25 2.25z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
]
|
||||
interface CpuStats {
|
||||
model: string
|
||||
cores: number
|
||||
usagePercent: number
|
||||
}
|
||||
|
||||
interface MemoryStats {
|
||||
usagePercent: number
|
||||
}
|
||||
|
||||
interface OsStats {
|
||||
name: string
|
||||
version: string
|
||||
arch: string
|
||||
javaVersion: string
|
||||
uptimeSeconds: number
|
||||
}
|
||||
|
||||
interface SystemStats {
|
||||
cpu: CpuStats
|
||||
memory: MemoryStats
|
||||
os: OsStats
|
||||
}
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL ?? ''
|
||||
|
||||
function formatUptime(seconds: number) {
|
||||
const d = Math.floor(seconds / 86400)
|
||||
const h = Math.floor((seconds % 86400) / 3600)
|
||||
const m = Math.floor((seconds % 3600) / 60)
|
||||
if (d > 0) return `${d} 天 ${h} 小时`
|
||||
if (h > 0) return `${h} 小时 ${m} 分钟`
|
||||
return `${m} 分钟`
|
||||
}
|
||||
|
||||
function UsageBar({ percent }: { percent: number }) {
|
||||
return (
|
||||
<div className="mt-3 h-2 w-full overflow-hidden rounded-full bg-slate-100">
|
||||
<div
|
||||
className="h-full rounded-full bg-indigo-500 transition-all"
|
||||
style={{ width: `${Math.min(100, Math.max(0, percent))}%` }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function StatItem({
|
||||
icon,
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
icon: React.ReactNode
|
||||
label: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2 px-6 py-4 text-center">
|
||||
<div className="grid size-11 shrink-0 place-items-center rounded-lg bg-indigo-50 text-indigo-600">
|
||||
{icon}
|
||||
</div>
|
||||
<p className="text-sm font-semibold text-slate-900">{label}</p>
|
||||
<div className="w-full">{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const iconProps = {
|
||||
fill: 'none',
|
||||
viewBox: '0 0 24 24',
|
||||
strokeWidth: 1.8,
|
||||
stroke: 'currentColor',
|
||||
className: 'size-6',
|
||||
'aria-hidden': true,
|
||||
} as const
|
||||
|
||||
export default function Home() {
|
||||
const [stats, setStats] = useState<SystemStats | null>(null)
|
||||
const [error, setError] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
fetch(`${API_BASE}/api/system/stats`)
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error('Failed to fetch stats')
|
||||
return res.json()
|
||||
})
|
||||
.then((data: SystemStats) => setStats(data))
|
||||
.catch(() => setError(true))
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div>
|
||||
<section className="relative flex h-[calc(100vh-4rem)] items-center justify-center overflow-hidden">
|
||||
@@ -75,21 +108,94 @@ export default function Home() {
|
||||
|
||||
<section className="border-t border-slate-200 py-20">
|
||||
<div className="mx-auto max-w-6xl px-6">
|
||||
<h2 className="text-center text-2xl font-semibold text-slate-900">功能展示</h2>
|
||||
<p className="mt-1 text-center text-sm text-slate-500">JuiceWorkStation 提供的核心能力</p>
|
||||
<div className="mt-10 grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{features.map((feature) => (
|
||||
<div
|
||||
key={feature.title}
|
||||
className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm transition-shadow hover:shadow-md"
|
||||
>
|
||||
<div className={`grid size-11 place-items-center rounded-lg ${feature.bg}`}>
|
||||
{feature.icon}
|
||||
</div>
|
||||
<h3 className="mt-4 font-semibold text-slate-900">{feature.title}</h3>
|
||||
<p className="mt-2 text-sm leading-relaxed text-slate-500">{feature.description}</p>
|
||||
<h2 className="text-center text-2xl font-semibold text-slate-900">系统状态</h2>
|
||||
<p className="mt-1 text-center text-sm text-slate-500">
|
||||
{error
|
||||
? '无法获取系统信息,请确认后端服务已启动'
|
||||
: stats
|
||||
? '实时运行状态一览'
|
||||
: '正在获取系统信息…'}
|
||||
</p>
|
||||
|
||||
<div className="mt-10 rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
|
||||
{stats ? (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4 lg:divide-x lg:divide-slate-100">
|
||||
<StatItem
|
||||
icon={
|
||||
<svg {...iconProps}>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25m18 0A2.25 2.25 0 0018.75 3H5.25A2.25 2.25 0 003 5.25m18 0V12a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 12V5.25"
|
||||
/>
|
||||
</svg>
|
||||
}
|
||||
label="CPU 占用率"
|
||||
>
|
||||
<span className="text-2xl font-bold text-slate-900">
|
||||
{stats.cpu.usagePercent}%
|
||||
</span>
|
||||
<UsageBar percent={stats.cpu.usagePercent} />
|
||||
</StatItem>
|
||||
|
||||
<StatItem
|
||||
icon={
|
||||
<svg {...iconProps}>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M8.25 3v1.5M4.5 8.25H3m18 0h-1.5M4.5 12H3m18 0h-1.5m-15 3.75H3m18 0h-1.5M8.25 19.5V21M12 3v1.5m0 15V21m3.75-18v1.5m0 15V21m-9-1.5h10.5a2.25 2.25 0 002.25-2.25V6.75a2.25 2.25 0 00-2.25-2.25H6.75A2.25 2.25 0 004.5 6.75v10.5a2.25 2.25 0 002.25 2.25z"
|
||||
/>
|
||||
</svg>
|
||||
}
|
||||
label="内存占用率"
|
||||
>
|
||||
<span className="text-2xl font-bold text-slate-900">
|
||||
{stats.memory.usagePercent}%
|
||||
</span>
|
||||
<UsageBar percent={stats.memory.usagePercent} />
|
||||
</StatItem>
|
||||
|
||||
<StatItem
|
||||
icon={
|
||||
<svg {...iconProps}>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M8.25 3v1.5M4.5 8.25H3m18 0h-1.5M4.5 12H3m18 0h-1.5m-15 3.75H3m18 0h-1.5M8.25 19.5V21M12 3v1.5m0 15V21m3.75-18v1.5m0 15V21m-9-1.5h10.5a2.25 2.25 0 002.25-2.25V6.75a2.25 2.25 0 00-2.25-2.25H6.75A2.25 2.25 0 004.5 6.75v10.5a2.25 2.25 0 002.25 2.25z"
|
||||
/>
|
||||
</svg>
|
||||
}
|
||||
label="系统与运行环境"
|
||||
>
|
||||
<p className="text-sm text-slate-600">
|
||||
{stats.os.name} {stats.os.version} · {stats.os.arch}
|
||||
</p>
|
||||
<p className="text-sm text-slate-600">Java {stats.os.javaVersion}</p>
|
||||
</StatItem>
|
||||
|
||||
<StatItem
|
||||
icon={
|
||||
<svg {...iconProps}>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
}
|
||||
label="开机时间"
|
||||
>
|
||||
<span className="text-2xl font-bold text-slate-900">
|
||||
{formatUptime(stats.os.uptimeSeconds)}
|
||||
</span>
|
||||
</StatItem>
|
||||
</div>
|
||||
))}
|
||||
) : (
|
||||
<p className="py-16 text-center text-sm text-slate-400">
|
||||
{error ? '无法获取系统信息,请确认后端服务已启动' : '正在获取系统信息…'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -5,4 +5,12 @@ import tailwindcss from '@tailwindcss/vite'
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:9018',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in new issue
Block a user