diff --git a/backend/.gitattributes b/backend/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/backend/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/backend/.gitignore @@ -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/ diff --git a/backend/build.gradle b/backend/build.gradle new file mode 100644 index 0000000..ce10ec7 --- /dev/null +++ b/backend/build.gradle @@ -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() +} diff --git a/backend/gradle/wrapper/gradle-wrapper.jar b/backend/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b1b8ef5 Binary files /dev/null and b/backend/gradle/wrapper/gradle-wrapper.jar differ diff --git a/backend/gradle/wrapper/gradle-wrapper.properties b/backend/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..df6a6ad --- /dev/null +++ b/backend/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/backend/gradlew b/backend/gradlew new file mode 100644 index 0000000..b9bb139 --- /dev/null +++ b/backend/gradlew @@ -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" "$@" diff --git a/backend/gradlew.bat b/backend/gradlew.bat new file mode 100644 index 0000000..24c62d5 --- /dev/null +++ b/backend/gradlew.bat @@ -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% diff --git a/backend/settings.gradle b/backend/settings.gradle new file mode 100644 index 0000000..096502d --- /dev/null +++ b/backend/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'server' diff --git a/backend/src/main/java/cn/xiaozhou233/workstation/server/ServerApplication.java b/backend/src/main/java/cn/xiaozhou233/workstation/server/ServerApplication.java new file mode 100644 index 0000000..4614750 --- /dev/null +++ b/backend/src/main/java/cn/xiaozhou233/workstation/server/ServerApplication.java @@ -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); + } + +} diff --git a/backend/src/main/java/cn/xiaozhou233/workstation/server/config/WebConfig.java b/backend/src/main/java/cn/xiaozhou233/workstation/server/config/WebConfig.java new file mode 100644 index 0000000..132a2c7 --- /dev/null +++ b/backend/src/main/java/cn/xiaozhou233/workstation/server/config/WebConfig.java @@ -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("*"); + } +} diff --git a/backend/src/main/java/cn/xiaozhou233/workstation/server/controller/SystemInfoController.java b/backend/src/main/java/cn/xiaozhou233/workstation/server/controller/SystemInfoController.java new file mode 100644 index 0000000..0cc2eb9 --- /dev/null +++ b/backend/src/main/java/cn/xiaozhou233/workstation/server/controller/SystemInfoController.java @@ -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(); + } +} diff --git a/backend/src/main/java/cn/xiaozhou233/workstation/server/dto/SystemStats.java b/backend/src/main/java/cn/xiaozhou233/workstation/server/dto/SystemStats.java new file mode 100644 index 0000000..7e513c1 --- /dev/null +++ b/backend/src/main/java/cn/xiaozhou233/workstation/server/dto/SystemStats.java @@ -0,0 +1,27 @@ +package cn.xiaozhou233.workstation.server.dto; + +import java.util.List; + +public record SystemStats( + CpuStats cpu, + MemoryStats memory, + List disks, + List 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 addresses) { + } + + public record OsStats(String name, String version, String arch, String javaVersion, String hostname, + long uptimeSeconds) { + } +} diff --git a/backend/src/main/java/cn/xiaozhou233/workstation/server/service/SystemInfoService.java b/backend/src/main/java/cn/xiaozhou233/workstation/server/service/SystemInfoService.java new file mode 100644 index 0000000..77444f5 --- /dev/null +++ b/backend/src/main/java/cn/xiaozhou233/workstation/server/service/SystemInfoService.java @@ -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 getDiskStats() { + List 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 getNetworkStats() { + List networks = new ArrayList<>(); + try { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + for (NetworkInterface ni : Collections.list(interfaces)) { + if (ni.isLoopback() || !ni.isUp()) { + continue; + } + List 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; + } +} diff --git a/backend/src/main/resources/application.yaml b/backend/src/main/resources/application.yaml new file mode 100644 index 0000000..6ecaeb8 --- /dev/null +++ b/backend/src/main/resources/application.yaml @@ -0,0 +1,6 @@ +server: + port: 9018 + +spring: + application: + name: server diff --git a/backend/src/test/java/cn/xiaozhou233/workstation/server/ServerApplicationTests.java b/backend/src/test/java/cn/xiaozhou233/workstation/server/ServerApplicationTests.java new file mode 100644 index 0000000..6532540 --- /dev/null +++ b/backend/src/test/java/cn/xiaozhou233/workstation/server/ServerApplicationTests.java @@ -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() { + } + +} diff --git a/dashboard/.env.example b/dashboard/.env.example new file mode 100644 index 0000000..4a41c09 --- /dev/null +++ b/dashboard/.env.example @@ -0,0 +1,3 @@ +# 后端 API 基础地址 +# 开发环境留空即可(走 Vite 代理,避免 CORS);生产环境按需指定,例如 http://your-server:9018 +VITE_API_BASE_URL= diff --git a/dashboard/src/pages/Home.tsx b/dashboard/src/pages/Home.tsx index c62b5f8..b9b0e56 100644 --- a/dashboard/src/pages/Home.tsx +++ b/dashboard/src/pages/Home.tsx @@ -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: ( - - - - ), - }, - { - title: '任务管理', - description: '统一管理各服务器上的任务,创建、跟踪与批量执行尽在掌控。', - bg: 'bg-emerald-50 text-emerald-600', - icon: ( - - - - ), - }, - { - title: '自动化', - description: '编排自动化流程与定时调度,让重复工作自动完成,释放人力。', - bg: 'bg-amber-50 text-amber-600', - icon: ( - - - - - ), - }, - { - title: '日志中心', - description: '统一收集与检索各服务器运行日志,问题定位更加高效。', - bg: 'bg-rose-50 text-rose-600', - icon: ( - - - - ), - }, -] +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 ( +
+
+
+ ) +} + +function StatItem({ + icon, + label, + children, +}: { + icon: React.ReactNode + label: string + children: React.ReactNode +}) { + return ( +
+
+ {icon} +
+

{label}

+
{children}
+
+ ) +} + +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(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 (
@@ -75,21 +108,94 @@ export default function Home() {
-

功能展示

-

JuiceWorkStation 提供的核心能力

-
- {features.map((feature) => ( -
-
- {feature.icon} -
-

{feature.title}

-

{feature.description}

+

系统状态

+

+ {error + ? '无法获取系统信息,请确认后端服务已启动' + : stats + ? '实时运行状态一览' + : '正在获取系统信息…'} +

+ +
+ {stats ? ( +
+ + + + } + label="CPU 占用率" + > + + {stats.cpu.usagePercent}% + + + + + + + + } + label="内存占用率" + > + + {stats.memory.usagePercent}% + + + + + + + + } + label="系统与运行环境" + > +

+ {stats.os.name} {stats.os.version} · {stats.os.arch} +

+

Java {stats.os.javaVersion}

+
+ + + + + } + label="开机时间" + > + + {formatUptime(stats.os.uptimeSeconds)} + +
- ))} + ) : ( +

+ {error ? '无法获取系统信息,请确认后端服务已启动' : '正在获取系统信息…'} +

+ )}
diff --git a/dashboard/vite.config.ts b/dashboard/vite.config.ts index c4069b7..14f7ceb 100644 --- a/dashboard/vite.config.ts +++ b/dashboard/vite.config.ts @@ -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, + }, + }, + }, })