mirror of
https://github.com/whyour/qinglong.git
synced 2026-08-11 19:05:20 +08:00
Compare commits
70
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bb41ebe96 | ||
|
|
d67f33df39 | ||
|
|
24d539fc05 | ||
|
|
214e23a63d | ||
|
|
ddb3ab7ac3 | ||
|
|
da6dac8bf1 | ||
|
|
9b17a41987 | ||
|
|
cdfa6c3c3c | ||
|
|
1953022b99 | ||
|
|
38d84f9f31 | ||
|
|
e92ddb0aed | ||
|
|
a0d57c78c5 | ||
|
|
a942a5686f | ||
|
|
a1ccd9947d | ||
|
|
327c3a317b | ||
|
|
d3016431ce | ||
|
|
5fbff0e1c8 | ||
|
|
3044f63f03 | ||
|
|
369dd13212 | ||
|
|
b5a5fb3be6 | ||
|
|
0ee0b83207 | ||
|
|
5f2d5bb24a | ||
|
|
949d956aef | ||
|
|
96b4c90398 | ||
|
|
7d8feadc78 | ||
|
|
d1dfde3ca9 | ||
|
|
6796068523 | ||
|
|
05f8fd3805 | ||
|
|
946731ac8d | ||
|
|
617cf7e5b4 | ||
|
|
662adc0f9c | ||
|
|
23b41893a3 | ||
|
|
34d4526413 | ||
|
|
ad92e0c2c0 | ||
|
|
c14390cf41 | ||
|
|
fd6b4e4cde | ||
|
|
865e3035b9 | ||
|
|
d8d30c3619 | ||
|
|
4e803df51e | ||
|
|
e8ac195c96 | ||
|
|
c0b7527148 | ||
|
|
ca347c5854 | ||
|
|
4bee3fbdf4 | ||
|
|
b6537e27ef | ||
|
|
0e5b8bef4b | ||
|
|
e06c3571a8 | ||
|
|
c2eac8b8fd | ||
|
|
3aab1233bb | ||
|
|
2fe9470ff0 | ||
|
|
abad29cbf9 | ||
|
|
84d730d510 | ||
|
|
57d58c871e | ||
|
|
bb6d436c19 | ||
|
|
8bc0906949 | ||
|
|
7a8917f8e4 | ||
|
|
66f9457be8 | ||
|
|
0c5e3b5d04 | ||
|
|
400e4770de | ||
|
|
40d4de9017 | ||
|
|
3464c4da61 | ||
|
|
1315578878 | ||
|
|
a1ae08da58 | ||
|
|
66700ebe1a | ||
|
|
07bf0c705b | ||
|
|
fd516977e3 | ||
|
|
c39f4ef846 | ||
|
|
275d8af4e2 | ||
|
|
544c432f49 | ||
|
|
6bec52dca1 | ||
|
|
ce599d306f |
@@ -1,6 +1,11 @@
|
||||
GRPC_PORT=5500
|
||||
BACK_PORT=5700
|
||||
|
||||
# 服务绑定地址,默认 ::(IPv6 通配,双栈系统同时支持 IPv4/IPv6)
|
||||
# 纯 IPv4 环境自动 fallback 到 0.0.0.0,也可手动指定
|
||||
# BIND_HOST=0.0.0.0
|
||||
# BIND_HOST_GRPC=0.0.0.0
|
||||
|
||||
LOG_LEVEL='info'
|
||||
|
||||
JWT_SECRET=
|
||||
|
||||
@@ -11,6 +11,9 @@ on:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
code_gitlab:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -18,14 +21,16 @@ jobs:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: Yikun/hub-mirror-action@master
|
||||
with:
|
||||
src: github/whyour
|
||||
dst: gitlab/whyour
|
||||
dst_key: ${{ secrets.GITLAB_SSH_PK }}
|
||||
dst_token: ${{ secrets.GITLAB_TOKEN }}
|
||||
static_list: "qinglong"
|
||||
force_update: true
|
||||
- name: Push to GitLab
|
||||
run: |
|
||||
set +e
|
||||
mkdir -p ~/.ssh
|
||||
printf '%s\n' "${{ secrets.GITLAB_SSH_PK }}" > ~/.ssh/id_rsa
|
||||
chmod 600 ~/.ssh/id_rsa
|
||||
ssh-keyscan -T 10 gitlab.com >> ~/.ssh/known_hosts 2>/dev/null
|
||||
git remote add gitlab git@gitlab.com:whyour/qinglong.git 2>/dev/null
|
||||
git push --force --all gitlab 2>&1 || echo "::warning::GitLab push failed"
|
||||
git push --force --tags gitlab 2>&1 || echo "::warning::GitLab tags push failed"
|
||||
|
||||
code_gitee:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -33,26 +38,42 @@ jobs:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: Yikun/hub-mirror-action@master
|
||||
with:
|
||||
src: github/whyour
|
||||
dst: gitee/whyour
|
||||
dst_key: ${{ secrets.GITLAB_SSH_PK }}
|
||||
dst_token: ${{ secrets.GITEE_TOKEN }}
|
||||
static_list: "qinglong"
|
||||
force_update: true
|
||||
- name: Push to Gitee
|
||||
env:
|
||||
GITEE_TOKEN: ${{ secrets.GITEE_TOKEN }}
|
||||
run: |
|
||||
set +e
|
||||
mkdir -p ~/.ssh
|
||||
printf '%s\n' "${{ secrets.GITLAB_SSH_PK }}" > ~/.ssh/id_rsa
|
||||
chmod 600 ~/.ssh/id_rsa
|
||||
ssh-keyscan -T 10 gitee.com >> ~/.ssh/known_hosts 2>/dev/null
|
||||
git remote add gitee git@gitee.com:whyour/qinglong.git 2>/dev/null
|
||||
|
||||
if git push --force --all gitee 2>&1; then
|
||||
echo "::notice::Gitee push --all succeeded"
|
||||
else
|
||||
echo "::warning::Push failed, trying to create repo via API..."
|
||||
curl -sS --connect-timeout 30 --max-time 60 \
|
||||
-X POST "https://gitee.com/api/v5/user/repos" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name":"qinglong","private":"false"}' \
|
||||
"?access_token=$GITEE_TOKEN" 2>/dev/null
|
||||
git push --force --all gitee 2>&1 && echo "::notice::Gitee push succeeded after repo creation" || echo "::warning::Gitee push failed after retry"
|
||||
fi
|
||||
git push --force --tags gitee 2>&1 || echo "::warning::Gitee tags push failed"
|
||||
|
||||
build-static:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: "8.3.1"
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: build front and back
|
||||
run: |
|
||||
@@ -64,9 +85,6 @@ jobs:
|
||||
env:
|
||||
GITHUB_REPO: github.com/${{ github.repository_owner }}/qinglong-static
|
||||
GITHUB_BRANCH: ${{ github.ref_name }}
|
||||
REPO_GITEE: git@gitee.com:whyour/qinglong-static.git
|
||||
REPO_GITLAB: git@gitlab.com:whyour/qinglong-static.git
|
||||
PRIVATE_KEY: ${{ secrets.GITLAB_SSH_PK }}
|
||||
run: |
|
||||
mkdir -p tmp
|
||||
cd ./tmp
|
||||
@@ -81,73 +99,83 @@ jobs:
|
||||
needs: build-static
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: Yikun/hub-mirror-action@master
|
||||
with:
|
||||
src: github/whyour
|
||||
dst: gitlab/whyour
|
||||
dst_key: ${{ secrets.GITLAB_SSH_PK }}
|
||||
dst_token: ${{ secrets.GITLAB_TOKEN }}
|
||||
static_list: "qinglong-static"
|
||||
force_update: true
|
||||
- name: Push qinglong-static to GitLab
|
||||
run: |
|
||||
set +e
|
||||
mkdir -p ~/.ssh
|
||||
printf '%s\n' "${{ secrets.GITLAB_SSH_PK }}" > ~/.ssh/id_rsa
|
||||
chmod 600 ~/.ssh/id_rsa
|
||||
ssh-keyscan -T 10 gitlab.com >> ~/.ssh/known_hosts 2>/dev/null
|
||||
git clone --depth=1 --single-branch https://github.com/whyour/qinglong-static.git static-mirror
|
||||
cd static-mirror
|
||||
git remote add gitlab git@gitlab.com:whyour/qinglong-static.git 2>/dev/null
|
||||
git push --force --all gitlab 2>&1 || echo "::warning::GitLab static push failed"
|
||||
git push --force --tags gitlab 2>&1 || echo "::warning::GitLab static tags push failed"
|
||||
|
||||
static_gitee:
|
||||
needs: build-static
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: Yikun/hub-mirror-action@master
|
||||
with:
|
||||
src: github/whyour
|
||||
dst: gitee/whyour
|
||||
dst_key: ${{ secrets.GITLAB_SSH_PK }}
|
||||
dst_token: ${{ secrets.GITEE_TOKEN }}
|
||||
static_list: "qinglong-static"
|
||||
force_update: true
|
||||
- name: Push qinglong-static to Gitee
|
||||
env:
|
||||
GITEE_TOKEN: ${{ secrets.GITEE_TOKEN }}
|
||||
run: |
|
||||
set +e
|
||||
mkdir -p ~/.ssh
|
||||
printf '%s\n' "${{ secrets.GITLAB_SSH_PK }}" > ~/.ssh/id_rsa
|
||||
chmod 600 ~/.ssh/id_rsa
|
||||
ssh-keyscan -T 10 gitee.com >> ~/.ssh/known_hosts 2>/dev/null
|
||||
git clone --depth=1 --single-branch https://github.com/whyour/qinglong-static.git static-mirror
|
||||
cd static-mirror
|
||||
git remote add gitee git@gitee.com:whyour/qinglong-static.git 2>/dev/null
|
||||
|
||||
build:
|
||||
if git push --force --all gitee 2>&1; then
|
||||
echo "::notice::Gitee static push succeeded"
|
||||
else
|
||||
echo "::warning::Push failed, trying to create repo via API..."
|
||||
curl -sS --connect-timeout 30 --max-time 60 \
|
||||
-X POST "https://gitee.com/api/v5/user/repos" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name":"qinglong-static","private":"false"}' \
|
||||
"?access_token=$GITEE_TOKEN" 2>/dev/null
|
||||
git push --force --all gitee 2>&1 && echo "::notice::Gitee static push succeeded after repo creation" || echo "::warning::Gitee static push failed after retry"
|
||||
fi
|
||||
git push --force --tags gitee 2>&1 || echo "::warning::Gitee static tags push failed"
|
||||
|
||||
build-alpine:
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
needs: build-static
|
||||
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Read version from version.yaml
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(grep '^version:' version.yaml | awk '{print $2}')
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "Version: $VERSION"
|
||||
|
||||
- name: Setup timezone
|
||||
uses: szenius/set-timezone@v2.0
|
||||
with:
|
||||
timezoneLinux: Asia/Shanghai
|
||||
run: sudo timedatectl set-timezone Asia/Shanghai
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -155,7 +183,7 @@ jobs:
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: |
|
||||
${{ github.repository }}
|
||||
@@ -169,104 +197,261 @@ jobs:
|
||||
type=semver,pattern={{version}}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@v4
|
||||
with:
|
||||
cache-image: false
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v6
|
||||
- name: Build and push (Alpine)
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
build-args: |
|
||||
MAINTAINER=${{ github.repository_owner }}
|
||||
QL_BRANCH=${{ github.ref_name }}
|
||||
SOURCE_COMMIT=${{ github.sha }}
|
||||
network: host
|
||||
# linux/s390x npm 暂不可用
|
||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/386
|
||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386
|
||||
context: .
|
||||
file: ./docker/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache,mode=max
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache-alpine
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache-alpine,mode=max
|
||||
|
||||
- name: Image digest
|
||||
run: |
|
||||
echo ${{ steps.docker_build.outputs.digest }}
|
||||
|
||||
build310:
|
||||
if: ${{ github.ref_name == 'master' }}
|
||||
build-debian:
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
needs: build-static
|
||||
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Read version from version.yaml
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(grep '^version:' version.yaml | awk '{print $2}')
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "Version: $VERSION"
|
||||
|
||||
- name: Setup timezone
|
||||
uses: szenius/set-timezone@v2.0
|
||||
with:
|
||||
timezoneLinux: Asia/Shanghai
|
||||
run: sudo timedatectl set-timezone Asia/Shanghai
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: |
|
||||
${{ github.repository }}
|
||||
ghcr.io/${{ github.repository }}
|
||||
flavor: |
|
||||
latest=false
|
||||
tags: |
|
||||
type=raw,value=debian-dev,enable=${{ github.ref == format('refs/heads/{0}', 'develop') }}
|
||||
type=raw,value=debian,enable=${{ github.ref == format('refs/heads/{0}', 'master') }}
|
||||
type=raw,value=${{ steps.version.outputs.version }}-debian,enable=${{ github.ref == format('refs/heads/{0}', 'master') }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@v4
|
||||
with:
|
||||
cache-image: false
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Build and push python3.10
|
||||
id: docker_build_310
|
||||
uses: docker/build-push-action@v6
|
||||
- name: Build and push (Debian)
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
build-args: |
|
||||
MAINTAINER=${{ github.repository_owner }}
|
||||
QL_BRANCH=${{ github.ref_name }}
|
||||
SOURCE_COMMIT=${{ github.sha }}
|
||||
network: host
|
||||
# linux/s390x npm 暂不可用
|
||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/386
|
||||
# Keep s390x on Debian: npm can hang under QEMU with Alpine (nodejs/docker-node#1973).
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x
|
||||
context: .
|
||||
file: ./docker/310.Dockerfile
|
||||
file: ./docker/Dockerfile.debian
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache-debian
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache-debian,mode=max
|
||||
|
||||
build-alpine310:
|
||||
if: ${{ github.ref_name == 'master' }}
|
||||
needs: build-static
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Read version from version.yaml
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(grep '^version:' version.yaml | awk '{print $2}')
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Setup timezone
|
||||
run: sudo timedatectl set-timezone Asia/Shanghai
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
with:
|
||||
cache-image: false
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Build and push (Alpine Python 3.10)
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
build-args: |
|
||||
MAINTAINER=${{ github.repository_owner }}
|
||||
QL_BRANCH=${{ github.ref_name }}
|
||||
SOURCE_COMMIT=${{ github.sha }}
|
||||
network: host
|
||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386
|
||||
context: .
|
||||
file: ./docker/Dockerfile.310
|
||||
push: true
|
||||
tags: |
|
||||
whyour/qinglong:python3.10
|
||||
whyour/qinglong:${{ steps.version.outputs.version }}-python3.10
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache-python3.10
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache-python3.10,mode=max
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache-alpine-python3.10
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache-alpine-python3.10,mode=max
|
||||
|
||||
- name: Image digest
|
||||
build-debian310:
|
||||
if: ${{ github.ref_name == 'master' }}
|
||||
needs: build-static
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Read version from version.yaml
|
||||
id: version
|
||||
run: |
|
||||
echo ${{ steps.docker_build_310.outputs.digest }}
|
||||
VERSION=$(grep '^version:' version.yaml | awk '{print $2}')
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Setup timezone
|
||||
run: sudo timedatectl set-timezone Asia/Shanghai
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
with:
|
||||
cache-image: false
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Build and push (Debian Python 3.10)
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
build-args: |
|
||||
MAINTAINER=${{ github.repository_owner }}
|
||||
QL_BRANCH=${{ github.ref_name }}
|
||||
SOURCE_COMMIT=${{ github.sha }}
|
||||
network: host
|
||||
# Keep s390x on Debian: npm can hang under QEMU with Alpine (nodejs/docker-node#1973).
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x
|
||||
context: .
|
||||
file: ./docker/Dockerfile.debian310
|
||||
push: true
|
||||
tags: |
|
||||
whyour/qinglong:debian-python3.10
|
||||
whyour/qinglong:${{ steps.version.outputs.version }}-debian-python3.10
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache-debian-python3.10
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache-debian-python3.10,mode=max
|
||||
|
||||
publish:
|
||||
if: ${{ github.ref_name == 'master' }}
|
||||
needs: [build-alpine, build-debian]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: "8.3.1"
|
||||
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
cache: "pnpm"
|
||||
|
||||
- name: build front and back
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm build:front
|
||||
pnpm build:back
|
||||
|
||||
- name: publish npm package
|
||||
run: |
|
||||
echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" >> ~/.npmrc
|
||||
npm publish
|
||||
|
||||
@@ -28,3 +28,10 @@ __pycache__
|
||||
/shell/preload/notify.*
|
||||
/shell/preload/*-notify.json
|
||||
/shell/preload/__ql_notify__.*
|
||||
/shell/preload/lang_env.sh
|
||||
|
||||
.deepseek/
|
||||
.claude/
|
||||
|
||||
# local Kubernetes overlays
|
||||
/deploy/kubernetes/overlays/local/
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
/.tmp/
|
||||
/.github/
|
||||
/.vscode/
|
||||
/.history/
|
||||
/back/**/*.ts
|
||||
/back/**/*.json
|
||||
/cli/
|
||||
/data/
|
||||
/src/
|
||||
/static/**/*.js.map
|
||||
/static/**/*.gz
|
||||
/.editorconfig
|
||||
/.gitignore
|
||||
/.prettierignore
|
||||
/.prettierrc
|
||||
/.umirc.ts
|
||||
/nodemon.json
|
||||
/pnpm-lock.yaml
|
||||
/tsconfig.back.json
|
||||
/tsconfig.json
|
||||
/typings.d.ts
|
||||
/.env
|
||||
@@ -0,0 +1,43 @@
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **qinglong** (2778 symbols, 6698 relationships, 233 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
|
||||
|
||||
## Always Do
|
||||
|
||||
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
|
||||
- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "develop"})`.
|
||||
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
|
||||
- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
|
||||
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`.
|
||||
|
||||
## Never Do
|
||||
|
||||
- NEVER edit a function, class, or method without first running `impact` on it.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
|
||||
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
|
||||
- NEVER commit changes without running `detect_changes()` to check affected scope.
|
||||
|
||||
## Resources
|
||||
|
||||
| Resource | Use for |
|
||||
|----------|---------|
|
||||
| `gitnexus://repo/qinglong/context` | Codebase overview, check index freshness |
|
||||
| `gitnexus://repo/qinglong/clusters` | All functional areas |
|
||||
| `gitnexus://repo/qinglong/processes` | All execution flows |
|
||||
| `gitnexus://repo/qinglong/process/{name}` | Step-by-step execution trace |
|
||||
|
||||
## CLI
|
||||
|
||||
| Task | Read this skill file |
|
||||
|------|---------------------|
|
||||
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
|
||||
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
|
||||
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
|
||||
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
|
||||
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
|
||||
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
|
||||
|
||||
<!-- gitnexus:end -->
|
||||
@@ -48,6 +48,17 @@ docker pull whyour/qinglong:latest
|
||||
docker pull whyour/qinglong:debian
|
||||
```
|
||||
|
||||
When running the `debian` image as a non-root user, specify `--user qinglong`:
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
-v /path/to/ql/data:/ql/data \
|
||||
-p 5700:5700 \
|
||||
--user qinglong \
|
||||
--name qinglong \
|
||||
whyour/qinglong:debian
|
||||
```
|
||||
|
||||
### npm
|
||||
|
||||
The npm version supports `debian/ubuntu/alpine` systems and requires `node/npm/python3/pip3/pnpm` to be installed.
|
||||
|
||||
@@ -50,6 +50,17 @@ docker pull whyour/qinglong:latest
|
||||
docker pull whyour/qinglong:debian
|
||||
```
|
||||
|
||||
使用 `debian` 镜像以非 root 用户运行时,需指定 `--user qinglong`:
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
-v /path/to/ql/data:/ql/data \
|
||||
-p 5700:5700 \
|
||||
--user qinglong \
|
||||
--name qinglong \
|
||||
whyour/qinglong:debian
|
||||
```
|
||||
|
||||
### npm
|
||||
|
||||
npm 版本支持 `debian/ubuntu/alpine` 系统,需要自行安装 `node/npm/python3/pip3/pnpm`
|
||||
|
||||
+19
-9
@@ -4,8 +4,9 @@ import { Logger } from 'winston';
|
||||
import config from '../config';
|
||||
import * as fs from 'fs/promises';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import { join } from 'path';
|
||||
import { join, basename } from 'path';
|
||||
import { SAMPLE_FILES } from '../config/const';
|
||||
import { t } from '../shared/i18n';
|
||||
import ConfigService from '../services/config';
|
||||
import { writeFileWithLock } from '../shared/utils';
|
||||
const route = Router();
|
||||
@@ -14,7 +15,7 @@ export default (app: Router) => {
|
||||
app.use('/configs', route);
|
||||
|
||||
route.get(
|
||||
'/sample',
|
||||
'/samples',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
res.send({
|
||||
@@ -71,15 +72,24 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const { name, content } = req.body;
|
||||
if (config.blackFileList.includes(name)) {
|
||||
res.send({ code: 403, message: '文件无法访问' });
|
||||
}
|
||||
let path = join(config.configPath, name);
|
||||
// Resolve path first to prevent traversal attacks
|
||||
let basePath = config.configPath;
|
||||
if (name.startsWith('data/scripts/')) {
|
||||
path = join(config.rootPath, name);
|
||||
basePath = join(config.rootPath, 'data/scripts');
|
||||
}
|
||||
await writeFileWithLock(path, content);
|
||||
res.send({ code: 200, message: '保存成功' });
|
||||
const cleanName = name.replace(/^data\/scripts\//, '');
|
||||
const resolvedPath = join(basePath, cleanName);
|
||||
const normalized = join(resolvedPath);
|
||||
// Verify the resolved path stays within allowed directory
|
||||
if (!normalized.startsWith(basePath)) {
|
||||
return res.send({ code: 403, message: t('文件路径无效') });
|
||||
}
|
||||
// Check blacklist on actual filename (not user input)
|
||||
if (config.blackFileList.includes(basename(normalized))) {
|
||||
return res.send({ code: 403, message: t('文件无法访问') });
|
||||
}
|
||||
await writeFileWithLock(normalized, content);
|
||||
res.send({ code: 200, message: t('保存成功') });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
|
||||
+51
-3
@@ -5,6 +5,11 @@ import CronService from '../services/cron';
|
||||
import CronViewService from '../services/cronView';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import { commonCronSchema } from '../validation/schedule';
|
||||
import {
|
||||
RunningInstanceModel,
|
||||
InstanceStatus,
|
||||
} from '../data/runningInstance';
|
||||
import { t } from '../shared/i18n';
|
||||
|
||||
const route = Router();
|
||||
|
||||
@@ -60,7 +65,7 @@ export default (app: Router) => {
|
||||
try {
|
||||
const cronViewService = Container.get(CronViewService);
|
||||
if (req.body.type === 1) {
|
||||
return res.send({ code: 400, message: '参数错误' });
|
||||
return res.send({ code: 400, message: t('参数错误') });
|
||||
} else {
|
||||
const data = await cronViewService.update(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
@@ -307,8 +312,8 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.log(req.params.id);
|
||||
return res.send({ code: 200, data });
|
||||
const result = await cronService.log(req.params.id);
|
||||
return res.send({ code: 200, data: result.content, logStatus: result.status });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
@@ -429,6 +434,7 @@ export default (app: Router) => {
|
||||
log_path: Joi.string().optional().allow(null),
|
||||
last_running_time: Joi.number().optional().allow(null),
|
||||
last_execution_time: Joi.number().optional().allow(null),
|
||||
exit_code: Joi.number().optional().allow(null),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -446,6 +452,48 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/:id/instances',
|
||||
celebrate({
|
||||
params: Joi.object({
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const instances = await RunningInstanceModel.findAll({
|
||||
where: {
|
||||
cron_id: req.params.id,
|
||||
},
|
||||
order: [['started_at', 'DESC']],
|
||||
raw: true,
|
||||
});
|
||||
return res.send({ code: 200, data: instances });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/:id/instances/:instanceId/stop',
|
||||
celebrate({
|
||||
params: Joi.object({
|
||||
id: Joi.number().required(),
|
||||
instanceId: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number; instanceId: number }>, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.stopInstance(req.params.instanceId);
|
||||
return res.send(data);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/:id/logs',
|
||||
celebrate({
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
import { fn, col, where, Op } from 'sequelize';
|
||||
import { CrontabModel } from '../data/cron';
|
||||
import { CrontabStatModel } from '../data/cronStats';
|
||||
import {
|
||||
RunningInstanceModel,
|
||||
InstanceStatus,
|
||||
} from '../data/runningInstance';
|
||||
import dayjs from 'dayjs';
|
||||
import os from 'os';
|
||||
import { isEmpty } from 'lodash';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
|
||||
const route = Router();
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/dashboard', route);
|
||||
|
||||
route.post('/record', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { ref_id, code, elapsed } = req.body;
|
||||
if (!ref_id) return res.send({ code: 400, message: 'ref_id required' });
|
||||
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
const isSuccess = code === 0 ? 1 : 0;
|
||||
const isFail = code !== 0 ? 1 : 0;
|
||||
const elapsedMs = (Number(elapsed) || 0) * 1000;
|
||||
|
||||
const existing = await CrontabStatModel.findOne({
|
||||
where: { ref_id: Number(ref_id), date: today },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
await CrontabStatModel.update(
|
||||
{
|
||||
run_count: (existing.run_count || 0) + 1,
|
||||
success_count: (existing.success_count || 0) + isSuccess,
|
||||
fail_count: (existing.fail_count || 0) + isFail,
|
||||
total_time: (existing.total_time || 0) + elapsedMs,
|
||||
max_time: Math.max(existing.max_time || 0, elapsedMs),
|
||||
},
|
||||
{ where: { id: existing.id } },
|
||||
);
|
||||
} else {
|
||||
await CrontabStatModel.create({
|
||||
ref_id: Number(ref_id),
|
||||
date: today,
|
||||
run_count: 1,
|
||||
success_count: isSuccess,
|
||||
fail_count: isFail,
|
||||
total_time: elapsedMs,
|
||||
max_time: elapsedMs,
|
||||
});
|
||||
}
|
||||
|
||||
res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
res.send({ code: 500 });
|
||||
}
|
||||
});
|
||||
|
||||
route.get(
|
||||
'/overview',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
|
||||
const [total, enabled, disabled, stats] = await Promise.all([
|
||||
CrontabModel.count(),
|
||||
CrontabModel.count({ where: { isDisabled: 0 } }),
|
||||
CrontabModel.count({ where: { isDisabled: 1 } }),
|
||||
CrontabStatModel.findOne({
|
||||
attributes: [
|
||||
[fn('SUM', col('run_count')), 'total_runs'],
|
||||
[fn('SUM', col('success_count')), 'total_success'],
|
||||
[fn('SUM', col('fail_count')), 'total_fail'],
|
||||
[fn('SUM', col('total_time')), 'total_time'],
|
||||
],
|
||||
where: { date: today },
|
||||
raw: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
const row = stats as any;
|
||||
const totalRuns = Number(row?.total_runs) || 0;
|
||||
const totalSuccess = Number(row?.total_success) || 0;
|
||||
const totalFail = Number(row?.total_fail) || 0;
|
||||
const totalTime = Number(row?.total_time) || 0;
|
||||
|
||||
res.send({
|
||||
code: 200,
|
||||
data: {
|
||||
total,
|
||||
enabled,
|
||||
disabled,
|
||||
todayRuns: totalRuns,
|
||||
todaySuccess: totalSuccess,
|
||||
todayFail: totalFail,
|
||||
successRate: totalRuns > 0 ? ((totalSuccess / totalRuns) * 100).toFixed(1) : '0',
|
||||
avgTime: totalRuns > 0 ? Math.round(totalTime / totalRuns) : 0,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/trend',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const days = parseInt(req.query.days as string) || 7;
|
||||
const dates: string[] = [];
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
dates.push(dayjs().subtract(i, 'day').format('YYYY-MM-DD'));
|
||||
}
|
||||
|
||||
const rows = (await CrontabStatModel.findAll({
|
||||
attributes: [
|
||||
'date',
|
||||
[fn('SUM', col('run_count')), 'total_runs'],
|
||||
[fn('SUM', col('success_count')), 'total_success'],
|
||||
[fn('SUM', col('fail_count')), 'total_fail'],
|
||||
],
|
||||
where: {
|
||||
date: { [Op.in]: dates },
|
||||
},
|
||||
group: ['date'],
|
||||
order: [['date', 'ASC']],
|
||||
raw: true,
|
||||
})) as any[];
|
||||
|
||||
const dataMap: Record<string, any> = {};
|
||||
rows.forEach((r: any) => {
|
||||
dataMap[r.date] = {
|
||||
total: Number(r.total_runs) || 0,
|
||||
success: Number(r.total_success) || 0,
|
||||
fail: Number(r.total_fail) || 0,
|
||||
};
|
||||
});
|
||||
|
||||
const data = dates.map((d) => ({
|
||||
date: dayjs(d).format('MM-DD'),
|
||||
...(dataMap[d] || { total: 0, success: 0, fail: 0 }),
|
||||
}));
|
||||
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/top-time',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
|
||||
const rows = (await CrontabStatModel.findAll({
|
||||
attributes: [
|
||||
'ref_id',
|
||||
[fn('SUM', col('total_time')), 'total_time'],
|
||||
[fn('SUM', col('run_count')), 'run_count'],
|
||||
[fn('MAX', col('max_time')), 'max_time'],
|
||||
],
|
||||
where: { date: today, run_count: { [Op.gt]: 0 } },
|
||||
group: ['ref_id'],
|
||||
order: [[fn('SUM', col('total_time')), 'DESC']],
|
||||
limit: 5,
|
||||
raw: true,
|
||||
})) as any[];
|
||||
|
||||
const ids = rows.map((r) => Number(r.ref_id));
|
||||
const crons = await CrontabModel.findAll({
|
||||
where: { id: { [Op.in]: ids } },
|
||||
raw: true,
|
||||
});
|
||||
const nameMap: Record<number, string> = {};
|
||||
crons.forEach((c: any) => { nameMap[c.id] = c.name || c.command; });
|
||||
|
||||
const data = rows.map((r: any, i) => ({
|
||||
rank: i + 1,
|
||||
name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id),
|
||||
avgTime: Math.round(Number(r.total_time) / Number(r.run_count)),
|
||||
maxTime: Number(r.max_time),
|
||||
}));
|
||||
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/top-count',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
|
||||
const rows = (await CrontabStatModel.findAll({
|
||||
attributes: [
|
||||
'ref_id',
|
||||
[fn('SUM', col('run_count')), 'run_count'],
|
||||
[fn('SUM', col('total_time')), 'total_time'],
|
||||
[fn('SUM', col('success_count')), 'success_count'],
|
||||
],
|
||||
where: { date: today, run_count: { [Op.gt]: 0 } },
|
||||
group: ['ref_id'],
|
||||
order: [[fn('SUM', col('run_count')), 'DESC']],
|
||||
limit: 5,
|
||||
raw: true,
|
||||
})) as any[];
|
||||
|
||||
const ids = rows.map((r) => Number(r.ref_id));
|
||||
const crons = await CrontabModel.findAll({
|
||||
where: { id: { [Op.in]: ids } },
|
||||
raw: true,
|
||||
});
|
||||
const nameMap: Record<number, string> = {};
|
||||
crons.forEach((c: any) => { nameMap[c.id] = c.name || c.command; });
|
||||
|
||||
const data = rows.map((r: any, i) => ({
|
||||
rank: i + 1,
|
||||
name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id),
|
||||
runCount: Number(r.run_count),
|
||||
avgTime: Math.round(Number(r.total_time) / Number(r.run_count)),
|
||||
successRate:
|
||||
Number(r.run_count) > 0
|
||||
? ((Number(r.success_count) / Number(r.run_count)) * 100).toFixed(1)
|
||||
: '0',
|
||||
}));
|
||||
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/runtime',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const runningInstances = await RunningInstanceModel.findAll({
|
||||
where: {
|
||||
status: InstanceStatus.running,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const queuedCrons = await CrontabModel.findAll({
|
||||
where: {
|
||||
status: 3, // queued
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// Fetch cron names for running instances
|
||||
const cronIds = [
|
||||
...new Set(runningInstances.map((i: any) => i.cron_id)),
|
||||
];
|
||||
const crons =
|
||||
cronIds.length > 0
|
||||
? await CrontabModel.findAll({
|
||||
where: { id: cronIds },
|
||||
raw: true,
|
||||
})
|
||||
: [];
|
||||
const cronMap = new Map(crons.map((c: any) => [c.id, c]));
|
||||
|
||||
const now = dayjs().unix();
|
||||
const running = runningInstances.map((inst: any) => {
|
||||
const cron = cronMap.get(inst.cron_id);
|
||||
return {
|
||||
instanceId: inst.id,
|
||||
id: inst.cron_id,
|
||||
name: cron?.name || cron?.command || tf('任务#%s', inst.cron_id),
|
||||
pid: inst.pid,
|
||||
elapsed: inst.started_at ? now - inst.started_at : 0,
|
||||
logPath: inst.log_path,
|
||||
};
|
||||
});
|
||||
|
||||
const dayAgo = dayjs().subtract(24, 'hour').unix();
|
||||
const idleTasks = await CrontabModel.findAll({
|
||||
where: {
|
||||
isDisabled: 0,
|
||||
status: 1,
|
||||
last_execution_time: { [Op.lt]: dayAgo },
|
||||
},
|
||||
order: [['last_execution_time', 'ASC']],
|
||||
limit: 5,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
res.send({
|
||||
code: 200,
|
||||
data: {
|
||||
runningCount: running.length,
|
||||
queuedCount: queuedCrons.length,
|
||||
running,
|
||||
idleTasks: idleTasks.map((c: any) => ({
|
||||
id: c.id,
|
||||
name: c.name || c.command || tf('任务#%s', c.id),
|
||||
lastRun: c.last_execution_time
|
||||
? dayjs.unix(c.last_execution_time).format('MM-DD HH:mm')
|
||||
: '-',
|
||||
})),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/labels',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
const [crons, stats] = (await Promise.all([
|
||||
CrontabModel.findAll({ where: { isDisabled: 0 }, raw: true }),
|
||||
CrontabStatModel.findAll({ where: { date: today }, raw: true }),
|
||||
]));
|
||||
|
||||
const statMap: Record<number, any> = {};
|
||||
stats.forEach((s: any) => { statMap[s.ref_id] = s; });
|
||||
|
||||
const labelMap: Record<string, { count: number; runs: number; success: number; totalTime: number }> = {};
|
||||
crons.forEach((c) => {
|
||||
let rawLabels = c.labels;
|
||||
if (typeof rawLabels === 'string') rawLabels = JSON.parse(rawLabels);
|
||||
const labels: string[] = Array.isArray(rawLabels)
|
||||
? [...new Set((rawLabels as string[]).filter((l: string) => !isEmpty(l)))]
|
||||
: [];
|
||||
if (labels.length === 0) {
|
||||
labels.push(t('未分类'));
|
||||
}
|
||||
const st = statMap[c.id!];
|
||||
labels.forEach((label: string) => {
|
||||
if (!labelMap[label]) labelMap[label] = { count: 0, runs: 0, success: 0, totalTime: 0 };
|
||||
labelMap[label].count += 1;
|
||||
if (st) {
|
||||
labelMap[label].runs += Number(st.run_count) || 0;
|
||||
labelMap[label].success += Number(st.success_count) || 0;
|
||||
labelMap[label].totalTime += Number(st.total_time) || 0;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const data = Object.entries(labelMap)
|
||||
.map(([label, v]) => ({
|
||||
label,
|
||||
count: v.count,
|
||||
todayRuns: v.runs,
|
||||
successRate: v.runs > 0 ? ((v.success / v.runs) * 100).toFixed(1) : '0',
|
||||
avgTime: v.runs > 0 ? Math.round(v.totalTime / v.runs) : 0,
|
||||
}))
|
||||
.sort((a, b) => b.todayRuns - a.todayRuns);
|
||||
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/system',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const memUsage = process.memoryUsage();
|
||||
res.send({
|
||||
code: 200,
|
||||
data: {
|
||||
platform: os.platform(),
|
||||
uptime: Math.floor(process.uptime()),
|
||||
memTotal: os.totalmem(),
|
||||
memFree: os.freemem(),
|
||||
memUsagePercent: ((1 - os.freemem() / os.totalmem()) * 100).toFixed(1),
|
||||
heapUsed: Math.round(memUsage.heapUsed / 1024 / 1024),
|
||||
heapTotal: Math.round(memUsage.heapTotal / 1024 / 1024),
|
||||
loadAvg: os.loadavg().map((v) => Number(v.toFixed(2))),
|
||||
cpus: os.cpus().length,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
+48
-2
@@ -6,6 +6,7 @@ import { Container } from 'typedi';
|
||||
import { Logger } from 'winston';
|
||||
import config from '../config';
|
||||
import { safeJSONParse } from '../config/util';
|
||||
import { t } from '../shared/i18n';
|
||||
import EnvService from '../services/env';
|
||||
const route = Router();
|
||||
|
||||
@@ -18,6 +19,10 @@ const storage = multer.diskStorage({
|
||||
},
|
||||
});
|
||||
const upload = multer({ storage: storage });
|
||||
const labelSchema = Joi.array()
|
||||
.items(Joi.string().trim().required())
|
||||
.min(1)
|
||||
.required();
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/envs', route);
|
||||
@@ -44,6 +49,7 @@ export default (app: Router) => {
|
||||
.required()
|
||||
.pattern(/^[a-zA-Z_][0-9a-zA-Z_]*$/),
|
||||
remarks: Joi.string().optional().allow(''),
|
||||
labels: Joi.array().items(Joi.string().trim()).optional().allow(null),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
@@ -52,7 +58,7 @@ export default (app: Router) => {
|
||||
try {
|
||||
const envService = Container.get(EnvService);
|
||||
if (!req.body?.length) {
|
||||
return res.send({ code: 400, message: '参数不正确' });
|
||||
return res.send({ code: 400, message: t('参数不正确') });
|
||||
}
|
||||
const data = await envService.create(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
@@ -70,6 +76,7 @@ export default (app: Router) => {
|
||||
name: Joi.string().required(),
|
||||
remarks: Joi.string().optional().allow('').allow(null),
|
||||
id: Joi.number().required(),
|
||||
labels: Joi.array().items(Joi.string().trim()).optional().allow(null),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -230,6 +237,44 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/labels',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
ids: Joi.array().items(Joi.number().required()).min(1).required(),
|
||||
labels: labelSchema,
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const envService = Container.get(EnvService);
|
||||
const data = await envService.addLabels(req.body.ids, req.body.labels);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.delete(
|
||||
'/labels',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
ids: Joi.array().items(Joi.number().required()).min(1).required(),
|
||||
labels: labelSchema,
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const envService = Container.get(EnvService);
|
||||
const data = await envService.removeLabels(req.body.ids, req.body.labels);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/upload',
|
||||
upload.single('env'),
|
||||
@@ -248,13 +293,14 @@ export default (app: Router) => {
|
||||
name: x.name,
|
||||
value: x.value,
|
||||
remarks: x.remarks,
|
||||
labels: x.labels,
|
||||
})),
|
||||
);
|
||||
return res.send({ code: 200, data: result });
|
||||
} else {
|
||||
return res.send({
|
||||
code: 400,
|
||||
message: '每条数据 name 或者 value 字段不能为空,参考导出文件格式',
|
||||
message: t('每条数据 name 或者 value 字段不能为空,参考导出文件格式'),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import dependence from './dependence';
|
||||
import system from './system';
|
||||
import subscription from './subscription';
|
||||
import update from './update';
|
||||
import dashboard from './dashboard';
|
||||
import health from './health';
|
||||
|
||||
export default () => {
|
||||
@@ -25,6 +26,7 @@ export default () => {
|
||||
system(app);
|
||||
subscription(app);
|
||||
update(app);
|
||||
dashboard(app);
|
||||
health(app);
|
||||
|
||||
return app;
|
||||
|
||||
+16
-5
@@ -3,6 +3,7 @@ import { NextFunction, Request, Response, Router } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
import { Logger } from 'winston';
|
||||
import config from '../config';
|
||||
import { t } from '../shared/i18n';
|
||||
import {
|
||||
getFileContentByName,
|
||||
readDirs,
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
rmPath,
|
||||
} from '../config/util';
|
||||
import LogService from '../services/log';
|
||||
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
||||
const route = Router();
|
||||
const blacklist = ['.tmp'];
|
||||
|
||||
@@ -42,11 +44,20 @@ export default (app: Router) => {
|
||||
if (!finalPath || blacklist.includes(req.query.path as string)) {
|
||||
return res.send({
|
||||
code: 403,
|
||||
message: '暂无权限',
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
}
|
||||
const logPath = `${req.query.path as string}/${req.query.file as string}`;
|
||||
const runningInstance = await RunningInstanceModel.findOne({
|
||||
where: { log_path: logPath, status: InstanceStatus.running },
|
||||
});
|
||||
|
||||
const content = await getFileContentByName(finalPath);
|
||||
res.send({ code: 200, data: removeAnsi(content) });
|
||||
res.send({
|
||||
code: 200,
|
||||
data: removeAnsi(content),
|
||||
logStatus: runningInstance ? 'running' : undefined,
|
||||
});
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
@@ -65,7 +76,7 @@ export default (app: Router) => {
|
||||
if (!finalPath || blacklist.includes(req.query.path as string)) {
|
||||
return res.send({
|
||||
code: 403,
|
||||
message: '暂无权限',
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
}
|
||||
const content = await getFileContentByName(finalPath);
|
||||
@@ -96,7 +107,7 @@ export default (app: Router) => {
|
||||
if (!finalPath || blacklist.includes(path)) {
|
||||
return res.send({
|
||||
code: 403,
|
||||
message: '暂无权限',
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
}
|
||||
await rmPath(finalPath);
|
||||
@@ -126,7 +137,7 @@ export default (app: Router) => {
|
||||
if (!filePath) {
|
||||
return res.send({
|
||||
code: 403,
|
||||
message: '暂无权限',
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
}
|
||||
return res.download(filePath, filename, (err) => {
|
||||
|
||||
+34
-11
@@ -7,10 +7,16 @@ import * as fs from 'fs/promises';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import path, { join, parse } from 'path';
|
||||
import ScriptService from '../services/script';
|
||||
import { t } from '../shared/i18n';
|
||||
import multer from 'multer';
|
||||
import { writeFileWithLock } from '../shared/utils';
|
||||
const route = Router();
|
||||
|
||||
function isPathAllowed(targetPath: string): boolean {
|
||||
const resolved = path.resolve(targetPath);
|
||||
return config.writePathList.some((x) => resolved.startsWith(x));
|
||||
}
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, config.scriptPath);
|
||||
@@ -155,29 +161,37 @@ export default (app: Router) => {
|
||||
if (config.writePathList.every((x) => !path.startsWith(x))) {
|
||||
return res.send({
|
||||
code: 403,
|
||||
message: '暂无权限',
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
}
|
||||
|
||||
if (req.file) {
|
||||
await fs.rename(req.file.path, join(path, filename));
|
||||
const uploadPath = join(path, filename);
|
||||
if (!isPathAllowed(uploadPath)) {
|
||||
return res.send({ code: 403, message: t('暂无权限') });
|
||||
}
|
||||
await fs.rename(req.file.path, uploadPath);
|
||||
return res.send({ code: 200 });
|
||||
}
|
||||
|
||||
if (directory) {
|
||||
await fs.mkdir(join(path, directory), { recursive: true });
|
||||
const dirPath = join(path, directory);
|
||||
if (!isPathAllowed(dirPath)) {
|
||||
return res.send({ code: 403, message: t('暂无权限') });
|
||||
}
|
||||
await fs.mkdir(dirPath, { recursive: true });
|
||||
return res.send({ code: 200 });
|
||||
}
|
||||
|
||||
if (!originFilename) {
|
||||
originFilename = filename;
|
||||
}
|
||||
const originFilePath = join(
|
||||
path,
|
||||
`${originFilename.replace(/\//g, '')}`,
|
||||
);
|
||||
const originFilePath = join(path, originFilename);
|
||||
const filePath = join(path, filename);
|
||||
if (!isPathAllowed(filePath) || !isPathAllowed(originFilePath)) {
|
||||
return res.send({ code: 403, message: t('暂无权限') });
|
||||
}
|
||||
await fs.mkdir(path, { recursive: true });
|
||||
const filePath = join(path, `${filename.replace(/\//g, '')}`);
|
||||
const fileExists = await fileExist(filePath);
|
||||
if (fileExists) {
|
||||
await fs.copyFile(
|
||||
@@ -217,7 +231,7 @@ export default (app: Router) => {
|
||||
if (!filePath) {
|
||||
return res.send({
|
||||
code: 403,
|
||||
message: '暂无权限',
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
}
|
||||
await writeFileWithLock(filePath, content);
|
||||
@@ -251,7 +265,7 @@ export default (app: Router) => {
|
||||
if (!filePath) {
|
||||
return res.send({
|
||||
code: 403,
|
||||
message: '暂无权限',
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
}
|
||||
await rmPath(filePath);
|
||||
@@ -284,7 +298,7 @@ export default (app: Router) => {
|
||||
if (!filePath) {
|
||||
return res.send({
|
||||
code: 403,
|
||||
message: '暂无权限',
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
}
|
||||
return res.download(filePath, filename, (err) => {
|
||||
@@ -316,6 +330,9 @@ export default (app: Router) => {
|
||||
}
|
||||
const { name, ext } = parse(filename);
|
||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
||||
if (!isPathAllowed(filePath)) {
|
||||
return res.send({ code: 403, message: t('暂无权限') });
|
||||
}
|
||||
await writeFileWithLock(filePath, content || '');
|
||||
|
||||
const scriptService = Container.get(ScriptService);
|
||||
@@ -344,6 +361,9 @@ export default (app: Router) => {
|
||||
}
|
||||
const { name, ext } = parse(filename);
|
||||
const filePath = join(config.scriptPath, path, `${name}.swap${ext}`);
|
||||
if (!isPathAllowed(filePath)) {
|
||||
return res.send({ code: 403, message: t('暂无权限') });
|
||||
}
|
||||
const logPath = join(config.logPath, path, `${name}.swap`);
|
||||
|
||||
const scriptService = Container.get(ScriptService);
|
||||
@@ -379,6 +399,9 @@ export default (app: Router) => {
|
||||
}
|
||||
const filePath = join(config.scriptPath, path, filename);
|
||||
const newPath = join(config.scriptPath, path, newFilename);
|
||||
if (!isPathAllowed(filePath) || !isPathAllowed(newPath)) {
|
||||
return res.send({ code: 403, message: t('暂无权限') });
|
||||
}
|
||||
await fs.rename(filePath, newPath);
|
||||
res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
|
||||
+44
-10
@@ -6,6 +6,8 @@ import config from '../config';
|
||||
import SystemService from '../services/system';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import UserService from '../services/user';
|
||||
import { t } from '../shared/i18n';
|
||||
import { isDefaultAuthInfo } from '../shared/auth';
|
||||
import {
|
||||
getUniqPath,
|
||||
handleLogPath,
|
||||
@@ -38,14 +40,7 @@ export default (app: Router) => {
|
||||
const { version, changeLog, changeLogLink, publishTime } =
|
||||
await parseVersion(config.versionFile);
|
||||
|
||||
let isInitialized = true;
|
||||
if (
|
||||
Object.keys(authInfo).length === 2 &&
|
||||
authInfo.username === 'admin' &&
|
||||
authInfo.password === 'admin'
|
||||
) {
|
||||
isInitialized = false;
|
||||
}
|
||||
const isInitialized = !isDefaultAuthInfo(authInfo);
|
||||
res.send({
|
||||
code: 200,
|
||||
data: {
|
||||
@@ -400,8 +395,11 @@ export default (app: Router) => {
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const userService = Container.get(UserService);
|
||||
await userService.resetAuthInfo(req.body);
|
||||
res.send({ code: 200, message: '更新成功' });
|
||||
const result = await userService.resetAuthInfo(req.body);
|
||||
if (result) {
|
||||
return res.send(result);
|
||||
}
|
||||
res.send({ code: 200, message: t('更新成功') });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
@@ -426,6 +424,42 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/config/lang',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
lang: Joi.string().allow('').allow(null),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const systemService = Container.get(SystemService);
|
||||
const result = await systemService.updateLanguage(req.body);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/config/panel-title',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
panelTitle: Joi.string().max(100).allow('').allow(null),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const systemService = Container.get(SystemService);
|
||||
const result = await systemService.updatePanelTitle(req.body);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/config/global-ssh-key',
|
||||
celebrate({
|
||||
|
||||
+6
-5
@@ -8,6 +8,7 @@ import path from 'path';
|
||||
import { v4 as uuidV4 } from 'uuid';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import config from '../config';
|
||||
import { t } from '../shared/i18n';
|
||||
import { isDemoEnv, getToken } from '../config/util';
|
||||
const route = Router();
|
||||
|
||||
@@ -76,11 +77,11 @@ export default (app: Router) => {
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
if (isDemoEnv()) {
|
||||
return res.send({ code: 450, message: '未知错误' });
|
||||
return res.send({ code: 450, message: t('未知错误') });
|
||||
}
|
||||
const userService = Container.get(UserService);
|
||||
await userService.updateUsernameAndPassword(req.body);
|
||||
res.send({ code: 200, message: '更新成功' });
|
||||
res.send({ code: 200, message: t('更新成功') });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
@@ -140,12 +141,12 @@ export default (app: Router) => {
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/two-factor/deactive',
|
||||
'/two-factor/deactivate',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const userService = Container.get(UserService);
|
||||
const data = await userService.deactiveTwoFactor();
|
||||
const data = await userService.deactivateTwoFactor();
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
@@ -229,7 +230,7 @@ export default (app: Router) => {
|
||||
try {
|
||||
const userService = Container.get(UserService);
|
||||
await userService.updateUsernameAndPassword(req.body);
|
||||
res.send({ code: 200, message: '更新成功' });
|
||||
res.send({ code: 200, message: t('更新成功') });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
|
||||
+26
-24
@@ -8,6 +8,7 @@ import { Container } from 'typedi';
|
||||
import config from './config';
|
||||
import Logger from './loaders/logger';
|
||||
import { monitoringMiddleware } from './middlewares/monitoring';
|
||||
import { errStack } from './config/util';
|
||||
import { type GrpcServerService } from './services/grpc';
|
||||
import { type HttpServerService } from './services/http';
|
||||
|
||||
@@ -48,7 +49,7 @@ class Application {
|
||||
await this.startWorkerProcess();
|
||||
}
|
||||
} catch (error) {
|
||||
Logger.error('Failed to start application:', error);
|
||||
Logger.error(`Failed to start application:\n${errStack(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -60,11 +61,11 @@ class Application {
|
||||
// Wait for gRPC worker to signal it's ready before starting HTTP worker
|
||||
this.waitForWorkerReady(grpcWorker, 30000)
|
||||
.then(() => {
|
||||
Logger.info('✌️ gRPC worker is ready, starting HTTP worker');
|
||||
Logger.info('[boot] gRPC worker is ready, starting HTTP worker');
|
||||
this.httpWorker = this.forkWorker('http');
|
||||
})
|
||||
.catch((error) => {
|
||||
Logger.error('✌️ Failed to wait for gRPC worker:', error);
|
||||
Logger.error(`[boot] Failed to wait for gRPC worker:\n${errStack(error)}`);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -73,7 +74,7 @@ class Application {
|
||||
if (metadata) {
|
||||
if (!this.isShuttingDown) {
|
||||
Logger.error(
|
||||
`✌️ ${metadata.serviceType} worker ${worker.process.pid} died (${signal || code
|
||||
`${metadata.serviceType} worker ${worker.process.pid} died (${signal || code
|
||||
}). Restarting...`,
|
||||
);
|
||||
// If gRPC worker died, restart it and wait for it to be ready
|
||||
@@ -81,26 +82,26 @@ class Application {
|
||||
const newGrpcWorker = this.forkWorker('grpc');
|
||||
this.waitForWorkerReady(newGrpcWorker, 30000)
|
||||
.then(() => {
|
||||
Logger.info('✌️ gRPC worker restarted and ready');
|
||||
Logger.info('gRPC worker restarted and ready');
|
||||
// Re-register cron jobs by notifying the HTTP worker
|
||||
if (this.httpWorker) {
|
||||
try {
|
||||
this.httpWorker.send('reregister-crons');
|
||||
Logger.info('✌️ Sent reregister-crons message to HTTP worker');
|
||||
Logger.info('Sent reregister-crons message to HTTP worker');
|
||||
} catch (error) {
|
||||
Logger.error('✌️ Failed to send reregister-crons message:', error);
|
||||
Logger.error(`Failed to send reregister-crons message:\n${errStack(error)}`);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
Logger.error('✌️ Failed to restart gRPC worker:', error);
|
||||
Logger.error(`Failed to restart gRPC worker:\n${errStack(error)}`);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
// For HTTP worker, just restart it
|
||||
const newWorker = this.forkWorker(metadata.serviceType);
|
||||
this.httpWorker = newWorker;
|
||||
Logger.info(`✌️ Restarted ${metadata.serviceType} worker (PID: ${newWorker.process.pid})`);
|
||||
Logger.info(`Restarted ${metadata.serviceType} worker (PID: ${newWorker.process.pid})`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,17 +170,14 @@ class Application {
|
||||
if (worker) {
|
||||
const exitPromise = new Promise<void>((resolve) => {
|
||||
worker.once('exit', () => {
|
||||
Logger.info(`✌️ Worker ${worker.process.pid} exited`);
|
||||
Logger.info(`Worker ${worker.process.pid} exited`);
|
||||
resolve();
|
||||
});
|
||||
|
||||
try {
|
||||
worker.send('shutdown');
|
||||
} catch (error) {
|
||||
Logger.warn(
|
||||
`✌️ Failed to send shutdown to worker ${worker.process.pid}:`,
|
||||
error,
|
||||
);
|
||||
Logger.warn(`Failed to send shutdown to worker ${worker.process.pid}:\n${errStack(error)}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -192,14 +190,14 @@ class Application {
|
||||
Promise.all(workerPromises),
|
||||
new Promise<void>((resolve) => {
|
||||
setTimeout(() => {
|
||||
Logger.warn('✌️ Worker shutdown timeout reached');
|
||||
Logger.warn('Worker shutdown timeout reached');
|
||||
resolve();
|
||||
}, 10000);
|
||||
}),
|
||||
]);
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
Logger.error('✌️ Error during worker shutdown:', error);
|
||||
Logger.error(`Error during worker shutdown:\n${errStack(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
@@ -211,11 +209,11 @@ class Application {
|
||||
private async startWorkerProcess() {
|
||||
const serviceType = process.env.SERVICE_TYPE;
|
||||
if (!serviceType || !['http', 'grpc'].includes(serviceType)) {
|
||||
Logger.error('✌️ Invalid SERVICE_TYPE:', serviceType);
|
||||
Logger.error('[boot] Invalid SERVICE_TYPE:', serviceType);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
Logger.info(`✌️ ${serviceType} worker started (PID: ${process.pid})`);
|
||||
Logger.info(`[boot] ${serviceType} worker started (PID: ${process.pid})`);
|
||||
|
||||
try {
|
||||
if (serviceType === 'http') {
|
||||
@@ -226,12 +224,16 @@ class Application {
|
||||
|
||||
process.send?.('ready');
|
||||
} catch (error) {
|
||||
Logger.error(`✌️ ${serviceType} worker failed:`, error);
|
||||
Logger.error(`[boot] ${serviceType} worker failed:\n${errStack(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private async startHttpService() {
|
||||
// 在导入任何 gRPC 客户端模块之前初始化 mTLS 证书
|
||||
const { initGrpcCerts } = await import('./config/grpcCerts');
|
||||
await initGrpcCerts();
|
||||
|
||||
this.setupMiddlewares();
|
||||
|
||||
const { HttpServerService } = await import('./services/http');
|
||||
@@ -265,13 +267,13 @@ class Application {
|
||||
} else if (msg === 'reregister-crons' && serviceType === 'http') {
|
||||
// Re-register cron jobs when gRPC worker restarts
|
||||
try {
|
||||
Logger.info('✌️ Received reregister-crons message, re-registering cron jobs...');
|
||||
Logger.info('[boot] Received reregister-crons message, re-registering cron jobs...');
|
||||
const CronService = (await import('./services/cron')).default;
|
||||
const cronService = Container.get(CronService);
|
||||
await cronService.autosave_crontab();
|
||||
Logger.info('✌️ Cron jobs re-registered successfully');
|
||||
Logger.info('[boot] Cron jobs re-registered successfully');
|
||||
} catch (error) {
|
||||
Logger.error('✌️ Failed to re-register cron jobs:', error);
|
||||
Logger.error(`[boot] Failed to re-register cron jobs:\n${errStack(error)}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -293,7 +295,7 @@ class Application {
|
||||
}
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
Logger.error(`✌️ [${serviceType}] Error during shutdown:`, error);
|
||||
Logger.error(`[${serviceType}] Error during shutdown:\n${errStack(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -301,6 +303,6 @@ class Application {
|
||||
|
||||
const app = new Application();
|
||||
app.start().catch((error) => {
|
||||
Logger.error('🙅♀️ Application failed to start:', error);
|
||||
Logger.error(`🙅♀️ Application failed to start:\n${errStack(error)}`);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { maybeSudo } from './container';
|
||||
|
||||
export const LOG_END_SYMBOL = ' ';
|
||||
|
||||
export const TASK_COMMAND = 'task';
|
||||
@@ -48,4 +50,40 @@ export const NotificationModeStringMap = {
|
||||
18: 'chronocat',
|
||||
19: 'ntfy',
|
||||
20: 'wxPusherBot',
|
||||
21: 'wxPusherSpt',
|
||||
} as const;
|
||||
|
||||
export const LINUX_DEPENDENCE_COMMAND: Record<
|
||||
'Debian' | 'Ubuntu' | 'Alpine',
|
||||
{
|
||||
install: string;
|
||||
uninstall: string;
|
||||
info: string;
|
||||
check(info: string): boolean;
|
||||
}
|
||||
> = {
|
||||
Debian: {
|
||||
install: maybeSudo('apt-get install -y'),
|
||||
uninstall: maybeSudo('apt-get remove -y'),
|
||||
info: maybeSudo('dpkg-query -s'),
|
||||
check(info: string) {
|
||||
return info.includes('install ok installed');
|
||||
},
|
||||
},
|
||||
Ubuntu: {
|
||||
install: maybeSudo('apt-get install -y'),
|
||||
uninstall: maybeSudo('apt-get remove -y'),
|
||||
info: maybeSudo('dpkg-query -s'),
|
||||
check(info: string) {
|
||||
return info.includes('install ok installed');
|
||||
},
|
||||
},
|
||||
Alpine: {
|
||||
install: 'apk add --no-check-certificate',
|
||||
uninstall: 'apk del',
|
||||
info: 'apk info -es',
|
||||
check(info: string) {
|
||||
return info.includes('installed');
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export function isInContainer(): boolean {
|
||||
return process.env.QL_CONTAINER === 'true';
|
||||
}
|
||||
|
||||
export function maybeSudo(cmd: string): string {
|
||||
return isInContainer() ? `sudo ${cmd}` : cmd;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { execSync } from 'child_process';
|
||||
import * as fs from 'fs/promises';
|
||||
import * as os from 'os';
|
||||
import path from 'path';
|
||||
import config from './index';
|
||||
import { fileExist } from './util';
|
||||
import Logger from '../loaders/logger';
|
||||
|
||||
export interface GrpcTlsConfig {
|
||||
caCert: string;
|
||||
serverCert: string;
|
||||
serverKey: string;
|
||||
clientCert: string;
|
||||
clientKey: string;
|
||||
}
|
||||
|
||||
const certDir = path.join(config.configPath, 'grpc');
|
||||
const caKeyPath = path.join(certDir, 'ca.key');
|
||||
const caCertPath = path.join(certDir, 'ca.crt');
|
||||
const serverKeyPath = path.join(certDir, 'server.key');
|
||||
const serverCertPath = path.join(certDir, 'server.crt');
|
||||
const clientKeyPath = path.join(certDir, 'client.key');
|
||||
const clientCertPath = path.join(certDir, 'client.crt');
|
||||
|
||||
let cachedConfig: GrpcTlsConfig | null = null;
|
||||
|
||||
function run(cmd: string, execOpts?: Record<string, unknown>): string {
|
||||
const opts = { stdio: 'pipe', timeout: 30000, encoding: 'utf-8', ...execOpts } as any;
|
||||
return (execSync(cmd, opts) as string).trim();
|
||||
}
|
||||
|
||||
async function tmpFile(prefix: string): Promise<string> {
|
||||
const dir = (await fileExist(certDir)) ? certDir : os.tmpdir();
|
||||
await fs.mkdir(dir, { recursive: true });
|
||||
return path.join(dir, `.${prefix}_${Date.now()}_${Math.random().toString(36).slice(2)}.pem`);
|
||||
}
|
||||
|
||||
async function generateAllCerts(): Promise<GrpcTlsConfig> {
|
||||
Logger.info('[boot] Generating gRPC mTLS certificates...');
|
||||
|
||||
const caKeyTmp = await tmpFile('ca_key');
|
||||
const caCertTmp = await tmpFile('ca_cert');
|
||||
const serverKeyTmp = await tmpFile('server_key');
|
||||
const serverCsrTmp = await tmpFile('server_csr');
|
||||
const serverExtTmp = await tmpFile('server_ext');
|
||||
const clientKeyTmp = await tmpFile('client_key');
|
||||
const clientCsrTmp = await tmpFile('client_csr');
|
||||
const clientExtTmp = await tmpFile('client_ext');
|
||||
const srlTmp = path.join(path.dirname(caKeyTmp), '.grpc_ca.srl');
|
||||
|
||||
const cleanup = async () => {
|
||||
for (const f of [caKeyTmp, caCertTmp, serverKeyTmp, serverCsrTmp, serverExtTmp,
|
||||
clientKeyTmp, clientCsrTmp, clientExtTmp, srlTmp]) {
|
||||
try { await fs.unlink(f); } catch {}
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
// 1. CA(私钥直接存盘,证书写入临时文件供签发使用)
|
||||
run(`openssl genrsa -out '${caKeyTmp}' 2048 2>/dev/null`);
|
||||
run(`openssl req -new -x509 -days 3650 -key '${caKeyTmp}' -out '${caCertTmp}' -subj '/CN=qinglong-ca/O=qinglong/C=CN' 2>/dev/null`);
|
||||
const caKey = await fs.readFile(caKeyTmp, 'utf-8');
|
||||
const caCert = await fs.readFile(caCertTmp, 'utf-8');
|
||||
await fs.mkdir(certDir, { recursive: true });
|
||||
await fs.writeFile(caKeyPath, caKey, { mode: 0o600 });
|
||||
|
||||
// 2. 服务端
|
||||
run(`openssl genrsa -out '${serverKeyTmp}' 2048 2>/dev/null`);
|
||||
run(`openssl req -new -key '${serverKeyTmp}' -out '${serverCsrTmp}' -subj '/CN=grpc-server' 2>/dev/null`);
|
||||
await fs.writeFile(serverExtTmp, 'subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1\n');
|
||||
const serverCert = run(
|
||||
`openssl x509 -req -days 3650 -in '${serverCsrTmp}' -CA '${caCertTmp}' -CAkey '${caKeyTmp}' -CAcreateserial -extfile '${serverExtTmp}' 2>/dev/null`,
|
||||
);
|
||||
const serverKey = await fs.readFile(serverKeyTmp, 'utf-8');
|
||||
|
||||
// 3. 客户端
|
||||
run(`openssl genrsa -out '${clientKeyTmp}' 2048 2>/dev/null`);
|
||||
run(`openssl req -new -key '${clientKeyTmp}' -out '${clientCsrTmp}' -subj '/CN=grpc-client' 2>/dev/null`);
|
||||
await fs.writeFile(clientExtTmp, 'extendedKeyUsage=clientAuth\n');
|
||||
const clientCert = run(
|
||||
`openssl x509 -req -days 3650 -in '${clientCsrTmp}' -CA '${caCertTmp}' -CAkey '${caKeyTmp}' -CAcreateserial -extfile '${clientExtTmp}' 2>/dev/null`,
|
||||
);
|
||||
const clientKey = await fs.readFile(clientKeyTmp, 'utf-8');
|
||||
|
||||
await cleanup();
|
||||
Logger.info('[boot] gRPC mTLS certificates generated successfully');
|
||||
|
||||
return { caCert, serverCert, serverKey, clientCert, clientKey };
|
||||
} catch (e) {
|
||||
await cleanup();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveCerts(tlsConfig: GrpcTlsConfig): Promise<void> {
|
||||
await fs.mkdir(certDir, { recursive: true });
|
||||
|
||||
await fs.writeFile(caCertPath, tlsConfig.caCert, { mode: 0o644 });
|
||||
await fs.writeFile(serverCertPath, tlsConfig.serverCert, { mode: 0o644 });
|
||||
await fs.writeFile(serverKeyPath, tlsConfig.serverKey, { mode: 0o600 });
|
||||
await fs.writeFile(clientCertPath, tlsConfig.clientCert, { mode: 0o644 });
|
||||
await fs.writeFile(clientKeyPath, tlsConfig.clientKey, { mode: 0o600 });
|
||||
|
||||
Logger.info(`[boot] gRPC mTLS certificates saved to ${certDir}`);
|
||||
}
|
||||
|
||||
async function loadExistingCerts(): Promise<GrpcTlsConfig | null> {
|
||||
const exists = await Promise.all([
|
||||
fileExist(caCertPath),
|
||||
fileExist(serverCertPath),
|
||||
fileExist(serverKeyPath),
|
||||
fileExist(clientCertPath),
|
||||
fileExist(clientKeyPath),
|
||||
]);
|
||||
|
||||
if (exists.some((e) => !e)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [caCert, serverCert, serverKey, clientCert, clientKey] = await Promise.all([
|
||||
fs.readFile(caCertPath, 'utf-8'),
|
||||
fs.readFile(serverCertPath, 'utf-8'),
|
||||
fs.readFile(serverKeyPath, 'utf-8'),
|
||||
fs.readFile(clientCertPath, 'utf-8'),
|
||||
fs.readFile(clientKeyPath, 'utf-8'),
|
||||
]);
|
||||
|
||||
Logger.info('[boot] Loaded existing gRPC mTLS certificates from disk');
|
||||
return { caCert, serverCert, serverKey, clientCert, clientKey };
|
||||
}
|
||||
|
||||
export async function initGrpcCerts(): Promise<GrpcTlsConfig> {
|
||||
if (cachedConfig) {
|
||||
return cachedConfig;
|
||||
}
|
||||
|
||||
let tlsConfig = await loadExistingCerts();
|
||||
|
||||
if (!tlsConfig) {
|
||||
tlsConfig = await generateAllCerts();
|
||||
await saveCerts(tlsConfig);
|
||||
}
|
||||
|
||||
cachedConfig = tlsConfig;
|
||||
return tlsConfig;
|
||||
}
|
||||
|
||||
export function getGrpcCerts(): GrpcTlsConfig | null {
|
||||
return cachedConfig;
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import dotenv from 'dotenv';
|
||||
import path from 'path';
|
||||
import { createRandomString } from './share';
|
||||
|
||||
dotenv.config({
|
||||
path: path.join(__dirname, '../../.env'),
|
||||
@@ -9,6 +8,8 @@ dotenv.config({
|
||||
interface Config {
|
||||
port: number;
|
||||
grpcPort: number;
|
||||
bindHost: string;
|
||||
bindHostGrpc: string;
|
||||
nodeEnv: string;
|
||||
isDevelopment: boolean;
|
||||
isProduction: boolean;
|
||||
@@ -31,6 +32,8 @@ interface Config {
|
||||
const config: Config = {
|
||||
port: parseInt(process.env.BACK_PORT || '5700', 10),
|
||||
grpcPort: parseInt(process.env.GRPC_PORT || '5500', 10),
|
||||
bindHost: process.env.BIND_HOST || '::',
|
||||
bindHostGrpc: process.env.BIND_HOST_GRPC || '::',
|
||||
nodeEnv: process.env.NODE_ENV || 'development',
|
||||
isDevelopment: process.env.NODE_ENV === 'development',
|
||||
isProduction: process.env.NODE_ENV === 'production',
|
||||
@@ -106,6 +109,7 @@ const jsEnvFile = path.join(preloadPath, 'env.js');
|
||||
const pyEnvFile = path.join(preloadPath, 'env.py');
|
||||
const jsNotifyFile = path.join(preloadPath, '__ql_notify__.js');
|
||||
const pyNotifyFile = path.join(preloadPath, '__ql_notify__.py');
|
||||
const langEnvFile = path.join(preloadPath, 'lang_env.sh');
|
||||
const confFile = path.join(configPath, 'config.sh');
|
||||
const crontabFile = path.join(configPath, 'crontab.list');
|
||||
const authConfigFile = path.join(configPath, 'auth.json');
|
||||
@@ -114,8 +118,6 @@ const confBakDir = path.join(dataPath, 'config/bak/');
|
||||
const sampleFile = path.join(samplePath, 'config.sample.sh');
|
||||
const sqliteFile = path.join(samplePath, 'database.sqlite');
|
||||
|
||||
const authError = '错误的用户名密码,请重试';
|
||||
const loginFaild = '请先登录!';
|
||||
const configString = 'config sample crontab shareCode diy';
|
||||
const versionFile = path.join(rootPath, 'version.yaml');
|
||||
const dataTgzFile = path.join(tmpPath, 'data.tgz');
|
||||
@@ -137,8 +139,6 @@ export default {
|
||||
shareShellFile,
|
||||
dependenceProxyFile,
|
||||
configString,
|
||||
loginFaild,
|
||||
authError,
|
||||
logPath,
|
||||
extraFile,
|
||||
authConfigFile,
|
||||
@@ -151,6 +151,7 @@ export default {
|
||||
pyEnvFile,
|
||||
jsNotifyFile,
|
||||
pyNotifyFile,
|
||||
langEnvFile,
|
||||
dbPath,
|
||||
uploadPath,
|
||||
configPath,
|
||||
@@ -167,6 +168,8 @@ export default {
|
||||
'env.js',
|
||||
'env.py',
|
||||
'token.json',
|
||||
'grpc',
|
||||
'__pycache__',
|
||||
],
|
||||
writePathList: [configPath, scriptPath],
|
||||
bakPath,
|
||||
|
||||
+202
-71
@@ -1,6 +1,6 @@
|
||||
import * as fs from 'fs/promises';
|
||||
import * as path from 'path';
|
||||
import { exec } from 'child_process';
|
||||
import { exec, execSync } from 'child_process';
|
||||
import psTreeFun from 'ps-tree';
|
||||
import { promisify } from 'util';
|
||||
import { load } from 'js-yaml';
|
||||
@@ -10,9 +10,39 @@ import Logger from '../loaders/logger';
|
||||
import { writeFileWithLock } from '../shared/utils';
|
||||
import { DependenceTypes } from '../data/dependence';
|
||||
import { FormData } from 'undici';
|
||||
import os from 'os';
|
||||
import { maybeSudo, isInContainer } from './container';
|
||||
|
||||
export * from './share';
|
||||
|
||||
let osType: 'Debian' | 'Ubuntu' | 'Alpine' | undefined;
|
||||
|
||||
function getOsTypeSync(): 'Debian' | 'Ubuntu' | 'Alpine' | undefined {
|
||||
// 1. 环境变量覆盖
|
||||
const envOs = process.env.QL_OS_TYPE?.toLowerCase();
|
||||
if (envOs === 'alpine') return 'Alpine';
|
||||
if (envOs === 'debian') return 'Debian';
|
||||
if (envOs === 'ubuntu') return 'Ubuntu';
|
||||
|
||||
// 2. 模块缓存(由 detectOS 设置)
|
||||
if (osType) return osType;
|
||||
|
||||
// 3. 能力检测:检查包管理器二进制
|
||||
try {
|
||||
execSync('which apt-get', { stdio: 'ignore' });
|
||||
return 'Debian';
|
||||
} catch {
|
||||
try {
|
||||
execSync('which apk', { stdio: 'ignore' });
|
||||
return 'Alpine';
|
||||
} catch {
|
||||
// macOS / 未知系统
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function getFileContentByName(fileName: string) {
|
||||
const _exsit = await fileExist(fileName);
|
||||
if (_exsit) {
|
||||
@@ -233,7 +263,10 @@ export async function readDir(
|
||||
baseDir: string = '',
|
||||
blacklist: string[] = [],
|
||||
): Promise<IFile[]> {
|
||||
const absoluteDir = path.join(baseDir, dir);
|
||||
const absoluteDir = path.resolve(baseDir, dir);
|
||||
if (!absoluteDir.startsWith(path.resolve(baseDir))) {
|
||||
return [];
|
||||
}
|
||||
const relativePath = path.relative(baseDir, absoluteDir);
|
||||
|
||||
try {
|
||||
@@ -405,7 +438,7 @@ export async function killTask(pid: number) {
|
||||
[pid, ...pids].reverse().forEach((x) => {
|
||||
process.kill(x, 15);
|
||||
});
|
||||
} catch (error) {}
|
||||
} catch (error) { }
|
||||
} else {
|
||||
process.kill(pid, 2);
|
||||
}
|
||||
@@ -503,11 +536,17 @@ export function safeJSONParse(value?: string) {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch (error) {
|
||||
Logger.error('[safeJSONParse失败]', error);
|
||||
Logger.error('[safeJSONParse error]', error);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function errStack(error: unknown): string {
|
||||
return error instanceof Error && error.stack
|
||||
? error.stack
|
||||
: String(error);
|
||||
}
|
||||
|
||||
export async function rmPath(path: string) {
|
||||
try {
|
||||
const _exsit = await fileExist(path);
|
||||
@@ -515,7 +554,7 @@ export async function rmPath(path: string) {
|
||||
await fs.rm(path, { force: true, recursive: true, maxRetries: 5 });
|
||||
}
|
||||
} catch (error) {
|
||||
Logger.error('[rmPath失败]', error);
|
||||
Logger.error('[rmPath error]', error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -525,53 +564,22 @@ export async function setSystemTimezone(timezone: string): Promise<boolean> {
|
||||
throw new Error('Invalid timezone');
|
||||
}
|
||||
|
||||
await promiseExec(`ln -sf /usr/share/zoneinfo/${timezone} /etc/localtime`);
|
||||
await promiseExec(`echo "${timezone}" > /etc/timezone`);
|
||||
await promiseExec(maybeSudo(`ln -sf /usr/share/zoneinfo/${timezone} /etc/localtime`));
|
||||
await promiseExec(`echo "${timezone}" | ${maybeSudo('tee /etc/timezone')}`);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
Logger.error('[setSystemTimezone失败]', error);
|
||||
Logger.error('[setSystemTimezone error]', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to check if a name is a GitHub URL
|
||||
function isGitHubUrl(name: string): boolean {
|
||||
// Support git+https://, git+http://, https://, and http:// URLs
|
||||
// This covers GitHub URLs and other git-compatible repositories
|
||||
return !!name.match(/^(git\+https?:\/\/|https?:\/\/)/i);
|
||||
}
|
||||
|
||||
// Helper function to check if a name is a requirements file
|
||||
function isRequirementsFile(name: string): boolean {
|
||||
return !!name.match(/requirements.*\.(txt|in)$/i);
|
||||
}
|
||||
|
||||
// Helper function to check if a name is a pyproject.toml file
|
||||
function isPyprojectToml(name: string): boolean {
|
||||
return name.endsWith('pyproject.toml');
|
||||
}
|
||||
|
||||
export function getGetCommand(type: DependenceTypes, name: string): string {
|
||||
const trimmedName = name.trim();
|
||||
|
||||
// For Python dependencies installed from GitHub or requirements files,
|
||||
// we can't reliably check if they're installed, so skip the check
|
||||
if (type === DependenceTypes.python3) {
|
||||
if (isGitHubUrl(trimmedName) ||
|
||||
isRequirementsFile(trimmedName) ||
|
||||
isPyprojectToml(trimmedName)) {
|
||||
// Return a command that will always indicate not installed
|
||||
// This ensures GitHub URLs and requirements files are always installed
|
||||
return 'echo ""';
|
||||
}
|
||||
}
|
||||
|
||||
const baseCommands = {
|
||||
[DependenceTypes.nodejs]: `pnpm ls -g | grep "${trimmedName}" | head -1`,
|
||||
[DependenceTypes.nodejs]: `pnpm ls -g | grep "${name}" | head -1`,
|
||||
[DependenceTypes.python3]: `
|
||||
python3 -c "exec('''
|
||||
name='${trimmedName}'
|
||||
name='${name}'
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
print(version(name))
|
||||
@@ -581,7 +589,9 @@ except:
|
||||
spec=u.find_spec(name)
|
||||
print(name if spec else '')
|
||||
''')"`,
|
||||
[DependenceTypes.linux]: `apk info -es ${trimmedName}`,
|
||||
[DependenceTypes.linux]: getOsTypeSync() === 'Alpine'
|
||||
? `apk info -es ${name}`
|
||||
: maybeSudo(`dpkg-query -s ${name}`),
|
||||
};
|
||||
|
||||
return baseCommands[type];
|
||||
@@ -592,7 +602,9 @@ export function getInstallCommand(type: DependenceTypes, name: string): string {
|
||||
[DependenceTypes.nodejs]: 'pnpm add -g',
|
||||
[DependenceTypes.python3]:
|
||||
'pip3 install --disable-pip-version-check --root-user-action=ignore',
|
||||
[DependenceTypes.linux]: 'apk add --no-check-certificate',
|
||||
[DependenceTypes.linux]: getOsTypeSync() === 'Alpine'
|
||||
? 'apk add --no-check-certificate'
|
||||
: maybeSudo('apt-get install -y'),
|
||||
};
|
||||
|
||||
let command = baseCommands[type];
|
||||
@@ -601,33 +613,7 @@ export function getInstallCommand(type: DependenceTypes, name: string): string {
|
||||
command = `${command} --prefix=${PYTHON_INSTALL_DIR}`;
|
||||
}
|
||||
|
||||
const trimmedName = name.trim();
|
||||
|
||||
// Handle different installation methods for Python
|
||||
if (type === DependenceTypes.python3) {
|
||||
// Check if it's a GitHub URL (support both git+ and direct URLs)
|
||||
if (isGitHubUrl(trimmedName)) {
|
||||
return `${command} ${trimmedName}`;
|
||||
}
|
||||
// Check if it's a requirements file path
|
||||
if (isRequirementsFile(trimmedName)) {
|
||||
return `${command} -r ${trimmedName}`;
|
||||
}
|
||||
// Check if it's a pyproject.toml file
|
||||
if (isPyprojectToml(trimmedName)) {
|
||||
// For pyproject.toml, install from the directory containing it
|
||||
const pathMatch = trimmedName.match(/^(.+)\/pyproject\.toml$/);
|
||||
if (pathMatch) {
|
||||
// Has a path prefix, use the directory
|
||||
return `${command} ${pathMatch[1]}`;
|
||||
} else {
|
||||
// Just "pyproject.toml", install current directory
|
||||
return `${command} .`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return `${command} ${trimmedName}`;
|
||||
return `${command} ${name.trim()}`;
|
||||
}
|
||||
|
||||
export function getUninstallCommand(
|
||||
@@ -638,7 +624,9 @@ export function getUninstallCommand(
|
||||
[DependenceTypes.nodejs]: 'pnpm remove -g',
|
||||
[DependenceTypes.python3]:
|
||||
'pip3 uninstall --disable-pip-version-check --root-user-action=ignore -y',
|
||||
[DependenceTypes.linux]: 'apk del',
|
||||
[DependenceTypes.linux]: getOsTypeSync() === 'Alpine'
|
||||
? 'apk del'
|
||||
: maybeSudo('apt-get remove -y'),
|
||||
};
|
||||
|
||||
return `${baseCommands[type]} ${name.trim()}`;
|
||||
@@ -647,3 +635,146 @@ export function getUninstallCommand(
|
||||
export function isDemoEnv() {
|
||||
return process.env.DeployEnv === 'demo';
|
||||
}
|
||||
|
||||
async function getOSReleaseInfo(): Promise<string> {
|
||||
const osRelease = await fs.readFile('/etc/os-release', 'utf8');
|
||||
return osRelease;
|
||||
}
|
||||
|
||||
function isDebian(osReleaseInfo: string): boolean {
|
||||
return osReleaseInfo.includes('Debian');
|
||||
}
|
||||
|
||||
function isUbuntu(osReleaseInfo: string): boolean {
|
||||
return osReleaseInfo.includes('Ubuntu');
|
||||
}
|
||||
|
||||
function isCentOS(osReleaseInfo: string): boolean {
|
||||
return osReleaseInfo.includes('CentOS') || osReleaseInfo.includes('Red Hat');
|
||||
}
|
||||
|
||||
function isAlpine(osReleaseInfo: string): boolean {
|
||||
return osReleaseInfo.includes('Alpine');
|
||||
}
|
||||
|
||||
export async function detectOS(): Promise<
|
||||
'Debian' | 'Ubuntu' | 'Alpine' | undefined
|
||||
> {
|
||||
if (osType) return osType;
|
||||
|
||||
const envOs = process.env.QL_OS_TYPE?.toLowerCase();
|
||||
if (envOs === 'alpine') {
|
||||
osType = 'Alpine';
|
||||
return osType;
|
||||
}
|
||||
if (envOs === 'debian') {
|
||||
osType = 'Debian';
|
||||
return osType;
|
||||
}
|
||||
if (envOs === 'ubuntu') {
|
||||
osType = 'Ubuntu';
|
||||
return osType;
|
||||
}
|
||||
|
||||
const platform = os.platform();
|
||||
|
||||
if (platform === 'linux') {
|
||||
const osReleaseInfo = await getOSReleaseInfo();
|
||||
if (isDebian(osReleaseInfo)) {
|
||||
osType = 'Debian';
|
||||
} else if (isUbuntu(osReleaseInfo)) {
|
||||
osType = 'Ubuntu';
|
||||
} else if (isAlpine(osReleaseInfo)) {
|
||||
osType = 'Alpine';
|
||||
} else {
|
||||
Logger.error(`Unknown Linux Distribution: ${osReleaseInfo}`);
|
||||
console.error(`Unknown Linux Distribution: ${osReleaseInfo}`);
|
||||
}
|
||||
} else if (platform === 'darwin') {
|
||||
osType = undefined;
|
||||
} else {
|
||||
Logger.error(`Unsupported platform: ${platform}`);
|
||||
console.error(`Unsupported platform: ${platform}`);
|
||||
}
|
||||
|
||||
return osType;
|
||||
}
|
||||
|
||||
async function getCurrentMirrorDomain(
|
||||
filePath: string,
|
||||
): Promise<string | null> {
|
||||
const fileContent = await fs.readFile(filePath, 'utf8');
|
||||
const lines = fileContent.split('\n');
|
||||
for (const line of lines) {
|
||||
if (line.trim().startsWith('#')) {
|
||||
continue;
|
||||
}
|
||||
const match = line.match(/https?:\/\/[^\/]+/);
|
||||
if (match) {
|
||||
return match[0];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function replaceDomainInFile(
|
||||
filePath: string,
|
||||
oldDomainWithScheme: string,
|
||||
newDomainWithScheme: string,
|
||||
): Promise<void> {
|
||||
let fileContent = await fs.readFile(filePath, 'utf8');
|
||||
let updatedContent = fileContent.replace(
|
||||
new RegExp(oldDomainWithScheme, 'g'),
|
||||
newDomainWithScheme,
|
||||
);
|
||||
|
||||
if (!newDomainWithScheme.endsWith('/')) {
|
||||
newDomainWithScheme += '/';
|
||||
}
|
||||
|
||||
await writeFileWithLock(filePath, updatedContent);
|
||||
}
|
||||
|
||||
async function _updateLinuxMirror(
|
||||
osType: string,
|
||||
mirrorDomainWithScheme: string,
|
||||
): Promise<string> {
|
||||
const S = isInContainer() ? 'sudo ' : '';
|
||||
let filePath: string, currentDomainWithScheme: string | null;
|
||||
switch (osType) {
|
||||
case 'Debian':
|
||||
filePath = '/etc/apt/sources.list.d/debian.sources';
|
||||
currentDomainWithScheme = await getCurrentMirrorDomain(filePath);
|
||||
if (currentDomainWithScheme) {
|
||||
return `${S}sed -i 's|${currentDomainWithScheme}|${mirrorDomainWithScheme || 'http://deb.debian.org'}|g' ${filePath} || (${S}mkdir -p /etc/apt/sources.list.d && echo -e "Types: deb\\nURIs: ${mirrorDomainWithScheme || 'http://deb.debian.org'}\\nSuites: \\$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2) \\$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2)-updates\\nComponents: main\\nSigned-By: /usr/share/keyrings/debian-archive-keyring.gpg" | ${S}tee ${filePath}) && ${S}apt-get update`;
|
||||
} else {
|
||||
return `${S}mkdir -p /etc/apt/sources.list.d && echo -e "Types: deb\\nURIs: ${mirrorDomainWithScheme || 'http://deb.debian.org'}\\nSuites: \\$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2) \\$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2)-updates\\nComponents: main\\nSigned-By: /usr/share/keyrings/debian-archive-keyring.gpg" | ${S}tee ${filePath} && ${S}apt-get update`;
|
||||
}
|
||||
case 'Ubuntu':
|
||||
filePath = '/etc/apt/sources.list.d/ubuntu.sources';
|
||||
currentDomainWithScheme = await getCurrentMirrorDomain(filePath);
|
||||
if (currentDomainWithScheme) {
|
||||
return `${S}sed -i 's|${currentDomainWithScheme}|${mirrorDomainWithScheme || 'http://archive.ubuntu.com'}|g' ${filePath} || (${S}mkdir -p /etc/apt/sources.list.d && echo -e "Types: deb\\nURIs: ${mirrorDomainWithScheme || 'http://archive.ubuntu.com'}\\nSuites: \\$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2) \\$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2)-updates \\$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2)-backports\\nComponents: main restricted universe multiverse\\nSigned-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg" | ${S}tee ${filePath}) && ${S}apt-get update`;
|
||||
} else {
|
||||
return `${S}mkdir -p /etc/apt/sources.list.d && echo -e "Types: deb\\nURIs: ${mirrorDomainWithScheme || 'http://archive.ubuntu.com'}\\nSuites: \\$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2) \\$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2)-updates \\$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2)-backports\\nComponents: main restricted universe multiverse\\nSigned-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg" | ${S}tee ${filePath} && ${S}apt-get update`;
|
||||
}
|
||||
case 'Alpine':
|
||||
filePath = '/etc/apk/repositories';
|
||||
currentDomainWithScheme = await getCurrentMirrorDomain(filePath);
|
||||
if (currentDomainWithScheme) {
|
||||
return `sed -i 's|${currentDomainWithScheme}|${mirrorDomainWithScheme || 'http://dl-cdn.alpinelinux.org'}|g' ${filePath} || (mkdir -p /etc/apk && echo -e "\\$(grep VERSION_ID /etc/os-release | cut -d= -f2 | cut -d. -f1,2)/main\\n\\$(grep VERSION_ID /etc/os-release | cut -d= -f2 | cut -d. -f1,2)/community" | sed "s|^|${mirrorDomainWithScheme || 'http://dl-cdn.alpinelinux.org'}/alpine/v|" | tee ${filePath}) && apk update`;
|
||||
} else {
|
||||
return `mkdir -p /etc/apk && echo -e "\\$(grep VERSION_ID /etc/os-release | cut -d= -f2 | cut -d. -f1,2)/main\\n\\$(grep VERSION_ID /etc/os-release | cut -d= -f2 | cut -d. -f1,2)/community" | sed "s|^|${mirrorDomainWithScheme || 'http://dl-cdn.alpinelinux.org'}/alpine/v|" | tee ${filePath} && apk update`;
|
||||
}
|
||||
default:
|
||||
throw Error('Unsupported OS type for updating mirrors.');
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateLinuxMirrorFile(mirror: string): Promise<string> {
|
||||
const detectedOS = await detectOS();
|
||||
if (!detectedOS) {
|
||||
throw Error(`Unknown Linux Distribution`);
|
||||
}
|
||||
return await _updateLinuxMirror(detectedOS, mirror);
|
||||
}
|
||||
|
||||
+5
-2
@@ -23,6 +23,7 @@ export class Crontab {
|
||||
task_after?: string;
|
||||
log_name?: string;
|
||||
allow_multiple_instances?: 1 | 0;
|
||||
work_dir?: string;
|
||||
|
||||
constructor(options: Crontab) {
|
||||
this.name = options.name;
|
||||
@@ -49,14 +50,15 @@ export class Crontab {
|
||||
this.task_after = options.task_after;
|
||||
this.log_name = options.log_name;
|
||||
this.allow_multiple_instances = options.allow_multiple_instances || 0;
|
||||
this.work_dir = options.work_dir;
|
||||
}
|
||||
}
|
||||
|
||||
export enum CrontabStatus {
|
||||
'running' = 0,
|
||||
'queued' = 0.5,
|
||||
'idle' = 1,
|
||||
'disabled',
|
||||
'disabled' = 2,
|
||||
'queued' = 3,
|
||||
}
|
||||
|
||||
export interface CronInstance extends Model<Crontab, Crontab>, Crontab {}
|
||||
@@ -90,4 +92,5 @@ export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
||||
task_after: DataTypes.STRING,
|
||||
log_name: DataTypes.STRING,
|
||||
allow_multiple_instances: DataTypes.NUMBER,
|
||||
work_dir: DataTypes.STRING,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { DataTypes, Model } from 'sequelize';
|
||||
import { sequelize } from '.';
|
||||
|
||||
export class CrontabStat {
|
||||
id?: number;
|
||||
ref_id!: number;
|
||||
date!: string;
|
||||
run_count?: number;
|
||||
success_count?: number;
|
||||
fail_count?: number;
|
||||
total_time?: number;
|
||||
max_time?: number;
|
||||
|
||||
constructor(options: CrontabStat) {
|
||||
this.id = options.id;
|
||||
this.ref_id = options.ref_id;
|
||||
this.date = options.date;
|
||||
this.run_count = options.run_count || 0;
|
||||
this.success_count = options.success_count || 0;
|
||||
this.fail_count = options.fail_count || 0;
|
||||
this.total_time = options.total_time || 0;
|
||||
this.max_time = options.max_time || 0;
|
||||
}
|
||||
}
|
||||
|
||||
export interface CrontabStatInstance extends Model<CrontabStat, CrontabStat>, CrontabStat {}
|
||||
|
||||
export const CrontabStatModel = sequelize.define<CrontabStatInstance>(
|
||||
'CrontabStat',
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
ref_id: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: false,
|
||||
},
|
||||
date: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
run_count: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
success_count: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
fail_count: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
total_time: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
max_time: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
indexes: [
|
||||
{ unique: true, fields: ['ref_id', 'date'] },
|
||||
{ fields: ['date'] },
|
||||
],
|
||||
},
|
||||
);
|
||||
@@ -10,6 +10,7 @@ export class Env {
|
||||
name?: string;
|
||||
remarks?: string;
|
||||
isPinned?: 1 | 0;
|
||||
labels?: string[];
|
||||
|
||||
constructor(options: Env) {
|
||||
this.value = options.value;
|
||||
@@ -23,6 +24,7 @@ export class Env {
|
||||
this.name = options.name;
|
||||
this.remarks = options.remarks || '';
|
||||
this.isPinned = options.isPinned || 0;
|
||||
this.labels = options.labels || [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,4 +47,5 @@ export const EnvModel = sequelize.define<EnvInstance>('Env', {
|
||||
name: { type: DataTypes.STRING, unique: 'compositeIndex' },
|
||||
remarks: DataTypes.STRING,
|
||||
isPinned: DataTypes.NUMBER,
|
||||
labels: DataTypes.JSON,
|
||||
});
|
||||
|
||||
+14
-1
@@ -20,6 +20,7 @@ export enum NotificationMode {
|
||||
'chronocat' = 'Chronocat',
|
||||
'ntfy' = 'ntfy',
|
||||
'wxPusherBot' = 'wxPusherBot',
|
||||
'openiLink' = 'openiLink',
|
||||
}
|
||||
|
||||
abstract class NotificationBaseInfo {
|
||||
@@ -161,6 +162,16 @@ export class WxPusherBotNotification extends NotificationBaseInfo {
|
||||
public wxPusherBotUids = '';
|
||||
}
|
||||
|
||||
export class WxPusherSptNotification extends NotificationBaseInfo {
|
||||
public wxPusherSptList = '';
|
||||
}
|
||||
|
||||
export class OpeniLinkNotification extends NotificationBaseInfo {
|
||||
public openiLinkAppToken = '';
|
||||
public openiLinkHubUrl = '';
|
||||
public openiLinkContextToken = '';
|
||||
}
|
||||
|
||||
export interface NotificationInfo
|
||||
extends GoCqHttpBotNotification,
|
||||
GotifyNotification,
|
||||
@@ -182,4 +193,6 @@ export interface NotificationInfo
|
||||
ChronocatNotification,
|
||||
LarkNotification,
|
||||
NtfyNotification,
|
||||
WxPusherBotNotification {}
|
||||
WxPusherBotNotification,
|
||||
WxPusherSptNotification,
|
||||
OpeniLinkNotification {}
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ export interface AppToken {
|
||||
expiration: number;
|
||||
}
|
||||
|
||||
export type AppScope = 'envs' | 'crons' | 'configs' | 'scripts' | 'logs' | 'system';
|
||||
export type AppScope = 'envs' | 'crons' | 'configs' | 'scripts' | 'logs' | 'system' | 'dashboard';
|
||||
|
||||
export interface AppInstance extends Model<App, App>, App {}
|
||||
export const AppModel = sequelize.define<AppInstance>('App', {
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model } from 'sequelize';
|
||||
|
||||
export enum InstanceStatus {
|
||||
'running' = 0,
|
||||
'finished' = 1,
|
||||
'stopped' = 2,
|
||||
'error' = 3,
|
||||
}
|
||||
|
||||
export interface RunningInstanceAttributes {
|
||||
id?: number;
|
||||
cron_id: number;
|
||||
pid?: number;
|
||||
log_path?: string;
|
||||
started_at: number;
|
||||
finished_at?: number;
|
||||
status: InstanceStatus;
|
||||
exit_code?: number;
|
||||
}
|
||||
|
||||
export class RunningInstance {
|
||||
id?: number;
|
||||
cron_id!: number;
|
||||
pid?: number;
|
||||
log_path?: string;
|
||||
started_at!: number;
|
||||
finished_at?: number;
|
||||
status!: InstanceStatus;
|
||||
exit_code?: number;
|
||||
|
||||
constructor(options: RunningInstanceAttributes) {
|
||||
this.id = options.id;
|
||||
this.cron_id = options.cron_id;
|
||||
this.pid = options.pid;
|
||||
this.log_path = options.log_path;
|
||||
this.started_at = options.started_at;
|
||||
this.finished_at = options.finished_at;
|
||||
this.status = options.status;
|
||||
this.exit_code = options.exit_code;
|
||||
}
|
||||
}
|
||||
|
||||
export interface RunningInstanceModel
|
||||
extends Model<RunningInstanceAttributes, RunningInstanceAttributes>,
|
||||
RunningInstanceAttributes {}
|
||||
|
||||
export const RunningInstanceModel = sequelize.define<RunningInstanceModel>(
|
||||
'RunningInstance',
|
||||
{
|
||||
cron_id: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: false,
|
||||
},
|
||||
pid: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: true,
|
||||
},
|
||||
log_path: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: true,
|
||||
},
|
||||
started_at: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: false,
|
||||
},
|
||||
finished_at: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: true,
|
||||
},
|
||||
status: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: false,
|
||||
defaultValue: InstanceStatus.running,
|
||||
},
|
||||
exit_code: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -2,11 +2,13 @@ export class SockMessage {
|
||||
message?: string;
|
||||
type?: SockMessageType;
|
||||
references?: number[];
|
||||
status?: number | string;
|
||||
|
||||
constructor(options: SockMessage) {
|
||||
this.type = options.type;
|
||||
this.message = options.message;
|
||||
this.references = options.references;
|
||||
this.status = options.status;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,8 @@ export enum AuthDataType {
|
||||
}
|
||||
|
||||
export interface SystemConfigInfo {
|
||||
lang?: string;
|
||||
panelTitle?: string;
|
||||
logRemoveFrequency?: number;
|
||||
cronConcurrency?: number;
|
||||
dependenceProxy?: string;
|
||||
|
||||
+7
-7
@@ -9,20 +9,20 @@ import initFile from './initFile';
|
||||
|
||||
export default async ({ app }: { app: Application }) => {
|
||||
depInjectorLoader();
|
||||
Logger.info('✌️ Dependency loaded');
|
||||
Logger.info('[boot] Dependency loaded');
|
||||
|
||||
await linkDeps();
|
||||
Logger.info('✌️ Link deps loaded');
|
||||
Logger.info('[boot] Link deps loaded');
|
||||
|
||||
initFile();
|
||||
Logger.info('✌️ Init file loaded');
|
||||
await initFile();
|
||||
Logger.info('[boot] Init file loaded');
|
||||
|
||||
await initData();
|
||||
Logger.info('✌️ Init data loaded');
|
||||
Logger.info('[boot] Init data loaded');
|
||||
|
||||
initTask();
|
||||
Logger.info('✌️ Init task loaded');
|
||||
Logger.info('[boot] Init task loaded');
|
||||
|
||||
expressLoader({ app });
|
||||
Logger.info('✌️ Express loaded');
|
||||
Logger.info('[boot] Express loaded');
|
||||
};
|
||||
|
||||
+8
-2
@@ -6,6 +6,8 @@ import { AppModel } from '../data/open';
|
||||
import { SystemModel } from '../data/system';
|
||||
import { SubscriptionModel } from '../data/subscription';
|
||||
import { CrontabViewModel } from '../data/cronView';
|
||||
import { CrontabStatModel } from '../data/cronStats';
|
||||
import { RunningInstanceModel } from '../data/runningInstance';
|
||||
import { sequelize } from '../data';
|
||||
|
||||
export default async () => {
|
||||
@@ -17,6 +19,8 @@ export default async () => {
|
||||
await EnvModel.sync();
|
||||
await SubscriptionModel.sync();
|
||||
await CrontabViewModel.sync();
|
||||
await CrontabStatModel.sync();
|
||||
await RunningInstanceModel.sync();
|
||||
|
||||
// 初始化新增字段
|
||||
const migrations = [
|
||||
@@ -39,7 +43,9 @@ export default async () => {
|
||||
column: 'allow_multiple_instances',
|
||||
type: 'NUMBER',
|
||||
},
|
||||
{ table: 'Crontabs', column: 'work_dir', type: 'VARCHAR(255)' },
|
||||
{ table: 'Envs', column: 'isPinned', type: 'NUMBER' },
|
||||
{ table: 'Envs', column: 'labels', type: 'JSON' },
|
||||
];
|
||||
|
||||
for (const migration of migrations) {
|
||||
@@ -52,8 +58,8 @@ export default async () => {
|
||||
}
|
||||
}
|
||||
|
||||
Logger.info('✌️ DB loaded');
|
||||
Logger.info('[boot] DB loaded');
|
||||
} catch (error) {
|
||||
Logger.error('✌️ DB load failed', error);
|
||||
Logger.error('[boot] DB load failed', error);
|
||||
}
|
||||
};
|
||||
|
||||
+1
-25
@@ -1,22 +1,9 @@
|
||||
import path from 'path';
|
||||
import fs from 'fs/promises';
|
||||
import os from 'os';
|
||||
import chokidar from 'chokidar';
|
||||
import config from '../config/index';
|
||||
import Logger from './logger';
|
||||
|
||||
async function linkToNodeModule(src: string, dst?: string) {
|
||||
const target = path.join(config.rootPath, 'node_modules', dst || src);
|
||||
const source = path.join(config.rootPath, src);
|
||||
|
||||
try {
|
||||
const stats = await fs.lstat(target);
|
||||
if (!stats) {
|
||||
await fs.symlink(source, target, 'dir');
|
||||
}
|
||||
} catch (error) { }
|
||||
}
|
||||
|
||||
async function linkCommand() {
|
||||
const homeDir = os.homedir();
|
||||
let userBinDir = path.join(homeDir, 'bin');
|
||||
@@ -59,17 +46,6 @@ async function linkCommandToDir(commandDir: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export default async (src: string = 'deps') => {
|
||||
export default async () => {
|
||||
await linkCommand();
|
||||
await linkToNodeModule(src);
|
||||
|
||||
const source = path.join(config.rootPath, src);
|
||||
const watcher = chokidar.watch(source, {
|
||||
ignored: /(^|[\/\\])\../, // ignore dotfiles
|
||||
persistent: true,
|
||||
});
|
||||
|
||||
watcher
|
||||
.on('add', () => linkToNodeModule(src))
|
||||
.on('change', () => linkToNodeModule(src));
|
||||
};
|
||||
|
||||
+60
-26
@@ -8,14 +8,37 @@ import { getPlatform, getToken } from '../config/util';
|
||||
import rewrite from 'express-urlrewrite';
|
||||
import { errors } from 'celebrate';
|
||||
import { serveEnv } from '../config/serverEnv';
|
||||
import { IKeyvStore, shareStore } from '../shared/store';
|
||||
import { isValidToken } from '../shared/auth';
|
||||
import { shareStore } from '../shared/store';
|
||||
import { isValidToken, isDefaultAuthInfo } from '../shared/auth';
|
||||
import { AuthInfo } from '../data/system';
|
||||
import path from 'path';
|
||||
import { t } from '../shared/i18n';
|
||||
import { AppScope } from '../data/open';
|
||||
|
||||
export default ({ app }: { app: Application }) => {
|
||||
// Security: Enable strict routing to prevent case-insensitive path bypass
|
||||
app.set('case sensitive routing', true);
|
||||
app.set('strict routing', true);
|
||||
app.set('trust proxy', 'loopback');
|
||||
app.use(cors());
|
||||
|
||||
// Security: Path normalization middleware to prevent case variation attacks
|
||||
app.use((req, res, next) => {
|
||||
const originalPath = req.path;
|
||||
const normalizedPath = originalPath.toLowerCase();
|
||||
|
||||
// Block requests with case variations on protected paths
|
||||
if (originalPath !== normalizedPath &&
|
||||
(normalizedPath.startsWith('/api/') || normalizedPath.startsWith('/open/'))) {
|
||||
return res.status(400).json({
|
||||
code: 400,
|
||||
message: 'Invalid path format'
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
|
||||
// Rewrite URLs to strip baseUrl prefix if configured
|
||||
// This allows the rest of the app to work without baseUrl awareness
|
||||
if (config.baseUrl) {
|
||||
@@ -36,7 +59,7 @@ export default ({ app }: { app: Application }) => {
|
||||
secret: config.jwt.secret,
|
||||
algorithms: ['HS384'],
|
||||
}).unless({
|
||||
path: [...config.apiWhiteList, /^\/(?!api\/).*/],
|
||||
path: [...config.apiWhiteList, /^(\/(?!api\/).*)$/i],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -51,31 +74,41 @@ export default ({ app }: { app: Application }) => {
|
||||
});
|
||||
|
||||
app.use(async (req: Request, res, next) => {
|
||||
if (!['/open/', '/api/'].some((x) => req.path.startsWith(x))) {
|
||||
const pathLower = req.path.toLowerCase();
|
||||
if (!['/open/', '/api/'].some((x) => pathLower.startsWith(x))) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const headerToken = getToken(req);
|
||||
if (req.path.startsWith('/open/')) {
|
||||
if (pathLower.startsWith('/open/')) {
|
||||
const apps = await shareStore.getApps();
|
||||
const doc = apps?.filter((x) =>
|
||||
x.tokens?.find((y) => y.value === headerToken),
|
||||
)?.[0];
|
||||
if (doc && doc.tokens && doc.tokens.length > 0) {
|
||||
const currentToken = doc.tokens.find((x) => x.value === headerToken);
|
||||
const keyMatch = req.path.match(/\/open\/([a-z]+)\/*/);
|
||||
const keyMatch = pathLower.match(/\/open\/([a-z]+)\/*/);
|
||||
const key = keyMatch && keyMatch[1];
|
||||
if (
|
||||
doc.scopes.includes(key as any) &&
|
||||
currentToken &&
|
||||
currentToken.expiration >= Math.round(Date.now() / 1000)
|
||||
) {
|
||||
|
||||
if (!doc.scopes.includes(key as AppScope)) {
|
||||
const err = new UnauthorizedError('credentials_bad_scheme', {
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
return next(err);
|
||||
}
|
||||
|
||||
if (!currentToken || currentToken.expiration < Math.round(Date.now() / 1000)) {
|
||||
const err = new UnauthorizedError('invalid_token', {
|
||||
message: t('Token 已失效'),
|
||||
});
|
||||
return next(err);
|
||||
}
|
||||
|
||||
return next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const originPath = `${req.baseUrl}${req.path === '/' ? '' : req.path}`;
|
||||
const originPath = `${req.baseUrl}${pathLower === '/' ? '' : pathLower}`;
|
||||
if (
|
||||
!headerToken &&
|
||||
originPath &&
|
||||
@@ -91,30 +124,31 @@ export default ({ app }: { app: Application }) => {
|
||||
|
||||
const errorCode = headerToken ? 'invalid_token' : 'credentials_required';
|
||||
const errorMessage = headerToken
|
||||
? 'jwt malformed'
|
||||
: 'No authorization token was found';
|
||||
? t('Token 已失效')
|
||||
: t('请先登录');
|
||||
const err = new UnauthorizedError(errorCode, { message: errorMessage });
|
||||
next(err);
|
||||
});
|
||||
|
||||
app.use(async (req, res, next) => {
|
||||
if (!['/api/user/init', '/api/user/notification/init'].includes(req.path)) {
|
||||
const pathLower = req.path.toLowerCase();
|
||||
if (
|
||||
![
|
||||
'/api/user/init',
|
||||
'/api/user/notification/init',
|
||||
'/open/user/init',
|
||||
'/open/user/notification/init',
|
||||
].includes(pathLower)
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
const authInfo =
|
||||
(await shareStore.getAuthInfo()) || ({} as IKeyvStore['authInfo']);
|
||||
(await shareStore.getAuthInfo()) || ({} as AuthInfo);
|
||||
|
||||
let isInitialized = true;
|
||||
if (
|
||||
Object.keys(authInfo).length === 2 &&
|
||||
authInfo.username === 'admin' &&
|
||||
authInfo.password === 'admin'
|
||||
) {
|
||||
isInitialized = false;
|
||||
}
|
||||
let isInitialized = !isDefaultAuthInfo(authInfo);
|
||||
|
||||
if (isInitialized) {
|
||||
return res.send({ code: 450, message: '未知错误' });
|
||||
return res.send({ code: 450, message: t('未知错误') });
|
||||
} else {
|
||||
return next();
|
||||
}
|
||||
|
||||
@@ -13,11 +13,13 @@ import { AuthDataType, SystemModel } from '../data/system';
|
||||
import SystemService from '../services/system';
|
||||
import UserService from '../services/user';
|
||||
import { writeFile, readFile } from 'fs/promises';
|
||||
import { createRandomString, fileExist, safeJSONParse } from '../config/util';
|
||||
import { createRandomString, fileExist, isDemoEnv, safeJSONParse } from '../config/util';
|
||||
import OpenService from '../services/open';
|
||||
import { shareStore } from '../shared/store';
|
||||
import Logger from './logger';
|
||||
import { AppModel } from '../data/open';
|
||||
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
||||
import { setLang, systemLang } from '../shared/i18n';
|
||||
|
||||
export default async () => {
|
||||
const cronService = Container.get(CronService);
|
||||
@@ -36,10 +38,15 @@ export default async () => {
|
||||
if (!systemApp) {
|
||||
systemApp = await AppModel.create({
|
||||
name: 'system',
|
||||
scopes: ['crons', 'system'],
|
||||
scopes: ['crons', 'system', 'dashboard'],
|
||||
client_id: createRandomString(12, 12),
|
||||
client_secret: createRandomString(24, 24),
|
||||
});
|
||||
} else if (!systemApp.scopes.includes('dashboard')) {
|
||||
await AppModel.update(
|
||||
{ scopes: [...systemApp.scopes, 'dashboard'] },
|
||||
{ where: { name: 'system' } },
|
||||
);
|
||||
}
|
||||
const [systemConfig] = await SystemModel.findOrCreate({
|
||||
where: { type: AuthDataType.systemConfig },
|
||||
@@ -50,7 +57,7 @@ export default async () => {
|
||||
const [authConfig] = await SystemModel.findOrCreate({
|
||||
where: { type: AuthDataType.authConfig },
|
||||
});
|
||||
if (!authConfig?.info) {
|
||||
if (!authConfig?.info || isDemoEnv()) {
|
||||
let authInfo = {
|
||||
username: 'admin',
|
||||
password: 'admin',
|
||||
@@ -134,6 +141,12 @@ export default async () => {
|
||||
// 初始化更新所有任务状态为空闲
|
||||
await CrontabModel.update({ status: CrontabStatus.idle }, { where: {} });
|
||||
|
||||
// 清空所有运行中的实例记录(服务重启后进程已不存在)
|
||||
await RunningInstanceModel.update(
|
||||
{ status: InstanceStatus.stopped },
|
||||
{ where: { status: InstanceStatus.running } },
|
||||
);
|
||||
|
||||
// 初始化时执行一次所有的 ql repo 任务
|
||||
CrontabModel.findAll({
|
||||
where: {
|
||||
@@ -210,8 +223,21 @@ export default async () => {
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化语言(必须在 autosave_crontab 之前)
|
||||
const lang = systemConfig.info?.lang || systemLang();
|
||||
setLang(lang);
|
||||
|
||||
// 确保 lang_env.sh 存在
|
||||
try {
|
||||
const langEnvExist = await fileExist(config.langEnvFile);
|
||||
if (!langEnvExist) {
|
||||
await writeFile(config.langEnvFile, `export QL_LANG='${lang}'\n`);
|
||||
}
|
||||
} catch { }
|
||||
|
||||
// 初始化保存一次ck和定时任务数据
|
||||
await cronService.autosave_crontab();
|
||||
|
||||
await envService.set_envs();
|
||||
|
||||
const authInfo = await userService.getAuthInfo();
|
||||
|
||||
@@ -20,6 +20,7 @@ const uploadPath = path.join(dataPath, 'upload/');
|
||||
const bakPath = path.join(dataPath, 'bak/');
|
||||
const samplePath = path.join(rootPath, 'sample/');
|
||||
const tmpPath = path.join(logPath, '.tmp/');
|
||||
const rootTmpPath = path.join(rootPath, '.tmp/');
|
||||
const confFile = path.join(configPath, 'config.sh');
|
||||
const sampleConfigFile = path.join(samplePath, 'config.sample.sh');
|
||||
const sampleTaskShellFile = path.join(samplePath, 'task.sample.sh');
|
||||
@@ -44,6 +45,7 @@ const directories = [
|
||||
preloadPath,
|
||||
logPath,
|
||||
tmpPath,
|
||||
rootTmpPath,
|
||||
uploadPath,
|
||||
sshPath,
|
||||
bakPath,
|
||||
@@ -123,5 +125,5 @@ export default async () => {
|
||||
}
|
||||
}
|
||||
|
||||
Logger.info('✌️ Init file down');
|
||||
Logger.info('[boot] Init file down');
|
||||
};
|
||||
|
||||
@@ -6,6 +6,7 @@ import SshKeyService from '../services/sshKey';
|
||||
import config from '../config';
|
||||
import { fileExist } from '../config/util';
|
||||
import { join } from 'path';
|
||||
import { t } from '../shared/i18n';
|
||||
|
||||
export default async () => {
|
||||
const systemService = Container.get(SystemService);
|
||||
@@ -25,7 +26,7 @@ export default async () => {
|
||||
}
|
||||
const cron = {
|
||||
id: NaN,
|
||||
name: '生成token',
|
||||
name: t('生成token'),
|
||||
command: tokenCommand,
|
||||
runOrigin: 'system',
|
||||
} as ScheduleTaskType;
|
||||
@@ -44,7 +45,7 @@ export default async () => {
|
||||
if (data.info.logRemoveFrequency) {
|
||||
const rmlogCron = {
|
||||
id: data.id as number,
|
||||
name: '删除日志',
|
||||
name: t('删除日志'),
|
||||
command: `ql rmlog ${data.info.logRemoveFrequency}`,
|
||||
runOrigin: 'system' as const,
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ import Sock from './sock';
|
||||
|
||||
export default async ({ server }: { server: Server }) => {
|
||||
await Sock({ server });
|
||||
Logger.info('✌️ Sock loaded');
|
||||
Logger.info('[boot] Sock loaded');
|
||||
|
||||
process.on('uncaughtException', (error) => {
|
||||
Logger.error('Uncaught exception:', error);
|
||||
|
||||
@@ -151,6 +151,7 @@ enum NotificationMode {
|
||||
chronocat = 18;
|
||||
ntfy = 19;
|
||||
wxPusherBot = 20;
|
||||
wxPusherSpt = 21;
|
||||
}
|
||||
|
||||
message NotificationInfo {
|
||||
@@ -244,6 +245,8 @@ message NotificationInfo {
|
||||
optional string wxPusherBotAppToken = 66;
|
||||
optional string wxPusherBotTopicIds = 67;
|
||||
optional string wxPusherBotUids = 68;
|
||||
|
||||
optional string wxPusherSptList = 70;
|
||||
}
|
||||
|
||||
message SystemNotifyRequest {
|
||||
|
||||
@@ -43,6 +43,7 @@ export enum NotificationMode {
|
||||
chronocat = 18,
|
||||
ntfy = 19,
|
||||
wxPusherBot = 20,
|
||||
wxPusherSpt = 21,
|
||||
UNRECOGNIZED = -1,
|
||||
}
|
||||
|
||||
@@ -111,6 +112,9 @@ export function notificationModeFromJSON(object: any): NotificationMode {
|
||||
case 20:
|
||||
case "wxPusherBot":
|
||||
return NotificationMode.wxPusherBot;
|
||||
case 21:
|
||||
case "wxPusherSpt":
|
||||
return NotificationMode.wxPusherSpt;
|
||||
case -1:
|
||||
case "UNRECOGNIZED":
|
||||
default:
|
||||
@@ -162,6 +166,8 @@ export function notificationModeToJSON(object: NotificationMode): string {
|
||||
return "ntfy";
|
||||
case NotificationMode.wxPusherBot:
|
||||
return "wxPusherBot";
|
||||
case NotificationMode.wxPusherSpt:
|
||||
return "wxPusherSpt";
|
||||
case NotificationMode.UNRECOGNIZED:
|
||||
default:
|
||||
return "UNRECOGNIZED";
|
||||
@@ -393,6 +399,7 @@ export interface NotificationInfo {
|
||||
wxPusherBotAppToken?: string | undefined;
|
||||
wxPusherBotTopicIds?: string | undefined;
|
||||
wxPusherBotUids?: string | undefined;
|
||||
wxPusherSptList?: string | undefined;
|
||||
}
|
||||
|
||||
export interface SystemNotifyRequest {
|
||||
@@ -2959,6 +2966,7 @@ function createBaseNotificationInfo(): NotificationInfo {
|
||||
wxPusherBotAppToken: undefined,
|
||||
wxPusherBotTopicIds: undefined,
|
||||
wxPusherBotUids: undefined,
|
||||
wxPusherSptList: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3171,6 +3179,9 @@ export const NotificationInfo: MessageFns<NotificationInfo> = {
|
||||
if (message.wxPusherBotUids !== undefined) {
|
||||
writer.uint32(546).string(message.wxPusherBotUids);
|
||||
}
|
||||
if (message.wxPusherSptList !== undefined) {
|
||||
writer.uint32(562).string(message.wxPusherSptList);
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
@@ -3733,6 +3744,14 @@ export const NotificationInfo: MessageFns<NotificationInfo> = {
|
||||
message.wxPusherBotUids = reader.string();
|
||||
continue;
|
||||
}
|
||||
case 70: {
|
||||
if (tag !== 562) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.wxPusherSptList = reader.string();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
@@ -3825,6 +3844,7 @@ export const NotificationInfo: MessageFns<NotificationInfo> = {
|
||||
? globalThis.String(object.wxPusherBotTopicIds)
|
||||
: undefined,
|
||||
wxPusherBotUids: isSet(object.wxPusherBotUids) ? globalThis.String(object.wxPusherBotUids) : undefined,
|
||||
wxPusherSptList: isSet(object.wxPusherSptList) ? globalThis.String(object.wxPusherSptList) : undefined,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -4037,6 +4057,9 @@ export const NotificationInfo: MessageFns<NotificationInfo> = {
|
||||
if (message.wxPusherBotUids !== undefined) {
|
||||
obj.wxPusherBotUids = message.wxPusherBotUids;
|
||||
}
|
||||
if (message.wxPusherSptList !== undefined) {
|
||||
obj.wxPusherSptList = message.wxPusherSptList;
|
||||
}
|
||||
return obj;
|
||||
},
|
||||
|
||||
@@ -4114,6 +4137,7 @@ export const NotificationInfo: MessageFns<NotificationInfo> = {
|
||||
message.wxPusherBotAppToken = object.wxPusherBotAppToken ?? undefined;
|
||||
message.wxPusherBotTopicIds = object.wxPusherBotTopicIds ?? undefined;
|
||||
message.wxPusherBotUids = object.wxPusherBotUids ?? undefined;
|
||||
message.wxPusherSptList = object.wxPusherSptList ?? undefined;
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
+95
-11
@@ -1,16 +1,79 @@
|
||||
import { ServerUnaryCall, sendUnaryData } from '@grpc/grpc-js';
|
||||
import { ServerUnaryCall, sendUnaryData, status } from '@grpc/grpc-js';
|
||||
import { AddCronRequest, AddCronResponse } from '../protos/cron';
|
||||
import nodeSchedule from 'node-schedule';
|
||||
import { scheduleStacks } from './data';
|
||||
import { runCron } from '../shared/runCron';
|
||||
import Logger from '../loaders/logger';
|
||||
import { tf } from '../shared/i18n';
|
||||
|
||||
/**
|
||||
* 预校验 cron 表达式,检测 node-schedule 会拒绝但 cron-parser 会接受的 pattern。
|
||||
* node-schedule 对 bare /N(字段以 / 开头,如前无星号/数字前缀的 /6)返回 null,
|
||||
* 提前拦截避免走 scheduleJob 后才发现无效。
|
||||
*/
|
||||
const isValidCronField = (cron: string): boolean => {
|
||||
// 检测 bare /N 模式:字段以 / 开头如 "/6",或空格后紧跟 "/6"
|
||||
// node-schedule 会对这种字段返回 null
|
||||
if (/\s\/\d/.test(cron) || /^\/\d/.test(cron)) {
|
||||
return false;
|
||||
}
|
||||
// 检测 ? 字符:Quartz cron 语法,node-schedule 在大多数位置返回 null
|
||||
// cron-parser 接受但 node-schedule 拒绝,提前拦截
|
||||
if (/\?/.test(cron)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const addCron = (
|
||||
call: ServerUnaryCall<AddCronRequest, AddCronResponse>,
|
||||
callback: sendUnaryData<AddCronResponse>,
|
||||
) => {
|
||||
// ===== 第一遍:预校验所有 cron 表达式 =====
|
||||
const validationErrors: string[] = [];
|
||||
|
||||
for (const item of call.request.crons) {
|
||||
const { id, schedule, extra_schedules } = item;
|
||||
|
||||
if (!isValidCronField(schedule)) {
|
||||
validationErrors.push(
|
||||
tf(
|
||||
'任务ID %s: 无效的 cron 表达式 "%s"(不支持裸 /N 步长和 ? 字符)',
|
||||
String(id),
|
||||
schedule,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (extra_schedules?.length) {
|
||||
extra_schedules.forEach((x) => {
|
||||
if (!isValidCronField(x.schedule)) {
|
||||
validationErrors.push(
|
||||
tf(
|
||||
'任务ID %s (extra_schedule): 无效的 cron 表达式 "%s"(不支持裸 /N 步长和 ? 字符)',
|
||||
String(id),
|
||||
x.schedule,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (validationErrors.length > 0) {
|
||||
const details = validationErrors.join('\n');
|
||||
const err: any = new Error(details);
|
||||
err.code = status.INVALID_ARGUMENT;
|
||||
err.details = details;
|
||||
callback(err, null);
|
||||
return;
|
||||
}
|
||||
|
||||
// ===== 第二遍:注册所有任务 =====
|
||||
for (const item of call.request.crons) {
|
||||
const { id, schedule, command, extra_schedules, name } = item;
|
||||
|
||||
// 取消该 id 已有的旧任务
|
||||
if (scheduleStacks.has(id)) {
|
||||
scheduleStacks.get(id)?.forEach((x) => x.cancel());
|
||||
}
|
||||
@@ -35,20 +98,41 @@ const addCron = (
|
||||
});
|
||||
}
|
||||
|
||||
scheduleStacks.set(id, [
|
||||
nodeSchedule.scheduleJob(id, schedule, async () => {
|
||||
const mainJob = nodeSchedule.scheduleJob(id, schedule, async () => {
|
||||
Logger.info(`[schedule][准备运行任务] 命令: ${command}`);
|
||||
runCron(command, item);
|
||||
}),
|
||||
...(extra_schedules?.length
|
||||
? extra_schedules.map((x) =>
|
||||
nodeSchedule.scheduleJob(id, x.schedule, async () => {
|
||||
});
|
||||
|
||||
if (!mainJob) {
|
||||
Logger.warn(
|
||||
'[schedule][创建定时任务] scheduleJob 返回 null(不符合预期,已通过预校验): 任务ID: %s, cron: %s',
|
||||
id,
|
||||
schedule,
|
||||
);
|
||||
}
|
||||
|
||||
const extraJobs = extra_schedules?.length
|
||||
? extra_schedules.map((x) => {
|
||||
const job = nodeSchedule.scheduleJob(id, x.schedule, async () => {
|
||||
Logger.info(`[schedule][准备运行任务] 命令: ${command}`);
|
||||
runCron(command, item);
|
||||
}),
|
||||
)
|
||||
: []),
|
||||
]);
|
||||
});
|
||||
if (!job) {
|
||||
Logger.warn(
|
||||
'[schedule][创建定时任务] scheduleJob 返回 null(不符合预期,已通过预校验): 任务ID: %s, cron: %s',
|
||||
id,
|
||||
x.schedule,
|
||||
);
|
||||
}
|
||||
return job;
|
||||
})
|
||||
: [];
|
||||
|
||||
// 过滤 null(兜底保护,正常情况下预校验已拦截)
|
||||
const jobs = [mainJob, ...extraJobs].filter((x) => x != null);
|
||||
if (jobs.length > 0) {
|
||||
scheduleStacks.set(id, jobs);
|
||||
}
|
||||
}
|
||||
|
||||
callback(null, null);
|
||||
|
||||
@@ -250,7 +250,7 @@ const normalizeCronData = (data: CronItem | null): CronItem | undefined => {
|
||||
return {
|
||||
...data,
|
||||
sub_id: data.sub_id ?? undefined,
|
||||
extra_schedules: data.extra_schedules ?? undefined,
|
||||
extra_schedules: data.extra_schedules ?? [],
|
||||
pid: data.pid ?? undefined,
|
||||
task_before: data.task_before ?? undefined,
|
||||
task_after: data.task_after ?? undefined,
|
||||
|
||||
+16
-3
@@ -7,13 +7,26 @@ import {
|
||||
DeleteCronResponse,
|
||||
} from '../protos/cron';
|
||||
import config from '../config';
|
||||
import { getGrpcCerts } from '../config/grpcCerts';
|
||||
|
||||
class Client {
|
||||
private client = new CronClient(
|
||||
`0.0.0.0:${config.grpcPort}`,
|
||||
credentials.createInsecure(),
|
||||
private _client: CronClient | null = null;
|
||||
|
||||
private get client(): CronClient {
|
||||
if (!this._client) {
|
||||
const tlsConfig = getGrpcCerts()!;
|
||||
this._client = new CronClient(
|
||||
`localhost:${config.grpcPort}`,
|
||||
credentials.createSsl(
|
||||
Buffer.from(tlsConfig.caCert),
|
||||
Buffer.from(tlsConfig.clientKey),
|
||||
Buffer.from(tlsConfig.clientCert),
|
||||
),
|
||||
{ 'grpc.enable_http_proxy': 0 },
|
||||
);
|
||||
}
|
||||
return this._client;
|
||||
}
|
||||
|
||||
addCron(request: AddCronRequest['crons']): Promise<AddCronResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
|
||||
@@ -13,7 +13,20 @@ const delCron = (
|
||||
'[schedule][取消定时任务] 任务ID: %s',
|
||||
id,
|
||||
);
|
||||
scheduleStacks.get(id)?.forEach(x => x.cancel());
|
||||
// 过滤掉 nodeSchedule.scheduleJob() 对无效表达式返回的 null,
|
||||
// 否则对 null 调 cancel() 会让整个取消流程抛出 UNKNOWN 错误,
|
||||
// 进而导致 HTTP 端的 remove() 跳过 setCrontab(),造成 crontab.list 残留。
|
||||
scheduleStacks.get(id)?.filter((x) => x != null).forEach((x) => {
|
||||
try {
|
||||
x.cancel();
|
||||
} catch (error: any) {
|
||||
Logger.warn(
|
||||
'[schedule][取消任务失败] 任务ID: %s, 错误: %s',
|
||||
id,
|
||||
error?.message || error,
|
||||
);
|
||||
}
|
||||
});
|
||||
scheduleStacks.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ const check = async (
|
||||
switch (call.request.service) {
|
||||
case 'cron':
|
||||
const res = await promiseExec(
|
||||
`curl -s --noproxy '*' http://0.0.0.0:${config.port}/api/system`,
|
||||
`curl -s --noproxy '*' http://localhost:${config.port}/api/system`,
|
||||
);
|
||||
|
||||
if (res.includes('200')) {
|
||||
|
||||
+20
-13
@@ -2,6 +2,7 @@ import { Service, Inject } from 'typedi';
|
||||
import path, { join } from 'path';
|
||||
import config from '../config';
|
||||
import { getFileContentByName } from '../config/util';
|
||||
import { t } from '../shared/i18n';
|
||||
import { Response } from 'express';
|
||||
import { request } from 'undici';
|
||||
|
||||
@@ -11,19 +12,25 @@ export default class ConfigService {
|
||||
|
||||
public async getFile(filePath: string, res: Response) {
|
||||
let content = '';
|
||||
const avaliablePath = [config.rootPath, config.configPath].map((x) =>
|
||||
path.resolve(x, filePath),
|
||||
);
|
||||
|
||||
if (
|
||||
config.blackFileList.includes(filePath) ||
|
||||
avaliablePath.every(
|
||||
(x) =>
|
||||
!x.startsWith(config.scriptPath) && !x.startsWith(config.configPath),
|
||||
) ||
|
||||
!filePath
|
||||
) {
|
||||
return res.send({ code: 403, message: '文件无法访问' });
|
||||
if (!filePath) {
|
||||
return res.send({ code: 403, message: t('文件无法访问') });
|
||||
}
|
||||
const normalized = path.normalize(filePath);
|
||||
if (normalized.startsWith('..') || path.isAbsolute(normalized)) {
|
||||
return res.send({ code: 403, message: t('文件无法访问') });
|
||||
}
|
||||
const resolvedRoot = path.resolve(config.rootPath, normalized);
|
||||
const resolvedConfig = path.resolve(config.configPath, normalized);
|
||||
const isValidPath =
|
||||
resolvedRoot.startsWith(config.scriptPath) ||
|
||||
resolvedRoot.startsWith(config.configPath) ||
|
||||
resolvedConfig.startsWith(config.scriptPath) ||
|
||||
resolvedConfig.startsWith(config.configPath);
|
||||
if (!isValidPath) {
|
||||
return res.send({ code: 403, message: t('文件无法访问') });
|
||||
}
|
||||
if (config.blackFileList.includes(path.basename(normalized))) {
|
||||
return res.send({ code: 403, message: t('文件无法访问') });
|
||||
}
|
||||
|
||||
if (filePath.startsWith('sample/')) {
|
||||
|
||||
+214
-23
@@ -2,6 +2,10 @@ import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import config from '../config';
|
||||
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
||||
import {
|
||||
RunningInstanceModel,
|
||||
InstanceStatus,
|
||||
} from '../data/runningInstance';
|
||||
import { exec, execSync } from 'child_process';
|
||||
import fs from 'fs/promises';
|
||||
import CronExpressionParser from 'cron-parser';
|
||||
@@ -24,8 +28,10 @@ import dayjs from 'dayjs';
|
||||
import pickBy from 'lodash/pickBy';
|
||||
import omit from 'lodash/omit';
|
||||
import { writeFileWithLock } from '../shared/utils';
|
||||
import { t } from '../shared/i18n';
|
||||
import { ScheduleType } from '../interface/schedule';
|
||||
import { logStreamManager } from '../shared/logStreamManager';
|
||||
import { isEmpty } from 'lodash';
|
||||
|
||||
@Service()
|
||||
export default class CronService {
|
||||
@@ -39,6 +45,25 @@ export default class CronService {
|
||||
return false;
|
||||
}
|
||||
|
||||
private get schedulerMode(): 'system' | 'node' {
|
||||
const env = process.env.QL_SCHEDULER;
|
||||
if (env === 'system') return 'system';
|
||||
if (env === 'node') return 'node';
|
||||
try {
|
||||
execSync('which crond', { stdio: 'ignore' });
|
||||
return 'system';
|
||||
} catch {
|
||||
return 'node';
|
||||
}
|
||||
}
|
||||
|
||||
private shouldUseCronClient(cron: Crontab): boolean {
|
||||
if (this.schedulerMode === 'node') {
|
||||
return !this.isSpecialSchedule(cron.schedule);
|
||||
}
|
||||
return this.isNodeCron(cron) && !this.isSpecialSchedule(cron.schedule);
|
||||
}
|
||||
|
||||
private isOnceSchedule(schedule?: string) {
|
||||
return schedule?.startsWith(ScheduleType.ONCE);
|
||||
}
|
||||
@@ -80,7 +105,8 @@ export default class CronService {
|
||||
return doc;
|
||||
}
|
||||
|
||||
if (this.isNodeCron(doc) && !this.isSpecialSchedule(doc.schedule)) {
|
||||
if (this.shouldUseCronClient(doc)) {
|
||||
try {
|
||||
await cronClient.addCron([
|
||||
{
|
||||
name: doc.name || '',
|
||||
@@ -90,6 +116,18 @@ export default class CronService {
|
||||
extra_schedules: doc.extra_schedules || [],
|
||||
},
|
||||
]);
|
||||
} catch (error: any) {
|
||||
// gRPC 注册失败时回滚 DB 记录,避免产生"僵尸任务"
|
||||
// (DB 和 crontab.list 有记录但调度器永远不会执行)
|
||||
await CrontabModel.destroy({ where: { id: doc.id } });
|
||||
this.logger.error(
|
||||
'[crontab] Failed to register cron job in scheduler, task creation rolled back:',
|
||||
error?.message || error,
|
||||
);
|
||||
throw new Error(
|
||||
`${t('调度器注册失败,任务创建已回滚')}: ${(error as any)?.details || error?.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await this.setCrontab();
|
||||
@@ -111,11 +149,17 @@ export default class CronService {
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
if (this.isNodeCron(doc)) {
|
||||
await cronClient.delCron([String(doc.id)]);
|
||||
try {
|
||||
await cronClient.delCron([String(newDoc.id)]);
|
||||
} catch (error: any) {
|
||||
this.logger.warn(
|
||||
'[crontab] Failed to unregister cron job in scheduler:',
|
||||
error?.message || error,
|
||||
);
|
||||
}
|
||||
|
||||
if (this.isNodeCron(newDoc) && !this.isSpecialSchedule(newDoc.schedule)) {
|
||||
if (this.shouldUseCronClient(newDoc)) {
|
||||
try {
|
||||
await cronClient.addCron([
|
||||
{
|
||||
name: doc.name || '',
|
||||
@@ -125,6 +169,35 @@ export default class CronService {
|
||||
extra_schedules: newDoc.extra_schedules || [],
|
||||
},
|
||||
]);
|
||||
} catch (error: any) {
|
||||
// gRPC 注册新任务失败 → 回滚 DB 到旧数据,并尝试恢复旧调度注册
|
||||
await CrontabModel.update(doc, { where: { id: doc.id } });
|
||||
if (this.shouldUseCronClient(doc)) {
|
||||
try {
|
||||
await cronClient.addCron([
|
||||
{
|
||||
name: doc.name || '',
|
||||
id: String(doc.id),
|
||||
schedule: doc.schedule!,
|
||||
command: this.makeCommand(doc),
|
||||
extra_schedules: doc.extra_schedules || [],
|
||||
},
|
||||
]);
|
||||
} catch (_recoveryError: any) {
|
||||
this.logger.warn(
|
||||
'[crontab] Failed to restore old cron job in scheduler after rollback:',
|
||||
_recoveryError?.message || _recoveryError,
|
||||
);
|
||||
}
|
||||
}
|
||||
this.logger.error(
|
||||
'[crontab] Failed to register updated cron job in scheduler, update rolled back:',
|
||||
error?.message || error,
|
||||
);
|
||||
throw new Error(
|
||||
`${t('调度器注册失败,任务更新已回滚')}: ${(error as any)?.details || error?.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await this.setCrontab();
|
||||
@@ -143,6 +216,7 @@ export default class CronService {
|
||||
log_path,
|
||||
last_running_time = 0,
|
||||
last_execution_time = 0,
|
||||
exit_code,
|
||||
}: {
|
||||
ids: number[];
|
||||
status: CrontabStatus;
|
||||
@@ -150,6 +224,7 @@ export default class CronService {
|
||||
log_path: string;
|
||||
last_running_time: number;
|
||||
last_execution_time: number;
|
||||
exit_code?: number;
|
||||
}) {
|
||||
let options: any = {
|
||||
status,
|
||||
@@ -172,6 +247,40 @@ export default class CronService {
|
||||
if (status === CrontabStatus.idle && log_path !== cron.log_path) {
|
||||
options = omit(options, ['status', 'log_path', 'pid']);
|
||||
}
|
||||
|
||||
// Manage RunningInstance records for status transitions from shell scripts
|
||||
if (status === CrontabStatus.running) {
|
||||
// Create a new running instance record
|
||||
await RunningInstanceModel.create({
|
||||
cron_id: id,
|
||||
pid: pid || undefined,
|
||||
log_path: log_path || undefined,
|
||||
started_at: last_execution_time || dayjs().unix(),
|
||||
status: InstanceStatus.running,
|
||||
});
|
||||
} else if (status === CrontabStatus.idle) {
|
||||
// Mark the matching running instance as finished
|
||||
const finishedAt = dayjs().unix();
|
||||
const instanceStatus =
|
||||
exit_code !== undefined && exit_code !== null && exit_code !== 0
|
||||
? InstanceStatus.error
|
||||
: InstanceStatus.finished;
|
||||
await RunningInstanceModel.update(
|
||||
{
|
||||
finished_at: finishedAt,
|
||||
status: instanceStatus,
|
||||
exit_code: exit_code ?? undefined,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
cron_id: id,
|
||||
pid: pid || undefined,
|
||||
status: InstanceStatus.running,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
await CrontabModel.update(
|
||||
{ ...pickBy(options, (v) => v === 0 || !!v) },
|
||||
{ where: { id } },
|
||||
@@ -181,7 +290,14 @@ export default class CronService {
|
||||
|
||||
public async remove(ids: number[]) {
|
||||
await CrontabModel.destroy({ where: { id: ids } });
|
||||
try {
|
||||
await cronClient.delCron(ids.map(String));
|
||||
} catch (error: any) {
|
||||
this.logger.warn(
|
||||
'[crontab] Failed to unregister cron job in scheduler:',
|
||||
error?.message || error,
|
||||
);
|
||||
}
|
||||
await this.setCrontab();
|
||||
}
|
||||
|
||||
@@ -350,7 +466,7 @@ export default class CronService {
|
||||
}
|
||||
|
||||
private formatFilterQuery(query: any, filterQuery: any) {
|
||||
if (filterQuery) {
|
||||
if (!isEmpty(filterQuery)) {
|
||||
if (!query[Op.and]) {
|
||||
query[Op.and] = [];
|
||||
}
|
||||
@@ -482,12 +598,53 @@ export default class CronService {
|
||||
}
|
||||
}
|
||||
|
||||
// Mark all running instances as stopped
|
||||
const finishedAt = dayjs().unix();
|
||||
await RunningInstanceModel.update(
|
||||
{ status: InstanceStatus.stopped, finished_at: finishedAt },
|
||||
{ where: { cron_id: ids, status: InstanceStatus.running } },
|
||||
);
|
||||
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: undefined },
|
||||
{ where: { id: ids } },
|
||||
);
|
||||
}
|
||||
|
||||
public async stopInstance(instanceId: number) {
|
||||
const instance = await RunningInstanceModel.findOne({
|
||||
where: { id: instanceId, status: InstanceStatus.running },
|
||||
});
|
||||
if (!instance) {
|
||||
return { code: 400, message: t('实例不存在或已停止') };
|
||||
}
|
||||
if (instance.pid) {
|
||||
try {
|
||||
await killTask(instance.pid);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`[panel][停止实例失败] 实例ID: ${instanceId}, PID: ${instance.pid}, 错误: ${error}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
await RunningInstanceModel.update(
|
||||
{ status: InstanceStatus.stopped, finished_at: dayjs().unix(), exit_code: 143 },
|
||||
{ where: { id: instanceId } },
|
||||
);
|
||||
|
||||
// Check if there are still other running instances for this cron
|
||||
const otherRunning = await RunningInstanceModel.count({
|
||||
where: { cron_id: instance.cron_id, status: InstanceStatus.running },
|
||||
});
|
||||
if (otherRunning === 0) {
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: undefined },
|
||||
{ where: { id: instance.cron_id } },
|
||||
);
|
||||
}
|
||||
return { code: 200, message: t('实例已停止') };
|
||||
}
|
||||
|
||||
private async runSingle(cronId: number): Promise<number | void> {
|
||||
return taskLimit.manualRunWithCronLimit(() => {
|
||||
return new Promise(async (resolve: any) => {
|
||||
@@ -556,12 +713,7 @@ export default class CronService {
|
||||
JSON.stringify(params),
|
||||
code,
|
||||
);
|
||||
// Close the stream after task completion
|
||||
await logStreamManager.closeStream(absolutePath);
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: undefined },
|
||||
{ where: { id } },
|
||||
);
|
||||
resolve({ ...params, pid: cp.pid, code });
|
||||
});
|
||||
});
|
||||
@@ -570,15 +722,22 @@ export default class CronService {
|
||||
|
||||
public async disabled(ids: number[]) {
|
||||
await CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
||||
try {
|
||||
await cronClient.delCron(ids.map(String));
|
||||
} catch (error: any) {
|
||||
this.logger.warn(
|
||||
'[crontab] Failed to unregister cron job in scheduler:',
|
||||
error?.message || error,
|
||||
);
|
||||
}
|
||||
await this.setCrontab();
|
||||
}
|
||||
|
||||
public async enabled(ids: number[]) {
|
||||
await CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } });
|
||||
const docs = await CrontabModel.findAll({ where: { id: ids } });
|
||||
const sixCron = docs
|
||||
.filter((x) => this.isNodeCron(x) && !this.isSpecialSchedule(x.schedule))
|
||||
const crons = docs
|
||||
.filter((x) => this.shouldUseCronClient(x))
|
||||
.map((doc) => ({
|
||||
name: doc.name || '',
|
||||
id: String(doc.id),
|
||||
@@ -590,27 +749,44 @@ export default class CronService {
|
||||
if (isDemoEnv()) {
|
||||
return;
|
||||
}
|
||||
await cronClient.addCron(sixCron);
|
||||
|
||||
try {
|
||||
await cronClient.addCron(crons);
|
||||
} catch (error: any) {
|
||||
// gRPC 注册失败 → 回滚启用状态,避免 DB 显示已启用但调度器未注册
|
||||
await CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
||||
this.logger.error(
|
||||
'[crontab] Failed to register cron job in scheduler, enable rolled back:',
|
||||
error?.message || error,
|
||||
);
|
||||
throw new Error(
|
||||
`${t('调度器注册失败,任务启用已回滚')}: ${(error as any)?.details || error?.message}`,
|
||||
);
|
||||
}
|
||||
await this.setCrontab();
|
||||
}
|
||||
|
||||
public async log(id: number) {
|
||||
public async log(id: number): Promise<{ content: string; status: string }> {
|
||||
const doc = await this.getDb({ id });
|
||||
if (!doc) {
|
||||
return '';
|
||||
return { content: '', status: 'empty' };
|
||||
}
|
||||
if (doc.log_name === '/dev/null') {
|
||||
return '日志设置为忽略';
|
||||
return { content: t('日志设置为忽略'), status: 'ignored' };
|
||||
}
|
||||
const absolutePath = path.resolve(config.logPath, `${doc.log_path}`);
|
||||
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
||||
if (logFileExist) {
|
||||
return await getFileContentByName(`${absolutePath}`);
|
||||
const content = await getFileContentByName(`${absolutePath}`);
|
||||
const isRunning =
|
||||
typeof doc.status === 'number' &&
|
||||
[CrontabStatus.running, CrontabStatus.queued].includes(doc.status);
|
||||
return { content, status: isRunning ? 'running' : 'completed' };
|
||||
} else {
|
||||
return typeof doc.status === 'number' &&
|
||||
[CrontabStatus.queued, CrontabStatus.running].includes(doc.status)
|
||||
? '运行中...'
|
||||
: '日志不存在...';
|
||||
? { content: t('运行中...'), status: 'running' }
|
||||
: { content: t('日志不存在...'), status: 'notFound' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -661,6 +837,9 @@ export default class CronService {
|
||||
.replace(/;? *\n/g, ';')
|
||||
.trim()}' `;
|
||||
}
|
||||
if (tab.work_dir) {
|
||||
commandVariable += `work_dir='${tab.work_dir.replace(/'/g, "'\\''")}' `;
|
||||
}
|
||||
|
||||
const crontab_job_string = `${commandVariable}${command}`;
|
||||
return crontab_job_string;
|
||||
@@ -690,12 +869,14 @@ export default class CronService {
|
||||
|
||||
await writeFileWithLock(config.crontabFile, crontab_string);
|
||||
|
||||
if (this.schedulerMode === 'system') {
|
||||
try {
|
||||
execSync(`crontab ${config.crontabFile}`);
|
||||
} catch (error: any) {
|
||||
const errorMsg = error.message || String(error);
|
||||
this.logger.error('[crontab] Failed to update system crontab:', errorMsg);
|
||||
}
|
||||
}
|
||||
|
||||
await CrontabModel.update({ saved: true }, { where: {} });
|
||||
}
|
||||
@@ -745,8 +926,7 @@ export default class CronService {
|
||||
.filter(
|
||||
(x) =>
|
||||
x.isDisabled !== 1 &&
|
||||
this.isNodeCron(x) &&
|
||||
!this.isSpecialSchedule(x.schedule),
|
||||
this.shouldUseCronClient(x),
|
||||
)
|
||||
.map((doc) => ({
|
||||
name: doc.name || '',
|
||||
@@ -760,8 +940,19 @@ export default class CronService {
|
||||
await writeFileWithLock(config.crontabFile, '');
|
||||
return;
|
||||
}
|
||||
|
||||
// 先同步 crontab.list 与系统 crontab,确保其始终反映数据库真实状态。
|
||||
// gRPC 调度注册为尽力而为:失败时不阻断文件同步,调度器重启后会重新注册。
|
||||
// 这避免了因调度器短暂不可用导致 crontab.list 与数据库脱节(订阅更新误判任务已存在)。
|
||||
await this.setCrontab(tabs);
|
||||
try {
|
||||
await cronClient.addCron(regularCrons);
|
||||
this.setCrontab(tabs);
|
||||
} catch (error: any) {
|
||||
this.logger.warn(
|
||||
'[crontab] Failed to register cron job in scheduler:',
|
||||
error?.message || error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async bootTask() {
|
||||
@@ -775,7 +966,7 @@ export default class CronService {
|
||||
{ where: { id: bootTasks.map((t) => t.id!) } },
|
||||
);
|
||||
for (const task of bootTasks) {
|
||||
await this.runSingle(task.id!);
|
||||
this.runSingle(task.id!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+100
-38
@@ -22,6 +22,9 @@ import {
|
||||
} from '../config/util';
|
||||
import dayjs from 'dayjs';
|
||||
import taskLimit from '../shared/pLimit';
|
||||
import { detectOS } from '../config/util';
|
||||
import { LINUX_DEPENDENCE_COMMAND } from '../config/const';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
|
||||
@Service()
|
||||
export default class DependenceService {
|
||||
@@ -159,8 +162,19 @@ export default class DependenceService {
|
||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||
for (const doc of docs) {
|
||||
taskLimit.removeQueuedDependency(doc);
|
||||
const depInstallCommand = getInstallCommand(doc.type, doc.name);
|
||||
const depUnInstallCommand = getUninstallCommand(doc.type, doc.name);
|
||||
let depInstallCommand = getInstallCommand(doc.type, doc.name);
|
||||
let depUnInstallCommand = getUninstallCommand(doc.type, doc.name);
|
||||
const isLinuxDependence = doc.type === DependenceTypes.linux;
|
||||
|
||||
if (isLinuxDependence) {
|
||||
const osType = await detectOS();
|
||||
if (!osType) {
|
||||
continue;
|
||||
}
|
||||
const linuxCommand = LINUX_DEPENDENCE_COMMAND[osType];
|
||||
depInstallCommand = `${linuxCommand.install} ${doc.name.trim()}`;
|
||||
depUnInstallCommand = `${linuxCommand.uninstall} ${doc.name.trim()}`;
|
||||
}
|
||||
const pids = await Promise.all([
|
||||
getPid(depInstallCommand),
|
||||
getPid(depUnInstallCommand),
|
||||
@@ -217,39 +231,83 @@ export default class DependenceService {
|
||||
if (taskLimit.firstDependencyId !== dependency.id) {
|
||||
return resolve(null);
|
||||
}
|
||||
|
||||
taskLimit.removeQueuedDependency(dependency);
|
||||
|
||||
const depIds = [dependency.id!];
|
||||
let depName = dependency.name.trim();
|
||||
const actionText = isInstall ? t('安装') : t('删除');
|
||||
const socketMessageType = isInstall
|
||||
? 'installDependence'
|
||||
: 'uninstallDependence';
|
||||
const isNodeDependence = dependency.type === DependenceTypes.nodejs;
|
||||
const isLinuxDependence = dependency.type === DependenceTypes.linux;
|
||||
const isPythonDependence = dependency.type === DependenceTypes.python3;
|
||||
const osType = await detectOS();
|
||||
let linuxCommand = {} as typeof LINUX_DEPENDENCE_COMMAND.Alpine;
|
||||
taskLimit.removeQueuedDependency(dependency);
|
||||
if (isLinuxDependence) {
|
||||
if (!osType) {
|
||||
await DependenceModel.update(
|
||||
{ status: DependenceStatus.installFailed },
|
||||
{ where: { id: depIds } },
|
||||
);
|
||||
const startTime = dayjs();
|
||||
const message = tf(
|
||||
'开始%s依赖 %s,开始时间 %s\n\n当前系统不支持\n\n依赖%s失败,结束时间 %s,耗时 %s 秒',
|
||||
actionText,
|
||||
depName,
|
||||
startTime.format('YYYY-MM-DD HH:mm:ss'),
|
||||
actionText,
|
||||
startTime.format('YYYY-MM-DD HH:mm:ss'),
|
||||
String(startTime.diff(startTime, 'second')),
|
||||
);
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
message,
|
||||
references: depIds,
|
||||
status: DependenceStatus.installFailed,
|
||||
});
|
||||
this.updateLog(depIds, message);
|
||||
return resolve(null);
|
||||
}
|
||||
linuxCommand = LINUX_DEPENDENCE_COMMAND[osType];
|
||||
}
|
||||
|
||||
const status = isInstall
|
||||
? DependenceStatus.installing
|
||||
: DependenceStatus.removing;
|
||||
await DependenceModel.update({ status }, { where: { id: depIds } });
|
||||
|
||||
const socketMessageType = isInstall
|
||||
? 'installDependence'
|
||||
: 'uninstallDependence';
|
||||
let depName = dependency.name.trim();
|
||||
const command = isInstall
|
||||
let command = isInstall
|
||||
? getInstallCommand(dependency.type, depName)
|
||||
: getUninstallCommand(dependency.type, depName);
|
||||
const actionText = isInstall ? '安装' : '删除';
|
||||
if (isLinuxDependence) {
|
||||
command = isInstall
|
||||
? `${linuxCommand.install} ${depName.trim()}`
|
||||
: `${linuxCommand.uninstall} ${depName.trim()}`;
|
||||
}
|
||||
const startTime = dayjs();
|
||||
|
||||
const message = `开始${actionText}依赖 ${depName},开始时间 ${startTime.format(
|
||||
'YYYY-MM-DD HH:mm:ss',
|
||||
)}\n\n`;
|
||||
const message = tf(
|
||||
'开始%s依赖 %s,开始时间 %s\n\n',
|
||||
actionText,
|
||||
depName,
|
||||
startTime.format('YYYY-MM-DD HH:mm:ss'),
|
||||
);
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
message,
|
||||
references: depIds,
|
||||
status,
|
||||
});
|
||||
this.updateLog(depIds, message);
|
||||
|
||||
// 判断是否已经安装过依赖
|
||||
if (isInstall && !force) {
|
||||
const getCommand = getGetCommand(dependency.type, depName);
|
||||
let getCommand = getGetCommand(dependency.type, depName);
|
||||
const depVersionStr = versionDependenceCommandTypes[dependency.type];
|
||||
if (isLinuxDependence) {
|
||||
getCommand = `${linuxCommand.info} ${depName}`;
|
||||
}
|
||||
|
||||
let depVersion = '';
|
||||
if (depName.includes(depVersionStr)) {
|
||||
const symbolRegx = new RegExp(
|
||||
@@ -261,10 +319,6 @@ export default class DependenceService {
|
||||
depVersion = _depVersion;
|
||||
}
|
||||
}
|
||||
const isNodeDependence = dependency.type === DependenceTypes.nodejs;
|
||||
const isLinuxDependence = dependency.type === DependenceTypes.linux;
|
||||
const isPythonDependence =
|
||||
dependency.type === DependenceTypes.python3;
|
||||
const depInfo = (await promiseExecSuccess(getCommand))
|
||||
.replace(/\s{2,}/, ' ')
|
||||
.replace(/\s+$/, '');
|
||||
@@ -273,18 +327,24 @@ export default class DependenceService {
|
||||
depInfo &&
|
||||
((isNodeDependence && depInfo.split(' ')?.[0] === depName) ||
|
||||
(isLinuxDependence &&
|
||||
depInfo.toLocaleLowerCase().includes('installed')) ||
|
||||
linuxCommand.check(depInfo.toLocaleLowerCase())) ||
|
||||
isPythonDependence) &&
|
||||
(!depVersion || depInfo.includes(depVersion))
|
||||
) {
|
||||
const endTime = dayjs();
|
||||
const _message = `检测到已经安装 ${depName}\n\n${depInfo}\n\n跳过安装\n\n依赖${actionText}成功,结束时间 ${endTime.format(
|
||||
'YYYY-MM-DD HH:mm:ss',
|
||||
)},耗时 ${endTime.diff(startTime, 'second')} 秒`;
|
||||
const _message = tf(
|
||||
'检测到已经安装 %s\n\n%s\n\n跳过安装\n\n依赖%s成功,结束时间 %s,耗时 %s 秒',
|
||||
depName,
|
||||
depInfo,
|
||||
actionText,
|
||||
endTime.format('YYYY-MM-DD HH:mm:ss'),
|
||||
String(endTime.diff(startTime, 'second')),
|
||||
);
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
message: _message,
|
||||
references: depIds,
|
||||
status: DependenceStatus.installed,
|
||||
});
|
||||
this.updateLog(depIds, _message);
|
||||
await DependenceModel.update(
|
||||
@@ -309,6 +369,7 @@ export default class DependenceService {
|
||||
type: socketMessageType,
|
||||
message: data.toString(),
|
||||
references: depIds,
|
||||
status,
|
||||
});
|
||||
this.updateLog(depIds, data.toString());
|
||||
});
|
||||
@@ -318,6 +379,7 @@ export default class DependenceService {
|
||||
type: socketMessageType,
|
||||
message: data.toString(),
|
||||
references: depIds,
|
||||
status,
|
||||
});
|
||||
this.updateLog(depIds, data.toString());
|
||||
});
|
||||
@@ -327,6 +389,7 @@ export default class DependenceService {
|
||||
type: socketMessageType,
|
||||
message: JSON.stringify(err),
|
||||
references: depIds,
|
||||
status,
|
||||
});
|
||||
this.updateLog(depIds, JSON.stringify(err));
|
||||
});
|
||||
@@ -334,28 +397,27 @@ export default class DependenceService {
|
||||
cp.on('exit', async (code) => {
|
||||
const endTime = dayjs();
|
||||
const isSucceed = code === 0;
|
||||
const resultText = isSucceed ? '成功' : '失败';
|
||||
const resultText = isSucceed ? t('成功') : t('失败');
|
||||
|
||||
const message = `\n依赖${actionText}${resultText},结束时间 ${endTime.format(
|
||||
'YYYY-MM-DD HH:mm:ss',
|
||||
)},耗时 ${endTime.diff(startTime, 'second')} 秒`;
|
||||
const message =
|
||||
'\n' +
|
||||
tf('依赖%s%s,结束时间 %s,耗时 %s 秒',
|
||||
actionText,
|
||||
resultText,
|
||||
endTime.format('YYYY-MM-DD HH:mm:ss'),
|
||||
String(endTime.diff(startTime, 'second')),
|
||||
);
|
||||
const exitStatus = isSucceed
|
||||
? (isInstall ? DependenceStatus.installed : DependenceStatus.removed)
|
||||
: (isInstall ? DependenceStatus.installFailed : DependenceStatus.removeFailed);
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
message,
|
||||
references: depIds,
|
||||
status: exitStatus,
|
||||
});
|
||||
this.updateLog(depIds, message);
|
||||
|
||||
let status: number;
|
||||
if (isSucceed) {
|
||||
status = isInstall
|
||||
? DependenceStatus.installed
|
||||
: DependenceStatus.removed;
|
||||
} else {
|
||||
status = isInstall
|
||||
? DependenceStatus.installFailed
|
||||
: DependenceStatus.removeFailed;
|
||||
}
|
||||
const docs = await DependenceModel.findAll({ where: { id: depIds } });
|
||||
const _docIds = docs
|
||||
.filter((x) => x.status !== DependenceStatus.cancelled)
|
||||
@@ -363,7 +425,7 @@ export default class DependenceService {
|
||||
|
||||
if (_docIds.length > 0) {
|
||||
await DependenceModel.update(
|
||||
{ status },
|
||||
{ status: exitStatus },
|
||||
{ where: { id: _docIds } },
|
||||
);
|
||||
}
|
||||
|
||||
+41
-3
@@ -27,7 +27,7 @@ export default class EnvService {
|
||||
envs.length > 0 &&
|
||||
typeof envs[envs.length - 1].position === 'number'
|
||||
) {
|
||||
position = envs[envs.length - 1].position!;
|
||||
position = this.getPrecisionPosition(envs[envs.length - 1].position!);
|
||||
}
|
||||
const tabs = payloads.map((x) => {
|
||||
position = position - stepPosition;
|
||||
@@ -100,7 +100,7 @@ export default class EnvService {
|
||||
}
|
||||
|
||||
private async checkPosition(position: number, edge: number = 0) {
|
||||
const precisionPosition = parseFloat(position.toPrecision(16));
|
||||
const precisionPosition = this.getPrecisionPosition(position);
|
||||
if (
|
||||
precisionPosition < minPosition ||
|
||||
precisionPosition > maxPosition ||
|
||||
@@ -116,7 +116,7 @@ export default class EnvService {
|
||||
}
|
||||
|
||||
private getPrecisionPosition(position: number): number {
|
||||
return parseFloat(position.toPrecision(16));
|
||||
return Math.trunc(parseFloat(position.toPrecision(16)));
|
||||
}
|
||||
|
||||
public async envs(searchText: string = '', query: any = {}): Promise<Env[]> {
|
||||
@@ -199,6 +199,44 @@ export default class EnvService {
|
||||
await EnvModel.update({ isPinned: 0 }, { where: { id: ids } });
|
||||
}
|
||||
|
||||
public async addLabels(ids: number[], labels: string[]) {
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
const docs = await EnvModel.findAll({
|
||||
where: { id: ids },
|
||||
transaction,
|
||||
});
|
||||
for (const doc of docs) {
|
||||
const env = doc.get({ plain: true });
|
||||
await EnvModel.update(
|
||||
{ labels: Array.from(new Set([...(env.labels || []), ...labels])) },
|
||||
{ where: { id: env.id }, transaction },
|
||||
);
|
||||
}
|
||||
});
|
||||
return await this.find({ id: ids });
|
||||
}
|
||||
|
||||
public async removeLabels(ids: number[], labels: string[]) {
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
const docs = await EnvModel.findAll({
|
||||
where: { id: ids },
|
||||
transaction,
|
||||
});
|
||||
for (const doc of docs) {
|
||||
const env = doc.get({ plain: true });
|
||||
await EnvModel.update(
|
||||
{
|
||||
labels: (env.labels || []).filter(
|
||||
(label: string) => !labels.includes(label),
|
||||
),
|
||||
},
|
||||
{ where: { id: env.id }, transaction },
|
||||
);
|
||||
}
|
||||
});
|
||||
return await this.find({ id: ids });
|
||||
}
|
||||
|
||||
public async set_envs() {
|
||||
const envs = await this.envs('', {
|
||||
name: { [Op.not]: null },
|
||||
|
||||
+36
-7
@@ -11,30 +11,59 @@ import { promisify } from 'util';
|
||||
import config from '../config';
|
||||
import { metricsService } from './metrics';
|
||||
import { Service } from 'typedi';
|
||||
import { initGrpcCerts } from '../config/grpcCerts';
|
||||
|
||||
@Service()
|
||||
export class GrpcServerService {
|
||||
private server: Server = new Server({ 'grpc.enable_http_proxy': 0 });
|
||||
|
||||
private formatGrpcAddress(host: string, port: number): string {
|
||||
if (host === '::') {
|
||||
return `[::]:${port}`;
|
||||
}
|
||||
return `${host}:${port}`;
|
||||
}
|
||||
|
||||
async initialize() {
|
||||
try {
|
||||
this.server.addService(HealthService, { check });
|
||||
this.server.addService(CronService, { addCron, delCron });
|
||||
this.server.addService(ApiService, Api);
|
||||
|
||||
const grpcPort = config.grpcPort;
|
||||
const bindAsync = promisify(this.server.bindAsync).bind(this.server);
|
||||
await bindAsync(
|
||||
`0.0.0.0:${grpcPort}`,
|
||||
ServerCredentials.createInsecure(),
|
||||
const tlsConfig = await initGrpcCerts();
|
||||
const credentials = ServerCredentials.createSsl(
|
||||
Buffer.from(tlsConfig.caCert),
|
||||
[{ cert_chain: Buffer.from(tlsConfig.serverCert), private_key: Buffer.from(tlsConfig.serverKey) }],
|
||||
true,
|
||||
);
|
||||
Logger.debug(`✌️ gRPC service started successfully`);
|
||||
|
||||
const grpcPort = config.grpcPort;
|
||||
const hostsToTry = [
|
||||
config.bindHostGrpc,
|
||||
...(config.bindHostGrpc !== '0.0.0.0' ? ['0.0.0.0'] : [])
|
||||
];
|
||||
const bindAsync = promisify(this.server.bindAsync).bind(this.server);
|
||||
|
||||
let lastError: Error | null = null;
|
||||
|
||||
for (const host of hostsToTry) {
|
||||
try {
|
||||
const address = this.formatGrpcAddress(host, grpcPort);
|
||||
await bindAsync(address, credentials);
|
||||
Logger.debug(`[boot] gRPC service started successfully on ${address}`);
|
||||
metricsService.record('grpc_service_start', 1, {
|
||||
port: grpcPort.toString(),
|
||||
host
|
||||
});
|
||||
|
||||
return grpcPort;
|
||||
} catch (err) {
|
||||
lastError = err as Error;
|
||||
Logger.warn(`Failed to bind gRPC on ${host}:${grpcPort}, trying next...`, err);
|
||||
}
|
||||
}
|
||||
|
||||
Logger.error('Failed to start gRPC service on all hosts');
|
||||
throw lastError || new Error('Failed to start gRPC service');
|
||||
} catch (err) {
|
||||
Logger.error('Failed to start gRPC service:', err);
|
||||
throw err;
|
||||
|
||||
+30
-10
@@ -3,31 +3,51 @@ import Logger from '../loaders/logger';
|
||||
import { metricsService } from './metrics';
|
||||
import { Service } from 'typedi';
|
||||
import { Server } from 'http';
|
||||
import config from '../config';
|
||||
|
||||
@Service()
|
||||
export class HttpServerService {
|
||||
private server?: Server = undefined;
|
||||
|
||||
async initialize(expressApp: express.Application, port: number) {
|
||||
const hostsToTry = [
|
||||
config.bindHost,
|
||||
...(config.bindHost !== '0.0.0.0' ? ['0.0.0.0'] : [])
|
||||
];
|
||||
|
||||
let lastError: Error | null = null;
|
||||
|
||||
for (const host of hostsToTry) {
|
||||
try {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.server = expressApp.listen(port, '0.0.0.0', () => {
|
||||
Logger.debug(`✌️ HTTP service started successfully`);
|
||||
const server = await this.tryListen(expressApp, port, host);
|
||||
Logger.debug(`[boot] HTTP service started successfully on ${host}:${port}`);
|
||||
metricsService.record('http_service_start', 1, {
|
||||
port: port.toString(),
|
||||
host
|
||||
});
|
||||
resolve(this.server);
|
||||
this.server = server;
|
||||
return server;
|
||||
} catch (err) {
|
||||
lastError = err as Error;
|
||||
Logger.warn(`Failed to bind HTTP on ${host}:${port}, trying next...`, err);
|
||||
}
|
||||
}
|
||||
|
||||
Logger.error('Failed to start HTTP service on all hosts');
|
||||
throw lastError || new Error('Failed to start HTTP service');
|
||||
}
|
||||
|
||||
private async tryListen(expressApp: express.Application, port: number, host: string): Promise<Server> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = expressApp.listen(port, host, () => {
|
||||
resolve(server);
|
||||
});
|
||||
|
||||
this.server?.on('error', (err: Error) => {
|
||||
Logger.error('Failed to start HTTP service:', err);
|
||||
server.on('error', (err: Error) => {
|
||||
server.close();
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
Logger.error('Failed to start HTTP service:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async shutdown() {
|
||||
|
||||
+97
-8
@@ -3,6 +3,7 @@ import nodemailer from 'nodemailer';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { parseBody, parseHeaders } from '../config/util';
|
||||
import { NotificationInfo } from '../data/notify';
|
||||
import { t } from '../shared/i18n';
|
||||
import UserService from './user';
|
||||
import { httpClient } from '../config/http';
|
||||
import { ProxyAgent } from 'undici';
|
||||
@@ -34,6 +35,8 @@ export default class NotificationService {
|
||||
['chronocat', this.chronocat],
|
||||
['ntfy', this.ntfy],
|
||||
['wxPusherBot', this.wxPusherBot],
|
||||
['wxPusherSpt', this.wxPusherSpt],
|
||||
['openiLink', this.openiLink],
|
||||
]);
|
||||
|
||||
private title = '';
|
||||
@@ -90,6 +93,14 @@ export default class NotificationService {
|
||||
return true;
|
||||
}
|
||||
|
||||
private parseMailRecipients(value?: string) {
|
||||
const recipients = (value || '')
|
||||
.split(/[;;]/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
return recipients.length > 0 ? recipients : undefined;
|
||||
}
|
||||
|
||||
private async gotify() {
|
||||
const { gotifyUrl, gotifyToken, gotifyPriority = 1 } = this.params;
|
||||
try {
|
||||
@@ -355,7 +366,7 @@ export default class NotificationService {
|
||||
{
|
||||
title: `${this.title}`,
|
||||
thumb_media_id,
|
||||
author: `智能助手`,
|
||||
author: t('智能助手'),
|
||||
content_source_url: ``,
|
||||
content: `${this.content.replace(/\n/g, '<br/>')}`,
|
||||
digest: `${this.content}`,
|
||||
@@ -371,7 +382,7 @@ export default class NotificationService {
|
||||
title: `${this.title}`,
|
||||
description: `${this.content}`,
|
||||
url: 'https://github.com/whyour/qinglong',
|
||||
btntxt: '更多',
|
||||
btntxt: t('更多'),
|
||||
},
|
||||
};
|
||||
break;
|
||||
@@ -422,7 +433,7 @@ export default class NotificationService {
|
||||
roomName: `${aibotkName}`,
|
||||
message: {
|
||||
type: 1,
|
||||
content: `【青龙快讯】\n\n${this.title}\n${this.content}`,
|
||||
content: `【${t('青龙快讯')}】\n\n${this.title}\n${this.content}`,
|
||||
},
|
||||
};
|
||||
break;
|
||||
@@ -433,7 +444,7 @@ export default class NotificationService {
|
||||
name: `${aibotkName}`,
|
||||
message: {
|
||||
type: 1,
|
||||
content: `【青龙快讯】\n\n${this.title}\n${this.content}`,
|
||||
content: `【${t('青龙快讯')}】\n\n${this.title}\n${this.content}`,
|
||||
},
|
||||
};
|
||||
break;
|
||||
@@ -591,6 +602,7 @@ export default class NotificationService {
|
||||
|
||||
private async email() {
|
||||
const { emailPass, emailService, emailUser, emailTo } = this.params;
|
||||
const recipients = this.parseMailRecipients(emailTo) || emailUser;
|
||||
|
||||
try {
|
||||
const transporter = nodemailer.createTransport({
|
||||
@@ -602,8 +614,8 @@ export default class NotificationService {
|
||||
});
|
||||
|
||||
const info = await transporter.sendMail({
|
||||
from: `"青龙快讯" <${emailUser}>`,
|
||||
to: emailTo ? emailTo.split(';') : emailUser,
|
||||
from: `"${t('青龙快讯')}" <${emailUser}>`,
|
||||
to: recipients,
|
||||
subject: `${this.title}`,
|
||||
html: `${this.content.replace(/\n/g, '<br/>')}`,
|
||||
});
|
||||
@@ -717,7 +729,7 @@ export default class NotificationService {
|
||||
|
||||
// topic_ids 和 uids 至少要有一个
|
||||
if (!topicIds.length && !uids.length) {
|
||||
throw new Error('wxPusher 服务的 TopicIds 和 Uids 至少配置一个才行');
|
||||
throw new Error(t('wxPusher 服务的 TopicIds 和 Uids 至少配置一个才行'));
|
||||
}
|
||||
|
||||
const url = `https://wxpusher.zjiecode.com/api/send/message`;
|
||||
@@ -745,6 +757,52 @@ export default class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
private async wxPusherSpt() {
|
||||
const { wxPusherSptList } = this.params;
|
||||
// 处理 SPT,将逗号分隔的字符串转为数组
|
||||
const spts = wxPusherSptList
|
||||
? wxPusherSptList
|
||||
.split(',')
|
||||
.map((spt) => spt.trim())
|
||||
.filter((spt) => spt)
|
||||
: [];
|
||||
|
||||
if (!spts.length) {
|
||||
throw new Error(t('wxPusher SPT 不能为空'));
|
||||
}
|
||||
if (spts.length > 10) {
|
||||
throw new Error(t('wxPusher SPT 最多支持 10 个'));
|
||||
}
|
||||
|
||||
const url = `https://wxpusher.zjiecode.com/api/send/message/simple-push`;
|
||||
const json: any = {
|
||||
content: `<h1>${this.title}</h1><br/><div style='white-space: pre-wrap;'>${this.content}</div>`,
|
||||
summary: this.title,
|
||||
contentType: 2,
|
||||
};
|
||||
// 单个 SPT 用 spt,多个用 sptList
|
||||
if (spts.length === 1) {
|
||||
json.spt = spts[0];
|
||||
} else {
|
||||
json.sptList = spts;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await httpClient.post(url, {
|
||||
...this.gotOption,
|
||||
json,
|
||||
});
|
||||
|
||||
if (res.code === 1000) {
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(JSON.stringify(res));
|
||||
}
|
||||
} catch (error: any) {
|
||||
throw new Error(error.response ? error.response.body : error);
|
||||
}
|
||||
}
|
||||
|
||||
private async chronocat() {
|
||||
const { chronocatURL, chronocatQQ, chronocatToken } = this.params;
|
||||
try {
|
||||
@@ -813,7 +871,7 @@ export default class NotificationService {
|
||||
} = this.params;
|
||||
|
||||
if (!webhookUrl?.includes('$title') && !webhookBody?.includes('$title')) {
|
||||
throw new Error('Url 或者 Body 中必须包含 $title');
|
||||
throw new Error(t('Url 或者 Body 中必须包含 $title'));
|
||||
}
|
||||
|
||||
const headers = parseHeaders(webhookHeaders);
|
||||
@@ -858,4 +916,35 @@ export default class NotificationService {
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
private async openiLink() {
|
||||
const { openiLinkAppToken, openiLinkHubUrl, openiLinkContextToken } =
|
||||
this.params;
|
||||
const baseUrl = openiLinkHubUrl?.replace(/\/$/, '') || 'https://hub.openilink.com';
|
||||
const url = `${baseUrl}/bot/v1/message/send`;
|
||||
const body: Record<string, string> = {
|
||||
type: 'text',
|
||||
content: `${this.title}\n\n${this.content}`,
|
||||
};
|
||||
if (openiLinkContextToken) {
|
||||
body.context_token = openiLinkContextToken;
|
||||
}
|
||||
try {
|
||||
const res = await httpClient.post(url, {
|
||||
...this.gotOption,
|
||||
json: body,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${openiLinkAppToken}`,
|
||||
},
|
||||
});
|
||||
if (res.ok) {
|
||||
return true;
|
||||
} else {
|
||||
throw new Error(JSON.stringify(res));
|
||||
}
|
||||
} catch (error: any) {
|
||||
throw new Error(error.response ? error.response.body : error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { App, AppModel } from '../data/open';
|
||||
import { v4 as uuidV4 } from 'uuid';
|
||||
import sequelize, { Op } from 'sequelize';
|
||||
import { shareStore } from '../shared/store';
|
||||
import { t } from '../shared/i18n';
|
||||
|
||||
@Service()
|
||||
export default class OpenService {
|
||||
@@ -151,7 +152,7 @@ export default class OpenService {
|
||||
},
|
||||
};
|
||||
} else {
|
||||
return { code: 400, message: 'client_id 或 client_seret 有误' };
|
||||
return { code: 400, message: t('client_id 或 client_seret 有误') };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,13 +42,11 @@ export default class SshKeyService {
|
||||
key: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await writeFileWithLock(
|
||||
path.join(this.sshPath, alias),
|
||||
`${key}${os.EOL}`,
|
||||
{
|
||||
mode: '400',
|
||||
},
|
||||
);
|
||||
const filePath = path.join(this.sshPath, alias);
|
||||
try {
|
||||
await rmPath(filePath);
|
||||
} catch { }
|
||||
await writeFileWithLock(filePath, `${key}${os.EOL}`, { mode: '400' });
|
||||
} catch (error) {
|
||||
this.logger.error('生成私钥文件失败', error);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import path, { join } from 'path';
|
||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||
import { SimpleIntervalSchedule } from 'toad-scheduler';
|
||||
import SockService from './sock';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
import SshKeyService from './sshKey';
|
||||
import dayjs from 'dayjs';
|
||||
import { LOG_END_SYMBOL } from '../config/const';
|
||||
@@ -130,14 +131,14 @@ export default class SubscriptionService {
|
||||
);
|
||||
const absolutePath = await handleLogPath(
|
||||
logPath as string,
|
||||
`## 开始执行... ${startTime.format('YYYY-MM-DD HH:mm:ss')}\n`,
|
||||
tf('## 开始执行... %s\n', startTime.format('YYYY-MM-DD HH:mm:ss')),
|
||||
);
|
||||
|
||||
// 执行sub_before
|
||||
let beforeStr = '';
|
||||
try {
|
||||
if (doc.sub_before) {
|
||||
await logStreamManager.write(absolutePath, `\n## 执行before命令...\n\n`);
|
||||
await logStreamManager.write(absolutePath, `\n## ${t('执行before命令...')}\n\n`);
|
||||
beforeStr = await promiseExec(doc.sub_before);
|
||||
}
|
||||
} catch (error: any) {
|
||||
@@ -164,7 +165,7 @@ export default class SubscriptionService {
|
||||
let afterStr = '';
|
||||
try {
|
||||
if (sub.sub_after) {
|
||||
await logStreamManager.write(absolutePath, `\n\n## 执行after命令...\n\n`);
|
||||
await logStreamManager.write(absolutePath, `\n\n## ${t('执行after命令...')}\n\n`);
|
||||
afterStr = await promiseExec(sub.sub_after);
|
||||
}
|
||||
} catch (error: any) {
|
||||
@@ -177,9 +178,13 @@ export default class SubscriptionService {
|
||||
|
||||
await logStreamManager.write(
|
||||
absolutePath,
|
||||
`\n## 执行结束... ${endTime.format(
|
||||
'YYYY-MM-DD HH:mm:ss',
|
||||
)} 耗时 ${diff} 秒${LOG_END_SYMBOL}`,
|
||||
'\n' +
|
||||
tf(
|
||||
'## 执行结束... %s 耗时 %s 秒',
|
||||
endTime.format('YYYY-MM-DD HH:mm:ss'),
|
||||
String(diff),
|
||||
) +
|
||||
LOG_END_SYMBOL,
|
||||
);
|
||||
|
||||
// Close the stream after task completion
|
||||
@@ -192,7 +197,7 @@ export default class SubscriptionService {
|
||||
|
||||
this.sockService.sendMessage({
|
||||
type: 'runSubscriptionEnd',
|
||||
message: '订阅执行完成',
|
||||
message: t('订阅执行完成'),
|
||||
references: [doc.id as number],
|
||||
});
|
||||
},
|
||||
|
||||
+62
-34
@@ -37,6 +37,8 @@ import ScheduleService, { TaskCallbacks } from './schedule';
|
||||
import SockService from './sock';
|
||||
import os from 'os';
|
||||
import dayjs from 'dayjs';
|
||||
import { t, setLang } from '../shared/i18n';
|
||||
import { updateLinuxMirrorFile } from '../config/util';
|
||||
|
||||
@Service()
|
||||
export default class SystemService {
|
||||
@@ -76,8 +78,8 @@ export default class SystemService {
|
||||
const code = Math.random().toString().slice(-6);
|
||||
const isSuccess = await this.notificationService.testNotify(
|
||||
notificationInfo,
|
||||
'青龙',
|
||||
`【蛟龙】测试通知 https://t.me/jiao_long`,
|
||||
t('青龙'),
|
||||
t('【蛟龙】测试通知 https://t.me/jiao_long'),
|
||||
);
|
||||
if (isSuccess) {
|
||||
const result = await this.updateAuthDb({
|
||||
@@ -86,7 +88,7 @@ export default class SystemService {
|
||||
});
|
||||
return { code: 200, data: { ...result, code } };
|
||||
} else {
|
||||
return { code: 400, message: '通知发送失败,请检查参数' };
|
||||
return { code: 400, message: t('通知发送失败,请检查参数') };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +100,7 @@ export default class SystemService {
|
||||
});
|
||||
const cron = {
|
||||
id: result.id as number,
|
||||
name: '删除日志',
|
||||
name: t('删除日志'),
|
||||
command: `ql rmlog ${info.logRemoveFrequency}`,
|
||||
runOrigin: 'system' as const,
|
||||
};
|
||||
@@ -177,6 +179,7 @@ export default class SystemService {
|
||||
this.sockService.sendMessage({
|
||||
type: 'updateNodeMirror',
|
||||
message: 'update node mirror end',
|
||||
status: 'completed',
|
||||
});
|
||||
},
|
||||
onError: async (message: string) => {
|
||||
@@ -214,33 +217,11 @@ export default class SystemService {
|
||||
onEnd?: () => void,
|
||||
) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
await this.updateAuthDb({
|
||||
...oDoc,
|
||||
info: { ...oDoc.info, ...info },
|
||||
});
|
||||
let defaultDomain = 'https://dl-cdn.alpinelinux.org';
|
||||
let targetDomain = 'https://dl-cdn.alpinelinux.org';
|
||||
if (os.platform() !== 'linux') {
|
||||
return;
|
||||
}
|
||||
const content = await fs.promises.readFile('/etc/apk/repositories', {
|
||||
encoding: 'utf-8',
|
||||
});
|
||||
const domainMatch = content.match(/(http.*)\/alpine\/.*/);
|
||||
if (domainMatch) {
|
||||
defaultDomain = domainMatch[1];
|
||||
}
|
||||
if (info.linuxMirror) {
|
||||
targetDomain = info.linuxMirror;
|
||||
}
|
||||
const command = `sed -i 's/${defaultDomain.replace(
|
||||
/\//g,
|
||||
'\\/',
|
||||
)}/${targetDomain.replace(
|
||||
/\//g,
|
||||
'\\/',
|
||||
)}/g' /etc/apk/repositories && apk update -f`;
|
||||
|
||||
const command = await updateLinuxMirrorFile(info.linuxMirror || '');
|
||||
let hasError = false;
|
||||
this.scheduleService.runTask(
|
||||
command,
|
||||
{
|
||||
@@ -252,10 +233,18 @@ export default class SystemService {
|
||||
this.sockService.sendMessage({
|
||||
type: 'updateLinuxMirror',
|
||||
message: 'update linux mirror end',
|
||||
status: 'completed',
|
||||
});
|
||||
onEnd?.();
|
||||
if (!hasError) {
|
||||
await this.updateAuthDb({
|
||||
...oDoc,
|
||||
info: { ...oDoc.info, ...info },
|
||||
});
|
||||
}
|
||||
},
|
||||
onError: async (message: string) => {
|
||||
hasError = true;
|
||||
this.sockService.sendMessage({ type: 'updateLinuxMirror', message });
|
||||
},
|
||||
onLog: async (message: string) => {
|
||||
@@ -353,6 +342,15 @@ export default class SystemService {
|
||||
this.sockService.sendMessage({
|
||||
type: 'updateSystemVersion',
|
||||
message: JSON.stringify(err),
|
||||
status: 'failed',
|
||||
});
|
||||
});
|
||||
|
||||
cp.on('exit', (code) => {
|
||||
this.sockService.sendMessage({
|
||||
type: 'updateSystemVersion',
|
||||
message: '',
|
||||
status: code === 0 ? 'success' : 'failed',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -395,9 +393,9 @@ export default class SystemService {
|
||||
notificationInfo,
|
||||
);
|
||||
if (isSuccess) {
|
||||
return { code: 200, message: '通知发送成功' };
|
||||
return { code: 200, message: t('通知发送成功') };
|
||||
} else {
|
||||
return { code: 400, message: '通知发送失败,请检查系统设置/通知配置' };
|
||||
return { code: 400, message: t('通知发送失败,请检查系统设置/通知配置') };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,7 +413,7 @@ export default class SystemService {
|
||||
|
||||
public async stop({ command, pid }: { command: string; pid: number }) {
|
||||
if (!pid && !command) {
|
||||
return { code: 400, message: '参数错误' };
|
||||
return { code: 400, message: t('参数错误') };
|
||||
}
|
||||
|
||||
if (pid) {
|
||||
@@ -431,7 +429,7 @@ export default class SystemService {
|
||||
await killTask(_pid);
|
||||
return { code: 200 };
|
||||
} else {
|
||||
return { code: 400, message: '任务未找到' };
|
||||
return { code: 400, message: t('任务未找到') };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -526,10 +524,40 @@ export default class SystemService {
|
||||
if (success) {
|
||||
return { code: 200, data: info };
|
||||
} else {
|
||||
return { code: 400, message: '设置时区失败' };
|
||||
return { code: 400, message: t('设置时区失败') };
|
||||
}
|
||||
}
|
||||
|
||||
public async updateLanguage(info: SystemModelInfo) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
const lang = info.lang || 'zh';
|
||||
await this.updateAuthDb({
|
||||
...oDoc,
|
||||
info: { ...oDoc.info, lang },
|
||||
});
|
||||
// Write to standalone lang_env.sh, sourced by shell scripts
|
||||
try {
|
||||
await fs.promises.writeFile(
|
||||
config.langEnvFile,
|
||||
`export QL_LANG='${lang}'\n`,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to write lang_env.sh: ${error}`);
|
||||
}
|
||||
setLang(lang);
|
||||
return { code: 200, data: { lang } };
|
||||
}
|
||||
|
||||
public async updatePanelTitle(info: SystemModelInfo) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
const panelTitle = info.panelTitle?.trim() || '';
|
||||
await this.updateAuthDb({
|
||||
...oDoc,
|
||||
info: { ...oDoc.info, panelTitle },
|
||||
});
|
||||
return { code: 200, data: { panelTitle } };
|
||||
}
|
||||
|
||||
public async updateGlobalSshKey(info: SystemModelInfo) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
const result = await this.updateAuthDb({
|
||||
@@ -553,7 +581,7 @@ export default class SystemService {
|
||||
|
||||
public async cleanDependence(type: 'node' | 'python3') {
|
||||
if (!type || !['node', 'python3'].includes(type)) {
|
||||
return { code: 400, message: '参数错误' };
|
||||
return { code: 400, message: t('参数错误') };
|
||||
}
|
||||
try {
|
||||
const finalPath = path.join(config.dependenceCachePath, type);
|
||||
|
||||
+42
-20
@@ -25,6 +25,7 @@ import uniq from 'lodash/uniq';
|
||||
import pickBy from 'lodash/pickBy';
|
||||
import isNil from 'lodash/isNil';
|
||||
import { shareStore } from '../shared/store';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
|
||||
@Service()
|
||||
export default class UserService {
|
||||
@@ -66,7 +67,7 @@ export default class UserService {
|
||||
);
|
||||
return {
|
||||
code: 410,
|
||||
message: `失败次数过多,请${waitTime}秒后重试`,
|
||||
message: tf('失败次数过多,请%s秒后重试', waitTime),
|
||||
data: waitTime,
|
||||
};
|
||||
}
|
||||
@@ -127,10 +128,19 @@ export default class UserService {
|
||||
isTwoFactorChecking: false,
|
||||
});
|
||||
this.notificationService.notify(
|
||||
'登录通知',
|
||||
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
||||
req.platform
|
||||
}端 登录成功,ip地址 ${ip}`,
|
||||
t('登录通知'),
|
||||
t('你于') +
|
||||
dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss') +
|
||||
t('在') +
|
||||
address +
|
||||
' ' +
|
||||
req.platform +
|
||||
t('端') +
|
||||
' ' +
|
||||
t('登录成功') +
|
||||
t(',ip地址') +
|
||||
' ' +
|
||||
ip,
|
||||
);
|
||||
await this.insertDb({
|
||||
type: AuthDataType.loginLog,
|
||||
@@ -163,10 +173,19 @@ export default class UserService {
|
||||
platform: req.platform,
|
||||
});
|
||||
this.notificationService.notify(
|
||||
'登录通知',
|
||||
`你于${dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${
|
||||
req.platform
|
||||
}端 登录失败,ip地址 ${ip}`,
|
||||
t('登录通知'),
|
||||
t('你于') +
|
||||
dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss') +
|
||||
t('在') +
|
||||
address +
|
||||
' ' +
|
||||
req.platform +
|
||||
t('端') +
|
||||
' ' +
|
||||
t('登录失败') +
|
||||
t(',ip地址') +
|
||||
' ' +
|
||||
ip,
|
||||
);
|
||||
await this.insertDb({
|
||||
type: AuthDataType.loginLog,
|
||||
@@ -183,11 +202,11 @@ export default class UserService {
|
||||
const waitTime = Math.round(Math.pow(3, retries + 1));
|
||||
return {
|
||||
code: 410,
|
||||
message: `失败次数过多,请${waitTime}秒后重试`,
|
||||
message: tf('失败次数过多,请%s秒后重试', waitTime),
|
||||
data: waitTime,
|
||||
};
|
||||
} else {
|
||||
return { code: 400, message: config.authError };
|
||||
return { code: 400, message: t('错误的用户名密码,请重试') };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,17 +277,17 @@ export default class UserService {
|
||||
password: string;
|
||||
}) {
|
||||
if (password === 'admin') {
|
||||
return { code: 400, message: '密码不能设置为admin' };
|
||||
return { code: 400, message: t('密码不能设置为admin') };
|
||||
}
|
||||
const authInfo = await this.getAuthInfo();
|
||||
await this.updateAuthInfo(authInfo, { username, password });
|
||||
return { code: 200, message: '更新成功' };
|
||||
return { code: 200, message: t('更新成功') };
|
||||
}
|
||||
|
||||
public async updateAvatar(avatar: string) {
|
||||
const authInfo = await this.getAuthInfo();
|
||||
await this.updateAuthInfo(authInfo, { avatar });
|
||||
return { code: 200, data: avatar, message: '更新成功' };
|
||||
return { code: 200, data: avatar, message: t('更新成功') };
|
||||
}
|
||||
|
||||
public async initTwoFactor() {
|
||||
@@ -302,7 +321,7 @@ export default class UserService {
|
||||
const authInfo = await this.getAuthInfo();
|
||||
const { isTwoFactorChecking, twoFactorSecret } = authInfo;
|
||||
if (!isTwoFactorChecking) {
|
||||
return { code: 450, message: '未知错误' };
|
||||
return { code: 450, message: t('未知错误') };
|
||||
}
|
||||
const isValid = authenticator.verify({
|
||||
token: code,
|
||||
@@ -326,11 +345,11 @@ export default class UserService {
|
||||
lastaddr: address,
|
||||
platform: req.platform,
|
||||
});
|
||||
return { code: 430, message: '验证失败' };
|
||||
return { code: 430, message: t('验证失败') };
|
||||
}
|
||||
}
|
||||
|
||||
public async deactiveTwoFactor() {
|
||||
public async deactivateTwoFactor() {
|
||||
const authInfo = await this.getAuthInfo();
|
||||
await this.updateAuthInfo(authInfo, {
|
||||
twoFactorActivated: false,
|
||||
@@ -388,8 +407,8 @@ export default class UserService {
|
||||
const code = Math.random().toString().slice(-6);
|
||||
const isSuccess = await this.notificationService.testNotify(
|
||||
notificationInfo,
|
||||
'青龙',
|
||||
`【蛟龙】测试通知 https://t.me/jiao_long`,
|
||||
t('青龙'),
|
||||
t('【蛟龙】测试通知 https://t.me/jiao_long'),
|
||||
);
|
||||
if (isSuccess) {
|
||||
const result = await this.updateAuthDb({
|
||||
@@ -398,7 +417,7 @@ export default class UserService {
|
||||
});
|
||||
return { code: 200, data: { ...result, code } };
|
||||
} else {
|
||||
return { code: 400, message: '通知发送失败,请检查参数' };
|
||||
return { code: 400, message: t('通知发送失败,请检查参数') };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -498,6 +517,9 @@ export default class UserService {
|
||||
|
||||
public async resetAuthInfo(info: Partial<AuthInfo>) {
|
||||
const { retries, twoFactorActivated, password, username } = info;
|
||||
if (password === 'admin') {
|
||||
return { code: 400, message: t('密码不能设置为admin') };
|
||||
}
|
||||
const authInfo = await this.getAuthInfo();
|
||||
const payload = pickBy(
|
||||
{
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { AuthInfo, TokenInfo } from '../data/system';
|
||||
|
||||
export function isDefaultAuthInfo(authInfo: AuthInfo): boolean {
|
||||
return (
|
||||
Object.keys(authInfo).length === 2 &&
|
||||
authInfo.username === 'admin' &&
|
||||
authInfo.password === 'admin'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates if a token exists in the authentication info.
|
||||
* Supports both legacy string tokens and new TokenInfo array format.
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import { shareStore } from './store';
|
||||
|
||||
const messages: Record<string, Record<string, string>> = {
|
||||
zh: {},
|
||||
en: {
|
||||
'暂无权限': 'Access denied',
|
||||
'参数错误': 'Invalid parameter',
|
||||
'参数不正确': 'Invalid parameter',
|
||||
'文件无法访问': 'File not accessible',
|
||||
'文件不存在': 'File not found',
|
||||
'路径不存在': 'Path does not exist',
|
||||
'路径不正确': 'Invalid path',
|
||||
'通知发送失败,请检查参数': 'Notification failed, check parameters',
|
||||
'通知发送失败,请检查系统设置/通知配置': 'Notification failed, check system settings',
|
||||
'通知发送成功': 'Notification sent successfully',
|
||||
'设置时区失败': 'Failed to set timezone',
|
||||
'任务未找到': 'Task not found',
|
||||
'密码不能设置为admin': 'Password cannot be admin',
|
||||
'更新成功': 'Update successful',
|
||||
'未知错误': 'Unknown error',
|
||||
'验证失败': 'Verification failed',
|
||||
'实例不存在或已停止': 'Instance does not exist or stopped',
|
||||
'实例已停止': 'Instance stopped',
|
||||
'确认停止实例': 'Confirm to stop instance',
|
||||
'确认停止运行实例': 'Confirm to stop running instance',
|
||||
'确认停止': 'Confirm to stop',
|
||||
'确认停止定时任务': 'Confirm to stop scheduled task',
|
||||
'确认删除': 'Confirm to delete',
|
||||
'确认删除定时任务': 'Confirm to delete scheduled task',
|
||||
'确认删除选中的定时任务吗': 'Confirm to delete selected tasks?',
|
||||
'确认运行': 'Confirm to run',
|
||||
'确认运行定时任务': 'Confirm to run scheduled task',
|
||||
'确认保存': 'Confirm to save',
|
||||
'确认保存文件': 'Confirm to save file',
|
||||
'确认重启': 'Confirm restart',
|
||||
'确认启用': 'Confirm to enable',
|
||||
'确认禁用': 'Confirm to disable',
|
||||
'确认': 'Confirm',
|
||||
'删除成功': 'Deleted successfully',
|
||||
'操作成功': 'Operation successful',
|
||||
'参数不完整': 'Incomplete parameters',
|
||||
'默认路径不支持删除': 'Default path cannot be deleted',
|
||||
'必须在日志目录下': 'Must be within log directory',
|
||||
'备份数据上传成功,确认覆盖数据': 'Backup uploaded, confirm overwrite',
|
||||
'如果恢复失败,可进入容器执行': 'If restore fails, run in container:',
|
||||
'系统将在': 'System will',
|
||||
'秒后自动刷新': 'refresh in seconds',
|
||||
'生成数据中...': 'Generating data...',
|
||||
'每条数据 name 或者 value 字段不能为空,参考导出文件格式': 'Each entry must have name and value, see export format',
|
||||
'不支持当前依赖类型': 'Unsupported dependency type',
|
||||
'依赖已存在': 'Dependency already exists',
|
||||
'依赖不存在': 'Dependency does not exist',
|
||||
'该脚本正在运行中': 'Script is running',
|
||||
'该脚本未在运行中': 'Script is not running',
|
||||
'文件内容为空': 'File content is empty',
|
||||
'文件名不能为空': 'File name cannot be empty',
|
||||
'标签不能为空': 'Label cannot be empty',
|
||||
'名称不能为空': 'Name cannot be empty',
|
||||
'名称不能为保留关键字': 'Name cannot be reserved keyword',
|
||||
'名称已存在': 'Name already exists',
|
||||
'密码错误': 'Incorrect password',
|
||||
'用户不存在': 'User does not exist',
|
||||
'请输入用户名和密码': 'Please enter username and password',
|
||||
'无权访问': 'Access denied',
|
||||
'登录成功': 'Login successful',
|
||||
'退出成功': 'Logout successful',
|
||||
'Token 已失效': 'Token expired',
|
||||
'Token 无效': 'Invalid token',
|
||||
'两步骤验证已开启': '2FA enabled',
|
||||
'两步骤验证已关闭': '2FA disabled',
|
||||
'验证码错误': 'Invalid verification code',
|
||||
'验证码已过期': 'Verification code expired',
|
||||
'请先开启两步骤验证': 'Please enable 2FA first',
|
||||
'两步骤验证密钥不能为空': '2FA secret cannot be empty',
|
||||
'用户已存在': 'User already exists',
|
||||
'用户名不能为admin': 'Username cannot be admin',
|
||||
'不能删除自己': 'Cannot delete yourself',
|
||||
'不能禁用自己': 'Cannot disable yourself',
|
||||
'文件路径无效': 'Invalid file path',
|
||||
'保存成功': 'Saved successfully',
|
||||
'client_id 或 client_seret 有误': 'Invalid client_id or client_secret',
|
||||
'订阅执行完成': 'Subscription completed',
|
||||
'wxPusher 服务的 TopicIds 和 Uids 至少配置一个才行': 'wxPusher requires at least one of TopicIds or Uids',
|
||||
'wxPusher SPT 不能为空': 'wxPusher SPT cannot be empty',
|
||||
'wxPusher SPT 最多支持 10 个': 'wxPusher SPT supports at most 10 tokens',
|
||||
'Url 或者 Body 中必须包含 $title': 'Url or Body must contain $title',
|
||||
'绝对路径必须在日志目录内或使用 /dev/null':
|
||||
'Absolute path must be within log directory or use /dev/null',
|
||||
'请先登录': 'Please login first',
|
||||
'运行中...': 'Running...',
|
||||
'日志不存在...': 'Log does not exist...',
|
||||
'未分类': 'Uncategorized',
|
||||
'任务重复运行': 'Duplicate task execution',
|
||||
'日志设置为忽略': 'Log set to ignore',
|
||||
'定时规则不能为空': 'Schedule rule cannot be empty',
|
||||
'无效的定时规则': 'Invalid schedule rule',
|
||||
'日志名称只能包含字母、数字、下划线和连字符':
|
||||
'Log name can only contain letters, numbers, underscores, and hyphens',
|
||||
'日志名称不能超过100个字符': 'Log name cannot exceed 100 characters',
|
||||
'错误的用户名密码,请重试': 'Incorrect username or password, please try again',
|
||||
'青龙快讯': 'QingLong',
|
||||
'登录通知': 'Login Notification',
|
||||
'你于': 'You at ',
|
||||
'在': ' in ',
|
||||
端: '',
|
||||
登录失败: 'login failed',
|
||||
',ip地址': ', IP: ',
|
||||
'任务#%s': 'Task#%s',
|
||||
安装: 'Install',
|
||||
删除: 'Uninstall',
|
||||
成功: 'Succeeded',
|
||||
失败: 'Failed',
|
||||
'失败次数过多,请%s秒后重试':
|
||||
'Too many failed attempts, please retry in %s seconds',
|
||||
智能助手: 'Smart Assistant',
|
||||
更多: 'More',
|
||||
'开始%s依赖 %s,开始时间 %s\n\n当前系统不支持\n\n依赖%s失败,结束时间 %s,耗时 %s 秒':
|
||||
'Start %s dependency %s, start time %s\n\nCurrent system not supported\n\nDependency %s failed, end time %s, elapsed %s seconds',
|
||||
'检测到已经安装 %s\n\n%s\n\n跳过安装\n\n依赖%s成功,结束时间 %s,耗时 %s 秒':
|
||||
'Already installed %s\n\n%s\n\nSkipping install\n\nDependency %s succeeded, end time %s, elapsed %s seconds',
|
||||
'开始%s依赖 %s,开始时间 %s\n\n':
|
||||
'Start %s dependency %s, start time %s\n\n',
|
||||
'依赖%s%s,结束时间 %s,耗时 %s 秒':
|
||||
'Dependency %s%s, end time %s, elapsed %s seconds',
|
||||
'任务:%s,命令:%s,定时:%s,处于运行中的超过 %d 个,请检查定时设置':
|
||||
'Task: %s, command: %s, schedule: %s, more than %d instances running, please check schedule settings',
|
||||
青龙: 'QingLong',
|
||||
'【蛟龙】测试通知 https://t.me/jiao_long':
|
||||
'[JiaoLong] Test notification https://t.me/jiao_long',
|
||||
'生成token': 'Generate token',
|
||||
'删除日志': 'Delete logs',
|
||||
'## 开始执行... %s\n': '## Start executing... %s\n',
|
||||
'执行before命令...': 'Execute before command...',
|
||||
'执行after命令...': 'Execute after command...',
|
||||
'## 执行结束... %s 耗时 %s 秒': '## Execution finished... %s elapsed %s seconds',
|
||||
'调度器注册失败,任务创建已回滚':
|
||||
'Scheduler registration failed, task creation rolled back',
|
||||
'调度器注册失败,任务更新已回滚':
|
||||
'Scheduler registration failed, task update rolled back',
|
||||
'调度器注册失败,任务启用已回滚':
|
||||
'Scheduler registration failed, task enable rolled back',
|
||||
'任务ID %s: 无效的 cron 表达式 "%s"(不支持裸 /N 步长和 ? 字符)':
|
||||
'Task ID %s: invalid cron expression "%s" (bare /N steps and ? character not supported)',
|
||||
'任务ID %s (extra_schedule): 无效的 cron 表达式 "%s"(不支持裸 /N 步长和 ? 字符)':
|
||||
'Task ID %s (extra_schedule): invalid cron expression "%s" (bare /N steps and ? character not supported)',
|
||||
},
|
||||
};
|
||||
|
||||
let currentLang: string = 'zh';
|
||||
|
||||
export function setLang(lang: string) {
|
||||
currentLang = lang || 'zh';
|
||||
shareStore.setLang(currentLang);
|
||||
}
|
||||
|
||||
/** 系统默认语言:Intl 检测 → 'zh'(仅返回 zh/en) */
|
||||
export function systemLang(): string {
|
||||
const prefix = Intl.DateTimeFormat().resolvedOptions().locale.split('-')[0];
|
||||
return prefix === 'en' ? 'en' : 'zh';
|
||||
}
|
||||
|
||||
export function t(key: string, lang?: string): string {
|
||||
const effectiveLang = lang || currentLang;
|
||||
if (effectiveLang === 'en' && messages.en[key]) {
|
||||
return messages.en[key];
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
export function tf(key: string, ...args: (string | number)[]): string {
|
||||
return args.reduce<string>(
|
||||
(str, arg) => str.replace(/%s|%d/, String(arg)),
|
||||
t(key),
|
||||
);
|
||||
}
|
||||
+28
-5
@@ -4,6 +4,7 @@ import { AuthDataType, SystemModel } from '../data/system';
|
||||
import Logger from '../loaders/logger';
|
||||
import { Dependence } from '../data/dependence';
|
||||
import NotificationService from '../services/notify';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
import {
|
||||
ICronFn,
|
||||
IDependencyFn,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
import config from '../config';
|
||||
import { credentials } from '@grpc/grpc-js';
|
||||
import { ApiClient } from '../protos/api';
|
||||
import { getGrpcCerts } from '../config/grpcCerts';
|
||||
|
||||
class TaskLimit {
|
||||
private dependenyLimit = new PQueue({ concurrency: 1 });
|
||||
@@ -36,11 +38,26 @@ class TaskLimit {
|
||||
private systemLimit = new PQueue({
|
||||
concurrency: Math.max(os.cpus().length, 4),
|
||||
});
|
||||
private client = new ApiClient(
|
||||
`0.0.0.0:${config.grpcPort}`,
|
||||
credentials.createInsecure(),
|
||||
private _client: ApiClient | null = null;
|
||||
|
||||
private get client(): ApiClient {
|
||||
if (!this._client) {
|
||||
const tlsConfig = getGrpcCerts();
|
||||
const creds = tlsConfig
|
||||
? credentials.createSsl(
|
||||
Buffer.from(tlsConfig.caCert),
|
||||
Buffer.from(tlsConfig.clientKey),
|
||||
Buffer.from(tlsConfig.clientCert),
|
||||
)
|
||||
: credentials.createInsecure();
|
||||
this._client = new ApiClient(
|
||||
`localhost:${config.grpcPort}`,
|
||||
creds,
|
||||
{ 'grpc.enable_http_proxy': 0 },
|
||||
);
|
||||
}
|
||||
return this._client;
|
||||
}
|
||||
|
||||
get cronLimitActiveCount() {
|
||||
return this.cronLimit.pending;
|
||||
@@ -136,8 +153,14 @@ class TaskLimit {
|
||||
this.repeatCronNotifyMap.set(cron.id, repeatTimes + 1);
|
||||
this.client.systemNotify(
|
||||
{
|
||||
title: '任务重复运行',
|
||||
content: `任务:${cron.name},命令:${cron.command},定时:${cron.schedule},处于运行中的超过 5 个,请检查定时设置`,
|
||||
title: t('任务重复运行'),
|
||||
content: tf(
|
||||
'任务:%s,命令:%s,定时:%s,处于运行中的超过 %d 个,请检查定时设置',
|
||||
cron.name || '',
|
||||
cron.command || '',
|
||||
cron.schedule || '',
|
||||
5,
|
||||
),
|
||||
},
|
||||
(err, res) => {
|
||||
if (err) {
|
||||
|
||||
@@ -4,6 +4,11 @@ import Logger from '../loaders/logger';
|
||||
import { ICron } from '../protos/cron';
|
||||
import { CrontabModel, CrontabStatus } from '../data/cron';
|
||||
import { killTask } from '../config/util';
|
||||
import {
|
||||
RunningInstanceModel,
|
||||
InstanceStatus,
|
||||
} from '../data/runningInstance';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
export function runCron(cmd: string, cron: ICron): Promise<number | void> {
|
||||
return taskLimit.runWithCronLimit(cron, () => {
|
||||
@@ -29,6 +34,12 @@ export function runCron(cmd: string, cron: ICron): Promise<number | void> {
|
||||
`[schedule][停止已运行任务] 任务ID: ${cron.id}, PID: ${existingCron.pid}`,
|
||||
);
|
||||
await killTask(existingCron.pid);
|
||||
// Mark old running instances as stopped
|
||||
const stoppedAt = dayjs().unix();
|
||||
await RunningInstanceModel.update(
|
||||
{ status: InstanceStatus.stopped, finished_at: stoppedAt },
|
||||
{ where: { cron_id: Number(cron.id), status: InstanceStatus.running } },
|
||||
);
|
||||
// Update the status to idle after killing
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: undefined },
|
||||
|
||||
@@ -8,11 +8,13 @@ import path from 'path';
|
||||
export enum EKeyv {
|
||||
'apps' = 'apps',
|
||||
'authInfo' = 'authInfo',
|
||||
'lang' = 'lang',
|
||||
}
|
||||
|
||||
export interface IKeyvStore {
|
||||
apps: App[];
|
||||
authInfo: AuthInfo;
|
||||
lang: string;
|
||||
}
|
||||
|
||||
const keyvSqlite = new KeyvSqlite(path.join(config.dbPath, 'keyv.sqlite'));
|
||||
@@ -31,4 +33,10 @@ export const shareStore = {
|
||||
updateApps(apps: App[]) {
|
||||
return keyvStore.set<IKeyvStore['apps']>(EKeyv.apps, apps);
|
||||
},
|
||||
getLang() {
|
||||
return keyvStore.get<IKeyvStore['lang']>(EKeyv.lang);
|
||||
},
|
||||
setLang(value: IKeyvStore['lang']) {
|
||||
return keyvStore.set<IKeyvStore['lang']>(EKeyv.lang, value);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -12,6 +12,16 @@ const validateSchedule = (value: string, helpers: any) => {
|
||||
return value;
|
||||
}
|
||||
|
||||
// 检测裸 /N 模式:cron-parser 会接受,但 node-schedule 会返回 null
|
||||
// 提前拦截,避免任务入库后调度器注册失败
|
||||
if (/\s\/\d/.test(value) || /^\/\d/.test(value)) {
|
||||
return helpers.error('any.invalid');
|
||||
}
|
||||
// 检测 ? 字符:Quartz cron 语法,node-schedule 在大多数字段上返回 null
|
||||
if (/\?/.test(value)) {
|
||||
return helpers.error('any.invalid');
|
||||
}
|
||||
|
||||
try {
|
||||
if (CronExpressionParser.parse(value).hasNext()) {
|
||||
return value;
|
||||
@@ -82,4 +92,5 @@ export const commonCronSchema = {
|
||||
'string.unsafePath': '绝对路径必须在日志目录内或使用 /dev/null',
|
||||
}),
|
||||
allow_multiple_instances: Joi.number().optional().valid(0, 1).allow(null),
|
||||
work_dir: Joi.string().optional().allow('').allow(null),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# Kubernetes deployment
|
||||
|
||||
This deploys Qinglong as a single-replica `StatefulSet` with persistent data at `/ql/data`.
|
||||
|
||||
```bash
|
||||
kubectl apply -k deploy/kubernetes/overlays/local
|
||||
kubectl -n qinglong rollout status statefulset/qinglong
|
||||
```
|
||||
|
||||
Open the panel locally:
|
||||
|
||||
```bash
|
||||
kubectl -n qinglong port-forward svc/qinglong 5700:5700
|
||||
```
|
||||
|
||||
Then visit <http://127.0.0.1:5700>.
|
||||
|
||||
## Image registry overlays
|
||||
|
||||
Use `overlays/example` as the committed template for registry customization:
|
||||
|
||||
```yaml
|
||||
whyour/qinglong:debian -> registry.example.com/whyour/qinglong:debian
|
||||
```
|
||||
|
||||
Create `overlays/local/kustomization.yaml` for the actual cluster image. The `local` overlay is ignored by git so private registry names, digests, and credentials-related references stay local.
|
||||
|
||||
## Storage
|
||||
|
||||
The manifest creates a 5 GiB `ReadWriteOnce` PVC from the cluster's default `StorageClass`.
|
||||
If your cluster has no default storage class, add `storageClassName` under:
|
||||
|
||||
```yaml
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
name: data
|
||||
spec:
|
||||
storageClassName: your-storage-class
|
||||
```
|
||||
|
||||
Keep `replicas: 1`. Qinglong stores state in the persistent data directory, including SQLite files, so multiple replicas should not share the same data volume.
|
||||
|
||||
## Ingress example
|
||||
|
||||
If you expose Qinglong through an Ingress path other than `/`, set `QlBaseUrl` to the same path with leading and trailing slashes.
|
||||
|
||||
```yaml
|
||||
env:
|
||||
- name: QlBaseUrl
|
||||
value: "/qinglong/"
|
||||
```
|
||||
|
||||
Example Ingress:
|
||||
|
||||
```yaml
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: qinglong
|
||||
namespace: qinglong
|
||||
spec:
|
||||
rules:
|
||||
- host: qinglong.example.com
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: qinglong
|
||||
port:
|
||||
number: 5700
|
||||
```
|
||||
|
||||
## Maintenance commands
|
||||
|
||||
```bash
|
||||
kubectl -n qinglong logs -f statefulset/qinglong
|
||||
kubectl -n qinglong exec -it statefulset/qinglong -- ql check
|
||||
kubectl -n qinglong exec -it statefulset/qinglong -- ql update
|
||||
```
|
||||
@@ -0,0 +1,5 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
resources:
|
||||
- qinglong.yaml
|
||||
@@ -0,0 +1,95 @@
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: qinglong
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: qinglong
|
||||
namespace: qinglong
|
||||
labels:
|
||||
app.kubernetes.io/name: qinglong
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
app.kubernetes.io/name: qinglong
|
||||
ports:
|
||||
- name: http
|
||||
port: 5700
|
||||
targetPort: http
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: qinglong
|
||||
namespace: qinglong
|
||||
labels:
|
||||
app.kubernetes.io/name: qinglong
|
||||
spec:
|
||||
serviceName: qinglong
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: qinglong
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/name: qinglong
|
||||
spec:
|
||||
securityContext:
|
||||
fsGroup: 5432
|
||||
fsGroupChangePolicy: OnRootMismatch
|
||||
containers:
|
||||
- name: qinglong
|
||||
image: whyour/qinglong:debian
|
||||
imagePullPolicy: IfNotPresent
|
||||
env:
|
||||
- name: QlBaseUrl
|
||||
value: "/"
|
||||
- name: TZ
|
||||
value: Asia/Shanghai
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 5700
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /api/health
|
||||
port: http
|
||||
initialDelaySeconds: 20
|
||||
periodSeconds: 10
|
||||
timeoutSeconds: 3
|
||||
failureThreshold: 6
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /api/health
|
||||
port: http
|
||||
initialDelaySeconds: 60
|
||||
periodSeconds: 20
|
||||
timeoutSeconds: 3
|
||||
failureThreshold: 6
|
||||
startupProbe:
|
||||
httpGet:
|
||||
path: /api/health
|
||||
port: http
|
||||
periodSeconds: 5
|
||||
timeoutSeconds: 3
|
||||
failureThreshold: 60
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 256Mi
|
||||
limits:
|
||||
memory: 1Gi
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /ql/data
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
name: data
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 5Gi
|
||||
@@ -0,0 +1,10 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
resources:
|
||||
- ../../base
|
||||
|
||||
images:
|
||||
- name: whyour/qinglong
|
||||
newName: registry.example.com/whyour/qinglong
|
||||
newTag: debian
|
||||
+32
-11
@@ -1,11 +1,26 @@
|
||||
FROM python:3.11-alpine3.18 AS builder
|
||||
# Run Node package installation natively on the builder. Node/npm can spin at
|
||||
# 100% CPU when Alpine s390x is emulated through QEMU.
|
||||
FROM --platform=$BUILDPLATFORM node:18-alpine3.18 AS builder
|
||||
|
||||
ARG TARGETARCH
|
||||
ENV NPM_CONFIG_PREFIX=/opt/node-global
|
||||
ENV PATH=/opt/node-global/bin:${PATH}
|
||||
|
||||
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
|
||||
RUN set -x \
|
||||
&& apk update \
|
||||
&& apk add nodejs npm git \
|
||||
&& npm i -g pnpm@8.3.1 pm2 ts-node \
|
||||
&& apk add --no-cache git \
|
||||
&& npm i -g pnpm@8.3.1 pm2 ts-node typescript@5 \
|
||||
&& cd /tmp/build \
|
||||
&& pnpm install --prod
|
||||
&& case "${TARGETARCH}" in \
|
||||
amd64) NODE_ARCH=x64 ;; \
|
||||
386) NODE_ARCH=ia32 ;; \
|
||||
ppc64le) NODE_ARCH=ppc64 ;; \
|
||||
*) NODE_ARCH="${TARGETARCH}" ;; \
|
||||
esac \
|
||||
&& npm_config_target_platform=linux \
|
||||
npm_config_target_arch="${NODE_ARCH}" \
|
||||
npm_config_target_libc=musl \
|
||||
pnpm install --prod
|
||||
|
||||
FROM python:3.11-alpine
|
||||
|
||||
@@ -17,6 +32,7 @@ ARG PYTHON_SHORT_VERSION=3.11
|
||||
|
||||
ENV QL_DIR=/ql \
|
||||
QL_BRANCH=${QL_BRANCH} \
|
||||
QL_CONTAINER=true \
|
||||
LANG=C.UTF-8 \
|
||||
SHELL=/bin/bash \
|
||||
PS1="\u@\h:\w \$ "
|
||||
@@ -25,8 +41,8 @@ VOLUME /ql/data
|
||||
|
||||
EXPOSE 5700
|
||||
|
||||
COPY --from=builder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
|
||||
COPY --from=builder /usr/local/bin/. /usr/local/bin/
|
||||
COPY --from=builder /opt/node-global/lib/node_modules/. /usr/local/lib/node_modules/
|
||||
COPY --from=builder /opt/node-global/bin/. /usr/local/bin/
|
||||
|
||||
RUN set -x \
|
||||
&& apk update -f \
|
||||
@@ -69,10 +85,11 @@ RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
||||
|
||||
ENV PNPM_HOME=${QL_DIR}/data/dep_cache/node \
|
||||
PYTHON_HOME=${QL_DIR}/data/dep_cache/python3 \
|
||||
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3
|
||||
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3 \
|
||||
HOME=/root
|
||||
|
||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin \
|
||||
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules:${PNPM_HOME}/global/5/node_modules \
|
||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin:${HOME}/bin \
|
||||
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules \
|
||||
PIP_CACHE_DIR=${PYTHON_HOME}/pip \
|
||||
PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
|
||||
|
||||
@@ -80,9 +97,13 @@ RUN pip3 install --prefix ${PYTHON_HOME} requests
|
||||
|
||||
COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
||||
|
||||
RUN ln -sf ${QL_DIR}/shell/task.sh /usr/local/bin/task \
|
||||
&& ln -sf ${QL_DIR}/shell/update.sh /usr/local/bin/ql \
|
||||
&& chmod +x /usr/local/bin/task /usr/local/bin/ql
|
||||
|
||||
WORKDIR ${QL_DIR}
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
||||
CMD curl -sf --noproxy '*' http://127.0.0.1:5700/api/health || exit 1
|
||||
CMD curl -sf --noproxy '*' http://localhost:${QlPort:-5700}/api/health || exit 1
|
||||
|
||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
FROM python:3.10-alpine3.18 AS builder
|
||||
# Run Node package installation natively on the builder. Node/npm can spin at
|
||||
# 100% CPU when Alpine s390x is emulated through QEMU.
|
||||
FROM --platform=$BUILDPLATFORM node:18-alpine3.18 AS builder
|
||||
|
||||
ARG TARGETARCH
|
||||
ENV NPM_CONFIG_PREFIX=/opt/node-global
|
||||
ENV PATH=/opt/node-global/bin:${PATH}
|
||||
|
||||
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
|
||||
RUN set -x \
|
||||
&& apk update \
|
||||
&& apk add nodejs npm git \
|
||||
&& npm i -g pnpm@8.3.1 pm2 ts-node \
|
||||
&& apk add --no-cache git \
|
||||
&& npm i -g pnpm@8.3.1 pm2 ts-node typescript@5 \
|
||||
&& cd /tmp/build \
|
||||
&& pnpm install --prod
|
||||
&& case "${TARGETARCH}" in \
|
||||
amd64) NODE_ARCH=x64 ;; \
|
||||
386) NODE_ARCH=ia32 ;; \
|
||||
ppc64le) NODE_ARCH=ppc64 ;; \
|
||||
*) NODE_ARCH="${TARGETARCH}" ;; \
|
||||
esac \
|
||||
&& npm_config_target_platform=linux \
|
||||
npm_config_target_arch="${NODE_ARCH}" \
|
||||
npm_config_target_libc=musl \
|
||||
pnpm install --prod
|
||||
|
||||
FROM python:3.10-alpine
|
||||
|
||||
@@ -17,6 +32,7 @@ ARG PYTHON_SHORT_VERSION=3.10
|
||||
|
||||
ENV QL_DIR=/ql \
|
||||
QL_BRANCH=${QL_BRANCH} \
|
||||
QL_CONTAINER=true \
|
||||
LANG=C.UTF-8 \
|
||||
SHELL=/bin/bash \
|
||||
PS1="\u@\h:\w \$ "
|
||||
@@ -25,8 +41,8 @@ VOLUME /ql/data
|
||||
|
||||
EXPOSE 5700
|
||||
|
||||
COPY --from=builder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
|
||||
COPY --from=builder /usr/local/bin/. /usr/local/bin/
|
||||
COPY --from=builder /opt/node-global/lib/node_modules/. /usr/local/lib/node_modules/
|
||||
COPY --from=builder /opt/node-global/bin/. /usr/local/bin/
|
||||
|
||||
RUN set -x \
|
||||
&& apk update -f \
|
||||
@@ -69,10 +85,11 @@ RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
||||
|
||||
ENV PNPM_HOME=${QL_DIR}/data/dep_cache/node \
|
||||
PYTHON_HOME=${QL_DIR}/data/dep_cache/python3 \
|
||||
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3
|
||||
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3 \
|
||||
HOME=/root
|
||||
|
||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin \
|
||||
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules:${PNPM_HOME}/global/5/node_modules \
|
||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin:${HOME}/bin \
|
||||
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules \
|
||||
PIP_CACHE_DIR=${PYTHON_HOME}/pip \
|
||||
PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
|
||||
|
||||
@@ -80,9 +97,13 @@ RUN pip3 install --prefix ${PYTHON_HOME} requests
|
||||
|
||||
COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
||||
|
||||
RUN ln -sf ${QL_DIR}/shell/task.sh /usr/local/bin/task \
|
||||
&& ln -sf ${QL_DIR}/shell/update.sh /usr/local/bin/ql \
|
||||
&& chmod +x /usr/local/bin/task /usr/local/bin/ql
|
||||
|
||||
WORKDIR ${QL_DIR}
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
||||
CMD curl -sf --noproxy '*' http://127.0.0.1:5700/api/health || exit 1
|
||||
CMD curl -sf --noproxy '*' http://localhost:${QlPort:-5700}/api/health || exit 1
|
||||
|
||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||
@@ -0,0 +1,122 @@
|
||||
# Node 20 Bookworm is the latest official Node image variant that covers the
|
||||
# full Debian build matrix, including arm/v7, ppc64le, and s390x.
|
||||
FROM node:20-bookworm-slim AS nodebuilder
|
||||
|
||||
FROM python:3.11-slim-bookworm AS builder
|
||||
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
|
||||
COPY --from=nodebuilder /usr/local/bin/node /usr/local/bin/
|
||||
COPY --from=nodebuilder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
|
||||
RUN set -x && \
|
||||
ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \
|
||||
apt-get update && \
|
||||
apt-get install --no-install-recommends -y libatomic1 && \
|
||||
npm i -g pnpm@8.3.1 && \
|
||||
cd /tmp/build && \
|
||||
pnpm install --prod
|
||||
|
||||
FROM python:3.11-slim-bookworm
|
||||
|
||||
ARG QL_MAINTAINER="whyour"
|
||||
LABEL maintainer="${QL_MAINTAINER}"
|
||||
ARG QL_URL=https://github.com/${QL_MAINTAINER}/qinglong.git
|
||||
ARG QL_BRANCH=develop
|
||||
ARG PYTHON_SHORT_VERSION=3.11
|
||||
|
||||
ENV QL_DIR=/ql \
|
||||
QL_BRANCH=${QL_BRANCH} \
|
||||
QL_CONTAINER=true \
|
||||
LANG=C.UTF-8 \
|
||||
SHELL=/bin/bash \
|
||||
PS1="\u@\h:\w \$ "
|
||||
|
||||
ARG QL_UID=5432
|
||||
ARG QL_GID=5432
|
||||
RUN groupadd -g ${QL_GID} qinglong && \
|
||||
useradd -m -u ${QL_UID} -g ${QL_GID} -s /bin/bash qinglong && \
|
||||
mkdir -p /home/qinglong/bin /home/qinglong/.ssh && \
|
||||
chmod 700 /home/qinglong/.ssh && \
|
||||
chown -R ${QL_UID}:${QL_GID} /home/qinglong && \
|
||||
mkdir -p /etc/sudoers.d && \
|
||||
echo 'qinglong ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/qinglong
|
||||
|
||||
ENV QL_USER=qinglong
|
||||
ENV QL_HOME=/home/$QL_USER
|
||||
|
||||
COPY --from=nodebuilder /usr/local/bin/node /usr/local/bin/
|
||||
COPY --from=nodebuilder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
|
||||
|
||||
RUN set -x && \
|
||||
ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \
|
||||
ln -s /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx && \
|
||||
apt-get update && \
|
||||
apt-get upgrade -y && \
|
||||
apt-get install --no-install-recommends -y git \
|
||||
curl \
|
||||
wget \
|
||||
tzdata \
|
||||
perl \
|
||||
openssl \
|
||||
openssh-client \
|
||||
jq \
|
||||
procps \
|
||||
netcat-openbsd \
|
||||
sudo \
|
||||
unzip \
|
||||
libatomic1 && \
|
||||
apt-get clean && \
|
||||
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
|
||||
echo "Asia/Shanghai" >/etc/timezone && \
|
||||
git config --global user.email "qinglong@users.noreply.github.com" && \
|
||||
git config --global user.name "qinglong" && \
|
||||
git config --global http.postBuffer 524288000 && \
|
||||
npm install -g pnpm@8.3.1 pm2 ts-node typescript@5 && \
|
||||
rm -rf /root/.cache && \
|
||||
rm -rf /root/.npm && \
|
||||
rm -rf /etc/apt/apt.conf.d/docker-clean && \
|
||||
ulimit -c 0
|
||||
|
||||
RUN mkdir -p ${QL_DIR} && \
|
||||
chown -R ${QL_UID}:${QL_GID} ${QL_DIR}
|
||||
|
||||
USER qinglong
|
||||
ARG SOURCE_COMMIT
|
||||
RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} && \
|
||||
cd ${QL_DIR} && \
|
||||
cp -f .env.example .env && \
|
||||
chmod 777 ${QL_DIR}/shell/*.sh && \
|
||||
chmod 777 ${QL_DIR}/docker/*.sh && \
|
||||
git clone --depth=1 -b ${QL_BRANCH} https://github.com/${QL_MAINTAINER}/qinglong-static.git /tmp/static && \
|
||||
mkdir -p ${QL_DIR}/static && \
|
||||
cp -rf /tmp/static/* ${QL_DIR}/static && \
|
||||
rm -rf /tmp/static
|
||||
|
||||
ENV PNPM_HOME=${QL_DIR}/data/dep_cache/node \
|
||||
PYTHON_HOME=${QL_DIR}/data/dep_cache/python3 \
|
||||
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3 \
|
||||
HOME=/home/qinglong
|
||||
|
||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin:${HOME}/bin \
|
||||
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules \
|
||||
PIP_CACHE_DIR=${PYTHON_HOME}/pip \
|
||||
PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
|
||||
|
||||
RUN pip3 install --prefix ${PYTHON_HOME} requests
|
||||
|
||||
COPY --chown=qinglong:qinglong --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
||||
|
||||
USER root
|
||||
|
||||
RUN ln -sf ${QL_DIR}/shell/task.sh /usr/local/bin/task \
|
||||
&& ln -sf ${QL_DIR}/shell/update.sh /usr/local/bin/ql \
|
||||
&& chmod +x /usr/local/bin/task /usr/local/bin/ql
|
||||
|
||||
WORKDIR ${QL_DIR}
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
||||
CMD curl -sf --noproxy '*' http://localhost:${QlPort:-5700}/api/health || exit 1
|
||||
|
||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||
|
||||
VOLUME /ql/data
|
||||
|
||||
EXPOSE 5700
|
||||
@@ -0,0 +1,122 @@
|
||||
# Node 20 Bookworm is the latest official Node image variant that covers the
|
||||
# full Debian build matrix, including arm/v7, ppc64le, and s390x.
|
||||
FROM node:20-bookworm-slim AS nodebuilder
|
||||
|
||||
FROM python:3.10-slim-bookworm AS builder
|
||||
COPY package.json .npmrc pnpm-lock.yaml /tmp/build/
|
||||
COPY --from=nodebuilder /usr/local/bin/node /usr/local/bin/
|
||||
COPY --from=nodebuilder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
|
||||
RUN set -x && \
|
||||
ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \
|
||||
apt-get update && \
|
||||
apt-get install --no-install-recommends -y libatomic1 && \
|
||||
npm i -g pnpm@8.3.1 && \
|
||||
cd /tmp/build && \
|
||||
pnpm install --prod
|
||||
|
||||
FROM python:3.10-slim-bookworm
|
||||
|
||||
ARG QL_MAINTAINER="whyour"
|
||||
LABEL maintainer="${QL_MAINTAINER}"
|
||||
ARG QL_URL=https://github.com/${QL_MAINTAINER}/qinglong.git
|
||||
ARG QL_BRANCH=develop
|
||||
ARG PYTHON_SHORT_VERSION=3.10
|
||||
|
||||
ENV QL_DIR=/ql \
|
||||
QL_BRANCH=${QL_BRANCH} \
|
||||
QL_CONTAINER=true \
|
||||
LANG=C.UTF-8 \
|
||||
SHELL=/bin/bash \
|
||||
PS1="\u@\h:\w \$ "
|
||||
|
||||
ARG QL_UID=5432
|
||||
ARG QL_GID=5432
|
||||
RUN groupadd -g ${QL_GID} qinglong && \
|
||||
useradd -m -u ${QL_UID} -g ${QL_GID} -s /bin/bash qinglong && \
|
||||
mkdir -p /home/qinglong/bin /home/qinglong/.ssh && \
|
||||
chmod 700 /home/qinglong/.ssh && \
|
||||
chown -R ${QL_UID}:${QL_GID} /home/qinglong && \
|
||||
mkdir -p /etc/sudoers.d && \
|
||||
echo 'qinglong ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/qinglong
|
||||
|
||||
ENV QL_USER=qinglong
|
||||
ENV QL_HOME=/home/$QL_USER
|
||||
|
||||
COPY --from=nodebuilder /usr/local/bin/node /usr/local/bin/
|
||||
COPY --from=nodebuilder /usr/local/lib/node_modules/. /usr/local/lib/node_modules/
|
||||
|
||||
RUN set -x && \
|
||||
ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \
|
||||
apt-get update && \
|
||||
apt-get upgrade -y && \
|
||||
apt-get install --no-install-recommends -y git \
|
||||
curl \
|
||||
wget \
|
||||
tzdata \
|
||||
perl \
|
||||
openssl \
|
||||
openssh-client \
|
||||
jq \
|
||||
procps \
|
||||
netcat-openbsd \
|
||||
sudo \
|
||||
unzip \
|
||||
libatomic1 && \
|
||||
apt-get clean && \
|
||||
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
|
||||
echo "Asia/Shanghai" >/etc/timezone && \
|
||||
git config --global user.email "qinglong@users.noreply.github.com" && \
|
||||
git config --global user.name "qinglong" && \
|
||||
git config --global http.postBuffer 524288000 && \
|
||||
npm install -g pnpm@8.3.1 pm2 ts-node typescript@5 && \
|
||||
rm -rf /root/.cache && \
|
||||
rm -rf /root/.npm && \
|
||||
rm -rf /etc/apt/apt.conf.d/docker-clean && \
|
||||
ulimit -c 0
|
||||
|
||||
RUN mkdir -p ${QL_DIR} && \
|
||||
chown -R ${QL_UID}:${QL_GID} ${QL_DIR}
|
||||
|
||||
USER qinglong
|
||||
|
||||
ARG SOURCE_COMMIT
|
||||
RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} && \
|
||||
cd ${QL_DIR} && \
|
||||
cp -f .env.example .env && \
|
||||
chmod 777 ${QL_DIR}/shell/*.sh && \
|
||||
chmod 777 ${QL_DIR}/docker/*.sh && \
|
||||
git clone --depth=1 -b ${QL_BRANCH} https://github.com/${QL_MAINTAINER}/qinglong-static.git /tmp/static && \
|
||||
mkdir -p ${QL_DIR}/static && \
|
||||
cp -rf /tmp/static/* ${QL_DIR}/static && \
|
||||
rm -rf /tmp/static
|
||||
|
||||
ENV PNPM_HOME=${QL_DIR}/data/dep_cache/node \
|
||||
PYTHON_HOME=${QL_DIR}/data/dep_cache/python3 \
|
||||
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3 \
|
||||
HOME=/home/qinglong
|
||||
|
||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin:${HOME}/bin \
|
||||
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules \
|
||||
PIP_CACHE_DIR=${PYTHON_HOME}/pip \
|
||||
PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
|
||||
|
||||
RUN pip3 install --prefix ${PYTHON_HOME} requests
|
||||
|
||||
COPY --chown=qinglong:qinglong --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
||||
|
||||
USER root
|
||||
|
||||
RUN ln -sf ${QL_DIR}/shell/task.sh /usr/local/bin/task \
|
||||
&& ln -sf ${QL_DIR}/shell/update.sh /usr/local/bin/ql \
|
||||
&& chmod +x /usr/local/bin/task /usr/local/bin/ql
|
||||
|
||||
WORKDIR ${QL_DIR}
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
||||
CMD curl -sf --noproxy '*' http://localhost:${QlPort:-5700}/api/health || exit 1
|
||||
|
||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||
|
||||
VOLUME /ql/data
|
||||
|
||||
EXPOSE 5700
|
||||
@@ -1,7 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
export PATH="$HOME/bin:$PATH"
|
||||
|
||||
dir_shell=/ql/shell
|
||||
. $dir_shell/share.sh
|
||||
|
||||
@@ -17,9 +15,68 @@ log_with_style() {
|
||||
printf "\n[%s] [%7s] %s\n" "${timestamp}" "${level}" "${message}"
|
||||
}
|
||||
|
||||
# ============================================
|
||||
# 确保当前用户对 /ql 和 /ql/data 目录有写入权限
|
||||
# /ql/data 是 Docker Volume 挂载点,权限可能与 /ql 不同,需单独检测
|
||||
# ============================================
|
||||
ensure_ql_permissions() {
|
||||
local current_uid
|
||||
local current_gid
|
||||
current_uid=$(id -u)
|
||||
current_gid=$(id -g)
|
||||
|
||||
if [ "$current_uid" -eq 0 ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
# ---- 检查 /ql 目录 ----
|
||||
if ! mkdir -p "$QL_DIR/.tmp" 2>/dev/null; then
|
||||
if chown -R "$current_uid:$current_gid" "$QL_DIR" 2>/dev/null; then
|
||||
log_with_style "INFO" "已修正 /ql 目录权限: UID=$current_uid GID=$current_gid"
|
||||
else
|
||||
local ql_owner
|
||||
ql_owner=$(stat -c '%u' "$QL_DIR" 2>/dev/null || stat -f '%u' "$QL_DIR" 2>/dev/null)
|
||||
log_with_style "ERROR" "============================================="
|
||||
log_with_style "ERROR" " 权限错误:无法写入 /ql 目录"
|
||||
log_with_style "ERROR" " 当前用户 UID: $current_uid"
|
||||
log_with_style "ERROR" " /ql 目录所有者 UID: ${ql_owner:-未知}"
|
||||
log_with_style "ERROR" ""
|
||||
log_with_style "ERROR" " 解决方案:"
|
||||
log_with_style "ERROR" " 1. 使用镜像内置用户: docker run --user ${ql_owner:-5432}:${ql_owner:-5432} ..."
|
||||
log_with_style "ERROR" " 2. 使用 root 运行: 移除 --user 参数"
|
||||
log_with_style "ERROR" " 3. 修正宿主机数据目录: chown -R $current_uid:$current_gid /path/to/ql/data"
|
||||
log_with_style "ERROR" "============================================="
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
rmdir "$QL_DIR/.tmp" 2>/dev/null || true
|
||||
|
||||
# ---- 检查 /ql/data 目录(Volume 挂载点,不在用户数据卷内创建临时文件) ----
|
||||
if [ ! -w "$QL_DIR/data" ] || [ ! -x "$QL_DIR/data" ]; then
|
||||
if chown "$current_uid:$current_gid" "$QL_DIR/data" 2>/dev/null; then
|
||||
log_with_style "INFO" "已修正 /ql/data 目录权限: UID=$current_uid GID=$current_gid"
|
||||
if [ ! -w "$QL_DIR/data" ] || [ ! -x "$QL_DIR/data" ]; then
|
||||
log_with_style "ERROR" "修正后仍无法写入 /ql/data,请检查挂载的数据卷权限"
|
||||
log_with_style "ERROR" "确保宿主机目录: chown -R $current_uid:$current_gid /your/data"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
local data_owner
|
||||
data_owner=$(stat -c '%u' "$QL_DIR/data" 2>/dev/null || stat -f '%u' "$QL_DIR/data" 2>/dev/null)
|
||||
log_with_style "ERROR" "============================================="
|
||||
log_with_style "ERROR" " 权限错误:无法写入 /ql/data (Volume 挂载点)"
|
||||
log_with_style "ERROR" " 当前用户 UID: $current_uid"
|
||||
log_with_style "ERROR" " /ql/data 所有者 UID: ${data_owner:-未知}"
|
||||
log_with_style "ERROR" ""
|
||||
log_with_style "ERROR" " 请修正宿主机数据目录权限:"
|
||||
log_with_style "ERROR" " chown -R $current_uid:$current_gid /your/ql/data"
|
||||
log_with_style "ERROR" "============================================="
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# Fix DNS resolution issues in Alpine Linux
|
||||
# Alpine uses musl libc which has known DNS resolver issues with certain domains
|
||||
# Adding ndots:0 prevents unnecessary search domain appending
|
||||
if [ -f /etc/alpine-release ]; then
|
||||
if ! grep -q "^options ndots:0" /etc/resolv.conf 2>/dev/null; then
|
||||
echo "options ndots:0" >> /etc/resolv.conf
|
||||
@@ -27,6 +84,26 @@ if [ -f /etc/alpine-release ]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
# 确保 /etc/hosts 包含 localhost 解析(应对精简镜像或仅 IPv4/IPv6 环境)
|
||||
if ! grep -qE '^127\.0\.0\.1[[:space:]]+.*localhost' /etc/hosts 2>/dev/null; then
|
||||
echo "127.0.0.1 localhost" >> /etc/hosts
|
||||
log_with_style "INFO" "🔧 0. 已添加 IPv4 localhost 解析"
|
||||
fi
|
||||
if ! grep -qE '^::1[[:space:]]+.*localhost' /etc/hosts 2>/dev/null; then
|
||||
echo "::1 localhost ip6-localhost ip6-loopback" >> /etc/hosts
|
||||
log_with_style "INFO" "🔧 0. 已添加 IPv6 localhost 解析"
|
||||
fi
|
||||
|
||||
# 自定义用户(非 qinglong/root)可能 HOME 为空或不可写
|
||||
# 修正 HOME 确保 npm/pip/pm2 等工具有可用的缓存目录
|
||||
if [ ! -w "$HOME" ]; then
|
||||
mkdir -p "$QL_DIR/.tmp"
|
||||
export HOME="$QL_DIR/.tmp"
|
||||
fi
|
||||
|
||||
# 在一切操作之前检查目录权限
|
||||
ensure_ql_permissions
|
||||
|
||||
log_with_style "INFO" "🚀 1. 检测配置文件..."
|
||||
load_ql_envs
|
||||
export_ql_envs
|
||||
@@ -52,6 +129,19 @@ fi
|
||||
|
||||
log_with_style "SUCCESS" "🎉 容器启动成功!"
|
||||
|
||||
crond -f >/dev/null
|
||||
# 自动检测调度模式:有 crond 二进制 → system 模式,否则 node 模式
|
||||
if [ -z "$QL_SCHEDULER" ]; then
|
||||
if command -v crond &>/dev/null; then
|
||||
export QL_SCHEDULER="system"
|
||||
else
|
||||
export QL_SCHEDULER="node"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$QL_SCHEDULER" = "system" ]; then
|
||||
crond -f > /dev/null
|
||||
else
|
||||
tail -f /dev/null
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
|
||||
@@ -0,0 +1,550 @@
|
||||
# Project Architecture Guide
|
||||
|
||||
This document is written for AI coding agents and maintainers who need to understand and modify this project safely. It focuses on where behavior lives, how the application starts, and which files are usually involved for common changes.
|
||||
|
||||
## Project Summary
|
||||
|
||||
Qinglong is a timed task management platform. It provides a web admin panel for managing cron jobs, scripts, environment variables, subscriptions, dependencies, logs, configuration files, and system settings.
|
||||
|
||||
The repository is organized as a full-stack TypeScript application:
|
||||
|
||||
- `src/`: frontend admin panel, built with Umi Max, React, Ant Design, and Ant Design Pro Layout.
|
||||
- `back/`: backend application, built with Express, TypeScript, typedi, Sequelize, SQLite, gRPC, and worker processes.
|
||||
- `shell/`: runtime shell scripts used to execute tasks and preload task environments.
|
||||
- `data/`: local runtime data, including scripts, logs, configs, SQLite database, uploaded files, and cloned repositories.
|
||||
- `static/`: built frontend and backend artifacts.
|
||||
- `docker/`: Docker images, compose file, and entrypoint.
|
||||
- `sample/`: sample scripts and default config templates.
|
||||
|
||||
## High-Level Runtime Flow
|
||||
|
||||
```text
|
||||
Browser
|
||||
-> src/pages/*
|
||||
-> src/utils/http.tsx
|
||||
-> /api/*
|
||||
-> back/api/*
|
||||
-> back/services/*
|
||||
-> back/data/* Sequelize models
|
||||
-> data/db/database.sqlite
|
||||
|
||||
Cron/task execution
|
||||
-> back/services/cron.ts
|
||||
-> shell/task.sh or shell/otask.sh
|
||||
-> data/scripts/*
|
||||
-> data/log/*
|
||||
|
||||
Frontend assets in production
|
||||
-> static/dist/*
|
||||
-> served by back/loaders/express.ts
|
||||
```
|
||||
|
||||
## Main Startup Path
|
||||
|
||||
Development starts from `package.json`:
|
||||
|
||||
```bash
|
||||
pnpm start
|
||||
```
|
||||
|
||||
This runs:
|
||||
|
||||
- `start:back`: `nodemon ./back/app.ts`
|
||||
- `start:front`: `max dev`
|
||||
|
||||
Backend startup begins in `back/app.ts`.
|
||||
|
||||
Important details:
|
||||
|
||||
- The backend uses Node `cluster`.
|
||||
- The primary process initializes the database first.
|
||||
- A gRPC worker starts before the HTTP worker.
|
||||
- The HTTP worker starts Express and serves API routes plus frontend static files.
|
||||
- If the gRPC worker restarts, the HTTP worker is asked to re-register cron jobs.
|
||||
|
||||
Production-style backend output is generated by:
|
||||
|
||||
```bash
|
||||
pnpm run build:back
|
||||
```
|
||||
|
||||
The compiled backend is placed under `static/build`.
|
||||
|
||||
Frontend output is generated by:
|
||||
|
||||
```bash
|
||||
pnpm run build:front
|
||||
```
|
||||
|
||||
The compiled frontend is placed under `static/dist`.
|
||||
|
||||
## Backend Architecture
|
||||
|
||||
### Entry Point
|
||||
|
||||
- `back/app.ts`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Creates the Express application.
|
||||
- Starts primary/worker process logic.
|
||||
- Initializes database in the primary process.
|
||||
- Starts gRPC and HTTP workers.
|
||||
- Handles graceful shutdown.
|
||||
- Re-registers cron jobs after gRPC worker recovery.
|
||||
|
||||
### Loaders
|
||||
|
||||
- `back/loaders/app.ts`
|
||||
- `back/loaders/express.ts`
|
||||
- `back/loaders/db.ts`
|
||||
- `back/loaders/depInjector.ts`
|
||||
- `back/loaders/initData.ts`
|
||||
- `back/loaders/initFile.ts`
|
||||
- `back/loaders/initTask.ts`
|
||||
- `back/loaders/server.ts`
|
||||
- `back/loaders/sock.ts`
|
||||
|
||||
Loader responsibilities:
|
||||
|
||||
- Register dependency injection bindings.
|
||||
- Sync Sequelize models.
|
||||
- Initialize files and default data.
|
||||
- Initialize scheduled tasks.
|
||||
- Configure Express middleware.
|
||||
- Register routes.
|
||||
- Attach socket/server behavior.
|
||||
|
||||
`back/loaders/express.ts` is the main HTTP middleware and routing setup. It handles:
|
||||
|
||||
- CORS.
|
||||
- Helmet.
|
||||
- body parser.
|
||||
- static frontend serving.
|
||||
- JWT validation.
|
||||
- token validation against shared auth state.
|
||||
- `/open/*` rewrite to `/api/*`.
|
||||
- route mounting through `back/api/index.ts`.
|
||||
- frontend fallback to `static/dist/index.html`.
|
||||
- API error handling.
|
||||
|
||||
### API Routes
|
||||
|
||||
- `back/api/index.ts`
|
||||
|
||||
This file registers all API modules:
|
||||
|
||||
- `user.ts`: login, initialization, authentication-related user endpoints.
|
||||
- `env.ts`: environment variable endpoints.
|
||||
- `config.ts`: config file endpoints.
|
||||
- `log.ts`: log endpoints.
|
||||
- `cron.ts`: cron/task endpoints.
|
||||
- `script.ts`: script file endpoints.
|
||||
- `open.ts`: open API/app token endpoints.
|
||||
- `dependence.ts`: dependency management endpoints.
|
||||
- `system.ts`: system information/settings endpoints.
|
||||
- `subscription.ts`: subscription endpoints.
|
||||
- `update.ts`: update/check endpoints.
|
||||
- `health.ts`: health check endpoints.
|
||||
|
||||
Route files should stay thin. They should validate input, get a service from `typedi`'s `Container`, call the service, and return `{ code, data, message }` style responses.
|
||||
|
||||
### Services
|
||||
|
||||
- `back/services/*`
|
||||
|
||||
Services contain most business logic. Common examples:
|
||||
|
||||
- `cron.ts`: create/update/delete/run cron jobs, generate crontab data, manage logs, call scheduler client.
|
||||
- `env.ts`: manage environment variables.
|
||||
- `config.ts`: read/write config files.
|
||||
- `script.ts`: manage script files.
|
||||
- `subscription.ts`: manage script subscriptions and repository pulls.
|
||||
- `dependence.ts`: install/manage runtime dependencies.
|
||||
- `system.ts`: system info and settings.
|
||||
- `notify.ts`: notification behavior.
|
||||
- `sock.ts`: socket/log stream behavior.
|
||||
- `grpc.ts`: gRPC server lifecycle.
|
||||
- `http.ts`: HTTP server lifecycle.
|
||||
|
||||
When changing backend behavior, first find the API route, then follow it into the matching service. In most cases, the service is the right place for behavioral changes.
|
||||
|
||||
### Data Models
|
||||
|
||||
- `back/data/index.ts`
|
||||
- `back/data/*.ts`
|
||||
|
||||
The backend uses Sequelize with SQLite. Database storage is configured in `back/data/index.ts`:
|
||||
|
||||
```text
|
||||
data/db/database.sqlite
|
||||
```
|
||||
|
||||
Common model files:
|
||||
|
||||
- `cron.ts`: cron job model.
|
||||
- `cronView.ts`: saved cron table views.
|
||||
- `env.ts`: environment variable model.
|
||||
- `dependence.ts`: dependency model.
|
||||
- `open.ts`: open API app/token model.
|
||||
- `subscription.ts`: subscription model.
|
||||
- `system.ts`: system settings model.
|
||||
- `notify.ts`: notification-related data.
|
||||
|
||||
Model sync and simple column migrations are currently handled in `back/loaders/db.ts`.
|
||||
|
||||
### Configuration
|
||||
|
||||
- `back/config/index.ts`
|
||||
|
||||
This is the central runtime config file. It reads `.env`, establishes `QL_DIR`, and defines important paths:
|
||||
|
||||
- `dataPath`: runtime data root.
|
||||
- `configPath`: config files.
|
||||
- `scriptPath`: user scripts.
|
||||
- `repoPath`: subscription repositories.
|
||||
- `logPath`: task logs.
|
||||
- `dbPath`: SQLite database location.
|
||||
- `uploadPath`: uploaded files.
|
||||
- `shellPath`: shell runtime scripts.
|
||||
- `preloadPath`: JS/Python/Shell preload files.
|
||||
|
||||
Before hardcoding paths, check `back/config/index.ts`.
|
||||
|
||||
### Scheduling And gRPC
|
||||
|
||||
- `back/schedule/*`
|
||||
- `back/protos/*`
|
||||
- `back/services/grpc.ts`
|
||||
|
||||
The project has two scheduling paths:
|
||||
|
||||
- Standard crontab-style tasks are persisted and written through backend cron logic.
|
||||
- Node/gRPC scheduler logic handles cases such as second-level cron expressions or additional schedules.
|
||||
|
||||
`back/services/cron.ts` decides whether a task needs the Node scheduler using schedule shape and `extra_schedules`.
|
||||
|
||||
### Shared Backend Utilities
|
||||
|
||||
- `back/shared/*`
|
||||
- `back/config/util.ts`
|
||||
- `back/config/share.ts`
|
||||
- `back/config/http.ts`
|
||||
|
||||
Use these before adding new global helpers. Existing shared code includes:
|
||||
|
||||
- auth helpers.
|
||||
- shared store.
|
||||
- log stream manager.
|
||||
- task runner helpers.
|
||||
- concurrency limits.
|
||||
- file locking utilities.
|
||||
- HTTP/proxy helpers.
|
||||
|
||||
## Frontend Architecture
|
||||
|
||||
### Umi Config
|
||||
|
||||
- `.umirc.ts`
|
||||
|
||||
Important behavior:
|
||||
|
||||
- Dev server proxies API requests to `http://127.0.0.1:5700/`.
|
||||
- Frontend build output is `static/dist`.
|
||||
- Runtime env script is loaded from `./api/env.js`.
|
||||
- `QlBaseUrl` affects frontend public path and routing base.
|
||||
|
||||
### App Initialization
|
||||
|
||||
- `src/app.ts`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Load Chinese and English locale JSON.
|
||||
- Determine locale from URL/cookie/localStorage.
|
||||
- Set Umi locale.
|
||||
- Apply `QlBaseUrl` as public path and router basename.
|
||||
|
||||
### Layout And Routes
|
||||
|
||||
- `src/layouts/defaultProps.tsx`
|
||||
- `src/layouts/index.tsx`
|
||||
|
||||
`defaultProps.tsx` defines the main route/menu list. If adding a new page visible in the sidebar, update this file.
|
||||
|
||||
Current major pages:
|
||||
|
||||
- `src/pages/crontab`: timed task management.
|
||||
- `src/pages/subscription`: subscription management.
|
||||
- `src/pages/env`: environment variables.
|
||||
- `src/pages/config`: config files.
|
||||
- `src/pages/script`: script management.
|
||||
- `src/pages/dependence`: dependency management.
|
||||
- `src/pages/log`: log management.
|
||||
- `src/pages/diff`: diff tool.
|
||||
- `src/pages/setting`: system settings.
|
||||
- `src/pages/login`: login.
|
||||
- `src/pages/initialization`: first-run initialization.
|
||||
- `src/pages/error`: error page.
|
||||
|
||||
### Frontend Utilities
|
||||
|
||||
- `src/utils/http.tsx`: API request helper.
|
||||
- `src/utils/websocket.ts`: socket connection behavior.
|
||||
- `src/utils/config.ts`: frontend config helpers.
|
||||
- `src/utils/const.ts`: constants.
|
||||
- `src/utils/date.ts`: date formatting helpers.
|
||||
- `src/utils/init.ts`: initialization helpers.
|
||||
- `src/utils/codemirror/*`: CodeMirror integration.
|
||||
- `src/utils/monaco/*`: Monaco integration.
|
||||
|
||||
When changing a page's API behavior, inspect both the page file and `src/utils/http.tsx`.
|
||||
|
||||
### Components And Styling
|
||||
|
||||
- `src/components/*`: reusable UI components.
|
||||
- `src/pages/**/index.less`: page-level styles.
|
||||
- `src/pages/script/index.module.less` and `src/pages/log/index.module.less`: CSS module styles.
|
||||
- `src/assets/fonts/*`: bundled fonts.
|
||||
- `src/locales/*.json`: i18n text.
|
||||
|
||||
Follow the existing Ant Design and Ant Design Pro patterns when modifying UI.
|
||||
|
||||
## Shell Runtime
|
||||
|
||||
- `shell/task.sh`: task execution path.
|
||||
- `shell/otask.sh`: alternate/manual task execution path.
|
||||
- `shell/api.sh`: shell-side API helpers.
|
||||
- `shell/env.sh`: environment setup.
|
||||
- `shell/check.sh`: runtime check helpers.
|
||||
- `shell/update.sh`: update helpers.
|
||||
- `shell/rmlog.sh`: log cleanup.
|
||||
- `shell/share.sh`: shared shell helpers.
|
||||
- `shell/preload/*`: preload files injected into JS/Python/Shell task environments.
|
||||
|
||||
The backend often coordinates task execution, but the actual user script process environment is shaped by files in `shell/`.
|
||||
|
||||
## Runtime Data Directory
|
||||
|
||||
- `data/`
|
||||
|
||||
This directory is runtime state, not just source code. Be careful when modifying or deleting files here.
|
||||
|
||||
Important subdirectories:
|
||||
|
||||
- `data/db`: SQLite database.
|
||||
- `data/config`: generated and user-edited config files.
|
||||
- `data/scripts`: user scripts.
|
||||
- `data/repo`: cloned subscription repositories.
|
||||
- `data/log`: task logs.
|
||||
- `data/upload`: uploaded files.
|
||||
- `data/syslog`: system logs.
|
||||
- `data/ssh.d`: SSH-related runtime data.
|
||||
- `data/dep_cache`: dependency cache, when present.
|
||||
|
||||
Many bugs that appear as "backend logic" may involve state stored under `data/`.
|
||||
|
||||
## Docker And Release Files
|
||||
|
||||
- `docker/Dockerfile`
|
||||
- `docker/310.Dockerfile`
|
||||
- `docker/docker-compose.yml`
|
||||
- `docker/docker-entrypoint.sh`
|
||||
- `ecosystem.config.js`
|
||||
- `version.yaml`
|
||||
|
||||
Use these when changing deployment, container startup, PM2 behavior, or release metadata.
|
||||
|
||||
## Common Modification Map
|
||||
|
||||
### Add Or Modify A Backend API
|
||||
|
||||
Typical files:
|
||||
|
||||
1. Add or update route in `back/api/<module>.ts`.
|
||||
2. Add or update service logic in `back/services/<module>.ts`.
|
||||
3. Add or update model in `back/data/<module>.ts` if persistence changes.
|
||||
4. Add validation with `celebrate`/`Joi` near the route.
|
||||
5. Update frontend caller in `src/pages/**` or `src/utils/**`.
|
||||
|
||||
### Add A New Frontend Page
|
||||
|
||||
Typical files:
|
||||
|
||||
1. Create `src/pages/<page>/index.tsx`.
|
||||
2. Add styles in `src/pages/<page>/index.less` if needed.
|
||||
3. Register route/menu in `src/layouts/defaultProps.tsx`.
|
||||
4. Add locale strings in `src/locales/zh-CN.json` and `src/locales/en-US.json`.
|
||||
5. Add API calls through the existing request helper.
|
||||
|
||||
### Change Cron/Task Behavior
|
||||
|
||||
Start with:
|
||||
|
||||
- `back/api/cron.ts`
|
||||
- `back/services/cron.ts`
|
||||
- `back/schedule/*`
|
||||
- `shell/task.sh`
|
||||
- `shell/otask.sh`
|
||||
- `shell/preload/*`
|
||||
|
||||
Also inspect:
|
||||
|
||||
- `back/data/cron.ts`
|
||||
- `back/validation/schedule.ts`
|
||||
- `data/config/crontab.list`
|
||||
- `data/log/*`
|
||||
|
||||
### Change Environment Variable Behavior
|
||||
|
||||
Start with:
|
||||
|
||||
- `back/api/env.ts`
|
||||
- `back/services/env.ts`
|
||||
- `back/data/env.ts`
|
||||
- `src/pages/env/index.tsx`
|
||||
|
||||
Also inspect:
|
||||
|
||||
- `shell/preload/env.sh`
|
||||
- `shell/preload/env.js`
|
||||
- `shell/preload/env.py`
|
||||
|
||||
### Change Script Management
|
||||
|
||||
Start with:
|
||||
|
||||
- `back/api/script.ts`
|
||||
- `back/services/script.ts`
|
||||
- `src/pages/script/index.tsx`
|
||||
- `data/scripts/*`
|
||||
|
||||
### Change Login/Auth/Security
|
||||
|
||||
Start with:
|
||||
|
||||
- `back/api/user.ts`
|
||||
- `back/services/user.ts`
|
||||
- `back/shared/auth.ts`
|
||||
- `back/shared/store.ts`
|
||||
- `back/loaders/express.ts`
|
||||
- `back/token.ts`
|
||||
- `src/pages/login/index.tsx`
|
||||
- `src/pages/initialization/index.tsx`
|
||||
|
||||
Be careful with:
|
||||
|
||||
- JWT behavior.
|
||||
- open API token behavior.
|
||||
- first-run initialization.
|
||||
- platform-specific session limits.
|
||||
|
||||
### Change Subscription Behavior
|
||||
|
||||
Start with:
|
||||
|
||||
- `back/api/subscription.ts`
|
||||
- `back/services/subscription.ts`
|
||||
- `back/data/subscription.ts`
|
||||
- `src/pages/subscription/index.tsx`
|
||||
- `data/repo/*`
|
||||
|
||||
### Change Dependency Management
|
||||
|
||||
Start with:
|
||||
|
||||
- `back/api/dependence.ts`
|
||||
- `back/services/dependence.ts`
|
||||
- `back/data/dependence.ts`
|
||||
- `src/pages/dependence/index.tsx`
|
||||
- `data/deps`
|
||||
- `data/dep_cache`
|
||||
|
||||
### Change Logs Or Live Log Streaming
|
||||
|
||||
Start with:
|
||||
|
||||
- `back/api/log.ts`
|
||||
- `back/services/log.ts`
|
||||
- `back/services/sock.ts`
|
||||
- `back/shared/logStreamManager.ts`
|
||||
- `src/pages/log/index.tsx`
|
||||
- `src/components/terminal.tsx`
|
||||
- `data/log/*`
|
||||
|
||||
## Coding Conventions
|
||||
|
||||
Backend:
|
||||
|
||||
- Prefer adding business logic to services, not route files.
|
||||
- Use `typedi` services consistently.
|
||||
- Use existing config paths from `back/config/index.ts`.
|
||||
- Return API responses in the existing `{ code, data, message }` shape.
|
||||
- Use existing utilities before adding new helpers.
|
||||
- Preserve current SQLite/Sequelize style unless doing a larger data-layer refactor.
|
||||
|
||||
Frontend:
|
||||
|
||||
- Follow existing Umi/React/Ant Design patterns.
|
||||
- Keep route/menu changes in `src/layouts/defaultProps.tsx`.
|
||||
- Use existing request/WebSocket helpers.
|
||||
- Add or update locale strings for visible UI text.
|
||||
- Keep page-specific styles near the page.
|
||||
|
||||
Shell/runtime:
|
||||
|
||||
- Treat `shell/` as part of production behavior.
|
||||
- Test task execution changes with realistic scripts when possible.
|
||||
- Be careful with path quoting and environment variable propagation.
|
||||
|
||||
Data:
|
||||
|
||||
- Treat `data/` as mutable runtime state.
|
||||
- Do not delete runtime state unless explicitly requested.
|
||||
- Schema changes should account for existing SQLite databases.
|
||||
|
||||
## Suggested First Steps For AI Agents
|
||||
|
||||
When asked to modify behavior:
|
||||
|
||||
1. Identify whether the change is frontend, backend, shell runtime, data model, or deployment.
|
||||
2. Search by feature name in `src/pages`, `back/api`, and `back/services`.
|
||||
3. Read the route file and matching service before editing.
|
||||
4. If persistence is involved, read the matching `back/data` model and `back/loaders/db.ts`.
|
||||
5. If task execution is involved, inspect `shell/` and `back/services/cron.ts`.
|
||||
6. Make the smallest scoped change that matches existing patterns.
|
||||
7. Run the most relevant check:
|
||||
- `pnpm run build:back` for backend TypeScript changes.
|
||||
- `pnpm run build:front` for frontend build changes.
|
||||
- targeted manual task/API checks for shell and scheduler changes.
|
||||
|
||||
## Quick Directory Reference
|
||||
|
||||
```text
|
||||
.
|
||||
├── back/ Backend TypeScript application
|
||||
│ ├── api/ Express route modules
|
||||
│ ├── config/ Runtime config, paths, constants, helpers
|
||||
│ ├── data/ Sequelize models and SQLite connection
|
||||
│ ├── loaders/ Startup initialization and Express setup
|
||||
│ ├── middlewares/ Express middlewares
|
||||
│ ├── protos/ gRPC proto files and generated TS
|
||||
│ ├── schedule/ Scheduler/gRPC client helpers
|
||||
│ ├── services/ Business logic services
|
||||
│ ├── shared/ Shared backend utilities
|
||||
│ └── validation/ Joi validation schemas
|
||||
├── src/ Frontend Umi/React application
|
||||
│ ├── assets/ Fonts and static frontend assets
|
||||
│ ├── components/ Shared UI components
|
||||
│ ├── hooks/ Frontend hooks
|
||||
│ ├── layouts/ Main layout and menu route config
|
||||
│ ├── locales/ i18n JSON
|
||||
│ ├── pages/ Feature pages
|
||||
│ └── utils/ HTTP, WebSocket, editor, date, and config utilities
|
||||
├── shell/ Task runtime shell scripts and preload files
|
||||
├── data/ Runtime state: db, logs, scripts, repos, configs
|
||||
├── docker/ Docker build and compose files
|
||||
├── sample/ Sample scripts and default config templates
|
||||
├── static/ Built frontend/backend artifacts
|
||||
└── docs/ Project documentation
|
||||
```
|
||||
+46
-29
@@ -1,6 +1,17 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@whyour/qinglong",
|
||||
"packageManager": "pnpm@8.3.1",
|
||||
"version": "2.21.0-16",
|
||||
"description": "Timed task management platform supporting Python3, JavaScript, Shell, Typescript",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/whyour/qinglong.git"
|
||||
},
|
||||
"author": "whyour",
|
||||
"license": "Apache License 2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/whyour/qinglong/issues"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "concurrently -n w: npm:start:*",
|
||||
"start:back": "nodemon ./back/app.ts",
|
||||
@@ -10,9 +21,7 @@
|
||||
"panel": "npm run build:back && node static/build/app.js",
|
||||
"gen:proto": "protoc --experimental_allow_proto3_optional --plugin=./node_modules/.bin/protoc-gen-ts_proto ./back/protos/*.proto --ts_proto_out=./ --ts_proto_opt=outputServices=grpc-js,env=node,esModuleInterop=true,snakeToCamel=false",
|
||||
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
|
||||
"postinstall": "max setup 2>/dev/null || true",
|
||||
"test": "umi-test",
|
||||
"test:coverage": "umi-test --coverage"
|
||||
"postinstall": "max setup 2>/dev/null || true"
|
||||
},
|
||||
"gitHooks": {
|
||||
"pre-commit": "lint-staged"
|
||||
@@ -25,6 +34,11 @@
|
||||
"prettier --parser=typescript --write"
|
||||
]
|
||||
},
|
||||
"bin": {
|
||||
"ql": "shell/update.sh",
|
||||
"task": "shell/task.sh",
|
||||
"qinglong": "shell/start.sh"
|
||||
},
|
||||
"pnpm": {
|
||||
"peerDependencyRules": {
|
||||
"ignoreMissing": [
|
||||
@@ -51,16 +65,22 @@
|
||||
}
|
||||
},
|
||||
"overrides": {
|
||||
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3"
|
||||
"sqlite3": "npm:@whyour/sqlite3@1.1.0",
|
||||
"@codemirror/state": "6.5.4",
|
||||
"@codemirror/view": "6.39.16"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/plots": "^2.6.8",
|
||||
"@bufbuild/protobuf": "^2.10.0",
|
||||
"@grpc/grpc-js": "^1.14.0",
|
||||
"@grpc/proto-loader": "^0.8.0",
|
||||
"@keyv/sqlite": "^4.0.1",
|
||||
"@otplib/preset-default": "^12.0.1",
|
||||
"body-parser": "^1.20.3",
|
||||
"celebrate": "^15.0.3",
|
||||
"chokidar": "^4.0.1",
|
||||
"compression": "^1.7.4",
|
||||
"cors": "^2.8.5",
|
||||
"cron-parser": "^5.4.0",
|
||||
"cross-spawn": "^7.0.6",
|
||||
@@ -70,51 +90,48 @@
|
||||
"express-jwt": "^8.4.1",
|
||||
"express-rate-limit": "^7.4.1",
|
||||
"express-urlrewrite": "^2.0.3",
|
||||
"undici": "^7.9.0",
|
||||
"helmet": "^8.1.0",
|
||||
"hpagent": "^1.2.0",
|
||||
"http-proxy-middleware": "^3.0.3",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"ip2region": "2.3.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"keyv": "^5.2.3",
|
||||
"lodash": "^4.17.21",
|
||||
"multer": "1.4.5-lts.1",
|
||||
"multer": "2.1.1",
|
||||
"node-schedule": "^2.1.0",
|
||||
"nodemailer": "^6.9.16",
|
||||
"nodemailer": "^8.0.1",
|
||||
"p-queue-cjs": "7.3.4",
|
||||
"@bufbuild/protobuf": "^2.10.0",
|
||||
"proper-lockfile": "^4.1.2",
|
||||
"ps-tree": "^1.2.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"request-ip": "3.3.0",
|
||||
"sequelize": "^6.37.5",
|
||||
"sockjs": "^0.3.24",
|
||||
"sqlite3": "git+https://github.com/whyour/node-sqlite3.git#v1.0.3",
|
||||
"sqlite3": "npm:@whyour/sqlite3@1.1.0",
|
||||
"toad-scheduler": "^3.0.1",
|
||||
"typedi": "^0.10.0",
|
||||
"undici": "^7.9.0",
|
||||
"uuid": "^11.0.3",
|
||||
"winston": "^3.17.0",
|
||||
"winston-daily-rotate-file": "^5.0.0",
|
||||
"request-ip": "3.3.0",
|
||||
"ip2region": "2.3.0",
|
||||
"keyv": "^5.2.3",
|
||||
"@keyv/sqlite": "^4.0.1",
|
||||
"proper-lockfile": "^4.1.2",
|
||||
"compression": "^1.7.4",
|
||||
"helmet": "^8.1.0"
|
||||
"winston-daily-rotate-file": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"moment": "2.30.1",
|
||||
"@ant-design/icons": "^5.0.1",
|
||||
"@ant-design/pro-layout": "6.38.22",
|
||||
"@codemirror/view": "^6.34.1",
|
||||
"@codemirror/state": "^6.4.1",
|
||||
"@codemirror/state": "6.5.4",
|
||||
"@codemirror/view": "6.39.16",
|
||||
"@monaco-editor/react": "4.2.1",
|
||||
"@react-hook/resize-observer": "^2.0.2",
|
||||
"react-router-dom": "6.26.1",
|
||||
"@types/body-parser": "^1.19.2",
|
||||
"@types/compression": "^1.7.2",
|
||||
"@types/cors": "^2.8.12",
|
||||
"@types/cross-spawn": "^6.0.2",
|
||||
"@types/express": "^4.17.13",
|
||||
"@types/express-jwt": "^6.0.4",
|
||||
"@types/file-saver": "2.0.2",
|
||||
"@types/helmet": "^4.0.0",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"@types/jsonwebtoken": "^8.5.8",
|
||||
"@types/lodash": "^4.14.185",
|
||||
@@ -122,17 +139,17 @@
|
||||
"@types/node": "^17.0.21",
|
||||
"@types/node-schedule": "^1.3.2",
|
||||
"@types/nodemailer": "^6.4.4",
|
||||
"@types/proper-lockfile": "^4.1.4",
|
||||
"@types/ps-tree": "^1.1.6",
|
||||
"@types/qrcode.react": "^1.0.2",
|
||||
"@types/react": "^18.0.20",
|
||||
"@types/react-copy-to-clipboard": "^5.0.4",
|
||||
"@types/react-dom": "^18.0.6",
|
||||
"@types/request-ip": "0.0.41",
|
||||
"@types/serve-handler": "^6.1.1",
|
||||
"@types/sockjs": "^0.3.33",
|
||||
"@types/sockjs-client": "^1.5.1",
|
||||
"@types/uuid": "^8.3.4",
|
||||
"@types/request-ip": "0.0.41",
|
||||
"@types/proper-lockfile": "^4.1.4",
|
||||
"@types/ps-tree": "^1.1.6",
|
||||
"@uiw/codemirror-extensions-langs": "^4.21.9",
|
||||
"@uiw/react-codemirror": "^4.21.9",
|
||||
"@umijs/max": "^4.4.4",
|
||||
@@ -144,9 +161,9 @@
|
||||
"axios": "^1.4.0",
|
||||
"compression-webpack-plugin": "9.2.0",
|
||||
"concurrently": "^7.0.0",
|
||||
"react-hotkeys-hook": "^4.6.1",
|
||||
"file-saver": "2.0.2",
|
||||
"lint-staged": "^13.0.3",
|
||||
"moment": "2.30.1",
|
||||
"monaco-editor": "0.33.0",
|
||||
"nodemon": "^3.0.1",
|
||||
"prettier": "^2.5.1",
|
||||
@@ -162,7 +179,9 @@
|
||||
"react-dnd": "^16.0.1",
|
||||
"react-dnd-html5-backend": "^16.0.1",
|
||||
"react-dom": "18.3.1",
|
||||
"react-hotkeys-hook": "^4.6.1",
|
||||
"react-intl-universal": "^2.12.0",
|
||||
"react-router-dom": "6.26.1",
|
||||
"react-split-pane": "^0.1.92",
|
||||
"sockjs-client": "^1.6.0",
|
||||
"ts-node": "^10.9.2",
|
||||
@@ -170,8 +189,6 @@
|
||||
"tslib": "^2.4.0",
|
||||
"typescript": "5.2.2",
|
||||
"vh-check": "^2.0.5",
|
||||
"virtualizedtableforantd4": "1.3.0",
|
||||
"@types/compression": "^1.7.2",
|
||||
"@types/helmet": "^4.0.0"
|
||||
"virtualizedtableforantd4": "1.3.0"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+1315
-714
File diff suppressed because it is too large
Load Diff
+19
-3
@@ -195,12 +195,14 @@ export SMTP_SERVER=""
|
||||
## SMTP 发送邮件服务器是否使用 SSL,填写 true 或 false
|
||||
export SMTP_SSL=""
|
||||
|
||||
## smtp_email 填写 SMTP 收发件邮箱,通知将会由自己发给自己
|
||||
## smtp_email 填写 SMTP 发件邮箱
|
||||
export SMTP_EMAIL=""
|
||||
## smtp_password 填写 SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
|
||||
export SMTP_PASSWORD=""
|
||||
## smtp_name 填写 SMTP 收发件人姓名,可随意填写
|
||||
export SMTP_NAME=""
|
||||
## smtp_email_to 填写 SMTP 收件邮箱,多个用英文;分隔,不填默认发给发件邮箱
|
||||
export SMTP_EMAIL_TO=""
|
||||
|
||||
## 17. PushMe
|
||||
## 官方说明文档:https://push.i-i.me/
|
||||
@@ -239,14 +241,19 @@ export NTFY_PASSWORD=""
|
||||
export NTFY_ACTIONS=""
|
||||
|
||||
## 21. wxPusher
|
||||
## 官方文档: https://wxpusher.zjiecode.com/docs/
|
||||
## 管理后台: https://wxpusher.zjiecode.com/admin/
|
||||
### 方式一:标准发送(更强大)
|
||||
#### 官方文档: https://wxpusher.zjiecode.com/docs/
|
||||
#### 管理后台: https://wxpusher.zjiecode.com/admin/
|
||||
## wxPusher 的 appToken
|
||||
export WXPUSHER_APP_TOKEN=""
|
||||
## wxPusher 的 topicIds,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||
export WXPUSHER_TOPIC_IDS=""
|
||||
## wxPusher 的 用户ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||
export WXPUSHER_UIDS=""
|
||||
### 方式二:极简发送(最简单,简单好用,一键配置,更推荐)
|
||||
#### wxPusher 的 SPT(极简推送),扫码获取 https://wxpusher.zjiecode.com/docs/#/?id=spt
|
||||
#### 多个用英文逗号,分隔,最多10个;与上面的 appToken 方式二选一即可
|
||||
export WXPUSHER_SPT_LIST=""
|
||||
|
||||
## 22. 自定义通知
|
||||
## 自定义通知 接收回调的URL
|
||||
@@ -259,4 +266,13 @@ export WEBHOOK_METHOD=""
|
||||
## 支持 text/plain、application/json、multipart/form-data、application/x-www-form-urlencoded
|
||||
export WEBHOOK_CONTENT_TYPE=""
|
||||
|
||||
## 23. OpeniLink
|
||||
## 官方文档: https://openilink.com/docs/hub/apps
|
||||
## 在 OpeniLink Hub 后台安装 App 后获取 app_token
|
||||
export OPENILINK_APP_TOKEN=""
|
||||
## OpeniLink Hub 地址,默认为 https://hub.openilink.com,自建 Hub 时填写自己的地址
|
||||
export OPENILINK_HUB_URL=""
|
||||
## OpeniLink 的 context_token,用于标识消息会话上下文,可从消息事件中获取
|
||||
export OPENILINK_CONTEXT_TOKEN=""
|
||||
|
||||
## 其他需要的变量,脚本中需要的变量使用 export 变量名= 声明即可
|
||||
|
||||
+145
-9
@@ -108,8 +108,8 @@ const push_config = {
|
||||
|
||||
QYWX_KEY: '', // 企业微信机器人的 webhook(详见文档 https://work.weixin.qq.com/api/doc/90000/90136/91770),例如:693a91f6-7xxx-4bc4-97a0-0ec2sifa5aaa
|
||||
|
||||
TG_BOT_TOKEN: '', // tg 机器人的 TG_BOT_TOKEN,例:1407203283:AAG9rt-6RDaaX0HBLZQq0laNOh898iFYaRQ
|
||||
TG_USER_ID: '', // tg 机器人的 TG_USER_ID,例:1434078534
|
||||
TG_BOT_TOKEN: '', // tg 机器人的 TG_BOT_TOKEN,例:1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
|
||||
TG_USER_ID: '', // tg 机器人的 TG_USER_ID,例:1234567890
|
||||
TG_API_HOST: 'https://api.telegram.org', // tg 代理 api
|
||||
TG_PROXY_AUTH: '', // tg 代理认证参数
|
||||
TG_PROXY_HOST: '', // tg 机器人的 TG_PROXY_HOST
|
||||
@@ -121,7 +121,8 @@ const push_config = {
|
||||
|
||||
SMTP_SERVICE: '', // 邮箱服务名称,比如 126、163、Gmail、QQ 等,支持列表 https://github.com/nodemailer/nodemailer/blob/master/lib/well-known/services.json
|
||||
SMTP_EMAIL: '', // SMTP 发件邮箱
|
||||
SMTP_TO: '', // SMTP 收件邮箱,默认通知将会发给发件邮箱
|
||||
SMTP_TO: '', // SMTP 收件邮箱,兼容旧参数名,默认通知将会发给发件邮箱
|
||||
SMTP_EMAIL_TO: '', // SMTP 收件邮箱,多个分号分隔,默认发给发件邮箱
|
||||
SMTP_PASSWORD: '', // SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
|
||||
SMTP_NAME: '', // SMTP 收发件人姓名,可随意填写
|
||||
|
||||
@@ -146,11 +147,21 @@ const push_config = {
|
||||
NTFY_PASSWORD: '', // 推送用户密码,可选
|
||||
NTFY_ACTIONS: '', // 推送用户动作,可选
|
||||
|
||||
// 方式一:标准发送(更强大)
|
||||
// 官方文档: https://wxpusher.zjiecode.com/docs/
|
||||
// 管理后台: https://wxpusher.zjiecode.com/admin/
|
||||
WXPUSHER_APP_TOKEN: '', // wxpusher 的 appToken
|
||||
WXPUSHER_TOPIC_IDS: '', // wxpusher 的 主题ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||
WXPUSHER_UIDS: '', // wxpusher 的 用户ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||
// 方式二:极简发送(最简单,简单好用,一键配置,更推荐)
|
||||
// wxPusher 的 SPT(极简推送),扫码获取 https://wxpusher.zjiecode.com/docs/#/?id=spt
|
||||
// 多个用英文逗号,分隔,最多10个;与上面的 appToken 方式二选一即可
|
||||
WXPUSHER_SPT_LIST: '', // wxpusher 的 SPT(极简推送),多个用英文逗号,分隔,最多10个
|
||||
|
||||
// 官方文档: https://openilink.com/docs/hub/apps
|
||||
OPENILINK_APP_TOKEN: '', // OpeniLink 的 app_token,在 OpeniLink Hub 后台安装 App 后获取
|
||||
OPENILINK_HUB_URL: '', // OpeniLink Hub 地址,默认为 https://hub.openilink.com,自建 Hub 时填写自己的地址
|
||||
OPENILINK_CONTEXT_TOKEN: '', // OpeniLink 的 context_token,用于标识消息会话上下文,可从消息事件中获取
|
||||
};
|
||||
|
||||
for (const key in push_config) {
|
||||
@@ -301,7 +312,7 @@ function serverNotify(text, desp) {
|
||||
console.log('Server 酱发送通知调用API失败😞\n', err);
|
||||
} else {
|
||||
// server酱和Server酱·Turbo版的返回json格式不太一样
|
||||
if (data.errno === 0 || data.data.errno === 0) {
|
||||
if (data.errno === 0 || data.code === 0) {
|
||||
console.log('Server 酱发送通知消息成功🎉\n');
|
||||
} else if (data.errno === 1024) {
|
||||
// 一分钟内发送相同的内容会触发
|
||||
@@ -1046,8 +1057,14 @@ function fsBotNotify(text, desp) {
|
||||
}
|
||||
|
||||
async function smtpNotify(text, desp) {
|
||||
const { SMTP_EMAIL, SMTP_TO, SMTP_PASSWORD, SMTP_SERVICE, SMTP_NAME } =
|
||||
push_config;
|
||||
const {
|
||||
SMTP_EMAIL,
|
||||
SMTP_TO,
|
||||
SMTP_EMAIL_TO,
|
||||
SMTP_PASSWORD,
|
||||
SMTP_SERVICE,
|
||||
SMTP_NAME,
|
||||
} = push_config;
|
||||
if (![SMTP_EMAIL, SMTP_PASSWORD].every(Boolean) || !SMTP_SERVICE) {
|
||||
return;
|
||||
}
|
||||
@@ -1063,9 +1080,20 @@ async function smtpNotify(text, desp) {
|
||||
});
|
||||
|
||||
const addr = SMTP_NAME ? `"${SMTP_NAME}" <${SMTP_EMAIL}>` : SMTP_EMAIL;
|
||||
const recipients = [SMTP_EMAIL_TO, SMTP_TO].reduce((list, value) => {
|
||||
if (!value) {
|
||||
return list;
|
||||
}
|
||||
return list.concat(
|
||||
value
|
||||
.split(/[;;]/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
}, []);
|
||||
const info = await transporter.sendMail({
|
||||
from: addr,
|
||||
to: SMTP_TO ? SMTP_TO.split(';') : addr,
|
||||
to: recipients.length ? recipients : SMTP_EMAIL,
|
||||
subject: text,
|
||||
html: `${desp.replace(/\n/g, '<br/>')}`,
|
||||
});
|
||||
@@ -1408,6 +1436,112 @@ function wxPusherNotify(text, desp) {
|
||||
});
|
||||
}
|
||||
|
||||
function wxPusherSptNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
const { WXPUSHER_SPT_LIST } = push_config;
|
||||
if (WXPUSHER_SPT_LIST) {
|
||||
// 处理 SPT,将逗号分隔的字符串转为数组
|
||||
const spts = WXPUSHER_SPT_LIST.split(',')
|
||||
.map((spt) => spt.trim())
|
||||
.filter((spt) => spt);
|
||||
|
||||
if (!spts.length) {
|
||||
console.log('wxpusher SPT 不能为空!!');
|
||||
return resolve();
|
||||
}
|
||||
if (spts.length > 10) {
|
||||
console.log('wxpusher SPT 最多支持 10 个!!');
|
||||
return resolve();
|
||||
}
|
||||
|
||||
const body = {
|
||||
content: `<h1>${text}</h1><br/><div style='white-space: pre-wrap;'>${desp}</div>`,
|
||||
summary: text,
|
||||
contentType: 2,
|
||||
// 单个 SPT 用 spt,多个用 sptList
|
||||
...(spts.length === 1 ? { spt: spts[0] } : { sptList: spts }),
|
||||
};
|
||||
|
||||
const options = {
|
||||
url: 'https://wxpusher.zjiecode.com/api/send/message/simple-push',
|
||||
body: JSON.stringify(body),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout,
|
||||
};
|
||||
|
||||
$.post(options, (err, resp, data) => {
|
||||
try {
|
||||
if (err) {
|
||||
console.log('wxpusher SPT 发送通知消息失败!\n', err);
|
||||
} else {
|
||||
if (data.code === 1000) {
|
||||
console.log('wxpusher SPT 发送通知消息完成!');
|
||||
} else {
|
||||
console.log(`wxpusher SPT 发送通知消息异常:${data.msg}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
$.logErr(e, resp);
|
||||
} finally {
|
||||
resolve(data);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function openiLinkNotify(text, desp) {
|
||||
return new Promise((resolve) => {
|
||||
const { OPENILINK_APP_TOKEN, OPENILINK_HUB_URL, OPENILINK_CONTEXT_TOKEN } =
|
||||
push_config;
|
||||
if (OPENILINK_APP_TOKEN) {
|
||||
const baseUrl = OPENILINK_HUB_URL
|
||||
? OPENILINK_HUB_URL.replace(/\/$/, '')
|
||||
: 'https://hub.openilink.com';
|
||||
const body = {
|
||||
type: 'text',
|
||||
content: `${text}\n\n${desp}`,
|
||||
};
|
||||
if (OPENILINK_CONTEXT_TOKEN) {
|
||||
body.context_token = OPENILINK_CONTEXT_TOKEN;
|
||||
}
|
||||
const options = {
|
||||
url: `${baseUrl}/bot/v1/message/send`,
|
||||
body: JSON.stringify(body),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${OPENILINK_APP_TOKEN}`,
|
||||
},
|
||||
timeout,
|
||||
};
|
||||
|
||||
$.post(options, (err, resp, data) => {
|
||||
try {
|
||||
if (err) {
|
||||
console.log('OpeniLink 发送通知消息失败!\n', err);
|
||||
} else {
|
||||
if (data.ok) {
|
||||
console.log('OpeniLink 发送通知消息成功!');
|
||||
} else {
|
||||
console.log(`OpeniLink 发送通知消息异常:${data.error}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
$.logErr(e, resp);
|
||||
} finally {
|
||||
resolve(data);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function parseString(input, valueFormatFn) {
|
||||
const regex = /(\w+):\s*((?:(?!\n\w+:).)*)/g;
|
||||
const matches = {};
|
||||
@@ -1511,7 +1645,7 @@ async function sendNotify(text, desp, params = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
if (push_config.HITOKOTO !== 'false') {
|
||||
if (![false, 'false'].includes(push_config.HITOKOTO)) {
|
||||
desp += '\n\n' + (await one());
|
||||
}
|
||||
|
||||
@@ -1527,7 +1661,7 @@ async function sendNotify(text, desp, params = {}) {
|
||||
iGotNotify(text, desp, params), // iGot
|
||||
gobotNotify(text, desp), // go-cqhttp
|
||||
gotifyNotify(text, desp), // gotify
|
||||
chatNotify(text, desp), // synolog chat
|
||||
chatNotify(text, desp), // synology chat
|
||||
pushDeerNotify(text, desp), // PushDeer
|
||||
aibotkNotify(text, desp), // 智能微秘书
|
||||
fsBotNotify(text, desp), // 飞书机器人
|
||||
@@ -1538,6 +1672,8 @@ async function sendNotify(text, desp, params = {}) {
|
||||
qmsgNotify(text, desp), // 自定义通知
|
||||
ntfyNotify(text, desp), // Ntfy
|
||||
wxPusherNotify(text, desp), // wxpusher
|
||||
wxPusherSptNotify(text, desp), // wxpusher SPT
|
||||
openiLinkNotify(text, desp), // OpeniLink
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
+110
-11
@@ -94,8 +94,8 @@ push_config = {
|
||||
|
||||
'QYWX_KEY': '', # 企业微信机器人
|
||||
|
||||
'TG_BOT_TOKEN': '', # tg 机器人的 TG_BOT_TOKEN,例:1407203283:AAG9rt-6RDaaX0HBLZQq0laNOh898iFYaRQ
|
||||
'TG_USER_ID': '', # tg 机器人的 TG_USER_ID,例:1434078534
|
||||
'TG_BOT_TOKEN': '', # tg 机器人的 TG_BOT_TOKEN,例:1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
|
||||
'TG_USER_ID': '', # tg 机器人的 TG_USER_ID,例:1234567890
|
||||
'TG_API_HOST': '', # tg 代理 api
|
||||
'TG_PROXY_AUTH': '', # tg 代理认证参数
|
||||
'TG_PROXY_HOST': '', # tg 机器人的 TG_PROXY_HOST
|
||||
@@ -107,7 +107,8 @@ push_config = {
|
||||
|
||||
'SMTP_SERVER': '', # SMTP 发送邮件服务器,形如 smtp.exmail.qq.com:465
|
||||
'SMTP_SSL': 'false', # SMTP 发送邮件服务器是否使用 SSL,填写 true 或 false
|
||||
'SMTP_EMAIL': '', # SMTP 收发件邮箱,通知将会由自己发给自己
|
||||
'SMTP_EMAIL': '', # SMTP 发件邮箱
|
||||
'SMTP_EMAIL_TO': '', # SMTP 收件邮箱,多个分号分隔,默认发给发件邮箱
|
||||
'SMTP_PASSWORD': '', # SMTP 登录密码,也可能为特殊口令,视具体邮件服务商说明而定
|
||||
'SMTP_NAME': '', # SMTP 收发件人姓名,可随意填写
|
||||
|
||||
@@ -132,9 +133,20 @@ push_config = {
|
||||
'NTFY_PASSWORD': '', # 推送用户密码,可选
|
||||
'NTFY_ACTIONS': '', # 推送用户动作,可选
|
||||
|
||||
### 方式一:标准发送(更强大)
|
||||
#### 官方文档: https://wxpusher.zjiecode.com/docs/
|
||||
#### 管理后台: https://wxpusher.zjiecode.com/admin/
|
||||
'WXPUSHER_APP_TOKEN': '', # wxpusher 的 appToken 官方文档: https://wxpusher.zjiecode.com/docs/ 管理后台: https://wxpusher.zjiecode.com/admin/
|
||||
'WXPUSHER_TOPIC_IDS': '', # wxpusher 的 主题ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||
'WXPUSHER_UIDS': '', # wxpusher 的 用户ID,多个用英文分号;分隔 topic_ids 与 uids 至少配置一个才行
|
||||
### 方式二:极简发送(最简单,简单好用,一键配置,更推荐)
|
||||
#### wxPusher 的 SPT(极简推送),扫码获取 https://wxpusher.zjiecode.com/docs/#/?id=spt
|
||||
#### 多个用英文逗号,分隔,最多10个;与上面的 appToken 方式二选一即可
|
||||
'WXPUSHER_SPT_LIST': '', # wxpusher 的 SPT(极简推送),多个用英文逗号,分隔,最多10个 官方文档: https://wxpusher.zjiecode.com/docs/#/?id=spt
|
||||
|
||||
'OPENILINK_APP_TOKEN': '', # OpeniLink 的 app_token,在 OpeniLink Hub 后台安装 App 后获取 官方文档: https://openilink.com/docs/hub/apps
|
||||
'OPENILINK_HUB_URL': '', # OpeniLink Hub 地址,默认为 https://hub.openilink.com,自建 Hub 时填写自己的地址
|
||||
'OPENILINK_CONTEXT_TOKEN': '', # OpeniLink 的 context_token,用于标识消息会话上下文,可从消息事件中获取
|
||||
}
|
||||
# fmt: on
|
||||
|
||||
@@ -690,6 +702,10 @@ def smtp(title: str, content: str) -> None:
|
||||
return
|
||||
print("SMTP 邮件 服务启动")
|
||||
|
||||
email_to = push_config.get("SMTP_EMAIL_TO") or push_config.get("SMTP_EMAIL")
|
||||
email_to_list = [
|
||||
item.strip() for item in re.split(r"[;;]", email_to) if item.strip()
|
||||
]
|
||||
message = MIMEText(content, "plain", "utf-8")
|
||||
message["From"] = formataddr(
|
||||
(
|
||||
@@ -697,12 +713,7 @@ def smtp(title: str, content: str) -> None:
|
||||
push_config.get("SMTP_EMAIL"),
|
||||
)
|
||||
)
|
||||
message["To"] = formataddr(
|
||||
(
|
||||
Header(push_config.get("SMTP_NAME"), "utf-8").encode(),
|
||||
push_config.get("SMTP_EMAIL"),
|
||||
)
|
||||
)
|
||||
message["To"] = ",".join(email_to_list)
|
||||
message["Subject"] = Header(title, "utf-8")
|
||||
|
||||
try:
|
||||
@@ -716,7 +727,7 @@ def smtp(title: str, content: str) -> None:
|
||||
)
|
||||
smtp_server.sendmail(
|
||||
push_config.get("SMTP_EMAIL"),
|
||||
push_config.get("SMTP_EMAIL"),
|
||||
email_to_list,
|
||||
message.as_bytes(),
|
||||
)
|
||||
smtp_server.close()
|
||||
@@ -898,6 +909,90 @@ def wxpusher_bot(title: str, content: str) -> None:
|
||||
print(f"wxpusher 推送失败!错误信息:{response.get('msg')}")
|
||||
|
||||
|
||||
def wxpusher_spt(title: str, content: str) -> None:
|
||||
"""
|
||||
通过 wxpusher 极简推送(SPT)推送消息。
|
||||
支持的环境变量:
|
||||
- WXPUSHER_SPT_LIST: SPT, 多个用英文逗号,分隔, 最多10个
|
||||
"""
|
||||
if not push_config.get("WXPUSHER_SPT_LIST"):
|
||||
return
|
||||
|
||||
# 处理 SPT,将逗号分隔的字符串转为数组
|
||||
spts = [
|
||||
spt.strip()
|
||||
for spt in push_config.get("WXPUSHER_SPT_LIST").split(",")
|
||||
if spt.strip()
|
||||
]
|
||||
|
||||
if not spts:
|
||||
print("wxpusher 服务的 WXPUSHER_SPT_LIST 不能为空!!")
|
||||
return
|
||||
if len(spts) > 10:
|
||||
print("wxpusher 服务的 WXPUSHER_SPT_LIST 最多支持 10 个!!")
|
||||
return
|
||||
|
||||
print("wxpusher SPT 服务启动")
|
||||
|
||||
url = "https://wxpusher.zjiecode.com/api/send/message/simple-push"
|
||||
|
||||
data = {
|
||||
"content": f"<h1>{title}</h1><br/><div style='white-space: pre-wrap;'>{content}</div>",
|
||||
"summary": title,
|
||||
"contentType": 2,
|
||||
}
|
||||
# 单个 SPT 用 spt,多个用 sptList
|
||||
if len(spts) == 1:
|
||||
data["spt"] = spts[0]
|
||||
else:
|
||||
data["sptList"] = spts
|
||||
|
||||
headers = {"Content-Type": "application/json"}
|
||||
response = requests.post(url=url, json=data, headers=headers).json()
|
||||
|
||||
if response.get("code") == 1000:
|
||||
print("wxpusher SPT 推送成功!")
|
||||
else:
|
||||
print(f"wxpusher SPT 推送失败!错误信息:{response.get('msg')}")
|
||||
|
||||
|
||||
def openilink(title: str, content: str) -> None:
|
||||
"""
|
||||
通过 OpeniLink 推送消息。
|
||||
支持的环境变量:
|
||||
- OPENILINK_APP_TOKEN: 在 OpeniLink Hub 后台安装 App 后获取的 app_token
|
||||
- OPENILINK_HUB_URL: OpeniLink Hub 地址,默认为 https://hub.openilink.com
|
||||
- OPENILINK_CONTEXT_TOKEN: 消息会话上下文 token,可从消息事件中获取
|
||||
"""
|
||||
if not push_config.get("OPENILINK_APP_TOKEN"):
|
||||
return
|
||||
|
||||
print("OpeniLink 服务启动")
|
||||
|
||||
base_url = (
|
||||
push_config.get("OPENILINK_HUB_URL", "").rstrip("/")
|
||||
or "https://hub.openilink.com"
|
||||
)
|
||||
url = f"{base_url}/bot/v1/message/send"
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f'Bearer {push_config.get("OPENILINK_APP_TOKEN")}',
|
||||
}
|
||||
data = {
|
||||
"type": "text",
|
||||
"content": f"{title}\n\n{content}",
|
||||
}
|
||||
if push_config.get("OPENILINK_CONTEXT_TOKEN"):
|
||||
data["context_token"] = push_config.get("OPENILINK_CONTEXT_TOKEN")
|
||||
|
||||
response = requests.post(url=url, json=data, headers=headers).json()
|
||||
|
||||
if response.get("ok"):
|
||||
print("OpeniLink 推送成功!")
|
||||
else:
|
||||
print(f'OpeniLink 推送失败!错误信息:{response.get("error")}')
|
||||
|
||||
|
||||
def parse_headers(headers):
|
||||
if not headers:
|
||||
return {}
|
||||
@@ -1063,6 +1158,10 @@ def add_notify_function():
|
||||
push_config.get("WXPUSHER_TOPIC_IDS") or push_config.get("WXPUSHER_UIDS")
|
||||
):
|
||||
notify_function.append(wxpusher_bot)
|
||||
if push_config.get("WXPUSHER_SPT_LIST"):
|
||||
notify_function.append(wxpusher_spt)
|
||||
if push_config.get("OPENILINK_APP_TOKEN"):
|
||||
notify_function.append(openilink)
|
||||
if not notify_function:
|
||||
print(f"无推送渠道,请检查通知变量是否正确")
|
||||
return notify_function
|
||||
@@ -1088,7 +1187,7 @@ def send(title: str, content: str, ignore_default_config: bool = False, **kwargs
|
||||
return
|
||||
|
||||
hitokoto = push_config.get("HITOKOTO")
|
||||
content += "\n\n" + one() if hitokoto != "false" else ""
|
||||
content += "\n\n" + one() if hitokoto not in [False, "false"] else ""
|
||||
|
||||
notify_function = add_notify_function()
|
||||
ts = [
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+51
-21
@@ -41,7 +41,7 @@ add_cron_api() {
|
||||
fi
|
||||
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:${ql_port}/open/crons?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
--data-raw "{\"name\":\"${name//\"/\\\"}\",\"command\":\"${command//\"/\\\"}\",\"schedule\":\"$schedule\",\"sub_id\":$sub_id}" \
|
||||
@@ -50,9 +50,9 @@ add_cron_api() {
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "$name -> 添加成功"
|
||||
t '%s -> 添加成功' "$name"
|
||||
else
|
||||
echo -e "$name -> 添加失败(${message})"
|
||||
t '%s -> 添加失败(%s)' "$name" "$message"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ update_cron_api() {
|
||||
fi
|
||||
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:${ql_port}/open/crons?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \
|
||||
-X 'PUT' \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
@@ -81,9 +81,9 @@ update_cron_api() {
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "$name -> 更新成功"
|
||||
t '%s -> 更新成功' "$name"
|
||||
else
|
||||
echo -e "$name -> 更新失败(${message})"
|
||||
t '%s -> 更新失败(%s)' "$name" "$message"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ update_cron_command_api() {
|
||||
fi
|
||||
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:${ql_port}/open/crons?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \
|
||||
-X 'PUT' \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
@@ -108,9 +108,9 @@ update_cron_command_api() {
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "$command -> 更新成功"
|
||||
t '%s -> 更新成功' "$command"
|
||||
else
|
||||
echo -e "$command -> 更新失败(${message})"
|
||||
t '%s -> 更新失败(%s)' "$command" "$message"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ del_cron_api() {
|
||||
local ids="$1"
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:${ql_port}/open/crons?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \
|
||||
-X 'DELETE' \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
@@ -128,9 +128,9 @@ del_cron_api() {
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "成功"
|
||||
t '成功'
|
||||
else
|
||||
echo -e "失败(${message})"
|
||||
t '失败(%s)' "$message"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -141,13 +141,19 @@ update_cron() {
|
||||
local logPath="$4"
|
||||
local lastExecutingTime="${5:-0}"
|
||||
local runningTime="${6:-0}"
|
||||
local exitCode="${7:-}"
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local dataRaw="{\"ids\":[$ids],\"status\":\"$status\",\"pid\":\"$pid\",\"log_path\":\"$logPath\",\"last_execution_time\":$lastExecutingTime,\"last_running_time\":$runningTime"
|
||||
if [[ -n $exitCode ]]; then
|
||||
dataRaw="${dataRaw},\"exit_code\":$exitCode"
|
||||
fi
|
||||
dataRaw="${dataRaw}}"
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:${ql_port}/open/crons/status?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons/status?t=$currentTimeStamp" \
|
||||
-X 'PUT' \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
--data-raw "{\"ids\":[$ids],\"status\":\"$status\",\"pid\":\"$pid\",\"log_path\":\"$logPath\",\"last_execution_time\":$lastExecutingTime,\"last_running_time\":$runningTime}" \
|
||||
--data-raw "$dataRaw" \
|
||||
--compressed
|
||||
)
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
@@ -165,7 +171,7 @@ notify_api() {
|
||||
local content="$2"
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:${ql_port}/open/system/notify?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://localhost:${ql_port}/open/system/notify?t=$currentTimeStamp" \
|
||||
-X 'PUT' \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
@@ -175,9 +181,9 @@ notify_api() {
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "通知发送成功🎉"
|
||||
t '通知发送成功🎉'
|
||||
else
|
||||
echo -e "通知失败(${message})"
|
||||
t '通知失败(%s)' "$message"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -185,7 +191,7 @@ find_cron_api() {
|
||||
local params="$1"
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:${ql_port}/open/crons/detail?$params&t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons/detail?$params&t=$currentTimeStamp" \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
--compressed
|
||||
@@ -204,7 +210,7 @@ update_auth_config() {
|
||||
local tip="$2"
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:${ql_port}/open/system/auth/reset?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://localhost:${ql_port}/open/system/auth/reset?t=$currentTimeStamp" \
|
||||
-X 'PUT' \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
@@ -214,9 +220,33 @@ update_auth_config() {
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
echo -e "${tip}成功🎉"
|
||||
t '%s成功🎉' "$tip"
|
||||
else
|
||||
echo -e "${tip}失败(${message})"
|
||||
t '%s失败(%s)' "$tip" "$message"
|
||||
fi
|
||||
}
|
||||
|
||||
record_cron_stat() {
|
||||
local ref_id="$1"
|
||||
local exit_code="${2:-0}"
|
||||
local elapsed="${3:-0}"
|
||||
[[ $ref_id ]] && [[ $ref_id -gt 0 ]] 2>/dev/null || return
|
||||
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://localhost:${ql_port:-5700}/open/dashboard/record" \
|
||||
-X POST \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
--data-raw "{\"ref_id\":$ref_id,\"code\":$exit_code,\"elapsed\":$elapsed}" \
|
||||
--compressed
|
||||
)
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code != 200 ]]; then
|
||||
if [[ ! $message ]]; then
|
||||
message="$api"
|
||||
fi
|
||||
echo -e "${message}"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
+31
-9
@@ -8,11 +8,33 @@ else
|
||||
repo_path="${dir_repo}/diybot"
|
||||
fi
|
||||
|
||||
echo -e "\n1、安装bot依赖...\n"
|
||||
apk --no-cache add -f zlib-dev gcc jpeg-dev python3-dev musl-dev freetype-dev
|
||||
echo -e "\nbot依赖安装成功...\n"
|
||||
t '\n1、安装bot依赖...\n'
|
||||
os_name="${QL_OS_TYPE:-}"
|
||||
if [ -z "$os_name" ]; then
|
||||
os_name=$(source /etc/os-release && echo "$ID")
|
||||
fi
|
||||
|
||||
echo -e "2、下载bot所需文件...\n"
|
||||
# 非 root 用户使用 sudo
|
||||
SUDO=""
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
SUDO="sudo"
|
||||
fi
|
||||
|
||||
case "$os_name" in
|
||||
alpine)
|
||||
$SUDO apk --no-cache add -f zlib-dev gcc jpeg-dev python3-dev musl-dev freetype-dev
|
||||
;;
|
||||
debian|ubuntu)
|
||||
$SUDO apt-get install -y gcc python3-dev musl-dev zlib1g-dev libjpeg-dev libfreetype-dev
|
||||
;;
|
||||
*)
|
||||
t '暂不支持此系统 %s' "$os_name"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
t '\nbot依赖安装成功...\n'
|
||||
|
||||
t '2、下载bot所需文件...\n'
|
||||
if [[ ! -d ${repo_path}/.git ]]; then
|
||||
rm -rf ${repo_path}
|
||||
git_clone_scripts ${url} ${repo_path} "main"
|
||||
@@ -22,9 +44,9 @@ cp -rf "$repo_path/jbot" $dir_data
|
||||
if [[ ! -f "$dir_config/bot.json" ]]; then
|
||||
cp -f "$repo_path/config/bot.json" "$dir_config"
|
||||
fi
|
||||
echo -e "\nbot文件下载成功...\n"
|
||||
t '\nbot文件下载成功...\n'
|
||||
|
||||
echo -e "3、安装python3依赖...\n"
|
||||
t '3、安装python3依赖...\n'
|
||||
cp -f "$repo_path/jbot/requirements.txt" "$dir_data"
|
||||
|
||||
cd $dir_data
|
||||
@@ -34,11 +56,11 @@ cat requirements.txt | while read LREAD; do
|
||||
fi
|
||||
done
|
||||
|
||||
echo -e "\npython3依赖安装成功...\n"
|
||||
t '\npython3依赖安装成功...\n'
|
||||
|
||||
echo -e "4、启动bot程序...\n"
|
||||
t '4、启动bot程序...\n'
|
||||
make_dir $dir_log/bot
|
||||
cd $dir_data
|
||||
ps -eo pid,command | grep "python3 -m jbot" | grep -v grep | awk '{print $1}' | xargs kill -9 2>/dev/null
|
||||
nohup python3 -m jbot >$dir_log/bot/nohup.log 2>&1 &
|
||||
echo -e "bot启动成功...\n"
|
||||
t 'bot启动成功...\n'
|
||||
|
||||
+22
-20
@@ -1,29 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
reset_env() {
|
||||
echo -e "---> 1. 开始检测配置文件\n"
|
||||
t '---> 1. 开始检测配置文件\n'
|
||||
fix_config
|
||||
echo -e "---> 配置文件检测完成\n"
|
||||
t '---> 配置文件检测完成\n'
|
||||
|
||||
echo -e "---> 2. 开始安装青龙依赖\n"
|
||||
t '---> 2. 开始安装青龙依赖\n'
|
||||
npm_install_2 $dir_root
|
||||
echo -e "---> 青龙依赖安装完成\n"
|
||||
t '---> 青龙依赖安装完成\n'
|
||||
|
||||
echo -e "---> 脚本依赖安装完成\n"
|
||||
t '---> 脚本依赖安装完成\n'
|
||||
}
|
||||
|
||||
copy_dep() {
|
||||
echo -e "---> 1. 复制通知文件\n"
|
||||
echo -e "---> 复制一份 $file_notify_py_sample 为 $file_notify_py\n"
|
||||
t '---> 1. 复制通知文件\n'
|
||||
t '---> 复制一份 %s 为 %s\n' "$file_notify_py_sample" "$file_notify_py"
|
||||
cp -fv $file_notify_py_sample $file_notify_py
|
||||
echo
|
||||
echo -e "---> 复制一份 $file_notify_js_sample 为 $file_notify_js\n"
|
||||
t '---> 复制一份 %s 为 %s\n' "$file_notify_js_sample" "$file_notify_js"
|
||||
cp -fv $file_notify_js_sample $file_notify_js
|
||||
echo -e "---> 通知文件复制完成\n"
|
||||
t '---> 通知文件复制完成\n'
|
||||
}
|
||||
|
||||
pm2_log() {
|
||||
echo -e "---> pm2日志"
|
||||
t '---> pm2日志'
|
||||
local panelOut="/root/.pm2/logs/qinglong-out.log"
|
||||
local panelError="/root/.pm2/logs/qinglong-error.log"
|
||||
tail -n 300 "$panelOut"
|
||||
@@ -31,10 +31,11 @@ pm2_log() {
|
||||
}
|
||||
|
||||
check_ql() {
|
||||
local api=$(curl -s --noproxy "*" "http://0.0.0.0:${ql_port}")
|
||||
echo -e "\n=====> 检测面板\n\n$api\n"
|
||||
local api=$(curl -s --noproxy "*" "http://localhost:${ql_port}")
|
||||
t '\n=====> 检测面板'
|
||||
echo -e "\n\n$api\n"
|
||||
if [[ $api =~ "<div id=\"root\"></div>" ]]; then
|
||||
echo -e "=====> 面板服务启动正常\n"
|
||||
t '=====> 面板服务启动正常\n'
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -42,29 +43,30 @@ check_pm2() {
|
||||
pm2_log
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local api=$(
|
||||
curl -s --noproxy "*" "http://0.0.0.0:${ql_port}/api/system?t=$currentTimeStamp" \
|
||||
curl -s --noproxy "*" "http://localhost:${ql_port}/api/system?t=$currentTimeStamp" \
|
||||
-H 'Accept: */*' \
|
||||
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36' \
|
||||
-H "Referer: http://0.0.0.0:${ql_port}/crontab" \
|
||||
-H "Referer: http://localhost:${ql_port}/crontab" \
|
||||
-H 'Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7' \
|
||||
--compressed
|
||||
)
|
||||
echo -e "\n=====> 检测后台\n\n$api\n"
|
||||
t '\n=====> 检测后台'
|
||||
echo -e "\n\n$api\n"
|
||||
if [[ $api =~ "{\"code\"" ]]; then
|
||||
echo -e "=====> 后台服务启动正常\n"
|
||||
t '=====> 后台服务启动正常\n'
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
echo -e "=====> 开始检测"
|
||||
npm i -g pnpm@8.3.1 pm2 ts-node
|
||||
t '=====> 开始检测'
|
||||
npm i -g pnpm@8.3.1 pm2 ts-node typescript@5
|
||||
|
||||
reset_env
|
||||
copy_dep
|
||||
check_ql
|
||||
check_pm2
|
||||
reload_pm2
|
||||
echo -e "\n=====> 检测结束\n"
|
||||
t '\n=====> 检测结束\n'
|
||||
}
|
||||
|
||||
main
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# English language pack
|
||||
declare -gA LANG_MESSAGES=(
|
||||
['任务随机延迟 %s 秒,将于 %s 开始,配置文件参数 RandomDelay 置空可取消延迟\n']='Task delayed %s seconds, will start at %s. Set RandomDelay to empty to cancel delay\n'
|
||||
['开始执行...\n']='Starting execution...\n'
|
||||
['已停止']='Stopped'
|
||||
['完成']='Completed'
|
||||
['失败(退出码 %s)']='Failed (exit code %s)'
|
||||
['安装 %s 依赖包...\n']='Installing %s dependencies...\n'
|
||||
['开始拉取仓库 %s 到 %s\n']='Cloning repository %s to %s\n'
|
||||
['添加成功']='Added successfully'
|
||||
['添加失败(%s)']='Add failed (%s)'
|
||||
['更新成功']='Updated successfully'
|
||||
['更新失败(%s)']='Update failed (%s)'
|
||||
['成功']='Success'
|
||||
['失败(%s)']='Failed (%s)'
|
||||
['通知发送成功🎉']='Notification sent successfully 🎉'
|
||||
['通知失败(%s)']='Notification failed (%s)'
|
||||
['当前有以下脚本可以运行:']='Available scripts:'
|
||||
['暂无脚本可以执行']='No scripts available'
|
||||
['警告:工作目录不存在 %s']='Warning: working directory does not exist: %s'
|
||||
['\n缺少并发运行的环境变量参数']='\nMissing concurrency environment variable'
|
||||
['\n缺少单独运行的参数 task xxx.js desi Test']='\nMissing parameter: task xxx.js desi Test'
|
||||
['暂不支持此系统 %s']='Unsupported system: %s'
|
||||
['检测到 pm2 服务正在运行']='pm2 service is running'
|
||||
['npm 模块位置: %s']='npm module location: %s'
|
||||
['导入数据成功 %s']='Data imported successfully: %s'
|
||||
['导出数据成功 %s']='Data exported successfully: %s'
|
||||
['当前版本: %s / 最新版本: %s']='Current: %s / Latest: %s'
|
||||
['已是最新版本']='Already up to date'
|
||||
['%s 个定时任务正在运行']='%s scheduled tasks running'
|
||||
['执行前置命令\n']='Running pre-command\n'
|
||||
['\n执行前置命令结束\n']='\nPre-command finished\n'
|
||||
['\n执行后置命令\n']='\nRunning post-command\n'
|
||||
['\n执行后置命令结束']='\nPost-command finished'
|
||||
['警告: PM2 启动失败 (退出码: %s),可能是由于硬件不兼容']='Warning: PM2 start failed (exit code: %s), possibly due to hardware incompatibility'
|
||||
['正在尝试直接使用 Node.js 启动服务...']='Attempting to start service with Node.js directly...'
|
||||
['已使用 Node.js 直接启动服务 (PID: %s)']='Service started with Node.js directly (PID: %s)'
|
||||
['注意: 使用此模式时,部分 PM2 管理功能将不可用']='Note: some PM2 management features are unavailable in this mode'
|
||||
['## 开始执行... %s\n']='## Starting... %s\n'
|
||||
['\n## 已停止 🛑... %s 耗时 %s 秒%s']='\n## Stopped 🛑... %s took %s seconds%s'
|
||||
['\n## 完成 ✅... %s 耗时 %s 秒%s']='\n## Completed ✅... %s took %s seconds%s'
|
||||
['\n## 失败 ❌(退出码 %s)... %s 耗时 %s 秒%s']='\n## Failed ❌(exit code %s)... %s took %s seconds%s'
|
||||
['%s -> 添加成功']='%s -> Added successfully'
|
||||
['%s -> 添加失败(%s)']='%s -> Add failed (%s)'
|
||||
['%s -> 更新成功']='%s -> Updated successfully'
|
||||
['%s -> 更新失败(%s)']='%s -> Update failed (%s)'
|
||||
['%s成功🎉']='%s succeeded 🎉'
|
||||
['%s失败(%s)']='%s failed (%s)'
|
||||
['检测到有%s的定时任务:']='Found %s scheduled tasks:'
|
||||
['\n开始尝试自动删除失效的定时任务...']='\nAttempting to remove invalid scheduled tasks...'
|
||||
['\n开始尝试自动添加定时任务...']='\nAttempting to add scheduled tasks...'
|
||||
['拉取 %s 成功...\n']='Pull %s succeeded...\n'
|
||||
['拉取 %s 失败,请检查日志...\n']='Pull %s failed, check logs...\n'
|
||||
['开始下载:%s 保存路径:%s\n']='Downloading: %s to: %s\n'
|
||||
['下载 %s 成功...\n']='Download %s succeeded...\n'
|
||||
['下载 %s 失败,保留之前正常下载的版本...\n']='Download %s failed, keeping previous version...\n'
|
||||
['%s文件不存在,跳过执行...\n']='%s does not exist, skipping...\n'
|
||||
['使用 %s 源更新...\n']='Updating using %s mirror...\n'
|
||||
['更新青龙源文件成功...\n']='Qinglong source updated successfully\n'
|
||||
['更新青龙源文件失败,请检查网络...\n']='Qinglong source update failed, check network\n'
|
||||
['更新青龙静态资源成功...\n']='Static assets updated successfully\n'
|
||||
['更新青龙静态资源失败,请检查网络...\n']='Static assets update failed, check network\n'
|
||||
['\n开始检测依赖...\n']='\nChecking dependencies...\n'
|
||||
['\n依赖检测安装成功...\n']='\nDependencies installed successfully\n'
|
||||
['更新包下载成功...\n']='Package download succeeded\n'
|
||||
['\n依赖检测安装失败,请检查网络...\n']='\nDependency installation failed, check network\n'
|
||||
['\n1、安装bot依赖...\n']='\n1. Installing bot dependencies...\n'
|
||||
['\nbot依赖安装成功...\n']='\nBot dependencies installed\n'
|
||||
['2、下载bot所需文件...\n']='2. Downloading bot files...\n'
|
||||
['\nbot文件下载成功...\n']='\nBot files downloaded\n'
|
||||
['3、安装python3依赖...\n']='3. Installing python3 dependencies...\n'
|
||||
['\npython3依赖安装成功...\n']='\nPython3 dependencies installed\n'
|
||||
['4、启动bot程序...\n']='4. Starting bot...\n'
|
||||
['bot启动成功...\n']='Bot started successfully\n'
|
||||
# check.sh
|
||||
['---> 1. 开始检测配置文件\n']='---> 1. Checking config...\n'
|
||||
['---> 配置文件检测完成\n']='---> Config check complete\n'
|
||||
['---> 2. 开始安装青龙依赖\n']='---> 2. Installing qinglong dependencies...\n'
|
||||
['---> 青龙依赖安装完成\n']='---> Dependencies installed\n'
|
||||
['---> 脚本依赖安装完成\n']='---> Script dependencies installed\n'
|
||||
['---> 1. 复制通知文件\n']='---> 1. Copying notification files...\n'
|
||||
['---> 复制一份 %s 为 %s\n']='---> Copying %s to %s\n'
|
||||
['---> 通知文件复制完成\n']='---> Notification files copied\n'
|
||||
['---> pm2日志']='---> pm2 log'
|
||||
['\n=====> 检测面板']='\n=====> Checking panel'
|
||||
['=====> 面板服务启动正常\n']='=====> Panel service running normally\n'
|
||||
['\n=====> 检测后台']='\n=====> Checking backend'
|
||||
['=====> 后台服务启动正常\n']='=====> Backend service running normally\n'
|
||||
['=====> 开始检测']='=====> Starting check'
|
||||
['\n=====> 检测结束\n']='\n=====> Check complete\n'
|
||||
# rmlog.sh
|
||||
['查询文件 %s']='Checking file: %s'
|
||||
['删除中~']='Deleting...'
|
||||
['正在被 %s 使用,跳过~']='In use by %s, skipping...'
|
||||
['查找旧日志文件中...\n']='Looking for old log files...\n'
|
||||
['删除旧日志执行完毕\n']='Old log cleanup complete\n'
|
||||
# start.sh
|
||||
['未找到 qinglong 模块,请先执行 npm i -g @whyour/qinglong 安装']='Module not found. Run: npm i -g @whyour/qinglong'
|
||||
['请先手动设置 export QL_DIR=%s,环境变量,并手动添加到系统环境变量,然后再次执行命令 qinglong 启动服务']='Set env: export QL_DIR=%s, then run qinglong to start'
|
||||
['请先手动设置数据存储目录 export QL_DATA_DIR 环境变量,目录必须以斜杠开头的绝对路径,并且以 /data 结尾,例如 /ql/data 并手动添加到系统环境变量']='Set QL_DATA_DIR (absolute path ending with /data, e.g. /ql/data)'
|
||||
['QL_DATA_DIR 必须以 /data 结尾,例如 /ql/data,如果有历史数据,请新建 data 目录,把历史数据放到 data 目录中']='QL_DATA_DIR must end with /data, e.g. /ql/data'
|
||||
['暂不支持此系统部署 %s']='Unsupported system for deployment: %s'
|
||||
# update.sh
|
||||
['命令输入错误...\n']='Invalid command...\n'
|
||||
)
|
||||
@@ -0,0 +1,105 @@
|
||||
# 中文语言包(zh key → zh value 恒等,en 包做实际翻译)
|
||||
declare -gA LANG_MESSAGES=(
|
||||
['任务随机延迟 %s 秒,将于 %s 开始,配置文件参数 RandomDelay 置空可取消延迟\n']='任务随机延迟 %s 秒,将于 %s 开始,配置文件参数 RandomDelay 置空可取消延迟\n'
|
||||
['开始执行...\n']='开始执行...\n'
|
||||
['已停止']='已停止'
|
||||
['完成']='完成'
|
||||
['失败(退出码 %s)']='失败(退出码 %s)'
|
||||
['安装 %s 依赖包...\n']='安装 %s 依赖包...\n'
|
||||
['开始拉取仓库 %s 到 %s\n']='开始拉取仓库 %s 到 %s\n'
|
||||
['添加成功']='添加成功'
|
||||
['添加失败(%s)']='添加失败(%s)'
|
||||
['更新成功']='更新成功'
|
||||
['更新失败(%s)']='更新失败(%s)'
|
||||
['成功']='成功'
|
||||
['失败(%s)']='失败(%s)'
|
||||
['通知发送成功🎉']='通知发送成功🎉'
|
||||
['通知失败(%s)']='通知失败(%s)'
|
||||
['当前有以下脚本可以运行:']='当前有以下脚本可以运行:'
|
||||
['暂无脚本可以执行']='暂无脚本可以执行'
|
||||
['警告:工作目录不存在 %s']='警告:工作目录不存在 %s'
|
||||
['\n缺少并发运行的环境变量参数']='\n缺少并发运行的环境变量参数'
|
||||
['\n缺少单独运行的参数 task xxx.js desi Test']='\n缺少单独运行的参数 task xxx.js desi Test'
|
||||
['暂不支持此系统 %s']='暂不支持此系统 %s'
|
||||
['检测到 pm2 服务正在运行']='检测到 pm2 服务正在运行'
|
||||
['npm 模块位置: %s']='npm 模块位置: %s'
|
||||
['导入数据成功 %s']='导入数据成功 %s'
|
||||
['导出数据成功 %s']='导出数据成功 %s'
|
||||
['当前版本: %s / 最新版本: %s']='当前版本: %s / 最新版本: %s'
|
||||
['已是最新版本']='已是最新版本'
|
||||
['%s 个定时任务正在运行']='%s 个定时任务正在运行'
|
||||
['执行前置命令\n']='执行前置命令\n'
|
||||
['\n执行前置命令结束\n']='\n执行前置命令结束\n'
|
||||
['\n执行后置命令\n']='\n执行后置命令\n'
|
||||
['\n执行后置命令结束']='\n执行后置命令结束'
|
||||
['警告: PM2 启动失败 (退出码: %s),可能是由于硬件不兼容']='警告: PM2 启动失败 (退出码: %s),可能是由于硬件不兼容'
|
||||
['正在尝试直接使用 Node.js 启动服务...']='正在尝试直接使用 Node.js 启动服务...'
|
||||
['已使用 Node.js 直接启动服务 (PID: %s)']='已使用 Node.js 直接启动服务 (PID: %s)'
|
||||
['注意: 使用此模式时,部分 PM2 管理功能将不可用']='注意: 使用此模式时,部分 PM2 管理功能将不可用'
|
||||
['## 开始执行... %s\n']='## 开始执行... %s\n'
|
||||
['\n## 已停止 🛑... %s 耗时 %s 秒%s']='\n## 已停止 🛑... %s 耗时 %s 秒%s'
|
||||
['\n## 完成 ✅... %s 耗时 %s 秒%s']='\n## 完成 ✅... %s 耗时 %s 秒%s'
|
||||
['\n## 失败 ❌(退出码 %s)... %s 耗时 %s 秒%s']='\n## 失败 ❌(退出码 %s)... %s 耗时 %s 秒%s'
|
||||
['%s -> 添加成功']='%s -> 添加成功'
|
||||
['%s -> 添加失败(%s)']='%s -> 添加失败(%s)'
|
||||
['%s -> 更新成功']='%s -> 更新成功'
|
||||
['%s -> 更新失败(%s)']='%s -> 更新失败(%s)'
|
||||
['%s成功🎉']='%s成功🎉'
|
||||
['%s失败(%s)']='%s失败(%s)'
|
||||
['检测到有%s的定时任务:']='检测到有%s的定时任务:'
|
||||
['\n开始尝试自动删除失效的定时任务...']='\n开始尝试自动删除失效的定时任务...'
|
||||
['\n开始尝试自动添加定时任务...']='\n开始尝试自动添加定时任务...'
|
||||
['拉取 %s 成功...\n']='拉取 %s 成功...\n'
|
||||
['拉取 %s 失败,请检查日志...\n']='拉取 %s 失败,请检查日志...\n'
|
||||
['开始下载:%s 保存路径:%s\n']='开始下载:%s 保存路径:%s\n'
|
||||
['下载 %s 成功...\n']='下载 %s 成功...\n'
|
||||
['下载 %s 失败,保留之前正常下载的版本...\n']='下载 %s 失败,保留之前正常下载的版本...\n'
|
||||
['%s文件不存在,跳过执行...\n']='%s文件不存在,跳过执行...\n'
|
||||
['使用 %s 源更新...\n']='使用 %s 源更新...\n'
|
||||
['更新青龙源文件成功...\n']='更新青龙源文件成功...\n'
|
||||
['更新青龙源文件失败,请检查网络...\n']='更新青龙源文件失败,请检查网络...\n'
|
||||
['更新青龙静态资源成功...\n']='更新青龙静态资源成功...\n'
|
||||
['更新青龙静态资源失败,请检查网络...\n']='更新青龙静态资源失败,请检查网络...\n'
|
||||
['\n开始检测依赖...\n']='\n开始检测依赖...\n'
|
||||
['\n依赖检测安装成功...\n']='\n依赖检测安装成功...\n'
|
||||
['更新包下载成功...\n']='更新包下载成功...\n'
|
||||
['\n依赖检测安装失败,请检查网络...\n']='\n依赖检测安装失败,请检查网络...\n'
|
||||
['\n1、安装bot依赖...\n']='\n1、安装bot依赖...\n'
|
||||
['\nbot依赖安装成功...\n']='\nbot依赖安装成功...\n'
|
||||
['2、下载bot所需文件...\n']='2、下载bot所需文件...\n'
|
||||
['\nbot文件下载成功...\n']='\nbot文件下载成功...\n'
|
||||
['3、安装python3依赖...\n']='3、安装python3依赖...\n'
|
||||
['\npython3依赖安装成功...\n']='\npython3依赖安装成功...\n'
|
||||
['4、启动bot程序...\n']='4、启动bot程序...\n'
|
||||
['bot启动成功...\n']='bot启动成功...\n'
|
||||
# check.sh
|
||||
['---> 1. 开始检测配置文件\n']='---> 1. 开始检测配置文件\n'
|
||||
['---> 配置文件检测完成\n']='---> 配置文件检测完成\n'
|
||||
['---> 2. 开始安装青龙依赖\n']='---> 2. 开始安装青龙依赖\n'
|
||||
['---> 青龙依赖安装完成\n']='---> 青龙依赖安装完成\n'
|
||||
['---> 脚本依赖安装完成\n']='---> 脚本依赖安装完成\n'
|
||||
['---> 1. 复制通知文件\n']='---> 1. 复制通知文件\n'
|
||||
['---> 复制一份 %s 为 %s\n']='---> 复制一份 %s 为 %s\n'
|
||||
['---> 通知文件复制完成\n']='---> 通知文件复制完成\n'
|
||||
['---> pm2日志']='---> pm2日志'
|
||||
['\n=====> 检测面板']='\n=====> 检测面板'
|
||||
['=====> 面板服务启动正常\n']='=====> 面板服务启动正常\n'
|
||||
['\n=====> 检测后台']='\n=====> 检测后台'
|
||||
['=====> 后台服务启动正常\n']='=====> 后台服务启动正常\n'
|
||||
['=====> 开始检测']='=====> 开始检测'
|
||||
['\n=====> 检测结束\n']='\n=====> 检测结束\n'
|
||||
# rmlog.sh
|
||||
['查询文件 %s']='查询文件 %s'
|
||||
['删除中~']='删除中~'
|
||||
['正在被 %s 使用,跳过~']='正在被 %s 使用,跳过~'
|
||||
['查找旧日志文件中...\n']='查找旧日志文件中...\n'
|
||||
['删除旧日志执行完毕\n']='删除旧日志执行完毕\n'
|
||||
# start.sh
|
||||
['未找到 qinglong 模块,请先执行 npm i -g @whyour/qinglong 安装']='未找到 qinglong 模块,请先执行 npm i -g @whyour/qinglong 安装'
|
||||
['请先手动设置 export QL_DIR=%s,环境变量,并手动添加到系统环境变量,然后再次执行命令 qinglong 启动服务']='请先手动设置 export QL_DIR=%s,环境变量,并手动添加到系统环境变量,然后再次执行命令 qinglong 启动服务'
|
||||
['请先手动设置数据存储目录 export QL_DATA_DIR 环境变量,目录必须以斜杠开头的绝对路径,并且以 /data 结尾,例如 /ql/data 并手动添加到系统环境变量']='请先手动设置数据存储目录 export QL_DATA_DIR 环境变量,目录必须以斜杠开头的绝对路径,并且以 /data 结尾,例如 /ql/data 并手动添加到系统环境变量'
|
||||
['QL_DATA_DIR 必须以 /data 结尾,例如 /ql/data,如果有历史数据,请新建 data 目录,把历史数据放到 data 目录中']='QL_DATA_DIR 必须以 /data 结尾,例如 /ql/data,如果有历史数据,请新建 data 目录,把历史数据放到 data 目录中'
|
||||
['暂不支持此系统部署 %s']='暂不支持此系统部署 %s'
|
||||
# update.sh
|
||||
['命令输入错误...\n']='命令输入错误...\n'
|
||||
)
|
||||
+116
-27
@@ -24,7 +24,13 @@ random_delay() {
|
||||
done
|
||||
|
||||
local delay_second=$(($(gen_random_num "$random_delay_max") + 1))
|
||||
echo -e "任务随机延迟 $delay_second 秒,配置文件参数 RandomDelay 置空可取消延迟 \n"
|
||||
local start_time
|
||||
if [[ $is_macos -eq 1 ]]; then
|
||||
start_time=$(date -v "+${delay_second}S" "+%Y-%m-%d %H:%M:%S")
|
||||
else
|
||||
start_time=$(date -d "+${delay_second} seconds" "+%Y-%m-%d %H:%M:%S")
|
||||
fi
|
||||
t '任务随机延迟 %s 秒,将于 %s 开始,配置文件参数 RandomDelay 置空可取消延迟\n' "$delay_second" "$start_time"
|
||||
sleep $delay_second
|
||||
fi
|
||||
}
|
||||
@@ -83,6 +89,61 @@ clear_non_sh_env() {
|
||||
fi
|
||||
}
|
||||
|
||||
append_node_dependency_path() {
|
||||
export PREV_NODE_PATH="${NODE_PATH:=}"
|
||||
|
||||
# 用户依赖目录加入 NODE_PATH,替代 symlink 到 node_modules 的方式
|
||||
export NODE_PATH="${NODE_PATH:+${NODE_PATH}:}${dir_dep}"
|
||||
|
||||
local pnpm_global_path=$(pnpm root -g 2>/dev/null)
|
||||
if [[ -n "$pnpm_global_path" ]]; then
|
||||
export QL_NODE_GLOBAL_PATH="$pnpm_global_path"
|
||||
export NODE_PATH="${NODE_PATH:+${NODE_PATH}:}${pnpm_global_path}"
|
||||
fi
|
||||
}
|
||||
|
||||
enter_script_workdir() {
|
||||
local use_dot_prefix="$1"
|
||||
|
||||
# 如果定时任务显式指定了工作目录,优先使用
|
||||
if [[ -n "${work_dir:=}" ]]; then
|
||||
local _target_dir
|
||||
if [[ "${work_dir}" == /* ]]; then
|
||||
_target_dir="${work_dir}"
|
||||
else
|
||||
_target_dir="${dir_scripts}/${work_dir}"
|
||||
fi
|
||||
if [[ -d "${_target_dir}" ]]; then
|
||||
cd "${_target_dir}"
|
||||
if [[ ${file_param} =~ "/" ]]; then
|
||||
local script_name="${file_param##*/}"
|
||||
if [[ "${use_dot_prefix}" == "true" ]]; then
|
||||
file_param="./${script_name}"
|
||||
else
|
||||
file_param="${script_name}"
|
||||
fi
|
||||
fi
|
||||
return
|
||||
fi
|
||||
t '警告:工作目录不存在 %s' "${_target_dir}"
|
||||
fi
|
||||
|
||||
cd $dir_scripts
|
||||
if [[ ${file_param} =~ "/" ]]; then
|
||||
local script_dir="${file_param%/*}"
|
||||
local script_name="${file_param##*/}"
|
||||
|
||||
if [[ -d ${script_dir} ]]; then
|
||||
cd ${script_dir}
|
||||
if [[ "${use_dot_prefix}" == "true" ]]; then
|
||||
file_param="./${script_name}"
|
||||
else
|
||||
file_param="${script_name}"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
## 正常运行单个脚本,$1:传入参数
|
||||
run_normal() {
|
||||
local file_param=$1
|
||||
@@ -90,12 +151,7 @@ run_normal() {
|
||||
random_delay "$file_param"
|
||||
fi
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ${file_param} != /* ]] && [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
enter_script_workdir
|
||||
|
||||
if [[ $isJsOrPythonFile == 'false' ]]; then
|
||||
clear_non_sh_env
|
||||
@@ -120,7 +176,7 @@ run_concurrent() {
|
||||
local env_param="$2"
|
||||
local num_param=$(echo "$3" | perl -pe "s|.*$2(.*)|\1|" | awk '{$1=$1};1')
|
||||
if [[ ! $env_param ]]; then
|
||||
echo -e "\n 缺少并发运行的环境变量参数"
|
||||
t '\n缺少并发运行的环境变量参数'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -128,12 +184,7 @@ run_concurrent() {
|
||||
time=$(date "+$mtime_format")
|
||||
single_log_time=$(format_log_time "$mtime_format" "$time")
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
enter_script_workdir
|
||||
|
||||
local j=0
|
||||
for i in ${array_run[@]}; do
|
||||
@@ -162,7 +213,7 @@ run_designated() {
|
||||
local env_param="$2"
|
||||
local num_param=$(echo "$3" | perl -pe "s|.*$2(.*)|\1|" | awk '{$1=$1};1')
|
||||
if [[ ! $env_param ]]; then
|
||||
echo -e "\n 缺少单独运行的参数 task xxx.js desi Test"
|
||||
t '\n缺少单独运行的参数 task xxx.js desi Test'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -182,12 +233,7 @@ run_designated() {
|
||||
clear_non_sh_env
|
||||
fi
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//}
|
||||
fi
|
||||
enter_script_workdir
|
||||
|
||||
envParam="${env_param}" numParam="${num_param}" $timeoutCmd $which_program $file_param "${script_params[@]}"
|
||||
}
|
||||
@@ -196,14 +242,53 @@ run_designated() {
|
||||
run_else() {
|
||||
local file_param="$1"
|
||||
|
||||
cd $dir_scripts
|
||||
local relative_path="${file_param%/*}"
|
||||
if [[ ! -z ${relative_path} ]] && [[ ${file_param} =~ "/" ]]; then
|
||||
cd ${relative_path}
|
||||
file_param=${file_param/$relative_path\//.\/}
|
||||
# 判断 file_param 本身是否是脚本文件
|
||||
local is_file_script="false"
|
||||
if [[ "$file_param" == *.js || "$file_param" == *.mjs ||
|
||||
"$file_param" == *.py || "$file_param" == *.pyc ||
|
||||
"$file_param" == *.sh || "$file_param" == *.ts ]]; then
|
||||
is_file_script="true"
|
||||
fi
|
||||
|
||||
if [[ "$is_file_script" != "true" ]]; then
|
||||
# file_param 不是脚本,从后续参数中查找脚本路径来确定工作目录
|
||||
local script_for_dir=""
|
||||
for arg in "$@"; do
|
||||
if [[ "$arg" == *.js || "$arg" == *.mjs ||
|
||||
"$arg" == *.py || "$arg" == *.pyc ||
|
||||
"$arg" == *.sh || "$arg" == *.ts ]]; then
|
||||
script_for_dir="$arg"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ -n "$script_for_dir" ]]; then
|
||||
local saved_file_param="$file_param"
|
||||
file_param="$script_for_dir"
|
||||
enter_script_workdir true
|
||||
local adjusted_script="$file_param"
|
||||
file_param="$saved_file_param"
|
||||
|
||||
shift
|
||||
local new_args=()
|
||||
for arg in "$@"; do
|
||||
if [[ "$arg" == "$script_for_dir" ]]; then
|
||||
new_args+=("$adjusted_script")
|
||||
else
|
||||
new_args+=("$arg")
|
||||
fi
|
||||
done
|
||||
set -- "${new_args[@]}"
|
||||
else
|
||||
# 没有找到脚本参数,只 cd 到 scripts 目录
|
||||
enter_script_workdir true
|
||||
shift
|
||||
fi
|
||||
else
|
||||
# file_param 本身就是脚本,直接用 enter_script_workdir 处理
|
||||
enter_script_workdir true
|
||||
shift
|
||||
fi
|
||||
|
||||
clear_non_sh_env
|
||||
$timeoutCmd $which_program $file_param "$@"
|
||||
@@ -242,7 +327,7 @@ check_nounset() {
|
||||
}
|
||||
|
||||
main() {
|
||||
if [[ $1 == *.js ]] || [[ $1 == *.py ]] || [[ $1 == *.pyc ]] || [[ $1 == *.sh ]] || [[ $1 == *.ts ]]; then
|
||||
if [[ $1 == *.js ]] || [[ $1 == *.mjs ]] || [[ $1 == *.py ]] || [[ $1 == *.pyc ]] || [[ $1 == *.sh ]] || [[ $1 == *.ts ]]; then
|
||||
if [[ $1 == *.sh ]]; then
|
||||
timeoutCmd=""
|
||||
fi
|
||||
@@ -278,15 +363,19 @@ main() {
|
||||
|
||||
handle_task_start "${task_shell_params[@]}"
|
||||
check_file "${task_shell_params[@]}"
|
||||
append_node_dependency_path
|
||||
if [[ $isJsOrPythonFile == 'false' ]]; then
|
||||
run_task_before "${task_shell_params[@]}"
|
||||
fi
|
||||
set_u_on="false"
|
||||
check_nounset
|
||||
main "${task_shell_params[@]}"
|
||||
_task_exit_code=$?
|
||||
if [[ "$set_u_on" == 'true' ]]; then
|
||||
set -u
|
||||
fi
|
||||
export NODE_PATH="${PREV_NODE_PATH}"
|
||||
unset QL_NODE_GLOBAL_PATH
|
||||
if [[ $isJsOrPythonFile == 'true' ]]; then
|
||||
export NODE_OPTIONS="${PREV_NODE_OPTIONS}"
|
||||
export PYTHONPATH="${PREV_PYTHONPATH}"
|
||||
|
||||
+20
-2
@@ -1,11 +1,29 @@
|
||||
const grpc = require('@grpc/grpc-js');
|
||||
const protoLoader = require('@grpc/proto-loader');
|
||||
const { readFileSync } = require('fs');
|
||||
const { join } = require('path');
|
||||
|
||||
class GrpcClient {
|
||||
static #certDir = join(
|
||||
process.env.QL_DATA_DIR || join(process.env.QL_DIR, 'data'),
|
||||
'config/grpc',
|
||||
);
|
||||
|
||||
static #loadTlsCredentials() {
|
||||
try {
|
||||
return grpc.credentials.createSsl(
|
||||
readFileSync(join(GrpcClient.#certDir, 'ca.crt')),
|
||||
readFileSync(join(GrpcClient.#certDir, 'client.key')),
|
||||
readFileSync(join(GrpcClient.#certDir, 'client.crt')),
|
||||
);
|
||||
} catch {
|
||||
return grpc.credentials.createInsecure();
|
||||
}
|
||||
}
|
||||
|
||||
static #config = {
|
||||
protoPath: join(process.env.QL_DIR, 'back/protos/api.proto'),
|
||||
serverAddress: `0.0.0.0:${process.env.GRPC_PORT || '5500'}`,
|
||||
serverAddress: `localhost:${process.env.GRPC_PORT || '5500'}`,
|
||||
protoOptions: {
|
||||
keepCase: true,
|
||||
longs: String,
|
||||
@@ -58,7 +76,7 @@ class GrpcClient {
|
||||
|
||||
this.#client = new apiProto.Api(
|
||||
serverAddress,
|
||||
grpc.credentials.createInsecure(),
|
||||
GrpcClient.#loadTlsCredentials(),
|
||||
grpcOptions,
|
||||
);
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const builtinModules = [
|
||||
'assert', 'buffer', 'child_process', 'cluster', 'crypto', 'dgram', 'dns',
|
||||
'events', 'fs', 'http', 'https', 'net', 'os', 'path', 'process', 'querystring',
|
||||
'readline', 'stream', 'string_decoder', 'timers', 'tls', 'tty', 'url', 'util',
|
||||
'v8', 'zlib',
|
||||
];
|
||||
|
||||
function isBareSpecifier(specifier) {
|
||||
return !specifier.startsWith('.') &&
|
||||
!specifier.startsWith('/') &&
|
||||
!specifier.startsWith('file:') &&
|
||||
!specifier.startsWith('node:') &&
|
||||
!builtinModules.includes(specifier) &&
|
||||
!builtinModules.includes(specifier.split('/')[0]);
|
||||
}
|
||||
|
||||
export function resolve(specifier, context, nextResolve) {
|
||||
if (!isBareSpecifier(specifier)) {
|
||||
return nextResolve(specifier, context);
|
||||
}
|
||||
|
||||
// 解析优先级:全局 pnpm > 系统全局
|
||||
const bases = [
|
||||
process.env.QL_NODE_GLOBAL_PATH,
|
||||
'/usr/local/lib/node_modules',
|
||||
].filter(Boolean);
|
||||
|
||||
for (const base of bases) {
|
||||
if (existsSync(join(base, specifier))) {
|
||||
return nextResolve(specifier, {
|
||||
...context,
|
||||
parentURL: new URL(`${join(base, specifier)}/`, 'file://').href,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return nextResolve(specifier, context);
|
||||
}
|
||||
@@ -1,7 +1,41 @@
|
||||
const { execSync } = require('child_process');
|
||||
const Module = require('module');
|
||||
const path = require('path');
|
||||
const client = require('./client.js');
|
||||
require(`./env.js`);
|
||||
|
||||
// 注册 ESM loader,使全局安装的包也可通过 import 导入
|
||||
try {
|
||||
Module.register(new URL('esm-loader.mjs', `file://${__dirname}/`).href);
|
||||
} catch (_) {}
|
||||
|
||||
function preferGlobalNodeModules() {
|
||||
const { QL_NODE_GLOBAL_PATH } = process.env;
|
||||
if (!QL_NODE_GLOBAL_PATH || Module._qlGlobalPathPatched) {
|
||||
return;
|
||||
}
|
||||
|
||||
const originalResolveFilename = Module._resolveFilename;
|
||||
Module._resolveFilename = function (request, parent, isMain, options) {
|
||||
if (
|
||||
!Module.builtinModules.includes(request) &&
|
||||
!request.startsWith('node:') &&
|
||||
!request.startsWith('.') &&
|
||||
!path.isAbsolute(request)
|
||||
) {
|
||||
try {
|
||||
return originalResolveFilename.call(this, request, parent, isMain, {
|
||||
...options,
|
||||
paths: [QL_NODE_GLOBAL_PATH],
|
||||
});
|
||||
} catch (error) {}
|
||||
}
|
||||
|
||||
return originalResolveFilename.call(this, request, parent, isMain, options);
|
||||
};
|
||||
Module._qlGlobalPathPatched = true;
|
||||
}
|
||||
|
||||
function expandRange(rangeStr, max) {
|
||||
const tempRangeStr = rangeStr
|
||||
.trim()
|
||||
@@ -64,7 +98,11 @@ function run() {
|
||||
const newEnvObject = JSON.parse(envStr);
|
||||
if (typeof newEnvObject === 'object' && newEnvObject !== null) {
|
||||
for (const key in newEnvObject) {
|
||||
if (Object.prototype.hasOwnProperty.call(newEnvObject, key)) {
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(newEnvObject, key) &&
|
||||
key !== 'NODE_PATH' &&
|
||||
key !== 'QL_NODE_GLOBAL_PATH'
|
||||
) {
|
||||
process.env[key] = newEnvObject[key];
|
||||
}
|
||||
}
|
||||
@@ -113,6 +151,8 @@ try {
|
||||
return;
|
||||
}
|
||||
|
||||
preferGlobalNodeModules();
|
||||
|
||||
process.on('SIGTERM', (code) => {
|
||||
process.exit(15);
|
||||
});
|
||||
|
||||
+5
-5
@@ -22,12 +22,12 @@ remove_js_log() {
|
||||
if [[ $diff_time -gt $((${days} * 86400)) ]]; then
|
||||
local log_path=$(echo "$log" | sed "s,${dir_log}/,,g")
|
||||
local result=$(find_cron_api "log_path=$log_path")
|
||||
echo -e "查询文件 $log_path"
|
||||
t '查询文件 %s' "$log_path"
|
||||
if [[ -z $result ]]; then
|
||||
echo -e "删除中~"
|
||||
t '删除中~'
|
||||
rm -vf $log
|
||||
else
|
||||
echo -e "正在被 $result 使用,跳过~"
|
||||
t '正在被 %s 使用,跳过~' "$result"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
@@ -43,8 +43,8 @@ remove_empty_dir() {
|
||||
}
|
||||
|
||||
if [[ ${days} ]]; then
|
||||
echo -e "查找旧日志文件中...\n"
|
||||
t '查找旧日志文件中...\n'
|
||||
remove_js_log
|
||||
remove_empty_dir
|
||||
echo -e "删除旧日志执行完毕\n"
|
||||
t '删除旧日志执行完毕\n'
|
||||
fi
|
||||
|
||||
+47
-28
@@ -65,17 +65,7 @@ link_name=(
|
||||
)
|
||||
|
||||
init_env() {
|
||||
local pnpm_global_path=$(pnpm root -g 2>/dev/null)
|
||||
export NODE_PATH="/usr/local/bin:/usr/local/lib/node_modules${pnpm_global_path:+:${pnpm_global_path}}"
|
||||
|
||||
# 如果存在 pnpm 全局路径,创建软链接
|
||||
if [[ -n "$pnpm_global_path" ]]; then
|
||||
# 确保目标目录存在
|
||||
mkdir -p "${dir_root}/node_modules"
|
||||
# 链接全局模块到项目的 node_modules
|
||||
ln -sf "${pnpm_global_path}/"* "${dir_root}/node_modules/" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
export NODE_PATH="/usr/local/bin:/usr/local/lib/node_modules"
|
||||
export PYTHONUNBUFFERED=1
|
||||
}
|
||||
|
||||
@@ -88,6 +78,16 @@ load_ql_envs() {
|
||||
|
||||
import_config() {
|
||||
[[ -f $file_config_user ]] && . $file_config_user
|
||||
[[ -f $dir_preload/lang_env.sh ]] && . $dir_preload/lang_env.sh
|
||||
|
||||
# 加载语言包(bash 4+ 支持 declare -A,不兼容时回退输出中文 key)
|
||||
local lang=${QL_LANG:-zh}
|
||||
local lang_file="$dir_shell/lang/${lang}.sh"
|
||||
if [[ ${BASH_VERSINFO[0]} -ge 4 ]] && [[ -f $lang_file ]]; then
|
||||
. $lang_file
|
||||
elif [[ ${BASH_VERSINFO[0]} -ge 4 ]]; then
|
||||
. "$dir_shell/lang/zh.sh"
|
||||
fi
|
||||
|
||||
load_ql_envs
|
||||
command_timeout_time=${CommandTimeoutTime:-""}
|
||||
@@ -101,6 +101,18 @@ import_config() {
|
||||
fi
|
||||
}
|
||||
|
||||
t() {
|
||||
local key="$1"
|
||||
shift
|
||||
local msg
|
||||
if declare -p LANG_MESSAGES &>/dev/null; then
|
||||
msg="${LANG_MESSAGES["$key"]}"
|
||||
fi
|
||||
[[ -z $msg ]] && msg="$key"
|
||||
# shellcheck disable=SC2059
|
||||
printf "$msg\n" "$@"
|
||||
}
|
||||
|
||||
set_proxy() {
|
||||
local proxy="$1"
|
||||
if [[ $proxy ]]; then
|
||||
@@ -235,7 +247,7 @@ npm_install_2() {
|
||||
local dir_work=$1
|
||||
|
||||
cd $dir_work
|
||||
echo -e "安装 $dir_work 依赖包...\n"
|
||||
t '安装 %s 依赖包...\n' "$dir_work"
|
||||
npm_install_sub
|
||||
cd $dir_current
|
||||
}
|
||||
@@ -254,7 +266,7 @@ git_clone_scripts() {
|
||||
local branch="$3"
|
||||
local proxy="$4"
|
||||
[[ $branch ]] && local part_cmd="-b $branch "
|
||||
echo -e "开始拉取仓库 ${uniq_path} 到 $dir\n"
|
||||
t '开始拉取仓库 %s 到 %s\n' "${uniq_path}" "$dir"
|
||||
|
||||
set_proxy "$proxy"
|
||||
|
||||
@@ -287,8 +299,8 @@ reload_pm2() {
|
||||
return 0
|
||||
else
|
||||
local exit_code=$?
|
||||
echo "警告: PM2 启动失败 (退出码: $exit_code),可能是由于硬件不兼容"
|
||||
echo "正在尝试直接使用 Node.js 启动服务..."
|
||||
t '警告: PM2 启动失败 (退出码: %s),可能是由于硬件不兼容' "$exit_code"
|
||||
t '正在尝试直接使用 Node.js 启动服务...'
|
||||
|
||||
# Kill any existing node processes for qinglong
|
||||
pkill -f "node.*static/build/app.js" 2>/dev/null || true
|
||||
@@ -297,8 +309,8 @@ reload_pm2() {
|
||||
nohup node static/build/app.js > $dir_log/qinglong.log 2>&1 &
|
||||
local node_pid=$!
|
||||
|
||||
echo "已使用 Node.js 直接启动服务 (PID: $node_pid)"
|
||||
echo "注意: 使用此模式时,部分 PM2 管理功能将不可用"
|
||||
t '已使用 Node.js 直接启动服务 (PID: %s)' "$node_pid"
|
||||
t '注意: 使用此模式时,部分 PM2 管理功能将不可用'
|
||||
return 0
|
||||
fi
|
||||
}
|
||||
@@ -370,16 +382,16 @@ handle_task_start() {
|
||||
error_message=", 任务状态更新失败(${error})"
|
||||
fi
|
||||
fi
|
||||
echo -e "## 开始执行... ${begin_time}${error_message}\n"
|
||||
t '## 开始执行... %s\n' "${begin_time}${error_message}"
|
||||
}
|
||||
|
||||
run_task_before() {
|
||||
. $file_task_before "$@"
|
||||
|
||||
if [[ ${task_before:=} ]]; then
|
||||
echo -e "执行前置命令\n"
|
||||
t '执行前置命令\n'
|
||||
eval "${task_before%;}"
|
||||
echo -e "\n执行前置命令结束\n"
|
||||
t '\n执行前置命令结束\n'
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -387,9 +399,9 @@ run_task_after() {
|
||||
. $file_task_after "$@"
|
||||
|
||||
if [[ ${task_after:=} ]]; then
|
||||
echo -e "\n执行后置命令\n"
|
||||
t '\n执行后置命令\n'
|
||||
eval "${task_after%;}"
|
||||
echo -e "\n执行后置命令结束"
|
||||
t '\n执行后置命令结束'
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -398,18 +410,25 @@ handle_task_end() {
|
||||
local end_time=$(format_time "$time_format" "$etime")
|
||||
local end_timestamp=$(format_timestamp "$time_format" "$etime")
|
||||
local diff_time=$(($end_timestamp - $begin_timestamp))
|
||||
local suffix=""
|
||||
[[ "${MANUAL:=}" == "true" ]] && suffix="(手动停止)"
|
||||
|
||||
local exit_code="${_task_exit_code:-0}"
|
||||
[[ "$diff_time" == 0 ]] && diff_time=1
|
||||
|
||||
if [[ $ID ]]; then
|
||||
local error=$(update_cron "\"$ID\"" "1" "$$" "$log_path" "$begin_timestamp" "$diff_time")
|
||||
local error=$(update_cron "\"$ID\"" "1" "$$" "$log_path" "$begin_timestamp" "$diff_time" "$exit_code")
|
||||
if [[ $error ]]; then
|
||||
error_message=", 任务状态更新失败(${error})"
|
||||
error_message=", 状态更新失败(${error})"
|
||||
fi
|
||||
fi
|
||||
echo -e "\n## 执行结束$suffix... $end_time 耗时 $diff_time 秒${error_message:=} "
|
||||
|
||||
record_cron_stat "$ID" "${exit_code:-0}" "$diff_time"
|
||||
|
||||
if [[ "${MANUAL:=}" == "true" ]]; then
|
||||
t '\n## 已停止 🛑... %s 耗时 %s 秒%s' "$end_time" "$diff_time" "${error_message:=} "
|
||||
elif [[ $exit_code -eq 0 ]]; then
|
||||
t '\n## 完成 ✅... %s 耗时 %s 秒%s' "$end_time" "$diff_time" "${error_message:=} "
|
||||
else
|
||||
t '\n## 失败 ❌(退出码 %s)... %s 耗时 %s 秒%s' "$exit_code" "$end_time" "$diff_time" "${error_message:=} "
|
||||
fi
|
||||
}
|
||||
|
||||
init_env
|
||||
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# 前置依赖 nodejs、npm、python3
|
||||
set -e
|
||||
set -x
|
||||
|
||||
if [[ ! $QL_DIR ]]; then
|
||||
npm_dir=$(npm root -g)
|
||||
pnpm_dir=$(pnpm root -g)
|
||||
if [[ -d "$npm_dir/@whyour/qinglong" ]]; then
|
||||
QL_DIR="$npm_dir/@whyour/qinglong"
|
||||
elif [[ -d "$pnpm_dir/@whyour/qinglong" ]]; then
|
||||
QL_DIR="$pnpm_dir/@whyour/qinglong"
|
||||
else
|
||||
t '未找到 qinglong 模块,请先执行 npm i -g @whyour/qinglong 安装'
|
||||
fi
|
||||
|
||||
if [[ $QL_DIR ]]; then
|
||||
t '请先手动设置 export QL_DIR=%s,环境变量,并手动添加到系统环境变量,然后再次执行命令 qinglong 启动服务' "$QL_DIR"
|
||||
fi
|
||||
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! $QL_DATA_DIR ]]; then
|
||||
t '请先手动设置数据存储目录 export QL_DATA_DIR 环境变量,目录必须以斜杠开头的绝对路径,并且以 /data 结尾,例如 /ql/data 并手动添加到系统环境变量'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ $QL_DATA_DIR != */data ]]; then
|
||||
t 'QL_DATA_DIR 必须以 /data 结尾,例如 /ql/data,如果有历史数据,请新建 data 目录,把历史数据放到 data 目录中'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
command="$1"
|
||||
|
||||
if [[ $command != "reload" ]]; then
|
||||
# 安装依赖
|
||||
os_name="${QL_OS_TYPE:-}"
|
||||
if [ -z "$os_name" ]; then
|
||||
os_name=$(source /etc/os-release && echo "$ID")
|
||||
fi
|
||||
|
||||
# 非 root 用户使用 sudo
|
||||
SUDO=""
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
SUDO="sudo"
|
||||
fi
|
||||
|
||||
case "$os_name" in
|
||||
alpine)
|
||||
$SUDO apk update
|
||||
$SUDO apk add -f bash \
|
||||
coreutils \
|
||||
git \
|
||||
curl \
|
||||
wget \
|
||||
tzdata \
|
||||
perl \
|
||||
openssl \
|
||||
jq \
|
||||
nginx \
|
||||
openssh \
|
||||
procps \
|
||||
netcat-openbsd
|
||||
;;
|
||||
debian|ubuntu)
|
||||
$SUDO apt-get update
|
||||
$SUDO apt-get install -y git curl wget tzdata perl openssl jq nginx procps netcat-openbsd openssh-client
|
||||
;;
|
||||
*)
|
||||
t '暂不支持此系统部署 %s' "$os_name"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
npm install -g pnpm@8.3.1 pm2 ts-node typescript@5
|
||||
fi
|
||||
|
||||
export PYTHON_SHORT_VERSION=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
|
||||
export PNPM_HOME=${QL_DIR}/data/dep_cache/node
|
||||
export PYTHON_HOME=${QL_DIR}/data/dep_cache/python3
|
||||
export PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3
|
||||
|
||||
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin
|
||||
export NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules:${PNPM_HOME}/global/5/node_modules
|
||||
export PIP_CACHE_DIR=${PYTHON_HOME}/pip
|
||||
export PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
|
||||
|
||||
if [[ $command != "reload" ]]; then
|
||||
pip3 install --prefix ${PYTHON_HOME} requests
|
||||
fi
|
||||
|
||||
cd ${QL_DIR}
|
||||
cp -f .env.example .env
|
||||
chmod 777 ${QL_DIR}/shell/*.sh
|
||||
|
||||
. ${QL_DIR}/shell/share.sh
|
||||
. ${QL_DIR}/shell/env.sh
|
||||
|
||||
log_with_style() {
|
||||
local level="$1"
|
||||
local message="$2"
|
||||
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
|
||||
printf "\n[%s] [%7s] %s\n" "${timestamp}" "${level}" "${message}"
|
||||
}
|
||||
|
||||
log_with_style "INFO" "🚀 1. 检测配置文件..."
|
||||
import_config "$@"
|
||||
make_dir /etc/nginx/conf.d
|
||||
make_dir /run/nginx
|
||||
fix_config
|
||||
|
||||
pm2 l &>/dev/null
|
||||
|
||||
log_with_style "INFO" "🔄 2. 启动 nginx..."
|
||||
nginx -s reload 2>/dev/null || nginx -c /etc/nginx/nginx.conf
|
||||
|
||||
log_with_style "INFO" "⚙️ 3. 启动 pm2 服务..."
|
||||
reload_pm2
|
||||
|
||||
if [[ $command != "reload" ]]; then
|
||||
if [[ $AutoStartBot == true ]]; then
|
||||
log_with_style "INFO" "🤖 4. 启动 bot..."
|
||||
nohup ql bot >$dir_log/bot.log 2>&1 &
|
||||
fi
|
||||
|
||||
if [[ $EnableExtraShell == true ]]; then
|
||||
log_with_style "INFO" "🛠️ 5. 执行自定义脚本..."
|
||||
nohup ql extra >$dir_log/extra.log 2>&1 &
|
||||
fi
|
||||
|
||||
pm2 startup
|
||||
pm2 save
|
||||
fi
|
||||
|
||||
log_with_style "SUCCESS" "🎉 启动成功!"
|
||||
+10
-2
@@ -4,9 +4,17 @@ dir_shell=$QL_DIR/shell
|
||||
. $dir_shell/share.sh
|
||||
. $dir_shell/api.sh
|
||||
|
||||
trap "single_hanle" 2 3 20 15 14 19 1
|
||||
trap 'single_hanle SIGINT' INT
|
||||
trap 'single_hanle SIGTERM' TERM
|
||||
trap 'single_hanle SIGHUP' HUP
|
||||
trap 'single_hanle SIGALRM' ALRM
|
||||
trap 'single_hanle SIGTSTP' TSTP
|
||||
trap 'single_hanle SIGQUIT' QUIT
|
||||
|
||||
single_hanle() {
|
||||
eval MANUAL=true handle_task_end "$@" "$cmd"
|
||||
_task_exit_code="${_task_exit_code:-$?}"
|
||||
[[ "$_task_exit_code" == "0" ]] && _task_exit_code="1"
|
||||
eval MANUAL=true handle_task_end "$@"
|
||||
exit 1
|
||||
}
|
||||
|
||||
|
||||
+22
-96
@@ -33,7 +33,7 @@ output_list_add_drop() {
|
||||
local list=$1
|
||||
local type=$2
|
||||
if [[ -s $list ]]; then
|
||||
echo -e "检测到有${type}的定时任务:"
|
||||
t '检测到有%s的定时任务:' "$type"
|
||||
cat $list
|
||||
fi
|
||||
}
|
||||
@@ -45,7 +45,7 @@ del_cron() {
|
||||
local path=$2
|
||||
local detail=""
|
||||
local ids=""
|
||||
echo -e "\n开始尝试自动删除失效的定时任务..."
|
||||
t '\n开始尝试自动删除失效的定时任务...'
|
||||
for cron in $(cat $list_drop); do
|
||||
local id=$(cat $list_crontab_user | grep -E "$cmd_task.* $cron" | perl -pe "s|.*ID=(.*) $cmd_task.* $cron\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
if [[ $ids ]]; then
|
||||
@@ -76,7 +76,7 @@ del_cron() {
|
||||
add_cron() {
|
||||
local list_add=$1
|
||||
local path=$2
|
||||
echo -e "\n开始尝试自动添加定时任务..."
|
||||
t '\n开始尝试自动添加定时任务...'
|
||||
local detail=""
|
||||
cd $dir_scripts
|
||||
for file in $(cat $list_add); do
|
||||
@@ -111,76 +111,6 @@ add_cron() {
|
||||
notify_api "$path 新增任务" "$detail"
|
||||
}
|
||||
|
||||
## 自动安装订阅仓库中的Python依赖
|
||||
auto_install_python_deps() {
|
||||
local repo_path="$1"
|
||||
local uniq_path="$2"
|
||||
|
||||
echo -e "\n检测订阅仓库中的Python依赖文件...\n"
|
||||
|
||||
get_token
|
||||
|
||||
# 检查 requirements.txt
|
||||
if [[ -f "${repo_path}/requirements.txt" ]]; then
|
||||
echo -e "发现 requirements.txt,开始自动安装依赖...\n"
|
||||
local req_file="${dir_scripts}/${uniq_path}/requirements.txt"
|
||||
|
||||
# 确保目标目录存在
|
||||
make_dir "${dir_scripts}/${uniq_path}"
|
||||
|
||||
# 复制文件并检查结果
|
||||
if cp -f "${repo_path}/requirements.txt" "${req_file}" 2>/dev/null; then
|
||||
# 调用API添加依赖安装任务
|
||||
local dep_name="${uniq_path}/requirements.txt"
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local result=$(curl -s --noproxy "*" "http://127.0.0.1:${ql_port}/open/dependencies?t=$currentTimeStamp" \
|
||||
-X POST \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
--data-raw "[{\"name\":\"${dep_name}\",\"type\":1,\"remark\":\"自动检测:${uniq_path} 订阅依赖\"}]" 2>/dev/null)
|
||||
|
||||
local code=$(echo "$result" | jq -r '.code' 2>/dev/null)
|
||||
if [[ "$code" == "200" ]]; then
|
||||
echo -e "已添加 requirements.txt 依赖安装任务\n"
|
||||
else
|
||||
echo -e "添加 requirements.txt 依赖失败,请手动添加\n"
|
||||
fi
|
||||
else
|
||||
echo -e "复制 requirements.txt 失败,跳过自动安装\n"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 检查 pyproject.toml
|
||||
if [[ -f "${repo_path}/pyproject.toml" ]]; then
|
||||
echo -e "发现 pyproject.toml,开始自动安装依赖...\n"
|
||||
local pyproject_file="${dir_scripts}/${uniq_path}/pyproject.toml"
|
||||
|
||||
# 确保目标目录存在
|
||||
make_dir "${dir_scripts}/${uniq_path}"
|
||||
|
||||
# 复制文件并检查结果
|
||||
if cp -f "${repo_path}/pyproject.toml" "${pyproject_file}" 2>/dev/null; then
|
||||
# 调用API添加依赖安装任务
|
||||
local dep_name="${uniq_path}/pyproject.toml"
|
||||
local currentTimeStamp=$(date +%s)
|
||||
local result=$(curl -s --noproxy "*" "http://127.0.0.1:${ql_port}/open/dependencies?t=$currentTimeStamp" \
|
||||
-X POST \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
--data-raw "[{\"name\":\"${dep_name}\",\"type\":1,\"remark\":\"自动检测:${uniq_path} 订阅依赖\"}]" 2>/dev/null)
|
||||
|
||||
local code=$(echo "$result" | jq -r '.code' 2>/dev/null)
|
||||
if [[ "$code" == "200" ]]; then
|
||||
echo -e "已添加 pyproject.toml 依赖安装任务\n"
|
||||
else
|
||||
echo -e "添加 pyproject.toml 依赖失败,请手动添加\n"
|
||||
fi
|
||||
else
|
||||
echo -e "复制 pyproject.toml 失败,跳过自动安装\n"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
## 更新仓库
|
||||
update_repo() {
|
||||
local url="$1"
|
||||
@@ -206,14 +136,10 @@ update_repo() {
|
||||
git_clone_scripts "${formatUrl}" ${repo_path} "${branch}" "${proxy}"
|
||||
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "拉取 ${uniq_path} 成功...\n"
|
||||
|
||||
# 自动检测并安装Python依赖
|
||||
auto_install_python_deps "${repo_path}" "${uniq_path}"
|
||||
|
||||
t '拉取 %s 成功...\n' "${uniq_path}"
|
||||
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions" "$autoAddCron" "$autoDelCron"
|
||||
else
|
||||
echo -e "拉取 ${uniq_path} 失败,请检查日志...\n"
|
||||
t '拉取 %s 失败,请检查日志...\n' "${uniq_path}"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -234,7 +160,7 @@ update_raw() {
|
||||
local raw_url="$url"
|
||||
local suffix="${raw_url##*.}"
|
||||
local raw_file_name="${uniq_path}.${suffix}"
|
||||
echo -e "开始下载:${raw_url} \n\n保存路径:$dir_raw/${raw_file_name}\n"
|
||||
t '开始下载:%s 保存路径:%s\n' "${raw_url}" "$dir_raw/${raw_file_name}"
|
||||
|
||||
set_proxy "$proxy"
|
||||
wget -q --no-check-certificate -O "$dir_raw/${raw_file_name}.new" ${raw_url}
|
||||
@@ -243,7 +169,7 @@ update_raw() {
|
||||
|
||||
if [[ $? -eq 0 ]]; then
|
||||
mv "$dir_raw/${raw_file_name}.new" "$dir_raw/${raw_file_name}"
|
||||
echo -e "下载 ${raw_file_name} 成功...\n"
|
||||
t '下载 %s 成功...\n' "${raw_file_name}"
|
||||
cd $dir_raw
|
||||
local filename="raw_${raw_file_name}"
|
||||
local cron_id=$(cat $list_crontab_user | grep -E "$cmd_task.* $filename" | perl -pe "s|.*ID=(.*) $cmd_task.* $filename\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
@@ -270,7 +196,7 @@ update_raw() {
|
||||
# update_cron_api "$cron_line:$cmd_task $filename:$cron_name:$cron_id"
|
||||
fi
|
||||
else
|
||||
echo -e "下载 ${raw_file_name} 失败,保留之前正常下载的版本...\n"
|
||||
t '下载 %s 失败,保留之前正常下载的版本...\n' "${raw_file_name}"
|
||||
[[ -f "$dir_raw/${raw_file_name}.new" ]] && rm -f "$dir_raw/${raw_file_name}.new"
|
||||
fi
|
||||
|
||||
@@ -281,13 +207,13 @@ run_extra_shell() {
|
||||
if [[ -f $file_extra_shell ]]; then
|
||||
. $file_extra_shell
|
||||
else
|
||||
echo -e "$file_extra_shell文件不存在,跳过执行...\n"
|
||||
t '%s文件不存在,跳过执行...\n' "$file_extra_shell"
|
||||
fi
|
||||
}
|
||||
|
||||
## 脚本用法
|
||||
usage() {
|
||||
echo -e "$cmd_update 命令使用方法:"
|
||||
t "$cmd_update 命令使用方法:"
|
||||
echo -e "1. $cmd_update update # 更新并重启青龙"
|
||||
echo -e "2. $cmd_update extra # 运行自定义脚本"
|
||||
echo -e "3. $cmd_update raw <fileurl> # 更新单个脚本文件"
|
||||
@@ -342,7 +268,7 @@ update_qinglong() {
|
||||
downloadQLUrl="https://github.com/whyour/qinglong/archive/refs/heads"
|
||||
downloadStaticUrl="https://github.com/whyour/qinglong-static/archive/refs/heads"
|
||||
fi
|
||||
echo -e "使用 ${mirror} 源更新...\n"
|
||||
t '使用 %s 源更新...\n' "${mirror}"
|
||||
|
||||
local primary_branch="master"
|
||||
if [[ "${QL_BRANCH}" == "develop" ]] || [[ "${QL_BRANCH}" == "debian" ]] || [[ "${QL_BRANCH}" == "debian-dev" ]]; then
|
||||
@@ -353,13 +279,13 @@ update_qinglong() {
|
||||
exit_status=$?
|
||||
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "更新青龙源文件成功...\n"
|
||||
t '更新青龙源文件成功...\n'
|
||||
|
||||
unzip -oq ${dir_tmp}/ql.zip -d ${dir_tmp}
|
||||
|
||||
update_qinglong_static
|
||||
else
|
||||
echo -e "更新青龙源文件失败,请检查网络...\n"
|
||||
t '更新青龙源文件失败,请检查网络...\n'
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -368,30 +294,30 @@ update_qinglong_static() {
|
||||
exit_status=$?
|
||||
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "更新青龙静态资源成功...\n"
|
||||
t '更新青龙静态资源成功...\n'
|
||||
unzip -oq ${dir_tmp}/static.zip -d ${dir_tmp}
|
||||
|
||||
check_update_dep
|
||||
else
|
||||
echo -e "更新青龙静态资源失败,请检查网络...\n"
|
||||
t '更新青龙静态资源失败,请检查网络...\n'
|
||||
fi
|
||||
}
|
||||
|
||||
check_update_dep() {
|
||||
echo -e "\n开始检测依赖...\n"
|
||||
t '\n开始检测依赖...\n'
|
||||
if [[ $(diff $dir_root/package.json ${dir_tmp}/qinglong-${primary_branch}/package.json) ]]; then
|
||||
npm_install_2 "${dir_tmp}/qinglong-${primary_branch}"
|
||||
fi
|
||||
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
echo -e "\n依赖检测安装成功...\n"
|
||||
echo -e "更新包下载成功..."
|
||||
t '\n依赖检测安装成功...\n'
|
||||
t '更新包下载成功...\n'
|
||||
|
||||
if [[ "$needRestart" == 'true' ]]; then
|
||||
reload_qinglong "system"
|
||||
fi
|
||||
else
|
||||
echo -e "\n依赖检测安装失败,请检查网络...\n"
|
||||
t '\n依赖检测安装失败,请检查网络...\n'
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -588,7 +514,7 @@ main() {
|
||||
if [[ -n $p2 ]]; then
|
||||
update_repo "$p2" "$p3" "$p4" "$p5" "$p6" "$p7" "$p8" "$p9" "$p10"
|
||||
else
|
||||
eval echo -e "命令输入错误...\\\n" $cmd
|
||||
t '命令输入错误...\n'
|
||||
eval usage $cmd
|
||||
fi
|
||||
;;
|
||||
@@ -597,7 +523,7 @@ main() {
|
||||
if [[ -n $p2 ]]; then
|
||||
update_raw "$p2" "$p3" "$p4" "$p5"
|
||||
else
|
||||
eval echo -e "命令输入错误...\\\n" $cmd
|
||||
t '命令输入错误...\n'
|
||||
eval usage $cmd
|
||||
fi
|
||||
;;
|
||||
@@ -623,7 +549,7 @@ main() {
|
||||
eval update_auth_config "\\\"username\\\":\\\"$p2\\\"" "重置用户名" $cmd
|
||||
;;
|
||||
*)
|
||||
eval echo -e "命令输入错误...\\\n" $cmd
|
||||
t '命令输入错误...\n'
|
||||
eval usage $cmd
|
||||
;;
|
||||
esac
|
||||
|
||||
@@ -66,9 +66,7 @@ const EditableTagGroup = ({
|
||||
}, [inputVisible]);
|
||||
|
||||
useEffect(() => {
|
||||
if (value) {
|
||||
setTags(value);
|
||||
}
|
||||
setTags(value || []);
|
||||
}, [value]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -29,10 +29,10 @@ const Terminal = ({
|
||||
const lastLineRef = useRef<null | HTMLElement>(null);
|
||||
|
||||
// An effect that handles scrolling into view the last line of terminal input or output
|
||||
const performScrolldown = useRef(false);
|
||||
const performScrollDown = useRef(false);
|
||||
useEffect(() => {
|
||||
if (performScrolldown.current) {
|
||||
// skip scrolldown when the component first loads
|
||||
if (performScrollDown.current) {
|
||||
// skip scrollDown when the component first loads
|
||||
setTimeout(
|
||||
() =>
|
||||
lastLineRef?.current?.scrollIntoView({
|
||||
@@ -42,7 +42,7 @@ const Terminal = ({
|
||||
500,
|
||||
);
|
||||
}
|
||||
performScrolldown.current = true;
|
||||
performScrollDown.current = true;
|
||||
}, [lineData.length]);
|
||||
|
||||
const renderedLineData = lineData.map((ld, i) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import intl from 'react-intl-universal';
|
||||
import { SettingOutlined } from '@ant-design/icons';
|
||||
import { SettingOutlined, DashboardOutlined } from '@ant-design/icons';
|
||||
import IconFont from '@/components/iconfont';
|
||||
import { BasicLayoutProps } from '@ant-design/pro-layout';
|
||||
|
||||
@@ -24,6 +24,12 @@ export default {
|
||||
hideInMenu: true,
|
||||
component: '@/pages/error/index',
|
||||
},
|
||||
{
|
||||
path: '/dashboard',
|
||||
name: intl.get('仪表盘'),
|
||||
icon: <DashboardOutlined />,
|
||||
component: '@/pages/dashboard/index',
|
||||
},
|
||||
{
|
||||
path: '/crontab',
|
||||
name: intl.get('定时任务'),
|
||||
|
||||
@@ -212,6 +212,7 @@ body {
|
||||
&.crontab-wrapper,
|
||||
&.log-wrapper,
|
||||
&.env-wrapper,
|
||||
&.dashboard-wrapper,
|
||||
&.config-wrapper {
|
||||
.CodeMirror {
|
||||
width: calc(100vw - 24px);
|
||||
|
||||
+51
-3
@@ -22,9 +22,11 @@ import WebSocketManager from '../utils/websocket';
|
||||
export interface SharedContext {
|
||||
headerStyle: React.CSSProperties;
|
||||
isPhone: boolean;
|
||||
siteTitle: string;
|
||||
theme: 'vs' | 'vs-dark';
|
||||
user: any;
|
||||
reloadUser: (needLoading?: boolean) => void;
|
||||
reloadSystemConfig: () => void;
|
||||
reloadTheme: () => void;
|
||||
systemInfo: TSystemInfo;
|
||||
}
|
||||
@@ -45,6 +47,9 @@ export default function () {
|
||||
const [user, setUser] = useState<any>({});
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [systemInfo, setSystemInfo] = useState<TSystemInfo>();
|
||||
const [siteTitle, setSiteTitle] = useState(
|
||||
() => localStorage.getItem('qinglong_panel_title')?.trim() || intl.get('青龙'),
|
||||
);
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [initLoading, setInitLoading] = useState<boolean>(true);
|
||||
const {
|
||||
@@ -89,7 +94,7 @@ export default function () {
|
||||
if (code === 200 && data.username) {
|
||||
setUser(data);
|
||||
if (location.pathname === '/') {
|
||||
history.push('/crontab');
|
||||
history.push('/dashboard');
|
||||
}
|
||||
}
|
||||
needLoading && setLoading(false);
|
||||
@@ -124,6 +129,31 @@ export default function () {
|
||||
getUser(needLoading);
|
||||
};
|
||||
|
||||
const reloadSystemConfig = () => {
|
||||
request
|
||||
.get(`${config.apiPrefix}system/config`)
|
||||
.then(({ data }: any) => {
|
||||
const panelTitle = data?.info?.panelTitle?.trim();
|
||||
if (panelTitle) {
|
||||
setSiteTitle(panelTitle);
|
||||
localStorage.setItem('qinglong_panel_title', panelTitle);
|
||||
} else {
|
||||
setSiteTitle(intl.get('青龙'));
|
||||
localStorage.removeItem('qinglong_panel_title');
|
||||
}
|
||||
if (!data?.info?.lang) {
|
||||
const browserLang =
|
||||
localStorage.getItem('lang') ||
|
||||
navigator.language?.slice(0, 2) ||
|
||||
'zh';
|
||||
request
|
||||
.put(`${config.apiPrefix}system/config/lang`, { lang: browserLang })
|
||||
.catch(() => {});
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (systemInfo && systemInfo.isInitialized && !user) {
|
||||
getUser();
|
||||
@@ -134,6 +164,19 @@ export default function () {
|
||||
getHealthStatus();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
reloadSystemConfig();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!['/login', '/initialization', '/error'].includes(location.pathname)) {
|
||||
return;
|
||||
}
|
||||
const title =
|
||||
(config.documentTitleMap as any)[location.pathname] || intl.get('未找到');
|
||||
document.title = `${title} - ${siteTitle}`;
|
||||
}, [location.pathname, siteTitle]);
|
||||
|
||||
useEffect(() => {
|
||||
if (theme === 'vs-dark') {
|
||||
document.body.setAttribute('data-dark', 'true');
|
||||
@@ -201,7 +244,7 @@ export default function () {
|
||||
|
||||
if (['/login', '/initialization', '/error'].includes(location.pathname)) {
|
||||
if (systemInfo?.isInitialized && location.pathname === '/initialization') {
|
||||
history.push('/crontab');
|
||||
history.push('/dashboard');
|
||||
}
|
||||
|
||||
if (systemInfo || location.pathname === '/error') {
|
||||
@@ -212,7 +255,10 @@ export default function () {
|
||||
theme,
|
||||
user,
|
||||
reloadUser,
|
||||
reloadSystemConfig,
|
||||
reloadTheme,
|
||||
siteTitle,
|
||||
systemInfo,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
@@ -293,7 +339,7 @@ export default function () {
|
||||
const title =
|
||||
(config.documentTitleMap as any)[location.pathname] ||
|
||||
intl.get('未找到');
|
||||
return `${title} - ${intl.get('青龙')}`;
|
||||
return `${title} - ${siteTitle}`;
|
||||
}}
|
||||
onCollapse={setCollapsed}
|
||||
collapsed={collapsed}
|
||||
@@ -355,7 +401,9 @@ export default function () {
|
||||
theme,
|
||||
user,
|
||||
reloadUser,
|
||||
reloadSystemConfig,
|
||||
reloadTheme,
|
||||
siteTitle,
|
||||
systemInfo,
|
||||
}}
|
||||
/>
|
||||
|
||||
+579
-523
File diff suppressed because it is too large
Load Diff
+577
-521
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user