This commit is contained in:
2025-10-05 20:08:52 +08:00
parent acdf544b08
commit ca793b4de7
31 changed files with 4714 additions and 81 deletions

View File

@@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf

33
reisa-admin/reisaAdminSpring/.gitignore vendored Normal file
View File

@@ -0,0 +1,33 @@
HELP.md
target/
.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

View File

@@ -0,0 +1,3 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip

295
reisa-admin/reisaAdminSpring/mvnw vendored Executable file
View File

@@ -0,0 +1,295 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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
#
# http://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
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"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

189
reisa-admin/reisaAdminSpring/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,189 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

View File

@@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.ast</groupId>
<artifactId>reisaAdminSpring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>reisaAdminSpring</name>
<description>reisaAdminSpring</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>25</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JSch library for SSH connections -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,15 @@
package org.ast.reisaadminspring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class ReisaAdminSpringApplication {
public static void main(String[] args) {
SpringApplication.run(ReisaAdminSpringApplication.class, args);
}
}

View File

@@ -0,0 +1,141 @@
package org.ast.reisaadminspring.api;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;
import jakarta.annotation.PostConstruct;
import org.ast.reisaadminspring.been.Server;
import org.ast.reisaadminspring.been.Status;
import org.ast.reisaadminspring.dao.ServerDao;
import org.ast.reisaadminspring.dao.StatusDao;
import org.ast.reisaadminspring.service.SystemStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/v1")
public class ApiServerV1 {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ApiServerV1.class);
@Autowired
private ServerDao serverDao;
@Autowired
private StatusDao statusDao;
@Autowired
private SystemStatusService systemStatusService;
private static Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (src, typeOfSrc, context) ->
new JsonPrimitive(src.toString()))
.setPrettyPrinting()
.create();
private static final Map<String, Status> statusMap = new ConcurrentHashMap<>();
private static volatile List<Server> tempServerList = new CopyOnWriteArrayList<>();
@PostConstruct
@Scheduled(fixedRate = 60000)
public void updateStatus() {
// 使用 CompletableFuture 异步执行每个服务器的状态获取
for (String ip : statusMap.keySet()) {
for (Server server : tempServerList) {
if (server.getIpAddress().equals(ip)) {
CompletableFuture.runAsync(() -> {
try {
log.info("Updating status for server: {}", server.getName());
Status status = systemStatusService.getStatus(
server.getIpAddress(),
server.getSshUsername(),
server.getSshPassword()
);
statusMap.put(ip, status);
server.setOutIpAddress(status.getPublicIp());
serverDao.save(server);
statusDao.save(status);
log.info("Status updated for server: {}", server.getName());
} catch (Exception e) {
// 异常处理
log.error("Error updating status for server: {}", server.getName(), e);
e.printStackTrace();
}
});
break;
}
}
}
}
@GetMapping("/status/history/{ip}")
public List<Status> getStatus(@PathVariable String ip, @RequestParam(defaultValue = "0", required = false) int limit) {
List<Status> statuses = statusDao.findByHostOrderByTimestampDesc(ip);
if (limit > 0) {
return statuses.stream().limit(limit).collect(Collectors.toList());
}
return statuses;
}
@GetMapping("/server")
public List<Server> getAllServers() {
List<Server> serverList = serverDao.findAll();
// 使用更高效的比较方式
boolean needsUpdate = tempServerList.size() != serverList.size();
if (!needsUpdate) {
for (int i = 0; i < serverList.size(); i++) {
if (!serverList.get(i).getId().equals(tempServerList.get(i).getId())) {
needsUpdate = true;
break;
}
}
}
if (needsUpdate) {
tempServerList = new ArrayList<>(serverList);
// 只更新变化的部分
updateStatusMap(serverList);
}
// 为每个服务器设置当前状态
for (Server server : serverList) {
server.setDevice(statusMap.get(server.getIpAddress()));
}
return serverList;
}
private void updateStatusMap(List<Server> serverList) {
Set<String> currentIps = serverList.stream()
.map(Server::getIpAddress)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
// 移除不再存在的服务器状态
statusMap.keySet().removeIf(ip -> !currentIps.contains(ip));
// 添加新服务器的初始状态
for (Server server : serverList) {
if (server.getIpAddress() != null && !statusMap.containsKey(server.getIpAddress())) {
statusMap.put(server.getIpAddress(), new Status());
}
}
}
@PostMapping("/server")
public Server addServer(@RequestBody Server server) {
return serverDao.save(server);
}
@PutMapping("/server")
public Server updateServer(@RequestBody Server server) {
return serverDao.save(server);
}
@DeleteMapping("/server")
public void deleteServer(@RequestBody Server server) {
serverDao.delete(server);
}
}

View File

@@ -0,0 +1,139 @@
package org.ast.reisaadminspring.been;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Server {
@Id
private String id;
private String name;
private String place;
private String ipAddress;
private String outIpAddress;
private String status;
private int sshPort ;
private String sshUsername;
private String sshPassword;
private String baoTaLogin;
private String baoTaUsername;
private String baoTaPassword;
@Transient
private Status device;
public String getId() {
return id;
}
public void setStatus(Status device) {
this.device = device;
}
public String getPlace() {
return place;
}
public Status getDevice() {
return device;
}
public void setDevice(Status device) {
this.device = device;
}
public void setPlace(String place) {
this.place = place;
}
public int getSshPort() {
return sshPort;
}
public void setSshPort(int sshPort) {
this.sshPort = sshPort;
}
public String getSshUsername() {
return sshUsername;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setSshUsername(String sshUsername) {
this.sshUsername = sshUsername;
}
public String getSshPassword() {
return sshPassword;
}
public void setSshPassword(String sshPassword) {
this.sshPassword = sshPassword;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getOutIpAddress() {
return outIpAddress;
}
public void setOutIpAddress(String outIpAddress) {
this.outIpAddress = outIpAddress;
}
public String getBaoTaLogin() {
return baoTaLogin;
}
public void setBaoTaLogin(String baoTaLogin) {
this.baoTaLogin = baoTaLogin;
}
public String getBaoTaUsername() {
return baoTaUsername;
}
public void setBaoTaUsername(String baoTaUsername) {
this.baoTaUsername = baoTaUsername;
}
public String getBaoTaPassword() {
return baoTaPassword;
}
public void setBaoTaPassword(String baoTaPassword) {
this.baoTaPassword = baoTaPassword;
}
}

View File

@@ -0,0 +1,579 @@
package org.ast.reisaadminspring.been;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.LocalDateTime;
import java.util.List;
@Document
public class Status {
private String id;
private String host;
private Long time;
private LocalDateTime timestamp;
private CpuInfo cpuInfo;
private MemoryInfo memoryInfo;
private List<GpuInfo> gpuInfo;
private String uptime;
private String publicIp;
private List<DiskInfo> diskUsage;
private List<NetworkInfo> networkInfo;
private List<ProcessInfo> processes;
private LoadAverage loadAverage;
private String systemInfo;
private String error;
// Constructors
public Status() {}
public Long getTime() {
return time;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setTime(Long time) {
this.time = time;
}
// Getters and Setters
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public CpuInfo getCpuInfo() {
return cpuInfo;
}
public void setCpuInfo(CpuInfo cpuInfo) {
this.cpuInfo = cpuInfo;
}
public MemoryInfo getMemoryInfo() {
return memoryInfo;
}
public void setMemoryInfo(MemoryInfo memoryInfo) {
this.memoryInfo = memoryInfo;
}
public List<GpuInfo> getGpuInfo() {
return gpuInfo;
}
public void setGpuInfo(List<GpuInfo> gpuInfo) {
this.gpuInfo = gpuInfo;
}
public String getUptime() {
return uptime;
}
public void setUptime(String uptime) {
this.uptime = uptime;
}
public String getPublicIp() {
return publicIp;
}
public void setPublicIp(String publicIp) {
this.publicIp = publicIp;
}
public List<DiskInfo> getDiskUsage() {
return diskUsage;
}
public void setDiskUsage(List<DiskInfo> diskUsage) {
this.diskUsage = diskUsage;
}
public List<NetworkInfo> getNetworkInfo() {
return networkInfo;
}
public void setNetworkInfo(List<NetworkInfo> networkInfo) {
this.networkInfo = networkInfo;
}
public List<ProcessInfo> getProcesses() {
return processes;
}
public void setProcesses(List<ProcessInfo> processes) {
this.processes = processes;
}
public LoadAverage getLoadAverage() {
return loadAverage;
}
public void setLoadAverage(LoadAverage loadAverage) {
this.loadAverage = loadAverage;
}
public String getSystemInfo() {
return systemInfo;
}
public void setSystemInfo(String systemInfo) {
this.systemInfo = systemInfo;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
// 内部类定义
public static class CpuInfo {
private String modelName;
private int sockets;
private int coresPerSocket;
private int threadsPerCore;
private double usagePercent;
// Getters and Setters
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public int getSockets() {
return sockets;
}
public void setSockets(int sockets) {
this.sockets = sockets;
}
public int getCoresPerSocket() {
return coresPerSocket;
}
public void setCoresPerSocket(int coresPerSocket) {
this.coresPerSocket = coresPerSocket;
}
public int getThreadsPerCore() {
return threadsPerCore;
}
public void setThreadsPerCore(int threadsPerCore) {
this.threadsPerCore = threadsPerCore;
}
public double getUsagePercent() {
return usagePercent;
}
public void setUsagePercent(double usagePercent) {
this.usagePercent = usagePercent;
}
}
public static class MemoryInfo {
private long totalBytes;
private long usedBytes;
private long freeBytes;
private long sharedBytes;
private long buffCacheBytes;
private long availableBytes;
private double usagePercent;
// Getters and Setters
public long getTotalBytes() {
return totalBytes;
}
public void setTotalBytes(long totalBytes) {
this.totalBytes = totalBytes;
}
public long getUsedBytes() {
return usedBytes;
}
public void setUsedBytes(long usedBytes) {
this.usedBytes = usedBytes;
}
public long getFreeBytes() {
return freeBytes;
}
public void setFreeBytes(long freeBytes) {
this.freeBytes = freeBytes;
}
public long getSharedBytes() {
return sharedBytes;
}
public void setSharedBytes(long sharedBytes) {
this.sharedBytes = sharedBytes;
}
public long getBuffCacheBytes() {
return buffCacheBytes;
}
public void setBuffCacheBytes(long buffCacheBytes) {
this.buffCacheBytes = buffCacheBytes;
}
public long getAvailableBytes() {
return availableBytes;
}
public void setAvailableBytes(long availableBytes) {
this.availableBytes = availableBytes;
}
public double getUsagePercent() {
return usagePercent;
}
public void setUsagePercent(double usagePercent) {
this.usagePercent = usagePercent;
}
}
// 在 Status.java 中更新 GpuInfo 类
public static class GpuInfo {
private String name;
private long memoryUsedBytes;
private long memoryTotalBytes;
private double gpuUtilizationPercent;
private List<GpuProcess> processes; // 新增GPU进程信息
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getMemoryUsedBytes() {
return memoryUsedBytes;
}
public void setMemoryUsedBytes(long memoryUsedBytes) {
this.memoryUsedBytes = memoryUsedBytes;
}
public long getMemoryTotalBytes() {
return memoryTotalBytes;
}
public void setMemoryTotalBytes(long memoryTotalBytes) {
this.memoryTotalBytes = memoryTotalBytes;
}
public double getGpuUtilizationPercent() {
return gpuUtilizationPercent;
}
public void setGpuUtilizationPercent(double gpuUtilizationPercent) {
this.gpuUtilizationPercent = gpuUtilizationPercent;
}
public List<GpuProcess> getProcesses() {
return processes;
}
public void setProcesses(List<GpuProcess> processes) {
this.processes = processes;
}
// GPU进程信息内部类
public static class GpuProcess {
private int pid;
private String processName;
private long usedGpuMemoryBytes;
private double gpuUtilizationPercent;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getProcessName() {
return processName;
}
public void setProcessName(String processName) {
this.processName = processName;
}
public long getUsedGpuMemoryBytes() {
return usedGpuMemoryBytes;
}
public void setUsedGpuMemoryBytes(long usedGpuMemoryBytes) {
this.usedGpuMemoryBytes = usedGpuMemoryBytes;
}
public double getGpuUtilizationPercent() {
return gpuUtilizationPercent;
}
public void setGpuUtilizationPercent(double gpuUtilizationPercent) {
this.gpuUtilizationPercent = gpuUtilizationPercent;
}
}
}
public static class DiskInfo {
private String filesystem;
private long sizeBytes;
private long usedBytes;
private long availableBytes;
private double usagePercent;
private String mountPoint;
// Getters and Setters
public String getFilesystem() {
return filesystem;
}
public void setFilesystem(String filesystem) {
this.filesystem = filesystem;
}
public long getSizeBytes() {
return sizeBytes;
}
public void setSizeBytes(long sizeBytes) {
this.sizeBytes = sizeBytes;
}
public long getUsedBytes() {
return usedBytes;
}
public void setUsedBytes(long usedBytes) {
this.usedBytes = usedBytes;
}
public long getAvailableBytes() {
return availableBytes;
}
public void setAvailableBytes(long availableBytes) {
this.availableBytes = availableBytes;
}
public double getUsagePercent() {
return usagePercent;
}
public void setUsagePercent(double usagePercent) {
this.usagePercent = usagePercent;
}
public String getMountPoint() {
return mountPoint;
}
public void setMountPoint(String mountPoint) {
this.mountPoint = mountPoint;
}
}
public static class NetworkInfo {
private String interfaceName;
private String status;
private List<String> ipAddresses;
// Getters and Setters
public String getInterfaceName() {
return interfaceName;
}
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<String> getIpAddresses() {
return ipAddresses;
}
public void setIpAddresses(List<String> ipAddresses) {
this.ipAddresses = ipAddresses;
}
}
public static class ProcessInfo {
private String user;
private int pid;
private double cpuPercent;
private double memoryPercent;
private long virtualMemorySize;
private long residentSetSize;
private String tty;
private String state;
private String startTime;
private String time;
private String command;
// Getters and Setters
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public double getCpuPercent() {
return cpuPercent;
}
public void setCpuPercent(double cpuPercent) {
this.cpuPercent = cpuPercent;
}
public double getMemoryPercent() {
return memoryPercent;
}
public void setMemoryPercent(double memoryPercent) {
this.memoryPercent = memoryPercent;
}
public long getVirtualMemorySize() {
return virtualMemorySize;
}
public void setVirtualMemorySize(long virtualMemorySize) {
this.virtualMemorySize = virtualMemorySize;
}
public long getResidentSetSize() {
return residentSetSize;
}
public void setResidentSetSize(long residentSetSize) {
this.residentSetSize = residentSetSize;
}
public String getTty() {
return tty;
}
public void setTty(String tty) {
this.tty = tty;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
public static class LoadAverage {
private double oneMinute;
private double fiveMinutes;
private double fifteenMinutes;
// Getters and Setters
public double getOneMinute() {
return oneMinute;
}
public void setOneMinute(double oneMinute) {
this.oneMinute = oneMinute;
}
public double getFiveMinutes() {
return fiveMinutes;
}
public void setFiveMinutes(double fiveMinutes) {
this.fiveMinutes = fiveMinutes;
}
public double getFifteenMinutes() {
return fifteenMinutes;
}
public void setFifteenMinutes(double fifteenMinutes) {
this.fifteenMinutes = fifteenMinutes;
}
}
}

View File

@@ -0,0 +1,9 @@
package org.ast.reisaadminspring.dao;
import org.ast.reisaadminspring.been.Server;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Service;
@Service
public interface ServerDao extends MongoRepository<Server, String> {
}

View File

@@ -0,0 +1,15 @@
package org.ast.reisaadminspring.dao;
import org.ast.reisaadminspring.been.Server;
import org.ast.reisaadminspring.been.Status;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface StatusDao extends MongoRepository<Status, String> {
List<Status> findByHost(String host);
List<Status> findByHostOrderByTimestampDesc(String ip);
}

View File

@@ -0,0 +1,449 @@
package org.ast.reisaadminspring.service;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;
import com.jcraft.jsch.*;
import org.ast.reisaadminspring.been.Status;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
public class SystemStatusService {
public static void main(String[] args) {
SystemStatusService service = new SystemStatusService();
Status status = service.getStatus("100.80.156.98", "mainrunner", "abcdef20060113");
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (src, typeOfSrc, context) ->
new JsonPrimitive(src.toString()))
.setPrettyPrinting()
.create();
System.out.println(gson.toJson(status));
}
/**
* 通过SSH获取远程Linux服务器的状态信息
* @param host 主机地址
* @param username 用户名
* @param password 密码
* @return Status对象包含系统详细信息
*/
public Status getStatus(String host, String username, String password) {
Status status = new Status();
JSch jsch = new JSch();
try {
Session session = jsch.getSession(username, host, 22);
session.setPassword(password);
// 设置SSH配置
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// 连接并认证
session.connect(30000); // 30秒超时
// 获取系统信息
status.setHost(host);
status.setTimestamp(LocalDateTime.now());
status.setCpuInfo(parseCpuInfo(getCpuInfo(session), getCpuUsage(session)));
status.setMemoryInfo(parseMemoryInfo(getMemoryInfo(session), getMemoryUsage(session)));
status.setGpuInfo(parseGpuInfo(getGpuInfo(session)));
status.setUptime(getUptime(session));
status.setPublicIp(getPublicIp(session));
status.setDiskUsage(parseDiskInfo(getDiskUsage(session)));
status.setNetworkInfo(parseNetworkInfo(getNetworkInfo(session)));
status.setProcesses(parseProcesses(getProcesses(session)));
status.setLoadAverage(parseLoadAverage(getLoadAverage(session)));
status.setSystemInfo(getSystemInfo(session));
status.setTime(System.currentTimeMillis());
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
// 处理异常情况
status.setError(e.getMessage());
}
return status;
}
/**
* 获取CPU信息
*/
private String getCpuInfo(Session session) throws Exception {
return executeCommand(session, "LANG=en_US.UTF-8 lscpu | grep -E 'Model name|Socket|Core|Thread'");
}
/**
* 获取CPU使用率
*/
private String getCpuUsage(Session session) throws Exception {
return executeCommand(session, "LANG=en_US.UTF-8 top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | sed 's/us,//'");
}
/**
* 获取GPU信息 (NVIDIA)
*/
private String getGpuInfo(Session session) throws Exception {
try {
// 获取GPU基本信息
String basicInfo = executeCommand(session, "nvidia-smi --query-gpu=name,memory.used,memory.total,utilization.gpu --format=csv");
// 获取GPU进程信息
String processInfo = executeCommand(session, "nvidia-smi pmon -c 1");
return basicInfo + "\n---PROCESS_INFO---\n" + processInfo;
} catch (Exception e) {
return "No NVIDIA GPU detected or nvidia-smi not available";
}
}
/**
* 获取内存信息
*/
private String getMemoryInfo(Session session) throws Exception {
return executeCommand(session, "LANG=en_US.UTF-8 free -b | grep Mem"); // 使用字节单位
}
/**
* 获取内存使用率
*/
private String getMemoryUsage(Session session) throws Exception {
return executeCommand(session, "LANG=en_US.UTF-8 free | grep Mem | awk '{printf(\"%.2f\"), $3/$2 * 100.0}'");
}
/**
* 获取系统运行时间
*/
private String getUptime(Session session) throws Exception {
return executeCommand(session, "LANG=en_US.UTF-8 uptime -p");
}
/**
* 获取公网IP地址
*/
private String getPublicIp(Session session) throws Exception {
try {
return executeCommand(session, "curl -s icanhazip.com");
} catch (Exception e) {
return "Unable to retrieve public IP";
}
}
/**
* 获取磁盘使用情况
*/
private String getDiskUsage(Session session) throws Exception {
return executeCommand(session, "LANG=en_US.UTF-8 df -B1 | grep -E '^/dev/'"); // 使用字节单位
}
/**
* 获取网络接口信息
*/
private String getNetworkInfo(Session session) throws Exception {
return executeCommand(session, "LANG=en_US.UTF-8 ip -br addr show | grep UP");
}
/**
* 获取进程列表 (前10个最占用资源的进程)
*/
private String getProcesses(Session session) throws Exception {
return executeCommand(session, "LANG=en_US.UTF-8 ps aux --sort=-%cpu | head -11");
}
/**
* 获取系统负载
*/
private String getLoadAverage(Session session) throws Exception {
return executeCommand(session, "LANG=en_US.UTF-8 uptime | awk -F'load average:' '{print $2}'");
}
/**
* 获取系统基本信息
*/
private String getSystemInfo(Session session) throws Exception {
return executeCommand(session, "LANG=en_US.UTF-8 uname -a");
}
/**
* 执行SSH命令
*/
private String executeCommand(Session session, String command) throws Exception {
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
StringBuilder output = new StringBuilder();
channel.connect();
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
channel.disconnect();
return output.toString().trim();
}
/**
* 解析CPU信息
*/
private Status.CpuInfo parseCpuInfo(String cpuInfoStr, String cpuUsageStr) {
Status.CpuInfo cpuInfo = new Status.CpuInfo();
if (cpuInfoStr != null && !cpuInfoStr.isEmpty()) {
String[] lines = cpuInfoStr.split("\n");
for (String line : lines) {
if (line.contains("Model name:") && !line.contains("BIOS Model")) {
// 处理不同的Model name格式
String[] parts = line.split(":", 2); // 只分割第一个冒号
if (parts.length >= 2) {
cpuInfo.setModelName(parts[1].trim());
}
} else if (line.contains("Model name:") && line.contains("BIOS Model")) {
String[] parts = line.split(":", 2);
cpuInfo.setModelName(cpuInfo.getModelName() + " " + parts[1].trim().replace(cpuInfo.getModelName(),""));
} else if (line.contains("Socket(s):")) {
try {
String value = line.split(":")[1].trim();
// 处理可能包含额外描述的情况
value = value.split("\\s+")[0]; // 只取第一个数字部分
cpuInfo.setSockets(Integer.parseInt(value));
} catch (NumberFormatException e) {
cpuInfo.setSockets(1); // 默认值
}
} else if (line.contains("Core(s) per socket:")) {
try {
String value = line.split(":")[1].trim();
value = value.split("\\s+")[0];
cpuInfo.setCoresPerSocket(Integer.parseInt(value));
} catch (NumberFormatException e) {
cpuInfo.setCoresPerSocket(1);
}
} else if (line.contains("Thread(s) per core:")) {
try {
String value = line.split(":")[1].trim();
value = value.split("\\s+")[0];
cpuInfo.setThreadsPerCore(Integer.parseInt(value));
} catch (NumberFormatException e) {
cpuInfo.setThreadsPerCore(1);
}
}
}
}
if (cpuUsageStr != null && !cpuUsageStr.isEmpty()) {
try {
cpuInfo.setUsagePercent(Double.parseDouble(cpuUsageStr.replace("%", "").trim()));
} catch (NumberFormatException e) {
cpuInfo.setUsagePercent(0.0);
}
}
return cpuInfo;
}
/**
* 解析内存信息
*/
private Status.MemoryInfo parseMemoryInfo(String memoryInfoStr, String memoryUsageStr) {
Status.MemoryInfo memoryInfo = new Status.MemoryInfo();
if (memoryInfoStr != null && !memoryInfoStr.isEmpty()) {
String[] parts = memoryInfoStr.split("\\s+");
if (parts.length >= 7) {
try {
memoryInfo.setTotalBytes(Long.parseLong(parts[1]));
memoryInfo.setUsedBytes(Long.parseLong(parts[2]));
memoryInfo.setFreeBytes(Long.parseLong(parts[3]));
memoryInfo.setSharedBytes(Long.parseLong(parts[4]));
memoryInfo.setBuffCacheBytes(Long.parseLong(parts[5]));
memoryInfo.setAvailableBytes(Long.parseLong(parts[6]));
} catch (NumberFormatException e) {
// 忽略解析错误
}
}
}
if (memoryUsageStr != null && !memoryUsageStr.isEmpty()) {
try {
memoryInfo.setUsagePercent(Double.parseDouble(memoryUsageStr.trim()));
} catch (NumberFormatException e) {
memoryInfo.setUsagePercent(0.0);
}
}
return memoryInfo;
}
/**
* 解析GPU信息
*/
private List<Status.GpuInfo> parseGpuInfo(String gpuInfoStr) {
List<Status.GpuInfo> gpuInfos = new ArrayList<>();
if (gpuInfoStr != null && !gpuInfoStr.isEmpty() &&
!gpuInfoStr.contains("No NVIDIA GPU detected")) {
String[] lines = gpuInfoStr.split("\n");
for (int i = 1; i < lines.length; i++) { // 跳过标题行
String[] parts = lines[i].split(",");
if (parts.length >= 4) {
Status.GpuInfo gpuInfo = new Status.GpuInfo();
gpuInfo.setName(parts[0].trim());
try {
// 解析内存使用情况 (去掉单位MiB)
String memoryUsedStr = parts[1].trim().replace(" MiB", "");
String memoryTotalStr = parts[2].trim().replace(" MiB", "");
gpuInfo.setMemoryUsedBytes(Long.parseLong(memoryUsedStr) * 1024 * 1024);
gpuInfo.setMemoryTotalBytes(Long.parseLong(memoryTotalStr) * 1024 * 1024);
// 解析GPU利用率 (去掉单位%)
String utilizationStr = parts[3].trim().replace(" %", "");
gpuInfo.setGpuUtilizationPercent(Double.parseDouble(utilizationStr));
} catch (NumberFormatException e) {
// 忽略解析错误
}
gpuInfos.add(gpuInfo);
}
}
}
return gpuInfos;
}
/**
* 解析磁盘信息
*/
private List<Status.DiskInfo> parseDiskInfo(String diskInfoStr) {
List<Status.DiskInfo> diskInfos = new ArrayList<>();
if (diskInfoStr != null && !diskInfoStr.isEmpty()) {
String[] lines = diskInfoStr.split("\n");
for (String line : lines) {
String[] parts = line.trim().split("\\s+");
if (parts.length >= 6) {
Status.DiskInfo diskInfo = new Status.DiskInfo();
diskInfo.setFilesystem(parts[0]);
try {
diskInfo.setSizeBytes(Long.parseLong(parts[1]));
diskInfo.setUsedBytes(Long.parseLong(parts[2]));
diskInfo.setAvailableBytes(Long.parseLong(parts[3]));
// 解析使用百分比 (去掉%符号)
String usagePercentStr = parts[4].replace("%", "");
diskInfo.setUsagePercent(Double.parseDouble(usagePercentStr));
diskInfo.setMountPoint(parts[5]);
} catch (NumberFormatException e) {
// 忽略解析错误
}
diskInfos.add(diskInfo);
}
}
}
return diskInfos;
}
/**
* 解析网络信息
*/
private List<Status.NetworkInfo> parseNetworkInfo(String networkInfoStr) {
List<Status.NetworkInfo> networkInfos = new ArrayList<>();
if (networkInfoStr != null && !networkInfoStr.isEmpty()) {
String[] lines = networkInfoStr.split("\n");
for (String line : lines) {
String[] parts = line.trim().split("\\s+");
if (parts.length >= 3) {
Status.NetworkInfo networkInfo = new Status.NetworkInfo();
networkInfo.setInterfaceName(parts[0]);
networkInfo.setStatus(parts[1]);
List<String> ipAddresses = new ArrayList<>();
for (int i = 2; i < parts.length; i++) {
ipAddresses.add(parts[i]);
}
networkInfo.setIpAddresses(ipAddresses);
networkInfos.add(networkInfo);
}
}
}
return networkInfos;
}
/**
* 解析进程信息
*/
private List<Status.ProcessInfo> parseProcesses(String processesStr) {
List<Status.ProcessInfo> processInfos = new ArrayList<>();
if (processesStr != null && !processesStr.isEmpty()) {
String[] lines = processesStr.split("\n");
// 跳过标题行
for (int i = 1; i < lines.length; i++) {
String[] parts = lines[i].trim().split("\\s+", 11);
if (parts.length >= 11) {
Status.ProcessInfo processInfo = new Status.ProcessInfo();
processInfo.setUser(parts[0]);
try {
processInfo.setPid(Integer.parseInt(parts[1]));
processInfo.setCpuPercent(Double.parseDouble(parts[2]));
processInfo.setMemoryPercent(Double.parseDouble(parts[3]));
processInfo.setVirtualMemorySize(Long.parseLong(parts[4]));
processInfo.setResidentSetSize(Long.parseLong(parts[5]));
processInfo.setTty(parts[6]);
processInfo.setState(parts[7]);
processInfo.setStartTime(parts[8]);
processInfo.setTime(parts[9]);
processInfo.setCommand(parts[10]);
} catch (NumberFormatException e) {
// 忽略解析错误
}
processInfos.add(processInfo);
}
}
}
return processInfos;
}
/**
* 解析负载平均值
*/
private Status.LoadAverage parseLoadAverage(String loadAverageStr) {
Status.LoadAverage loadAverage = new Status.LoadAverage();
if (loadAverageStr != null && !loadAverageStr.isEmpty()) {
String[] parts = loadAverageStr.trim().split(",");
if (parts.length >= 3) {
try {
loadAverage.setOneMinute(Double.parseDouble(parts[0].trim()));
loadAverage.setFiveMinutes(Double.parseDouble(parts[1].trim()));
loadAverage.setFifteenMinutes(Double.parseDouble(parts[2].trim()));
} catch (NumberFormatException e) {
// 忽略解析错误
}
}
}
return loadAverage;
}
}

View File

@@ -0,0 +1,6 @@
spring.application.name=reisaAdminSpring
spring.data.mongodb.uri=mongodb://reisaAdmin:nbAC8hi8xdJeBDDT@100.80.156.98:27017/reisaadmin
server.port=48102
spring.data.redis.host=127.0.0.1
spring.data.redis.port: 6379