jenkins CICD

This commit is contained in:
sophie committed 2026-04-24 14:26:26 +08:00
1 parent c5f868a8ef
commit d710a88d04
20 files changed
+1174 -25

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
.git
.gitignore
.venv
venv
**/__pycache__/
**/*.pyc
**/*.pyo
**/*.log
frontend/node_modules
frontend/dist
backend/venv
backend/local_test.db
deploy
docs
tmp_restore
tests
+1 -14
View File
@@ -1,10 +1,9 @@
# Environments
deploy.sh
deploy_docker_rsync.sh
docs/
venv/
backend/venv/
env/
# .env
.venv
build/
@@ -56,15 +55,3 @@ Thumbs.db
# Runtime files
.run/
docker-compose.yml
nginx.conf
deploy_docker_rsync.sh
gunicorn_config.py
hxops_menu.sh
nginx.conf
docker-compose.yml
gunicorn_config.py
hxops_menu.sh
Vendored
+138
View File
@@ -0,0 +1,138 @@
pipeline {
agent any
options {
timestamps()
disableConcurrentBuilds()
}
environment {
DEPLOY_CONFIG_CHANGED = 'false'
}
stages {
stage('Checkout') {
steps {
echo "[Checkout] BRANCH_NAME=${env.BRANCH_NAME}, GIT_BRANCH=${env.GIT_BRANCH}, commit=${env.GIT_COMMIT}"
checkout scm
}
}
stage('Detect Changes') {
steps {
script {
def branchName = env.BRANCH_NAME?.trim()
def baseCommit = env.GIT_PREVIOUS_SUCCESSFUL_COMMIT?.trim()
if (!baseCommit) {
baseCommit = sh(
returnStdout: true,
script: 'git rev-parse HEAD^ 2>/dev/null || true'
).trim()
}
List<String> changedFiles = []
if (baseCommit) {
changedFiles = sh(
returnStdout: true,
script: "git diff --name-only ${baseCommit} ${env.GIT_COMMIT}"
).trim().split('\n').findAll { it?.trim() }
} else {
changedFiles = ['frontend/', 'backend/']
}
def frontendChanged = changedFiles.any { it.startsWith('frontend/') }
def backendChanged = changedFiles.any { it.startsWith('backend/') }
def deployConfigChanged = changedFiles.any {
it.startsWith('deploy/') ||
it == 'docker-compose.yml' ||
it == 'Jenkinsfile' ||
it == 'scripts/deploy_compose.sh' ||
it == 'scripts/healthcheck.sh'
}
env.FRONTEND_CHANGED = frontendChanged ? 'true' : 'false'
env.BACKEND_CHANGED = backendChanged ? 'true' : 'false'
env.DEPLOY_CONFIG_CHANGED = deployConfigChanged ? 'true' : 'false'
env.FRONTEND_IMAGE = "hxops-frontend:${branchName}-${env.BUILD_NUMBER}"
env.BACKEND_IMAGE = "hxops-backend:${branchName}-${env.BUILD_NUMBER}"
echo "[Detect Changes] branchName=${branchName}, BRANCH_NAME=${env.BRANCH_NAME}, GIT_BRANCH=${env.GIT_BRANCH}"
echo "[Detect Changes] baseCommit=${baseCommit ?: 'none'}"
echo "[Detect Changes] changedFiles=${changedFiles.join(', ')}"
echo "[Detect Changes] FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
echo "[Detect Changes] FRONTEND_IMAGE=${env.FRONTEND_IMAGE}"
echo "[Detect Changes] BACKEND_IMAGE=${env.BACKEND_IMAGE}"
}
}
}
stage('Build Frontend Image') {
when {
expression { env.FRONTEND_CHANGED == 'true' }
}
steps {
echo "[Build Frontend Image] start"
sh '''
set -e
docker build -f frontend/Dockerfile -t "$FRONTEND_IMAGE" frontend
'''
echo "[Build Frontend Image] done"
}
}
stage('Build Backend Image') {
when {
expression { env.BACKEND_CHANGED == 'true' }
}
steps {
echo "[Build Backend Image] start"
sh '''
set -e
docker build -f backend/Dockerfile -t "$BACKEND_IMAGE" backend
'''
echo "[Build Backend Image] done"
}
}
stage('Deploy Local') {
when {
expression {
env.BRANCH_NAME in ['dev', 'sophie', 'test', 'prod'] &&
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
}
}
steps {
script {
def targetEnv = env.BRANCH_NAME == 'sophie' ? 'dev' : env.BRANCH_NAME
if (targetEnv == 'prod') {
input message: 'Confirm deployment to production?'
}
def frontendImageArg = env.FRONTEND_CHANGED == 'true' ? env.FRONTEND_IMAGE : ''
def backendImageArg = env.BACKEND_CHANGED == 'true' ? env.BACKEND_IMAGE : ''
echo "[Deploy Local] targetEnv=${targetEnv}, branchName=${env.BRANCH_NAME}, frontendChanged=${env.FRONTEND_CHANGED}, backendChanged=${env.BACKEND_CHANGED}, deployConfigChanged=${env.DEPLOY_CONFIG_CHANGED}"
echo "[Deploy Local] frontendImageArg=${frontendImageArg}"
echo "[Deploy Local] backendImageArg=${backendImageArg}"
sh """
set -e
cd "${WORKSPACE}"
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
./scripts/deploy_compose.sh ${targetEnv} '${frontendImageArg}' '${backendImageArg}' ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
"""
echo "[Deploy Local] deployment command finished"
}
}
}
}
post {
always {
echo "[Post] BRANCH_NAME=${env.BRANCH_NAME}, GIT_BRANCH=${env.GIT_BRANCH}, FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
}
}
}
+8
View File
@@ -0,0 +1,8 @@
venv
__pycache__
*.pyc
*.pyo
local_test.db
.git
.vscode
tests
+1 -1
View File
@@ -1,4 +1,4 @@
from flask import Blueprint, request, jsonify, current_app
from flask import Blueprint, request, jsonify, current_app
from app import db
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
+2 -1
View File
@@ -73,7 +73,8 @@ class DevelopmentConfig(Config):
SQLALCHEMY_DATABASE_URI = os.getenv(
'DATABASE_URL',
#'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
#'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
'postgresql://postgres:123456@localhost:5432/hxops_db',
)
+1 -1
View File
@@ -10,7 +10,7 @@ with app.app_context():
print(f'id={u.id}, username={u.username}, role={u.role}')
print()
print('=== 各用户对 Agent 3 的会话统计 ===')
print('=== 各用户对 Agent 3 的会话统计 ===')
for uid in [1, 2, 3, 4, 5]:
count = db.session.query(func.count(ChatLog.id)).filter(
ChatLog.user_id == uid,
+7
View File
@@ -0,0 +1,7 @@
# Copy this file to .env and fill secrets on server.
BACKEND_IMAGE=registry.example.com/hxops/hxops-backend:dev-placeholder
FRONTEND_IMAGE=registry.example.com/hxops/hxops-frontend:dev-placeholder
# DATABASE_URL=postgresql://postgres:change_me@127.0.0.1:5432/hxops_db
FLASK_APP=run.py
FLASK_ENV=development
+29
View File
@@ -0,0 +1,29 @@
services:
hxops-backend:
image: ${BACKEND_IMAGE}
container_name: hxops-backend
restart: always
env_file:
- .env
extra_hosts:
- "host.docker.internal:host-gateway"
ports:
- "5002:5000"
networks:
- ai-platform
hxops-frontend:
image: ${FRONTEND_IMAGE}
container_name: hxops-frontend
restart: always
depends_on:
- hxops-backend
ports:
- "8890:80"
networks:
- ai-platform
networks:
ai-platform:
name: ai-platform
driver: bridge
+7
View File
@@ -0,0 +1,7 @@
# Copy this file to .env and fill secrets on server.
BACKEND_IMAGE=registry.example.com/hxops/hxops-backend:prod-placeholder
FRONTEND_IMAGE=registry.example.com/hxops/hxops-frontend:prod-placeholder
DATABASE_URL=postgresql://postgres:change_me@127.0.0.1:5432/hxops_db
FLASK_APP=run.py
FLASK_ENV=production
+29
View File
@@ -0,0 +1,29 @@
services:
hxops-backend:
image: ${BACKEND_IMAGE}
container_name: hxops-backend
restart: always
env_file:
- .env
extra_hosts:
- "host.docker.internal:host-gateway"
ports:
- "5002:5000"
networks:
- ai-platform
hxops-frontend:
image: ${FRONTEND_IMAGE}
container_name: hxops-frontend
restart: always
depends_on:
- hxops-backend
ports:
- "8890:80"
networks:
- ai-platform
networks:
ai-platform:
name: ai-platform
driver: bridge
+7
View File
@@ -0,0 +1,7 @@
# Copy this file to .env and fill secrets on server.
BACKEND_IMAGE=registry.example.com/hxops/hxops-backend:test-placeholder
FRONTEND_IMAGE=registry.example.com/hxops/hxops-frontend:test-placeholder
DATABASE_URL=postgresql://postgres:change_me@127.0.0.1:5432/hxops_db
FLASK_APP=run.py
FLASK_ENV=production
+29
View File
@@ -0,0 +1,29 @@
services:
hxops-backend:
image: ${BACKEND_IMAGE}
container_name: hxops-backend
restart: always
env_file:
- .env
extra_hosts:
- "host.docker.internal:host-gateway"
ports:
- "5002:5000"
networks:
- ai-platform
hxops-frontend:
image: ${FRONTEND_IMAGE}
container_name: hxops-frontend
restart: always
depends_on:
- hxops-backend
ports:
- "8890:80"
networks:
- ai-platform
networks:
ai-platform:
name: ai-platform
driver: bridge
+5
View File
@@ -0,0 +1,5 @@
node_modules
dist
.npm-cache
.git
.vscode
+10 -7
View File
@@ -1,12 +1,15 @@
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
# 复制自定义 Nginx 配置
COPY nginx.conf /etc/nginx/conf.d/default.conf
# 复制构建好的静态资源
# 注意:在本地先执行 npm run build,然后将 dist 目录提交或在部署脚本中生成
COPY dist /usr/share/nginx/html
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
CMD ["nginx", "-g", "daemon off;"]
+1 -1
View File
@@ -18,7 +18,7 @@ const count = ref(0)
</div>
<p>
Check out
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
>create-vue</a
>, the official Vue + Vite starter
+1
View File
@@ -8,6 +8,7 @@
* 逻辑关系:
* - 通过 /api/admin/agents 管理 Agent 配置
* - 通过 /api/admin/users 与 /permissions 管理用户可访问的 Agent
* - 这个界面需要优化,进入管理台页面会请求所有接口数据,其实只需要请求dashboard数据
*/
import { ref, onMounted, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
+781
View File
@@ -0,0 +1,781 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if git -C "${SCRIPT_DIR}" rev-parse --show-toplevel >/dev/null 2>&1; then
ROOT_DIR="$(git -C "${SCRIPT_DIR}" rev-parse --show-toplevel)"
elif git -C "${SCRIPT_DIR}/.." rev-parse --show-toplevel >/dev/null 2>&1; then
ROOT_DIR="$(git -C "${SCRIPT_DIR}/.." rev-parse --show-toplevel)"
else
ROOT_DIR="${SCRIPT_DIR}"
fi
RUN_DIR="${ROOT_DIR}/.run"
BACKEND_DIR="${ROOT_DIR}/backend"
FRONTEND_DIR="${ROOT_DIR}/frontend"
BACKEND_PORT=5002
FRONTEND_PORT=8881
DB_PORT=5432
DB_DATA_DIR="/opt/homebrew/var/postgresql@18"
DB_BIN="/opt/homebrew/opt/postgresql@18/bin/postgres"
mkdir -p "${RUN_DIR}"
is_listening() {
local port="$1"
lsof -nP -iTCP:"${port}" -sTCP:LISTEN >/dev/null 2>&1
}
get_lan_ip() {
local ip=""
for iface in en0 en1; do
ip="$(ipconfig getifaddr "${iface}" 2>/dev/null || true)"
if [[ -n "${ip}" ]]; then
echo "${ip}"
return 0
fi
done
ip="$(ifconfig 2>/dev/null | awk '/inet / && $2 != "127.0.0.1" {print $2; exit}')"
if [[ -n "${ip}" ]]; then
echo "${ip}"
fi
}
print_access_links() {
local lan_ip
lan_ip="$(get_lan_ip || true)"
echo "== 访问链接 =="
echo "前端(本机): http://127.0.0.1:${FRONTEND_PORT}"
echo "后端(本机): http://127.0.0.1:${BACKEND_PORT}"
if [[ -n "${lan_ip}" ]]; then
echo "前端(局域网): http://${lan_ip}:${FRONTEND_PORT}"
echo "后端(局域网): http://${lan_ip}:${BACKEND_PORT}"
fi
}
start_project() {
echo "=== 启动 HXOPS 项目 ==="
if is_listening "${DB_PORT}"; then
echo "[数据库] 端口 ${DB_PORT} 已在监听,跳过启动。"
else
echo "[数据库] 正在启动..."
nohup env LC_ALL="en_US.UTF-8" "${DB_BIN}" -D "${DB_DATA_DIR}" > "${RUN_DIR}/postgres.log" 2>&1 &
echo $! > "${RUN_DIR}/postgres.pid"
sleep 2
if is_listening "${DB_PORT}"; then
echo "[数据库] 启动成功,端口 ${DB_PORT}。"
else
echo "[数据库] 启动失败,请查看日志: ${RUN_DIR}/postgres.log"
return 1
fi
fi
if is_listening "${BACKEND_PORT}"; then
echo "[后端] 端口 ${BACKEND_PORT} 已在监听,跳过启动。"
else
echo "[后端] 正在启动..."
(
cd "${BACKEND_DIR}"
source venv/bin/activate
nohup python3 run.py > "${RUN_DIR}/backend.log" 2>&1 &
echo $! > "${RUN_DIR}/backend.pid"
)
sleep 2
if is_listening "${BACKEND_PORT}"; then
echo "[后端] 启动成功,端口 ${BACKEND_PORT}。"
else
echo "[后端] 启动失败,请查看日志: ${RUN_DIR}/backend.log"
return 1
fi
fi
if is_listening "${FRONTEND_PORT}"; then
echo "[前端] 端口 ${FRONTEND_PORT} 已在监听,跳过启动。"
else
echo "[前端] 正在启动..."
(
cd "${FRONTEND_DIR}"
nohup npm run dev > "${RUN_DIR}/frontend.log" 2>&1 &
echo $! > "${RUN_DIR}/frontend.pid"
)
sleep 3
if is_listening "${FRONTEND_PORT}"; then
echo "[前端] 启动成功,端口 ${FRONTEND_PORT}。"
else
echo "[前端] 启动失败,请查看日志: ${RUN_DIR}/frontend.log"
return 1
fi
fi
print_access_links
echo "日志目录: ${RUN_DIR}"
}
kill_by_pid_file() {
local name="$1"
local pid_file="$2"
if [[ ! -f "${pid_file}" ]]; then
echo "[${name}] 未找到 PID 文件,跳过。"
return
fi
local pid
pid="$(cat "${pid_file}")"
if [[ -z "${pid}" ]] || ! kill -0 "${pid}" >/dev/null 2>&1; then
echo "[${name}] PID ${pid:-<empty>} 不存在,清理 PID 文件。"
rm -f "${pid_file}"
return
fi
echo "[${name}] 正在停止进程 PID=${pid}..."
kill "${pid}" >/dev/null 2>&1 || true
for _ in {1..10}; do
if ! kill -0 "${pid}" >/dev/null 2>&1; then
break
fi
sleep 0.5
done
if kill -0 "${pid}" >/dev/null 2>&1; then
echo "[${name}] 进程未退出,执行强制停止 PID=${pid}。"
kill -9 "${pid}" >/dev/null 2>&1 || true
fi
rm -f "${pid_file}"
echo "[${name}] 已停止。"
}
kill_by_port_if_needed() {
local name="$1"
local port="$2"
local pids
pids="$(lsof -ti tcp:${port} 2>/dev/null || true)"
if [[ -z "${pids}" ]]; then
return
fi
echo "[${name}] 检测到端口 ${port} 仍有进程: ${pids},尝试终止..."
for pid in ${pids}; do
kill "${pid}" >/dev/null 2>&1 || true
done
sleep 1
pids="$(lsof -ti tcp:${port} 2>/dev/null || true)"
if [[ -n "${pids}" ]]; then
for pid in ${pids}; do
kill -9 "${pid}" >/dev/null 2>&1 || true
done
fi
}
stop_project() {
echo "=== 关闭 HXOPS 项目 ==="
kill_by_pid_file "后端" "${RUN_DIR}/backend.pid"
kill_by_pid_file "前端" "${RUN_DIR}/frontend.pid"
kill_by_port_if_needed "后端" "${BACKEND_PORT}"
kill_by_port_if_needed "前端" "${FRONTEND_PORT}"
kill_by_pid_file "数据库" "${RUN_DIR}/postgres.pid"
kill_by_port_if_needed "数据库" "${DB_PORT}"
echo "关闭完成。"
}
push_gitee() {
echo "=== 上传代码到 Gitee ==="
if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "当前目录不是 Git 仓库,已退出。"
return 1
fi
local remote_url
remote_url="$(git -C "${ROOT_DIR}" remote get-url origin 2>/dev/null || true)"
if [[ -z "${remote_url}" ]]; then
echo "未找到 origin 远程仓库,请先配置后再上传。"
return 1
fi
if [[ "${remote_url}" != *"gitee.com"* ]]; then
echo "警告: 当前 origin 不是 Gitee: ${remote_url}"
read -r -p "仍要继续 push 到 origin 吗? (y/N): " force_push
if [[ ! "${force_push}" =~ ^[Yy]$ ]]; then
echo "已取消。"
return 0
fi
fi
local branch
branch="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD)"
local migration_check_script="${BACKEND_DIR}/scripts/ci_check_migrations.sh"
if [[ -x "${migration_check_script}" ]]; then
echo "== 提交前检查: 数据库结构一致性 =="
(
cd "${BACKEND_DIR}"
"${migration_check_script}"
) || {
echo "检查未通过,已阻止 commit/push。"
echo "请先修复 models/migrations/database 不一致问题后重试。"
return 1
}
else
echo "警告: 未找到可执行检查脚本 ${migration_check_script},跳过结构检查。"
fi
if [[ -n "$(git -C "${ROOT_DIR}" status --porcelain)" ]]; then
git -C "${ROOT_DIR}" add -A
read -r -p "请输入提交说明(留空使用默认): " commit_msg
if [[ -z "${commit_msg:-}" ]]; then
commit_msg="chore: update $(date '+%Y-%m-%d %H:%M:%S')"
fi
if [[ -n "$(git -C "${ROOT_DIR}" diff --cached --name-only)" ]]; then
git -C "${ROOT_DIR}" commit -m "${commit_msg}"
fi
else
echo "工作区无变更,将直接 push 当前分支。"
fi
echo "推送分支: ${branch} -> origin/${branch}"
git -C "${ROOT_DIR}" push origin "${branch}"
echo "上传完成。"
}
show_status() {
echo "== 项目服务状态 =="
if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
local compose_table
compose_table="$(docker compose -p hxops ps --format 'table {{.Name}}\t{{.Image}}\t{{.Command}}\t{{.Service}}\t{{.CreatedAt}}\t{{.State}}\t{{.Publishers}}' 2>/dev/null || true)"
if [[ -n "${compose_table}" ]]; then
echo "${compose_table}"
else
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
"NAME" "IMAGE" "COMMAND" "SERVICE" "CREATED" "STATUS" "PORTS"
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
"hxops-backend" "hxops-hxops-backend" "\"python3 run.py\"" "hxops-backend" "-" \
"$(is_listening "${BACKEND_PORT}" && echo "Up" || echo "Down")" \
"0.0.0.0:${BACKEND_PORT}->${BACKEND_PORT}/tcp, [::]:${BACKEND_PORT}->${BACKEND_PORT}/tcp"
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
"hxops-frontend" "hxops-hxops-frontend" "\"npm run dev\"" "hxops-frontend" "-" \
"$(is_listening "${FRONTEND_PORT}" && echo "Up" || echo "Down")" \
"0.0.0.0:${FRONTEND_PORT}->${FRONTEND_PORT}/tcp, [::]:${FRONTEND_PORT}->${FRONTEND_PORT}/tcp"
fi
else
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
"NAME" "IMAGE" "COMMAND" "SERVICE" "CREATED" "STATUS" "PORTS"
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
"hxops-backend" "hxops-hxops-backend" "\"python3 run.py\"" "hxops-backend" "-" \
"$(is_listening "${BACKEND_PORT}" && echo "Up" || echo "Down")" \
"0.0.0.0:${BACKEND_PORT}->${BACKEND_PORT}/tcp, [::]:${BACKEND_PORT}->${BACKEND_PORT}/tcp"
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
"hxops-frontend" "hxops-hxops-frontend" "\"npm run dev\"" "hxops-frontend" "-" \
"$(is_listening "${FRONTEND_PORT}" && echo "Up" || echo "Down")" \
"0.0.0.0:${FRONTEND_PORT}->${FRONTEND_PORT}/tcp, [::]:${FRONTEND_PORT}->${FRONTEND_PORT}/tcp"
fi
echo "=== 当前状态 ==="
if is_listening "${DB_PORT}"; then
echo "数据库: 运行中 (端口 ${DB_PORT})"
else
echo "数据库: 未运行"
fi
if is_listening "${BACKEND_PORT}"; then
echo "后端: 运行中 (端口 ${BACKEND_PORT})"
else
echo "后端: 未运行"
fi
if is_listening "${FRONTEND_PORT}"; then
echo "前端: 运行中 (端口 ${FRONTEND_PORT})"
else
echo "前端: 未运行"
fi
print_access_links
}
show_dev_open_ports() {
echo "=== 开发服务端口扫描(排除 macOS 常规系统服务) ==="
echo "说明: 仅显示当前用户 ${USER} 打开的 TCP 监听端口。"
echo ""
printf "%-20s %-8s %-24s\n" "进程名" "PID" "监听地址"
printf "%-20s %-8s %-24s\n" "--------------------" "--------" "------------------------"
local output
output="$(
lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null \
| awk -v user="${USER}" '
function ignored(cmd) {
return (cmd ~ /^(ControlCe|rapportd|cfprefsd|trustd|sharingd|identitys)$/)
}
NR > 1 && $3 == user {
if (ignored($1)) next
endpoint = $(NF-1)
key = $1 "|" $2 "|" endpoint
if (!seen[key]++) {
printf "%-20s %-8s %-24s\n", $1, $2, endpoint
}
}
'
)"
if [[ -z "${output}" ]]; then
echo "未发现当前用户启动的监听端口。"
return
fi
echo "${output}"
}
show_non_system_open_ports() {
echo "=== 非系统端口扫描(全量监听端口 - macOS 系统服务) ==="
echo "说明: 扫描所有 TCP 监听端口,过滤系统进程后按服务分组展示。"
local rows
rows="$(
lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null \
| awk '
NR > 1 {
cmd = $1
pid = $2
user = $3
endpoint = $(NF-1)
key = pid "|" endpoint
if (!seen[key]++) {
print pid "\t" user "\t" cmd "\t" endpoint
}
}
'
)"
if [[ -z "${rows}" ]]; then
echo "未发现监听端口。"
return
fi
local tmp_dir
tmp_dir="$(mktemp -d)"
trap 'rm -rf "${tmp_dir}"' RETURN
local f_openclaw="${tmp_dir}/openclaw.txt"
local f_hxops="${tmp_dir}/hxops.txt"
local f_central="${tmp_dir}/central.txt"
local f_erp="${tmp_dir}/erp.txt"
local f_pg="${tmp_dir}/pg.txt"
local f_other="${tmp_dir}/other.txt"
touch "${f_openclaw}" "${f_hxops}" "${f_central}" "${f_erp}" "${f_pg}" "${f_other}"
local matched=0
while IFS=$'\t' read -r pid user cmd endpoint; do
[[ -z "${pid}" ]] && continue
local full_cmd bin_path
full_cmd="$(ps -p "${pid}" -o command= 2>/dev/null || true)"
bin_path="${full_cmd%% *}"
# 过滤典型系统账号与系统二进制路径
if [[ "${user}" == _* ]]; then
continue
fi
if [[ "${bin_path}" == /System/* || "${bin_path}" == /usr/libexec/* ]]; then
continue
fi
# 过滤常见 macOS 系统守护进程
case "${cmd}" in
launchd|syslogd|mDNSResponder|distnoted|notifyd|powerd|configd|kernelmanagerd|airportd|\
cfprefsd|sharingd|trustd|identityservicesd|ControlCe|rapportd|runningboardd|\
UserEventAgent|logd|securityd|opendirectoryd)
continue
;;
esac
local port group target_file
port="${endpoint##*:}"
if [[ "${port}" == "18789" || "${cmd}" == "DingTalk" ]]; then
group="openclaw"
target_file="${f_openclaw}"
elif [[ "${port}" == "8881" ]]; then
group="hxops"
target_file="${f_hxops}"
elif [[ "${port}" == "8891" ]]; then
group="Central-Auth-Core"
target_file="${f_central}"
elif [[ "${port}" == "8892" ]]; then
group="ERP-Data-Agent"
target_file="${f_erp}"
elif [[ "${port}" == "5432" ]]; then
group="postgresql"
target_file="${f_pg}"
else
group="其它服务"
target_file="${f_other}"
fi
printf "%-20s %-10s %-8s %-24s %-18s\n" "${cmd}" "${user}" "${pid}" "${endpoint}" "${port}" >> "${target_file}"
matched=1
done <<< "${rows}"
if [[ "${matched}" -eq 0 ]]; then
echo "未发现非系统监听端口。"
return
fi
print_group() {
local title="$1"
local file="$2"
[[ ! -s "${file}" ]] && return
echo ""
echo "[$title]"
printf "%-20s %-10s %-8s %-24s %-18s\n" "进程名" "用户" "PID" "监听地址" "端口"
printf "%-20s %-10s %-8s %-24s %-18s\n" "--------------------" "----------" "--------" "------------------------" "------------------"
cat "${file}"
}
print_group "openclaw" "${f_openclaw}"
print_group "hxops" "${f_hxops}"
print_group "Central-Auth-Core" "${f_central}"
print_group "ERP-Data-Agent" "${f_erp}"
print_group "postgresql" "${f_pg}"
print_group "其它服务" "${f_other}"
}
show_local_changes_detail() {
echo "=== 本地改动详情(相对上游分支 @{u}) ==="
if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "当前目录不是 Git 仓库。"
return 1
fi
local branch upstream
branch="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD)"
upstream="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || true)"
if [[ -z "${upstream}" ]]; then
echo "当前分支 ${branch} 未设置上游分支,无法执行: git diff --stat @{u}.."
echo "可先执行: git branch --set-upstream-to origin/${branch} ${branch}"
return 1
fi
echo "当前分支: ${branch}"
echo "上游分支: ${upstream}"
echo ""
echo "== 统计(git diff --stat @{u}..) =="
git -C "${ROOT_DIR}" -c color.ui=always diff --stat --color=always '@{u}..' || true
local tracked_files
tracked_files="$(git -C "${ROOT_DIR}" diff --name-only '@{u}..' || true)"
if [[ -z "${tracked_files}" ]]; then
echo ""
echo "当前相对 ${upstream} 没有改动。"
return 0
fi
echo ""
echo "== 文件改动内容(彩色) =="
while IFS= read -r f; do
[[ -z "${f}" ]] && continue
echo ""
echo "---- ${f} ----"
git -C "${ROOT_DIR}" -c color.ui=always diff --color=always '@{u}..' -- "${f}" || true
done <<< "${tracked_files}"
}
show_remote_branch_changes_detail() {
echo "=== 远端分支改动详情(仅远端新增) ==="
if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "当前目录不是 Git 仓库。"
return 1
fi
local current_branch target_branch remote_ref
current_branch="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD)"
read -r -p "请输入远端分支名(默认 ${current_branch}): " target_branch
target_branch="${target_branch:-${current_branch}}"
remote_ref="origin/${target_branch}"
if ! git -C "${ROOT_DIR}" fetch origin "${target_branch}" --prune >/dev/null 2>&1; then
echo "警告: 拉取 origin/${target_branch} 失败,尝试使用本地已缓存的远端引用继续。"
fi
if ! git -C "${ROOT_DIR}" show-ref --verify --quiet "refs/remotes/${remote_ref}"; then
echo "未找到本地远端引用 ${remote_ref}。"
echo "请先确认分支存在,或手动执行: git fetch origin ${target_branch}"
return 1
fi
local remote_numstat remote_files
remote_numstat="$(git -C "${ROOT_DIR}" diff --numstat HEAD..${remote_ref} || true)"
remote_files="$(git -C "${ROOT_DIR}" diff --name-only HEAD..${remote_ref} || true)"
if [[ -z "${remote_files}" ]]; then
echo "远端分支相对本地 HEAD 没有新增改动。"
return 0
fi
echo "== 远端相对本地的文件与行数统计 =="
printf "%-10s %-10s %s\n" "ADDED" "DELETED" "FILE"
printf "%-10s %-10s %s\n" "----------" "----------" "------------------------------"
echo "${remote_numstat}" | awk '{printf "%-10s %-10s %s\n", $1, $2, $3}'
echo ""
echo "== 远端新增提交(HEAD..${remote_ref}) =="
git -C "${ROOT_DIR}" log --oneline --decorate HEAD..${remote_ref} | sed -n '1,200p'
echo ""
echo "== 远端每个文件改动内容(HEAD..${remote_ref}) =="
while IFS= read -r f; do
[[ -z "${f}" ]] && continue
echo ""
echo "---- ${f} ----"
git -C "${ROOT_DIR}" diff --no-color HEAD..${remote_ref} -- "${f}" || true
done <<< "${remote_files}"
}
show_local_remote_compare() {
echo "=== 本地与远端差异对比(直观) ==="
if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "当前目录不是 Git 仓库。"
return 1
fi
local current_branch target_branch remote_ref
current_branch="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD)"
read -r -p "请输入远端分支名(默认 ${current_branch}): " target_branch
target_branch="${target_branch:-${current_branch}}"
remote_ref="origin/${target_branch}"
if ! git -C "${ROOT_DIR}" fetch origin "${target_branch}" --prune >/dev/null 2>&1; then
echo "警告: 拉取 origin/${target_branch} 失败,尝试使用本地已缓存的远端引用继续。"
fi
if ! git -C "${ROOT_DIR}" show-ref --verify --quiet "refs/remotes/${remote_ref}"; then
echo "未找到本地远端引用 ${remote_ref}。"
echo "请先确认分支存在,或手动执行: git fetch origin ${target_branch}"
return 1
fi
local ahead behind
read -r ahead behind < <(git -C "${ROOT_DIR}" rev-list --left-right --count HEAD...${remote_ref})
echo "对比分支: HEAD vs ${remote_ref}"
echo "本地领先: ${ahead} 个提交"
echo "远端领先: ${behind} 个提交"
echo ""
echo "== 本地独有提交(${remote_ref}..HEAD) =="
git -C "${ROOT_DIR}" log --oneline --decorate "${remote_ref}..HEAD" | sed -n '1,120p'
echo ""
echo "== 远端独有提交(HEAD..${remote_ref}) =="
git -C "${ROOT_DIR}" log --oneline --decorate "HEAD..${remote_ref}" | sed -n '1,120p'
echo ""
echo "== 双向文件统计(git diff --stat HEAD...${remote_ref}) =="
git -C "${ROOT_DIR}" diff --stat HEAD..."${remote_ref}" || true
echo ""
echo "== 本地相对远端的改动(${remote_ref}..HEAD) =="
git -C "${ROOT_DIR}" diff --stat "${remote_ref}..HEAD" || true
echo ""
echo "== 远端相对本地的改动(HEAD..${remote_ref}) =="
git -C "${ROOT_DIR}" diff --stat "HEAD..${remote_ref}" || true
}
show_all_branches_info() {
echo "=== 分支总览(本地 + 远端) ==="
if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "当前目录不是 Git 仓库。"
return 1
fi
local current_branch local_default remote_default
current_branch="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD 2>/dev/null || echo '-')"
local_default="$(git -C "${ROOT_DIR}" symbolic-ref --short refs/heads/main 2>/dev/null || true)"
if [[ -z "${local_default}" ]]; then
local_default="$(git -C "${ROOT_DIR}" symbolic-ref --short refs/heads/master 2>/dev/null || true)"
fi
remote_default="$(git -C "${ROOT_DIR}" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)"
if ! git -C "${ROOT_DIR}" fetch origin --prune >/dev/null 2>&1; then
echo "警告: fetch origin 失败,将基于当前本地缓存的远端分支信息展示。"
fi
echo "== 本地分支 =="
echo "当前分支: ${current_branch}"
if [[ -n "${local_default}" ]]; then
echo "本地默认分支(按 main/master 识别): ${local_default}"
else
echo "本地默认分支: 未识别(可按团队约定确认)"
fi
git -C "${ROOT_DIR}" branch -vv
echo ""
echo "== 远端分支(origin) =="
if [[ -n "${remote_default}" ]]; then
echo "远端默认分支: ${remote_default}"
else
echo "远端默认分支: 未识别(可执行 git remote set-head origin -a 后重试)"
fi
git -C "${ROOT_DIR}" branch -r
}
run_schema_drift_check() {
echo "=== 检查数据库结构与 SQLAlchemy 模型是否一致 ==="
local python_bin="${BACKEND_DIR}/venv/bin/python3"
local check_script="${BACKEND_DIR}/scripts/check_schema_drift.py"
if [[ ! -x "${python_bin}" ]]; then
echo "未找到 Python: ${python_bin}"
return 1
fi
if [[ ! -f "${check_script}" ]]; then
echo "未找到检查脚本: ${check_script}"
return 1
fi
(
cd "${BACKEND_DIR}"
"${python_bin}" "scripts/check_schema_drift.py"
)
}
run_ci_migration_check() {
echo "=== 运行 CI 同款 migration 漂移检查 ==="
local check_script="${BACKEND_DIR}/scripts/ci_check_migrations.sh"
if [[ ! -x "${check_script}" ]]; then
echo "未找到可执行脚本: ${check_script}"
echo "可先执行: chmod +x ${check_script}"
return 1
fi
(
cd "${BACKEND_DIR}"
"${check_script}"
)
}
install_precommit_hook() {
echo "=== 安装 Git pre-commit Hook ==="
local install_script="${ROOT_DIR}/scripts/install_git_hooks.sh"
if [[ ! -x "${install_script}" ]]; then
echo "未找到可执行脚本: ${install_script}"
echo "可先执行: chmod +x ${install_script}"
return 1
fi
(
cd "${ROOT_DIR}"
"${install_script}"
)
}
show_help() {
cat <<'HELP'
可输入的指令与结果:
start 或 1 -> 启动项目(数据库+后端+前端)
stop 或 2 -> 关闭项目(后端+前端+数据库)
push 或 3 -> 提交并上传到 Gitee(origin)
status或 4 -> 查看服务运行状态
ports 或 5 -> 扫描当前用户开启的开发服务端口
allports或 6 -> 扫描所有非系统监听端口(应用/自装服务)
localchg或 31 -> 查看本地改了哪些文件/多少行/逐文件改动
remotechg或 32 -> 只查看远端分支改了哪些文件/多少行/逐文件改动
compare 或 33 -> 直观对比本地与远端差异(领先提交、双向改动)
branches或 34 -> 查看本地所有分支及默认分支、远端所有分支及默认分支
dbdrift或 41 -> 检查当前数据库结构与 SQLAlchemy 模型是否一致
migci 或 42 -> 运行 CI 同款迁移一致性检查(空库升级+漂移检测)
hook 或 43 -> 安装 pre-commit Hook(改 models 必须带 migration)
help 或 9 -> 再次显示本帮助
help -> 再次显示本帮助
exit 或 0 -> 退出脚本
HELP
}
confirm_and_run() {
local label="$1"
local fn_name="$2"
read -r -p "确认执行【${label}】? (y/N): " confirm
if [[ "${confirm}" =~ ^[Yy]$ ]]; then
"${fn_name}"
else
echo "已取消【${label}】。"
fi
}
main_loop() {
echo "===== HXOPS 单脚本控制台 ====="
show_help
while true; do
echo ""
read -r -p "请输入指令: " cmd
case "${cmd}" in
1|start)
confirm_and_run "启动项目" start_project
;;
2|stop)
confirm_and_run "关闭项目" stop_project
;;
3|push)
confirm_and_run "上传到 Gitee" push_gitee
;;
4|status)
show_status
;;
5|ports|scan)
show_dev_open_ports
;;
6|allports)
show_non_system_open_ports
;;
31|localchg)
show_local_changes_detail
;;
32|remotechg)
show_remote_branch_changes_detail
;;
33|compare)
show_local_remote_compare
;;
34|branches)
show_all_branches_info
;;
41|dbdrift)
run_schema_drift_check
;;
42|migci)
confirm_and_run "CI同款迁移一致性检查" run_ci_migration_check
;;
43|hook)
confirm_and_run "安装 pre-commit Hook" install_precommit_hook
;;
9|help)
show_help
;;
0|exit|quit)
echo "已退出。"
exit 0
;;
"")
echo "请输入有效指令,输入 help 可查看可用命令。"
;;
*)
echo "未知指令: ${cmd},输入 help 可查看可用命令。"
;;
esac
done
}
main_loop
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
set -euo pipefail
ENV_NAME="${1:?Environment is required: dev|test|prod}"
FRONTEND_IMAGE="${2:-}"
BACKEND_IMAGE="${3:-}"
FRONTEND_CHANGED="${4:-false}"
BACKEND_CHANGED="${5:-false}"
DEPLOY_CONFIG_CHANGED="${6:-false}"
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
COMPOSE_FILE="${ROOT_DIR}/deploy/${ENV_NAME}/docker-compose.yml"
ENV_FILE="${ROOT_DIR}/deploy/${ENV_NAME}/.env"
if [[ ! -f "${COMPOSE_FILE}" ]]; then
echo "Missing compose file: ${COMPOSE_FILE}"
exit 1
fi
if [[ ! -f "${ENV_FILE}" ]]; then
echo "Missing env file: ${ENV_FILE}"
exit 1
fi
if docker compose version >/dev/null 2>&1; then
DC_CMD=(docker compose)
elif command -v docker-compose >/dev/null 2>&1; then
DC_CMD=(docker-compose)
else
echo "Missing docker compose command. Install docker compose plugin or docker-compose."
exit 1
fi
echo "Using compose command: ${DC_CMD[*]}"
if [[ -n "${FRONTEND_IMAGE}" ]]; then
export FRONTEND_IMAGE
fi
if [[ -n "${BACKEND_IMAGE}" ]]; then
export BACKEND_IMAGE
fi
cd "${ROOT_DIR}"
services=()
if [[ "${FRONTEND_CHANGED}" == "true" ]]; then
services+=("hxops-frontend")
fi
if [[ "${BACKEND_CHANGED}" == "true" ]]; then
services+=("hxops-backend")
fi
if [[ ${#services[@]} -eq 0 && "${DEPLOY_CONFIG_CHANGED}" == "true" ]]; then
services=("hxops-frontend" "hxops-backend")
fi
if [[ ${#services[@]} -eq 0 ]]; then
echo "No service changes detected, skipping deployment."
exit 0
fi
echo "Deploying environment: ${ENV_NAME}"
echo "Services: ${services[*]}"
"${DC_CMD[@]}" -f "${COMPOSE_FILE}" --env-file "${ENV_FILE}" up -d "${services[@]}"
"${ROOT_DIR}/scripts/healthcheck.sh" "${ENV_NAME}" "${COMPOSE_FILE}" "${ENV_FILE}"
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
set -euo pipefail
ENV_NAME="${1:?Environment is required}"
COMPOSE_FILE="${2:?Compose file path required}"
ENV_FILE="${3:?Env file path required}"
if docker compose version >/dev/null 2>&1; then
DC_CMD=(docker compose)
elif command -v docker-compose >/dev/null 2>&1; then
DC_CMD=(docker-compose)
else
echo "Missing docker compose command. Install docker compose plugin or docker-compose."
exit 1
fi
max_attempts=20
sleep_seconds=3
for ((i=1; i<=max_attempts; i++)); do
status=$("${DC_CMD[@]}" -f "${COMPOSE_FILE}" --env-file "${ENV_FILE}" ps --status running --services | wc -l)
if [[ "${status}" -ge 2 ]]; then
echo "Healthcheck passed for ${ENV_NAME} environment."
exit 0
fi
echo "Healthcheck waiting (${i}/${max_attempts})..."
sleep "${sleep_seconds}"
done
echo "Healthcheck failed for ${ENV_NAME} environment."
"${DC_CMD[@]}" -f "${COMPOSE_FILE}" --env-file "${ENV_FILE}" ps
exit 1