mirror of
https://github.com/whyour/qinglong.git
synced 2026-11-17 15:51:07 +08:00
Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9e9e083ab | ||
|
|
8a9e70e90b | ||
|
|
3b6a873520 | ||
|
|
2ddb592800 | ||
|
|
b838d4bb42 | ||
|
|
73ad00ba32 | ||
|
|
27b322a10d | ||
|
|
1cfc0c8e2e | ||
|
|
cae580e02f | ||
|
|
76b285c3db | ||
|
|
13e0ff55d4 | ||
|
|
2bf814e562 | ||
|
|
41910b5236 | ||
|
|
442ab2c616 | ||
|
|
a5f22f8d44 | ||
|
|
f2c2f5e4f8 | ||
|
|
2efc5e4503 | ||
|
|
b92621bdb8 | ||
|
|
da9c6a6bbb | ||
|
|
d895fbba36 | ||
|
|
6862ad4f6c | ||
|
|
b8110c52eb | ||
|
|
99a4d0eff8 | ||
|
|
b486989399 | ||
|
|
77fe551425 | ||
|
|
2669f251ac | ||
|
|
3f02b04dff | ||
|
|
e8b6a30bd9 | ||
|
|
a36a77086a |
@@ -8,6 +8,10 @@ on:
|
||||
# CLI is verified separately; its shared Bash upgrade engine ships in images.
|
||||
- "!cli/**"
|
||||
- "cli/src/internal/maintenance/upgradeArtifacts.cjs"
|
||||
- "cli/src/internal/maintenance/platformBundle.cjs"
|
||||
- "cli/src/internal/maintenance/upgradePrestart.cjs"
|
||||
- "cli/src/internal/maintenance/panelUpgrade.cjs"
|
||||
- "cli/src/internal/maintenance/nodeRuntime.cjs"
|
||||
- "!.github/workflows/cli-package.yml"
|
||||
branches:
|
||||
- "master"
|
||||
@@ -29,10 +33,22 @@ on:
|
||||
type: choice
|
||||
options: [branch, tag]
|
||||
default: branch
|
||||
npm_rc_version:
|
||||
description: Publish the verified main npm RC from develop, for example 2.25.0-rc.0
|
||||
type: string
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Keep master image tags and their bundle indexes in one serialized release.
|
||||
# A rerun may intentionally replace a version, including from the same commit.
|
||||
# Develop image builds and their shared bundle index serialize separately.
|
||||
# Git-tag builds and static synchronization remain independent.
|
||||
concurrency:
|
||||
group: version-images-${{ github.ref == 'refs/heads/master' && 'master' || (github.ref == 'refs/heads/develop' && !inputs.static_sync_only && 'develop') || format('{0}-{1}', github.run_id, github.run_attempt) }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
if: ${{ !inputs.static_sync_only }}
|
||||
@@ -68,7 +84,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
@@ -79,6 +95,9 @@ jobs:
|
||||
pnpm build:back
|
||||
pnpm build:info
|
||||
|
||||
- name: Pack the npm panel archive from the verified build
|
||||
run: node scripts/verify-panel-package.cjs pack "$RUNNER_TEMP/npm-panel"
|
||||
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: qinglong-static-${{ github.sha }}
|
||||
@@ -86,19 +105,31 @@ jobs:
|
||||
if-no-files-found: error
|
||||
include-hidden-files: true
|
||||
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: qinglong-npm-${{ github.sha }}
|
||||
path: ${{ runner.temp }}/npm-panel/
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
- name: copy to static repo
|
||||
env:
|
||||
GITHUB_REPO: github.com/${{ github.repository_owner }}/qinglong-static
|
||||
GITHUB_BRANCH: ${{ github.ref_name }}
|
||||
GITHUB_REF_TYPE: ${{ github.ref_type }}
|
||||
STATIC_TOKEN: ${{ secrets.API_TOKEN }}
|
||||
run: |
|
||||
bash scripts/publish-static.sh "https://${{ secrets.API_TOKEN }}@${GITHUB_REPO}.git" "$GITHUB_BRANCH" "$GITHUB_REF_TYPE"
|
||||
: "${STATIC_TOKEN:?Missing static repository token}"
|
||||
bash scripts/publish-static.sh "https://x-access-token:${STATIC_TOKEN}@${GITHUB_REPO}.git" "$GITHUB_BRANCH" "$GITHUB_REF_TYPE"
|
||||
|
||||
- name: publish verified upgrade download sizes
|
||||
env:
|
||||
GITHUB_REPO: github.com/${{ github.repository_owner }}/qinglong-static
|
||||
GITHUB_BRANCH: ${{ github.ref_name }}
|
||||
run: node scripts/publish-upgrade-info.cjs "https://${{ secrets.API_TOKEN }}@${GITHUB_REPO}.git" "$GITHUB_BRANCH" "$GITHUB_SHA"
|
||||
STATIC_TOKEN: ${{ secrets.API_TOKEN }}
|
||||
run: |
|
||||
: "${STATIC_TOKEN:?Missing static repository token}"
|
||||
node scripts/publish-upgrade-info.cjs "https://x-access-token:${STATIC_TOKEN}@${GITHUB_REPO}.git" "$GITHUB_BRANCH" "$GITHUB_SHA"
|
||||
|
||||
static_gitlab:
|
||||
needs: build-static
|
||||
@@ -203,6 +234,8 @@ jobs:
|
||||
build-alpine:
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
needs: build-static
|
||||
outputs:
|
||||
image-digest: ${{ steps.image.outputs.digest }}
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
packages: write
|
||||
@@ -218,7 +251,7 @@ jobs:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "24"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
@@ -268,6 +301,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Build and push (Alpine)
|
||||
id: image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
build-args: |
|
||||
@@ -289,6 +323,8 @@ jobs:
|
||||
build-debian:
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
needs: build-static
|
||||
outputs:
|
||||
image-digest: ${{ steps.image.outputs.digest }}
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
packages: write
|
||||
@@ -304,7 +340,7 @@ jobs:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "24"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
@@ -353,6 +389,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Build and push (Debian)
|
||||
id: image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
build-args: |
|
||||
@@ -361,7 +398,7 @@ jobs:
|
||||
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
|
||||
platforms: linux/amd64,linux/arm64,linux/ppc64le,linux/s390x
|
||||
context: .
|
||||
file: ./docker/Dockerfile.debian
|
||||
push: true
|
||||
@@ -372,175 +409,78 @@ jobs:
|
||||
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
|
||||
# One unmodified amd64 package for migration acceptance only. This does not
|
||||
# publish bundles or advance development/formal channel indexes.
|
||||
build-npm-migration-bundle:
|
||||
needs: build-debian
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: qinglong-static-${{ github.sha }}
|
||||
path: static/
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Read version from version.yaml
|
||||
id: version
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
- name: Export the official platform package from this run's image digest
|
||||
env:
|
||||
IMAGE_DIGEST: ${{ needs.build-debian.outputs.image-digest }}
|
||||
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
|
||||
set -euo pipefail
|
||||
[[ "$IMAGE_DIGEST" =~ ^sha256:[a-f0-9]{64}$ ]]
|
||||
image="ghcr.io/${GITHUB_REPOSITORY}@${IMAGE_DIGEST}"
|
||||
docker buildx build --platform linux/amd64 --build-arg "BASE_IMAGE=$image" --file docker/Dockerfile.upgrade-bundle --output "type=local,dest=$RUNNER_TEMP/npm-migration-bundle" .
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
name: npm-migration-bundle-${{ github.sha }}
|
||||
path: ${{ runner.temp }}/npm-migration-bundle/*
|
||||
if-no-files-found: error
|
||||
retention-days: 3
|
||||
|
||||
- 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: |
|
||||
QL_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
|
||||
provenance: mode=max
|
||||
sbom: true
|
||||
tags: |
|
||||
whyour/qinglong:python3.10
|
||||
whyour/qinglong:${{ steps.version.outputs.version }}-python3.10
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache-alpine-python3.10
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache-alpine-python3.10,mode=max
|
||||
|
||||
build-debian310:
|
||||
if: ${{ github.ref_name == 'master' }}
|
||||
needs: build-static
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
verify-npm-package:
|
||||
needs: [build-static, build-npm-migration-bundle]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node: ['20.18.1', '24']
|
||||
container: node:${{ matrix.node }}-bookworm
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/download-artifact@v7
|
||||
- uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: qinglong-static-${{ github.sha }}
|
||||
path: static/
|
||||
- uses: pnpm/action-setup@v6
|
||||
name: qinglong-npm-${{ github.sha }}
|
||||
path: ${{ runner.temp }}/npm-panel/
|
||||
- uses: actions/download-artifact@v6
|
||||
with:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Read version from version.yaml
|
||||
id: version
|
||||
name: npm-migration-bundle-${{ github.sha }}
|
||||
path: ${{ runner.temp }}/npm-migration-bundle/
|
||||
- name: Install isolated service test tools
|
||||
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
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends python3 openssl curl jq nginx procps
|
||||
# The published legacy launcher resets PATH to standard directories.
|
||||
# /usr/local is confined to this disposable job container; PM2_HOME
|
||||
# remains private to each verification run.
|
||||
npm install --global --prefix /usr/local --no-audit --no-fund pm2@6.0.14
|
||||
- name: Install and upgrade the exact npm archive
|
||||
env:
|
||||
QL_PANEL_PACKAGE_TEST_ISOLATED: '1'
|
||||
QL_PANEL_TEST_PM2: /usr/local/bin/pm2
|
||||
QL_PANEL_TEST_BUNDLE_DIR: ${{ runner.temp }}/npm-migration-bundle
|
||||
run: node scripts/verify-panel-package.cjs verify "$RUNNER_TEMP/npm-panel" "$RUNNER_TEMP/npm-panel-results"
|
||||
- uses: actions/upload-artifact@v6
|
||||
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: |
|
||||
QL_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
|
||||
provenance: mode=max
|
||||
sbom: 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
|
||||
name: qinglong-npm-verification-${{ matrix.node }}-${{ github.sha }}
|
||||
path: ${{ runner.temp }}/npm-panel-results/
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
publish:
|
||||
if: ${{ github.repository == 'whyour/qinglong' && github.ref == 'refs/heads/master' }}
|
||||
needs: [build-alpine, build-debian, build-alpine310, build-debian310]
|
||||
if: ${{ github.repository == 'whyour/qinglong' && (github.ref == 'refs/heads/master' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/develop')) }}
|
||||
needs: [build-alpine, build-debian, verify-npm-package]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: "8.3.1"
|
||||
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: build front and back
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm build:front
|
||||
pnpm build:back
|
||||
|
||||
- name: Set up Node for trusted publishing
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
@@ -548,18 +488,124 @@ jobs:
|
||||
registry-url: https://registry.npmjs.org
|
||||
package-manager-cache: false
|
||||
|
||||
- uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: qinglong-npm-${{ github.sha }}
|
||||
path: npm-panel/
|
||||
|
||||
- name: Publish npm package with OIDC
|
||||
shell: bash
|
||||
env:
|
||||
NPM_RC_VERSION: ${{ inputs.npm_rc_version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
name=$(node -p 'require("./package.json").name')
|
||||
version=$(node -p 'require("./package.json").version')
|
||||
shopt -s nullglob
|
||||
archives=(npm-panel/*.tgz)
|
||||
if [ "${#archives[@]}" -ne 1 ]; then
|
||||
echo '::error::Expected exactly one verified panel npm archive.'
|
||||
exit 1
|
||||
fi
|
||||
archive="${archives[0]}"
|
||||
metadata=$(tar -xOf "$archive" package/package.json)
|
||||
name=$(jq -er '.name | select(. == "@whyour/qinglong")' <<< "$metadata")
|
||||
version=$(jq -er '.version | select(type == "string")' <<< "$metadata")
|
||||
if [[ "${GITHUB_EVENT_NAME:-}" == workflow_dispatch && "${GITHUB_REF:-}" == refs/heads/develop ]]; then
|
||||
if [[ ! "${NPM_RC_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-rc\.[0-9]+$ || "$version" != "${NPM_RC_VERSION:-}" ]]; then
|
||||
echo '::error::Develop npm publication requires the exact requested RC archive version.'
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
if npm view "$name@$version" version --json --registry=https://registry.npmjs.org > "$RUNNER_TEMP/npm-version.json" 2> "$RUNNER_TEMP/npm-version-error.log"; then
|
||||
jq -e --arg version "$version" '. == $version' "$RUNNER_TEMP/npm-version.json" > /dev/null
|
||||
echo "::notice::$name@$version is already published; skipping npm publication for this image rebuild."
|
||||
elif jq -e '.error.code == "E404"' "$RUNNER_TEMP/npm-version.json" > /dev/null; then
|
||||
npm publish --access public --registry=https://registry.npmjs.org
|
||||
if [[ "${GITHUB_EVENT_NAME:-}" == workflow_dispatch && "${GITHUB_REF:-}" == refs/heads/develop ]]; then
|
||||
npm publish "./$archive" --ignore-scripts --access public --tag rc --registry=https://registry.npmjs.org
|
||||
else
|
||||
npm publish "./$archive" --ignore-scripts --access public --registry=https://registry.npmjs.org
|
||||
fi
|
||||
else
|
||||
echo '::error::Could not check the published npm version; refusing to publish.'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
build-upgrade-bundles:
|
||||
# Both channels publish packages from this run's immutable image digests.
|
||||
if: ${{ !inputs.static_sync_only && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop') }}
|
||||
needs: [build-alpine, build-debian]
|
||||
# Node 24 can SIGILL while archiving ARM64 musl under x64 QEMU.
|
||||
runs-on: ${{ matrix.platform == 'linux/arm64' && 'ubuntu-24.04-arm' || 'ubuntu-22.04' }}
|
||||
timeout-minutes: 90
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { platform: linux/amd64, libc: musl, name: x64-musl }
|
||||
- { platform: linux/arm/v6, libc: musl, name: armv6-musl }
|
||||
- { platform: linux/arm/v7, libc: musl, name: armv7-musl }
|
||||
- { platform: linux/arm64, libc: musl, name: arm64-musl }
|
||||
- { platform: linux/ppc64le, libc: musl, name: ppc64-musl }
|
||||
- { platform: linux/s390x, libc: musl, name: s390x-musl }
|
||||
- { platform: linux/386, libc: musl, name: ia32-musl }
|
||||
- { platform: linux/amd64, libc: glibc, name: x64-glibc }
|
||||
- { platform: linux/arm64, libc: glibc, name: arm64-glibc }
|
||||
- { platform: linux/ppc64le, libc: glibc, name: ppc64-glibc }
|
||||
- { platform: linux/s390x, libc: glibc, name: s390x-glibc }
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: docker/setup-qemu-action@v4
|
||||
if: ${{ matrix.platform != 'linux/arm64' }}
|
||||
with:
|
||||
cache-image: false
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
- name: Build and probe the immutable platform package
|
||||
env:
|
||||
ALPINE_DIGEST: ${{ needs.build-alpine.outputs.image-digest }}
|
||||
DEBIAN_DIGEST: ${{ needs.build-debian.outputs.image-digest }}
|
||||
BUNDLE_LIBC: ${{ matrix.libc }}
|
||||
BUNDLE_PLATFORM: ${{ matrix.platform }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
digest="$ALPINE_DIGEST"
|
||||
if [ "$BUNDLE_LIBC" = glibc ]; then digest="$DEBIAN_DIGEST"; fi
|
||||
test -n "$digest"
|
||||
image="ghcr.io/${GITHUB_REPOSITORY}@${digest}"
|
||||
docker buildx build --platform "$BUNDLE_PLATFORM" --build-arg "BASE_IMAGE=$image" --file docker/Dockerfile.upgrade-bundle --output type=local,dest=output/upgrade .
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: upgrade-${{ matrix.name }}-${{ github.sha }}
|
||||
path: output/upgrade/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish-upgrade-bundles:
|
||||
if: ${{ !inputs.static_sync_only && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop') }}
|
||||
needs: build-upgrade-bundles
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
concurrency:
|
||||
group: upgrade-channel-${{ github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '24'
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: '8.3.1'
|
||||
- run: pnpm install --prod --frozen-lockfile
|
||||
- run: npm --prefix cli ci
|
||||
- uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: upgrade-*-${{ github.sha }}
|
||||
path: output/upgrade
|
||||
merge-multiple: true
|
||||
- run: node scripts/build-bundle-installer.cjs output/upgrade/install-bundle.cjs
|
||||
- name: Publish complete packages before advancing the channel
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: node scripts/publish-upgrade-bundles.cjs output/upgrade "$GITHUB_SHA" "$GITHUB_REPOSITORY" "$GITHUB_REF_NAME"
|
||||
|
||||
@@ -25,7 +25,7 @@ on:
|
||||
type: boolean
|
||||
default: false
|
||||
prerelease_version:
|
||||
description: Develop only, e.g. 0.1.2-beta.0 (alpha/beta/rc)
|
||||
description: Develop only, e.g. 0.1.5-beta.0 (alpha/beta/rc)
|
||||
type: string
|
||||
default: ''
|
||||
|
||||
@@ -93,8 +93,26 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
platform-smoke:
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest, ubuntu-24.04-arm]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: npm
|
||||
cache-dependency-path: cli/package-lock.json
|
||||
- run: npm ci --prefix cli --no-audit --no-fund
|
||||
- run: npm run build:cli
|
||||
- run: node --test cli/test/remote/platformSmoke.test.cjs
|
||||
|
||||
publish:
|
||||
needs: package
|
||||
needs: [package, platform-smoke]
|
||||
if: >-
|
||||
github.repository == 'whyour/qinglong' &&
|
||||
((github.ref == 'refs/heads/master' &&
|
||||
|
||||
@@ -6,6 +6,11 @@ on:
|
||||
- '.github/workflows/release-readiness.yml'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'docker/Dockerfile*'
|
||||
- 'shell/node-runtime-probe.cjs'
|
||||
- 'scripts/verify-panel-package.cjs'
|
||||
- 'scripts/verify-image-node-layers.py'
|
||||
- 'test/back/node-runtime-probe.test.cjs'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -41,6 +46,13 @@ jobs:
|
||||
path: static/
|
||||
include-hidden-files: true
|
||||
if-no-files-found: error
|
||||
- name: Pack the verified npm archive for isolated runtime validation
|
||||
run: node scripts/verify-panel-package.cjs pack "$RUNNER_TEMP/npm-panel"
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: release-readiness-npm-panel
|
||||
path: ${{ runner.temp }}/npm-panel/
|
||||
if-no-files-found: error
|
||||
|
||||
images:
|
||||
needs: [regression, static]
|
||||
@@ -57,15 +69,7 @@ jobs:
|
||||
- image: debian
|
||||
file: docker/Dockerfile.debian
|
||||
cache: debian
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x
|
||||
- image: alpine-python3.10
|
||||
file: docker/Dockerfile.310
|
||||
cache: alpine-python3.10
|
||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386
|
||||
- image: debian-python3.10
|
||||
file: docker/Dockerfile.debian310
|
||||
cache: debian-python3.10
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x
|
||||
platforms: linux/amd64,linux/arm64,linux/ppc64le,linux/s390x
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
@@ -121,16 +125,47 @@ jobs:
|
||||
docker run --rm --network none --entrypoint node \
|
||||
qinglong-readiness:${{ matrix.image }} \
|
||||
-e 'const assert=require("node:assert/strict"); const {createRequire}=require("node:module"); for(const [name,want] of Object.entries({"@grpc/grpc-js":"1.14.5",compression:"1.8.2",multer:"2.4.0",sequelize:"6.37.8"}))assert.equal(require(name+"/package.json").version,want); const expressRequire=createRequire(require.resolve("express")); assert.equal(expressRequire("proxy-addr/package.json").version,"2.0.8"); const sockRequire=createRequire(require.resolve("sockjs")); assert.equal(sockRequire("websocket-driver/package.json").version,"0.7.5"); require("sqlite3"); require("nodemailer"); require("undici"); console.log("Minimal production patches and runtime imports verified")'
|
||||
- name: Export native Debian image for isolated dev validation
|
||||
if: matrix.image == 'debian'
|
||||
run: |
|
||||
docker save qinglong-readiness:debian | gzip -1 > release-readiness-debian-image.tar.gz
|
||||
sha256sum release-readiness-debian-image.tar.gz > release-readiness-debian-image.sha256
|
||||
docker image inspect qinglong-readiness:debian > release-readiness-debian-image.json
|
||||
- uses: actions/upload-artifact@v6
|
||||
if: matrix.image == 'debian'
|
||||
- name: Load ARMv6 image for SQLite and Node regression checks
|
||||
if: startsWith(matrix.image, 'alpine')
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
name: release-readiness-debian-image
|
||||
path: release-readiness-debian-image.*
|
||||
context: .
|
||||
file: ${{ matrix.file }}
|
||||
platforms: linux/arm/v6
|
||||
build-args: |
|
||||
QL_URL=${{ steps.source.outputs.url }}
|
||||
QL_BRANCH=${{ steps.source.outputs.branch }}
|
||||
SOURCE_COMMIT=${{ steps.source.outputs.sha }}
|
||||
tags: qinglong-readiness:${{ matrix.image }}-armv6
|
||||
load: true
|
||||
push: false
|
||||
provenance: false
|
||||
sbom: false
|
||||
- name: Verify ARMv6 SQLite on an ARM1176 CPU without networking
|
||||
if: startsWith(matrix.image, 'alpine')
|
||||
run: |
|
||||
docker run --rm --network none --platform linux/arm/v6 \
|
||||
-e QEMU_CPU=arm1176 --entrypoint node \
|
||||
qinglong-readiness:${{ matrix.image }}-armv6 --jitless \
|
||||
-e 'const assert=require("node:assert/strict"); const sqlite3=require("sqlite3"); const db=new sqlite3.Database(":memory:"); db.get("SELECT 42 AS n",(error,row)=>{assert.ifError(error); assert.equal(row.n,42); db.close()});'
|
||||
- name: Check Node binaries in every serialized image layer
|
||||
if: startsWith(matrix.image, 'alpine')
|
||||
run: |
|
||||
docker save qinglong-readiness:${{ matrix.image }} -o "$RUNNER_TEMP/node-layers-amd64.tar"
|
||||
docker save qinglong-readiness:${{ matrix.image }}-armv6 -o "$RUNNER_TEMP/node-layers-arm.tar"
|
||||
python3 scripts/verify-image-node-layers.py "$RUNNER_TEMP/node-layers-amd64.tar" amd64
|
||||
python3 scripts/verify-image-node-layers.py "$RUNNER_TEMP/node-layers-arm.tar" arm
|
||||
rm "$RUNNER_TEMP/node-layers-amd64.tar" "$RUNNER_TEMP/node-layers-arm.tar"
|
||||
- name: Export native image for isolated dev validation
|
||||
if: matrix.image == 'debian' || matrix.image == 'alpine'
|
||||
run: |
|
||||
docker save qinglong-readiness:${{ matrix.image }} | gzip -1 > release-readiness-${{ matrix.image }}-image.tar.gz
|
||||
sha256sum release-readiness-${{ matrix.image }}-image.tar.gz > release-readiness-${{ matrix.image }}-image.sha256
|
||||
docker image inspect qinglong-readiness:${{ matrix.image }} > release-readiness-${{ matrix.image }}-image.json
|
||||
- uses: actions/upload-artifact@v6
|
||||
if: matrix.image == 'debian' || matrix.image == 'alpine'
|
||||
with:
|
||||
name: release-readiness-${{ matrix.image }}-image
|
||||
path: release-readiness-${{ matrix.image }}-image.*
|
||||
compression-level: 0
|
||||
if-no-files-found: error
|
||||
|
||||
@@ -29,6 +29,7 @@ __pycache__
|
||||
/shell/preload/*-notify.json
|
||||
/shell/preload/__ql_notify__.*
|
||||
/shell/preload/lang_env.sh
|
||||
/shell/upgrade-lock.yaml
|
||||
|
||||
.deepseek/
|
||||
.claude/
|
||||
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
/.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
|
||||
+122
-11
@@ -1,4 +1,10 @@
|
||||
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
|
||||
import { readDailyResults } from '../shared/legacyDailyStatistics';
|
||||
import { PendingCronInstall } from '../shared/errors';
|
||||
import { triggerHistory } from '../shared/triggerHistory';
|
||||
import { previewSchedule, withNextRun } from '../shared/cronPreview';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { literal, Op } from 'sequelize';
|
||||
import { Container } from 'typedi';
|
||||
import { Logger } from 'winston';
|
||||
import CronService from '../services/cron';
|
||||
@@ -164,14 +170,25 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.crontabs(req.query as any);
|
||||
return res.send({ code: 200, data });
|
||||
const result = await cronService.crontabs(req.query as any, true);
|
||||
return res.send({ code: 200, data: { ...result, data: result.data.map(withNextRun) } });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
});
|
||||
|
||||
route.get('/preview', celebrate({ query: Joi.object({
|
||||
schedule: Joi.string().required(),
|
||||
}).unknown(true) }), (req, res) => {
|
||||
try {
|
||||
const times = previewSchedule(String(req.query.schedule), 3, Date.now());
|
||||
return res.send({ code: 200, data: { times, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone } });
|
||||
} catch {
|
||||
return res.status(400).send({ code: 400, message: t('Cron表达式格式有误') });
|
||||
}
|
||||
});
|
||||
|
||||
route.get(
|
||||
'/detail',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -199,6 +216,11 @@ export default (app: Router) => {
|
||||
const data = await cronService.create(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
if (e instanceof PendingCronInstall) {
|
||||
return res.status(e.status).send({
|
||||
code: e.status, message: e.message, data: { id: e.cronId, saved: false },
|
||||
});
|
||||
}
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -224,13 +246,14 @@ export default (app: Router) => {
|
||||
route.put(
|
||||
'/stop',
|
||||
celebrate({
|
||||
headers: Joi.object({ 'idempotency-key': Joi.string().guid().optional() }).unknown(true),
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.stop(req.body);
|
||||
const data = await cronService.stop(req.body, req.get('Idempotency-Key'));
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
@@ -322,6 +345,11 @@ export default (app: Router) => {
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
query: Joi.object({
|
||||
triggerId: Joi.string().max(256).optional(),
|
||||
instanceId: Joi.number().integer().positive().optional(),
|
||||
previousPath: Joi.string().optional(),
|
||||
follow: Joi.boolean().optional(),
|
||||
cursor: Joi.string().pattern(/^\d{1,16}\.[a-f0-9]{64}$/).optional(),
|
||||
offset: Joi.number().integer().min(0).optional(),
|
||||
limit: Joi.number()
|
||||
.integer()
|
||||
@@ -337,6 +365,11 @@ export default (app: Router) => {
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const result = await cronService.log(req.params.id, {
|
||||
triggerId: req.query.triggerId as string | undefined,
|
||||
instanceId: req.query.instanceId === undefined ? undefined : Number(req.query.instanceId),
|
||||
previousPath: req.query.previousPath as string | undefined,
|
||||
follow: req.query.follow as unknown as boolean,
|
||||
cursor: req.query.cursor as string | undefined,
|
||||
offset: req.query.offset as unknown as number,
|
||||
limit: req.query.limit as unknown as number,
|
||||
tail: req.query.tail as unknown as boolean,
|
||||
@@ -345,6 +378,10 @@ export default (app: Router) => {
|
||||
code: 200,
|
||||
data: result.content,
|
||||
logStatus: result.status,
|
||||
logPath: result.logPath,
|
||||
triggerId: result.triggerId,
|
||||
cursor: result.cursor,
|
||||
reset: result.reset,
|
||||
offset: result.offset,
|
||||
nextOffset: result.nextOffset,
|
||||
total: result.total,
|
||||
@@ -379,7 +416,10 @@ export default (app: Router) => {
|
||||
route.delete(
|
||||
'/',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
body: Joi.array().min(1).items(Joi.number().integer().positive(), Joi.object({
|
||||
id: Joi.number().integer().positive().required(), script: Joi.string().required(),
|
||||
revision: Joi.number().integer(), command: Joi.string(), sub_id: Joi.number().integer().allow(null),
|
||||
})),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
@@ -452,8 +492,8 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.getDb({ id: req.params.id });
|
||||
return res.send({ code: 200, data });
|
||||
const data = await cronService.getDb({ id: req.params.id }, true);
|
||||
return res.send({ code: 200, data: withNextRun(data) });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
@@ -471,13 +511,19 @@ export default (app: Router) => {
|
||||
last_running_time: Joi.number().optional().allow(null),
|
||||
last_execution_time: Joi.number().optional().allow(null),
|
||||
exit_code: Joi.number().optional().allow(null),
|
||||
}),
|
||||
trigger_stopped: Joi.boolean().optional(),
|
||||
execution_id: Joi.string().pattern(executionIdPattern).optional(),
|
||||
trigger_id: Joi.string().pattern(/^[a-z0-9-]{1,120}$/).optional(),
|
||||
}).oxor('execution_id', 'trigger_id'),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const { execution_id, ...body } = req.body;
|
||||
const data = await cronService.status({
|
||||
...req.body,
|
||||
...body,
|
||||
finished_at: receiptFinishTime(req.get('X-QL-Finished-At')),
|
||||
...(execution_id && { trigger_id: executionTriggerId(execution_id) }),
|
||||
status: req.body.status ? parseInt(req.body.status) : undefined,
|
||||
pid: req.body.pid ? parseInt(req.body.pid) : undefined,
|
||||
});
|
||||
@@ -488,22 +534,87 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
|
||||
route.get('/:id/daily-results', celebrate({
|
||||
params: Joi.object({ id: Joi.number().integer().positive().required() }),
|
||||
}), async (req, res, next) => {
|
||||
try {
|
||||
const data = await readDailyResults(RunningInstanceModel.sequelize!, Number(req.params.id));
|
||||
return res.send({ code: 200, data });
|
||||
} catch (error) {
|
||||
return next(error);
|
||||
}
|
||||
});
|
||||
|
||||
route.get('/:id/triggers', celebrate({
|
||||
params: Joi.object({ id: Joi.number().integer().positive().required() }),
|
||||
query: Joi.object({
|
||||
offset: Joi.number().integer().min(0),
|
||||
limit: Joi.number().integer().min(1).max(26).default(25),
|
||||
ids: Joi.array().items(Joi.string().max(256)).min(1).max(25).single(),
|
||||
beforeTime: Joi.number().integer().min(0),
|
||||
beforeId: Joi.string().max(256),
|
||||
}).and('beforeTime', 'beforeId').oxor('offset', 'beforeTime', 'ids').unknown(true),
|
||||
}), async (req, res, next) => {
|
||||
try {
|
||||
const { offset, limit, beforeTime, beforeId, ids } = req.query;
|
||||
const history = triggerHistory();
|
||||
const before = beforeId ? { time: Number(beforeTime), id: String(beforeId) } : undefined;
|
||||
const data = ids
|
||||
? await history.visibleTriggers(Number(req.params.id), ids as string[])
|
||||
: await history.recent(Number(req.params.id), Number(offset || 0), Number(limit), before);
|
||||
if (req.query.withQueueWait === 'true') {
|
||||
const now = Date.now();
|
||||
return res.send({ code: 200, data: data.map(row => row.state === 'queued' && row.queued_at != null
|
||||
? { ...row, queue_wait_ms: Math.max(0, (row.dequeued_at ?? now) - row.queued_at) } : row) });
|
||||
}
|
||||
return res.send({ code: 200, data });
|
||||
} catch (err) { next(err); }
|
||||
});
|
||||
|
||||
route.get(
|
||||
'/:id/instances',
|
||||
celebrate({
|
||||
// This route historically ignored query parameters. Only validate and
|
||||
// apply cursor options when the caller explicitly requests pagination.
|
||||
query: Joi.alternatives().conditional(Joi.object({ paged: Joi.valid('true').required() }).unknown(), {
|
||||
then: Joi.object({
|
||||
limit: Joi.number().integer().min(1).max(100),
|
||||
before: Joi.number().integer().positive(),
|
||||
ids: Joi.string().pattern(/^\d+(,\d+){0,99}$/),
|
||||
}).unknown(true).oxor('ids', 'limit').oxor('ids', 'before'),
|
||||
otherwise: Joi.object().unknown(true),
|
||||
}),
|
||||
params: Joi.object({
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
// The instance row may retain a provisional end for cleanup after a restart.
|
||||
const pending = `EXISTS (SELECT 1 FROM CronTriggers t WHERE t.instance_id=RunningInstance.id
|
||||
AND (t.exit_pending=1 OR (t.state='unknown' AND t.reason='restart')))`;
|
||||
const paged = req.query.paged === 'true';
|
||||
const ids = paged && req.query.ids ? String(req.query.ids).split(',').map(Number) : undefined;
|
||||
const limit = paged && !ids ? Number(req.query.limit ?? 25) : undefined;
|
||||
const instances = await RunningInstanceModel.findAll({
|
||||
attributes: {
|
||||
exclude: ['finished_at', 'exit_code'],
|
||||
include: [
|
||||
[literal(`CASE WHEN ${pending} THEN NULL ELSE finished_at END`), 'finished_at'],
|
||||
[literal(`CASE WHEN ${pending} THEN NULL ELSE exit_code END`), 'exit_code'],
|
||||
],
|
||||
},
|
||||
where: {
|
||||
cron_id: req.params.id,
|
||||
...(ids && { id: { [Op.in]: ids } }),
|
||||
...(paged && req.query.before && { id: { [Op.lt]: Number(req.query.before) } }),
|
||||
},
|
||||
order: [['started_at', 'DESC']],
|
||||
order: paged ? [['id', 'DESC']] : [['started_at', 'DESC'], ['id', 'DESC']],
|
||||
...(limit && { limit: limit + 1 }),
|
||||
raw: true,
|
||||
});
|
||||
if (limit) return res.send({ code: 200, data: instances.slice(0, limit),
|
||||
next: instances.length > limit ? instances[limit - 1].id : null });
|
||||
return res.send({ code: 200, data: instances });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
@@ -522,8 +633,8 @@ export default (app: Router) => {
|
||||
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);
|
||||
const data = await cronService.stopInstance(Number(req.params.id), Number(req.params.instanceId));
|
||||
return res.status(data.code).send(data);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
|
||||
+43
-51
@@ -1,3 +1,7 @@
|
||||
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
|
||||
import { oldestQueued } from '../shared/queueDiagnostics';
|
||||
import { containerResources } from '../shared/containerResources';
|
||||
import { TriggerHistory } from '../shared/triggerHistory';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
import { fn, col, where, Op } from 'sequelize';
|
||||
@@ -12,6 +16,11 @@ import os from 'os';
|
||||
import { isEmpty } from 'lodash';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
|
||||
function averageElapsed(totalTime: number, runs: number, untimed: number) {
|
||||
const samples = Number(runs) - (Number(untimed) || 0);
|
||||
return samples > 0 ? Math.round(Number(totalTime) / samples) : 0;
|
||||
}
|
||||
|
||||
const route = Router();
|
||||
|
||||
export default (app: Router) => {
|
||||
@@ -19,41 +28,24 @@ export default (app: Router) => {
|
||||
|
||||
route.post('/record', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { ref_id, code, elapsed } = req.body;
|
||||
const { ref_id, code, elapsed, trigger_id, execution_id } = 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,
|
||||
});
|
||||
if (trigger_id != null && (typeof trigger_id !== 'string' || !/^[a-z0-9-]{1,120}$/.test(trigger_id))) {
|
||||
return res.send({ code: 400 });
|
||||
}
|
||||
|
||||
if (execution_id !== undefined && (trigger_id !== undefined ||
|
||||
typeof execution_id !== 'string' || !executionIdPattern.test(execution_id))) return res.send({ code: 400 });
|
||||
const id = execution_id ? executionTriggerId(execution_id) : trigger_id;
|
||||
// Old wrappers also send a status receipt with the process identity.
|
||||
// A stats-only retry cannot be distinguished from another identical run.
|
||||
if (!id) return res.send({ code: 200, data: { counted: false, reason: 'missing_execution_identity' } });
|
||||
const exitCode = typeof code === 'string' && /^-?\d+$/.test(code) ? Number(code) : code;
|
||||
const elapsedMs = Number(elapsed ?? 0) * 1000;
|
||||
if (!Number.isInteger(exitCode) || !Number.isSafeInteger(elapsedMs) || elapsedMs < 0) {
|
||||
return res.send({ code: 400, message: 'invalid exit code or elapsed time' });
|
||||
}
|
||||
await new TriggerHistory(CrontabStatModel.sequelize!).recordShellResult(id, Number(ref_id), exitCode, elapsedMs, Date.now(), receiptFinishTime(req.get('X-QL-Finished-At')));
|
||||
res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
res.send({ code: 500 });
|
||||
@@ -66,7 +58,7 @@ export default (app: Router) => {
|
||||
try {
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
|
||||
const [total, enabled, disabled, stats] = await Promise.all([
|
||||
const [total, enabled, disabled, stats, triggers] = await Promise.all([
|
||||
CrontabModel.count(),
|
||||
CrontabModel.count({ where: { isDisabled: 0 } }),
|
||||
CrontabModel.count({ where: { isDisabled: 1 } }),
|
||||
@@ -75,11 +67,13 @@ export default (app: Router) => {
|
||||
[fn('SUM', col('run_count')), 'total_runs'],
|
||||
[fn('SUM', col('success_count')), 'total_success'],
|
||||
[fn('SUM', col('fail_count')), 'total_fail'],
|
||||
[fn('SUM', col('untimed_count')), 'untimed_count'],
|
||||
[fn('SUM', col('total_time')), 'total_time'],
|
||||
],
|
||||
where: { date: today },
|
||||
raw: true,
|
||||
}),
|
||||
new TriggerHistory(CrontabStatModel.sequelize!).metrics(dayjs().startOf('day').valueOf()),
|
||||
]);
|
||||
|
||||
const row = stats as any;
|
||||
@@ -94,11 +88,13 @@ export default (app: Router) => {
|
||||
total,
|
||||
enabled,
|
||||
disabled,
|
||||
triggers,
|
||||
todayRuns: totalRuns,
|
||||
todaySuccess: totalSuccess,
|
||||
todayFail: totalFail,
|
||||
todayStopped: totalRuns - totalSuccess - totalFail,
|
||||
successRate: totalRuns > 0 ? ((totalSuccess / totalRuns) * 100).toFixed(1) : '0',
|
||||
avgTime: totalRuns > 0 ? Math.round(totalTime / totalRuns) : 0,
|
||||
avgTime: averageElapsed(totalTime,totalRuns,row?.untimed_count),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -202,6 +198,7 @@ export default (app: Router) => {
|
||||
const rows = (await CrontabStatModel.findAll({
|
||||
attributes: [
|
||||
'ref_id',
|
||||
[fn('SUM', col('untimed_count')), 'untimed_count'],
|
||||
[fn('SUM', col('total_time')), 'total_time'],
|
||||
[fn('SUM', col('run_count')), 'run_count'],
|
||||
[fn('MAX', col('max_time')), 'max_time'],
|
||||
@@ -224,7 +221,7 @@ export default (app: Router) => {
|
||||
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)),
|
||||
avgTime: averageElapsed(r.total_time,r.run_count,r.untimed_count),
|
||||
maxTime: Number(r.max_time),
|
||||
}));
|
||||
|
||||
@@ -245,6 +242,7 @@ export default (app: Router) => {
|
||||
attributes: [
|
||||
'ref_id',
|
||||
[fn('SUM', col('run_count')), 'run_count'],
|
||||
[fn('SUM', col('untimed_count')), 'untimed_count'],
|
||||
[fn('SUM', col('total_time')), 'total_time'],
|
||||
[fn('SUM', col('success_count')), 'success_count'],
|
||||
],
|
||||
@@ -267,7 +265,7 @@ export default (app: Router) => {
|
||||
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)),
|
||||
avgTime: averageElapsed(r.total_time,r.run_count,r.untimed_count),
|
||||
successRate:
|
||||
Number(r.run_count) > 0
|
||||
? ((Number(r.success_count) / Number(r.run_count)) * 100).toFixed(1)
|
||||
@@ -285,6 +283,7 @@ export default (app: Router) => {
|
||||
'/runtime',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const queued = await new TriggerHistory(CrontabModel.sequelize!).queueCounts();
|
||||
const runningInstances = await RunningInstanceModel.findAll({
|
||||
where: {
|
||||
status: InstanceStatus.running,
|
||||
@@ -292,13 +291,6 @@ export default (app: Router) => {
|
||||
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)),
|
||||
@@ -341,7 +333,9 @@ export default (app: Router) => {
|
||||
code: 200,
|
||||
data: {
|
||||
runningCount: running.length,
|
||||
queuedCount: queuedCrons.length,
|
||||
queuedCount: queued.triggers,
|
||||
queuedTasks: queued.tasks,
|
||||
oldestQueued: queued.triggers ? await oldestQueued(CrontabModel.sequelize!) : [],
|
||||
running,
|
||||
idleTasks: idleTasks.map((c: any) => ({
|
||||
id: c.id,
|
||||
@@ -371,7 +365,7 @@ export default (app: Router) => {
|
||||
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 }> = {};
|
||||
const labelMap: Record<string, { count: number; runs: number; success: number; untimed: number; totalTime: number }> = {};
|
||||
crons.forEach((c) => {
|
||||
let rawLabels = c.labels;
|
||||
if (typeof rawLabels === 'string') rawLabels = JSON.parse(rawLabels);
|
||||
@@ -383,11 +377,12 @@ export default (app: Router) => {
|
||||
}
|
||||
const st = statMap[c.id!];
|
||||
labels.forEach((label: string) => {
|
||||
if (!labelMap[label]) labelMap[label] = { count: 0, runs: 0, success: 0, totalTime: 0 };
|
||||
if (!labelMap[label]) labelMap[label] = { count: 0, runs: 0, success: 0, untimed: 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].untimed += Number(st.untimed_count) || 0;
|
||||
labelMap[label].totalTime += Number(st.total_time) || 0;
|
||||
}
|
||||
});
|
||||
@@ -399,7 +394,7 @@ export default (app: Router) => {
|
||||
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,
|
||||
avgTime: averageElapsed(v.totalTime,v.runs,v.untimed),
|
||||
}))
|
||||
.sort((a, b) => b.todayRuns - a.todayRuns);
|
||||
|
||||
@@ -420,13 +415,10 @@ export default (app: Router) => {
|
||||
data: {
|
||||
platform: os.platform(),
|
||||
uptime: Math.floor(process.uptime()),
|
||||
memTotal: os.totalmem(),
|
||||
memFree: os.freemem(),
|
||||
memUsagePercent: ((1 - os.freemem() / os.totalmem()) * 100).toFixed(1),
|
||||
...containerResources(),
|
||||
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) {
|
||||
|
||||
+68
-6
@@ -11,12 +11,11 @@ export default (app: Router) => {
|
||||
route.get(
|
||||
'/',
|
||||
celebrate({
|
||||
query:
|
||||
Joi.object({
|
||||
searchValue: Joi.string().optional().allow(''),
|
||||
type: Joi.string().optional().allow(''),
|
||||
status: Joi.string().optional().allow(''),
|
||||
}).unknown(true),
|
||||
query: Joi.object({
|
||||
searchValue: Joi.string().optional().allow(''),
|
||||
type: Joi.string().optional().allow(''),
|
||||
status: Joi.string().optional().allow(''),
|
||||
}).unknown(true),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
@@ -31,6 +30,69 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/refresh',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
type: Joi.string().valid('nodejs', 'python3').required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const dependenceService = Container.get(DependenceService);
|
||||
const { job, accepted } = dependenceService.startRefresh(req.body.type);
|
||||
if (!accepted) {
|
||||
return res.status(409).send({
|
||||
code: 409,
|
||||
message: 'Another dependency refresh is already running',
|
||||
});
|
||||
}
|
||||
return res.send({ code: 200, data: job });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/refresh/active',
|
||||
async (_req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const dependenceService = Container.get(DependenceService);
|
||||
res.set('Cache-Control', 'no-store');
|
||||
return res.send({
|
||||
code: 200,
|
||||
data: dependenceService.getActiveRefreshJob() || null,
|
||||
});
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/refresh/:id',
|
||||
celebrate({
|
||||
params: Joi.object({ id: Joi.string().uuid().required() }),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const dependenceService = Container.get(DependenceService);
|
||||
const job = dependenceService.getRefreshJob(req.params.id);
|
||||
if (!job) {
|
||||
return res.status(404).send({
|
||||
code: 404,
|
||||
message: 'Dependency refresh job not found',
|
||||
});
|
||||
}
|
||||
res.set('Cache-Control', 'no-store');
|
||||
return res.send({ code: 200, data: job });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/',
|
||||
celebrate({
|
||||
|
||||
@@ -20,7 +20,6 @@ export default (app: Router) => {
|
||||
res.status(500).send({
|
||||
code: 500,
|
||||
message: 'Health check failed',
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
+10
-1
@@ -1,3 +1,4 @@
|
||||
import { directoryCheckHandler, directoryPageHandler } from '../shared/directoryPageRoute';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import { NextFunction, Request, Response, Router } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
@@ -17,6 +18,8 @@ const blacklist = ['.tmp'];
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/logs', route);
|
||||
route.get('/entries', ...directoryPageHandler(() => config.logPath, blacklist, true));
|
||||
route.post('/entries/check', ...directoryCheckHandler(() => config.logPath, blacklist));
|
||||
|
||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
@@ -38,6 +41,8 @@ export default (app: Router) => {
|
||||
query: Joi.object({
|
||||
path: Joi.string().allow('').optional(),
|
||||
file: Joi.string().required(),
|
||||
follow: Joi.boolean().optional(),
|
||||
cursor: Joi.string().pattern(/^\d{1,16}\.[a-f0-9]{64}$/).optional(),
|
||||
offset: Joi.number().integer().min(0).optional(),
|
||||
limit: Joi.number()
|
||||
.integer()
|
||||
@@ -67,14 +72,18 @@ export default (app: Router) => {
|
||||
});
|
||||
|
||||
const chunk = await readLogChunk(finalPath, {
|
||||
follow: req.query.follow as unknown as boolean,
|
||||
cursor: req.query.cursor as string | undefined,
|
||||
offset: req.query.offset as unknown as number,
|
||||
limit: req.query.limit as unknown as number,
|
||||
tail: req.query.tail as unknown as boolean,
|
||||
});
|
||||
res.send({
|
||||
code: 200,
|
||||
data: removeAnsi(chunk.content),
|
||||
data: req.query.follow ? chunk.content : removeAnsi(chunk.content),
|
||||
logStatus: runningInstance ? 'running' : undefined,
|
||||
cursor: chunk.cursor,
|
||||
reset: chunk.reset,
|
||||
offset: chunk.offset,
|
||||
nextOffset: chunk.nextOffset,
|
||||
total: chunk.total,
|
||||
|
||||
+2
-2
@@ -27,7 +27,7 @@ export default (app: Router) => {
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
name: Joi.string().optional().allow('').disallow('system'),
|
||||
scopes: Joi.array().items(Joi.string().required()),
|
||||
scopes: Joi.array().items(Joi.string().required().invalid('apps')),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -47,7 +47,7 @@ export default (app: Router) => {
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
name: Joi.string().optional().allow(''),
|
||||
scopes: Joi.array().items(Joi.string()),
|
||||
scopes: Joi.array().items(Joi.string().invalid('apps')),
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
|
||||
+12
-8
@@ -1,3 +1,4 @@
|
||||
import { directoryCheckHandler, directoryPageHandler } from '../shared/directoryPageRoute';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { resolveFileAccess } from '../shared/fileAccess';
|
||||
import { fileExist, readDirs, readDir, rmPath, IFile } from '../config/util';
|
||||
@@ -18,6 +19,14 @@ import {
|
||||
HistoryUnavailableError,
|
||||
} from '../shared/scriptHistory';
|
||||
const route = Router();
|
||||
const blacklist = [
|
||||
'node_modules',
|
||||
'.git',
|
||||
'.pnpm',
|
||||
'pnpm-lock.yaml',
|
||||
'yarn.lock',
|
||||
'package-lock.json',
|
||||
];
|
||||
|
||||
function isPathAllowed(targetPath: string): boolean {
|
||||
const resolved = path.resolve(targetPath);
|
||||
@@ -75,6 +84,8 @@ const upload = multer({ storage: storage });
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/scripts', route);
|
||||
route.get('/entries', ...directoryPageHandler(() => config.scriptPath, blacklist, false));
|
||||
route.post('/entries/check', ...directoryCheckHandler(() => config.scriptPath, blacklist));
|
||||
|
||||
route.get(
|
||||
'/',
|
||||
@@ -87,14 +98,7 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
let result: IFile[] = [];
|
||||
const blacklist = [
|
||||
'node_modules',
|
||||
'.git',
|
||||
'.pnpm',
|
||||
'pnpm-lock.yaml',
|
||||
'yarn.lock',
|
||||
'package-lock.json',
|
||||
];
|
||||
|
||||
if (req.query.path) {
|
||||
if (
|
||||
!resolveFileAccess(config.scriptPath, [req.query.path as string])
|
||||
|
||||
+3
-1
@@ -4,6 +4,7 @@ import { Logger } from 'winston';
|
||||
import * as fs from 'fs/promises';
|
||||
import config from '../config';
|
||||
import SystemService from '../services/system';
|
||||
import { containerResources } from '../shared/containerResources';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import UserService from '../services/user';
|
||||
import { t } from '../shared/i18n';
|
||||
@@ -62,7 +63,8 @@ export default (app: Router) => {
|
||||
try {
|
||||
const systemService = Container.get(SystemService);
|
||||
const data = await systemService.getSystemConfig();
|
||||
res.send({ code: 200, data });
|
||||
res.send({ code: 200, data: { ...data, effectiveCronConcurrency: systemService.cronConcurrency,
|
||||
availableCpus: containerResources().cpus } });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
|
||||
@@ -310,20 +310,6 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/notification/init',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const userService = Container.get(UserService);
|
||||
const result = await userService.updateNotificationMode(req.body);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/avatar',
|
||||
upload.single('avatar'),
|
||||
|
||||
+42
-28
@@ -41,11 +41,18 @@ class Application {
|
||||
}
|
||||
|
||||
private startMasterProcess() {
|
||||
const readyTimeout =
|
||||
process.arch === 'arm' &&
|
||||
Number(
|
||||
(process.config.variables as { arm_version?: string | number }).arm_version,
|
||||
) === 6
|
||||
? 120000
|
||||
: 30000;
|
||||
// Fork gRPC worker first and wait for it to be ready
|
||||
const grpcWorker = this.forkWorker('grpc');
|
||||
|
||||
// Wait for gRPC worker to signal it's ready before starting HTTP worker
|
||||
this.waitForWorkerReady(grpcWorker, 30000)
|
||||
this.waitForWorkerReady(grpcWorker, readyTimeout)
|
||||
.then(() => {
|
||||
Logger.info('[boot] gRPC worker is ready, starting HTTP worker');
|
||||
this.httpWorker = this.forkWorker('http');
|
||||
@@ -71,7 +78,7 @@ class Application {
|
||||
Logger.warn('Unable to notify HTTP worker of scheduler exit');
|
||||
}
|
||||
const newGrpcWorker = this.forkWorker('grpc');
|
||||
this.waitForWorkerReady(newGrpcWorker, 30000)
|
||||
this.waitForWorkerReady(newGrpcWorker, readyTimeout)
|
||||
.then(() => {
|
||||
Logger.info('gRPC worker restarted and ready');
|
||||
// Re-register cron jobs by notifying the HTTP worker
|
||||
@@ -131,7 +138,19 @@ class Application {
|
||||
workerEnv.pmx = 'false';
|
||||
}
|
||||
const worker = cluster.fork(workerEnv);
|
||||
if (serviceType === 'grpc') worker.on('message', (msg) => {
|
||||
if (msg === 'crontab-install-failed' && this.httpWorker?.isConnected()) {
|
||||
this.httpWorker.send('reregister-crons');
|
||||
}
|
||||
});
|
||||
|
||||
if (serviceType === 'http') worker.on('message', (msg) => {
|
||||
if (msg?.type !== 'cancel-queued-triggers') return;
|
||||
for (const [id, meta] of this.workerMetadataMap) {
|
||||
const target = cluster.workers?.[id];
|
||||
if (meta.serviceType === 'grpc' && target?.isConnected()) target.send(msg);
|
||||
}
|
||||
});
|
||||
this.workerMetadataMap.set(worker.id, {
|
||||
id: worker.id,
|
||||
pid: worker.process.pid!,
|
||||
@@ -148,32 +167,8 @@ class Application {
|
||||
}
|
||||
|
||||
private async setupMiddlewares(): Promise<express.Application> {
|
||||
// Only the HTTP worker needs an Express application and its middleware.
|
||||
const [
|
||||
{ default: createExpress },
|
||||
{ default: helmet },
|
||||
{ default: cors },
|
||||
{ default: compression },
|
||||
{ monitoringMiddleware },
|
||||
] = await Promise.all([
|
||||
import('express'),
|
||||
import('helmet'),
|
||||
import('cors'),
|
||||
import('compression'),
|
||||
import('./middlewares/monitoring'),
|
||||
]);
|
||||
const app = createExpress();
|
||||
app.use((req, res, next) => {
|
||||
if (req.query.t) delete req.query.t;
|
||||
next();
|
||||
});
|
||||
app.use(helmet({
|
||||
contentSecurityPolicy: false,
|
||||
}));
|
||||
app.use(cors(config.cors));
|
||||
app.use(compression());
|
||||
app.use(monitoringMiddleware);
|
||||
return app;
|
||||
const { createHttpApplication } = await import('./loaders/httpApplication');
|
||||
return createHttpApplication();
|
||||
}
|
||||
|
||||
private setupMasterShutdown() {
|
||||
@@ -234,8 +229,21 @@ class Application {
|
||||
Logger.info(`[boot] ${serviceType} worker started (PID: ${process.pid})`);
|
||||
|
||||
try {
|
||||
const { triggerHistory } = await import('./shared/triggerHistory');
|
||||
const history = triggerHistory();
|
||||
await history.interrupt(serviceType);
|
||||
if (serviceType === 'http') {
|
||||
await this.startHttpService();
|
||||
const retryExits = async () => {
|
||||
try {
|
||||
await history.retryPendingExits();
|
||||
} catch (error) {
|
||||
Logger.error(`[scheduler] Exit receipt retry failed: ${errStack(error)}`);
|
||||
} finally {
|
||||
if (!this.isShuttingDown) setTimeout(retryExits, 15000).unref();
|
||||
}
|
||||
};
|
||||
setTimeout(retryExits, 15000).unref();
|
||||
} else {
|
||||
await this.startGrpcService();
|
||||
}
|
||||
@@ -282,6 +290,10 @@ class Application {
|
||||
process.on('message', async (msg) => {
|
||||
if (msg === 'shutdown') {
|
||||
this.gracefulShutdown(serviceType);
|
||||
} else if (serviceType === 'grpc' && typeof msg === 'object' && msg &&
|
||||
'type' in msg && msg.type === 'cancel-queued-triggers' && 'ids' in msg && Array.isArray(msg.ids)) {
|
||||
const { cancelWaitingTriggers } = await import('./shared/runCron');
|
||||
cancelWaitingTriggers(msg.ids);
|
||||
} else if (serviceType === 'http' &&
|
||||
(msg === 'reregister-crons' || msg === 'scheduler-unavailable')) {
|
||||
const { default: cronClient } = await import('./schedule/client');
|
||||
@@ -299,6 +311,8 @@ class Application {
|
||||
this.isShuttingDown = true;
|
||||
|
||||
try {
|
||||
const { triggerHistory } = await import('./shared/triggerHistory');
|
||||
await triggerHistory().interrupt(serviceType);
|
||||
if (serviceType === 'http') {
|
||||
await this.httpServerService?.shutdown();
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { storageFull, writeExit } from '../shared/managedExit.cjs';
|
||||
import { QueryTypes } from 'sequelize';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { sequelize } from '../data';
|
||||
import { systemOwner, TriggerHistory } from '../shared/triggerHistory';
|
||||
|
||||
async function receipt() {
|
||||
const [action, task, pid, id, status, end] = process.argv.slice(2);
|
||||
const history = new TriggerHistory(sequelize);
|
||||
if (action === 'start') {
|
||||
await history.recoverSystemOwners(Number(task));
|
||||
const triggerId = id || `system-${task}-${randomUUID()}`;
|
||||
const owner = systemOwner(Number(pid));
|
||||
const command = status ? systemOwner(Number(status)) : owner;
|
||||
const at = Number(process.env.QL_SYSTEM_ENTERED);
|
||||
const rule = process.env.QL_SYSTEM_RULE;
|
||||
const dispatched = Number(process.env.QL_SYSTEM_DISPATCHED) * 1000;
|
||||
const dispatch = Number.isSafeInteger(dispatched) && dispatched > 0 && dispatched <= at ? dispatched : undefined;
|
||||
const wrapper = rule && Number.isSafeInteger(at) && at > 0 && at <= Date.now() ? { rule, at, dispatch } : undefined;
|
||||
const acquired = await history.startSystem(triggerId, Number(task), owner, command, wrapper);
|
||||
if (!acquired) process.exitCode = 75;
|
||||
else if (!id) process.stdout.write(triggerId);
|
||||
} else if (action === 'finish') {
|
||||
// The live wrapper inherited both IDs from the start it just claimed. A
|
||||
// standalone retry must match the registered system task before writing.
|
||||
const fromWrapper = process.env.QL_TRIGGER_ID === id && process.env.ID === task;
|
||||
if (!fromWrapper || !id?.startsWith(`system-${Number(task)}-`)) {
|
||||
const [registered] = await sequelize.query(
|
||||
`SELECT 1 FROM CronTriggers WHERE id=$id AND cron_id=$task AND source='system' AND owner LIKE 'crond:%'
|
||||
UNION ALL SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=$id AND cron_id=$task AND source='system' LIMIT 1`,
|
||||
{ bind: { id, task: Number(task) }, type: QueryTypes.SELECT });
|
||||
if (!registered) return;
|
||||
}
|
||||
const code = Number(status);
|
||||
const finishedAt = end && /^\d{13}$/.test(end) && Number(end) <= Date.now() ? Number(end) : undefined;
|
||||
const bound = fromWrapper && finishedAt !== undefined;
|
||||
let journaled = false;
|
||||
if (bound) {
|
||||
try { writeExit(id, code, null, finishedAt); journaled = true; }
|
||||
catch (error) {
|
||||
if (!storageFull(error)) throw error;
|
||||
console.error('[crond] Receipt storage full; settling the observed exit in SQLite:', error);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await history.complete(id, code === 0 ? 'finished' : 'failed', null, code, finishedAt,
|
||||
bound ? { version: 1, code, signal: null, time: finishedAt } : finishedAt === undefined ? undefined : 'legacy');
|
||||
} catch (error) {
|
||||
if (!journaled || !storageFull(error)) throw error;
|
||||
// The regular recovery pass will settle the receipt after space returns.
|
||||
}
|
||||
} else {
|
||||
throw new Error('Unknown crond receipt action');
|
||||
}
|
||||
}
|
||||
|
||||
receipt().catch((error) => {
|
||||
console.error('[crond] Failed to persist execution receipt:', error);
|
||||
// At start, 75 means that another execution already owns the slot.
|
||||
process.exitCode = process.argv[2] === 'finish' && storageFull(error) ? 75 : 1;
|
||||
}).finally(() => sequelize.close());
|
||||
@@ -0,0 +1,139 @@
|
||||
// A single, disposable backend process. Resolve startup dependencies, but never
|
||||
// run appLoader: its initData/initTask hooks install dependencies and start user work.
|
||||
import 'reflect-metadata';
|
||||
import dns from 'dns';
|
||||
import http from 'http';
|
||||
|
||||
// The first scheduler connection can outlive its short RPC deadline. Let the
|
||||
// normal single-flight recovery finish within the supervised startup budget.
|
||||
async function waitForUpgradeScheduler(
|
||||
readiness: { recover(): Promise<boolean> },
|
||||
timeoutMs: number,
|
||||
retryMs = 250,
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
do {
|
||||
if (await readiness.recover()) return;
|
||||
const remaining = deadline - Date.now();
|
||||
if (remaining <= 0) break;
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, Math.min(retryMs, remaining)),
|
||||
);
|
||||
} while (Date.now() < deadline);
|
||||
throw new Error('Upgrade scheduler readiness failed');
|
||||
}
|
||||
|
||||
async function probeUpgrade() {
|
||||
if (!process.send || process.env.QL_UPGRADE_PROBE !== '1')
|
||||
throw new Error('Upgrade probe requires its isolated supervisor');
|
||||
dns.setDefaultResultOrder('ipv4first');
|
||||
const { default: config } = await import('../config');
|
||||
const { sequelize } = await import('../data');
|
||||
const { default: loadDatabase } = await import('../loaders/db');
|
||||
const { Container } = await import('typedi');
|
||||
const { GrpcServerService } = await import('../services/grpc');
|
||||
const { HttpServerService } = await import('../services/http');
|
||||
const { createHttpApplication } = await import('../loaders/httpApplication');
|
||||
const { default: loadServer } = await import('../loaders/server');
|
||||
const { default: loadExpress } = await import('../loaders/express');
|
||||
await import('../loaders/app'); // Resolve normal startup hooks without running them.
|
||||
const { default: inject } = await import('../loaders/depInjector');
|
||||
const grpc = Container.get(GrpcServerService);
|
||||
const server = Container.get(HttpServerService);
|
||||
try {
|
||||
await loadDatabase();
|
||||
// Exercise an actual on-disk transaction as well as schema initialization.
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
await sequelize.query('CREATE TABLE upgrade_probe (value INTEGER)', {
|
||||
transaction,
|
||||
});
|
||||
await sequelize.query('INSERT INTO upgrade_probe VALUES (42)', {
|
||||
transaction,
|
||||
});
|
||||
const [rows] = await sequelize.query('SELECT value FROM upgrade_probe', {
|
||||
transaction,
|
||||
});
|
||||
if ((rows[0] as { value: number })?.value !== 42)
|
||||
throw new Error('Upgrade database readback failed');
|
||||
});
|
||||
inject();
|
||||
config.grpcPort = await grpc.initialize();
|
||||
const { default: cronClient } = await import('../schedule/client');
|
||||
cronClient.readiness.configure(async () => {});
|
||||
await waitForUpgradeScheduler(
|
||||
cronClient.readiness,
|
||||
process.arch === 'arm' &&
|
||||
Number(
|
||||
(process.config.variables as { arm_version?: string | number })
|
||||
.arm_version,
|
||||
) === 6
|
||||
? 60000
|
||||
: 10000,
|
||||
);
|
||||
const app = await createHttpApplication();
|
||||
loadExpress({ app });
|
||||
const listener = await server.initialize(app, 0);
|
||||
await loadServer({ server: listener });
|
||||
const address = listener.address();
|
||||
if (!address || typeof address === 'string')
|
||||
throw new Error('No probe HTTP port');
|
||||
const health = await new Promise<any>((resolve, reject) => {
|
||||
const request = http.get(
|
||||
`http://127.0.0.1:${address.port}/api/health`,
|
||||
(response) => {
|
||||
let body = '';
|
||||
response.on('data', (chunk) => {
|
||||
body += chunk;
|
||||
});
|
||||
response.on('error', reject);
|
||||
response.on('end', () => {
|
||||
try {
|
||||
const result = JSON.parse(body);
|
||||
if (
|
||||
response.statusCode !== 200 ||
|
||||
result.code !== 200 ||
|
||||
result.data?.status !== 'ok' ||
|
||||
!result.data.services?.grpc ||
|
||||
!result.data.services?.http
|
||||
)
|
||||
throw new Error('Upgrade HTTP/gRPC health check failed');
|
||||
resolve(result.data);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
request.setTimeout(10000, () =>
|
||||
request.destroy(new Error('Upgrade health request timed out')),
|
||||
);
|
||||
request.on('error', reject);
|
||||
});
|
||||
process.send!({
|
||||
type: 'upgrade-probe',
|
||||
ok: true,
|
||||
build: health.build,
|
||||
memory: process.memoryUsage(),
|
||||
pid: process.pid,
|
||||
});
|
||||
} finally {
|
||||
await server.shutdown();
|
||||
grpc.getServer().forceShutdown();
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
|
||||
process.once('disconnect', () => process.exit(1));
|
||||
probeUpgrade()
|
||||
.then(() => process.exit(0))
|
||||
.catch((error) => {
|
||||
process.send?.({
|
||||
type: 'upgrade-probe',
|
||||
ok: false,
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
});
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -180,12 +180,10 @@ export default {
|
||||
'/api/user/two-factor/login',
|
||||
'/api/system',
|
||||
'/api/user/init',
|
||||
'/api/user/notification/init',
|
||||
'/open/user/login',
|
||||
'/open/user/two-factor/login',
|
||||
'/open/system',
|
||||
'/open/user/init',
|
||||
'/open/user/notification/init',
|
||||
],
|
||||
versionFile,
|
||||
lastVersionFile,
|
||||
|
||||
+60
-16
@@ -1,3 +1,5 @@
|
||||
import { cronOperand } from '../shared/cronOperand';
|
||||
import { finishStoppedTree, isProcessDescendant, systemOwner } from '../shared/cronProcess';
|
||||
import * as fs from 'fs/promises';
|
||||
import { statSync } from 'fs';
|
||||
import * as path from 'path';
|
||||
@@ -6,7 +8,7 @@ import psTreeFun from 'ps-tree';
|
||||
import { promisify } from 'util';
|
||||
import { load } from 'js-yaml';
|
||||
import config from './index';
|
||||
import { PYTHON_INSTALL_DIR, PYTHON_VENV_DIR, TASK_COMMAND } from './const';
|
||||
import { PYTHON_INSTALL_DIR, PYTHON_VENV_DIR } from './const';
|
||||
import Logger from '../loaders/logger';
|
||||
import { writeFileWithLock } from '../shared/utils';
|
||||
import { DependenceTypes } from '../data/dependence';
|
||||
@@ -496,13 +498,17 @@ export function psTree(pid: number): Promise<number[]> {
|
||||
});
|
||||
}
|
||||
|
||||
export async function killTask(pid: number, waitForExit = false) {
|
||||
export async function killTask(pid: number, waitForExit = false, verifyOwner?: () => void,
|
||||
withStopRequest?: (signalTree: () => Error | void, targets: string[]) => Promise<void | { targets: string[]; signalledAt: number | null }>) {
|
||||
const descendants = await psTree(pid);
|
||||
verifyOwner?.();
|
||||
const signal = (target: number, sig: NodeJS.Signals) => {
|
||||
try {
|
||||
process.kill(target, sig);
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
if (error.code !== 'ESRCH') throw error;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
if (!waitForExit) {
|
||||
@@ -515,8 +521,53 @@ export async function killTask(pid: number, waitForExit = false) {
|
||||
return;
|
||||
}
|
||||
const pids = [...descendants.reverse(), pid];
|
||||
for (const target of pids) signal(target, 'SIGTERM');
|
||||
const births = new Map<number, string>();
|
||||
if (verifyOwner) {
|
||||
for (const target of pids) {
|
||||
try {
|
||||
const birth = systemOwner(target);
|
||||
if (target === pid || isProcessDescendant(target, pid)) births.set(target, birth);
|
||||
} catch (error) {
|
||||
if (!['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) throw error;
|
||||
}
|
||||
}
|
||||
verifyOwner();
|
||||
}
|
||||
const sameProcess = (target: number) => {
|
||||
if (!verifyOwner) return true;
|
||||
if (!births.has(target)) return false;
|
||||
try { return births.get(target) === systemOwner(target); }
|
||||
catch (error) {
|
||||
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) return false;
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
const signalTree = () => {
|
||||
verifyOwner?.();
|
||||
// The root owns the command's result. An ESRCH here must roll back the
|
||||
// stop claim even if a descendant is still draining the output pipe.
|
||||
if (verifyOwner && (!sameProcess(pid) || !signal(pid, 'SIGTERM'))) {
|
||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
||||
}
|
||||
let deliveryError: Error | undefined;
|
||||
for (const target of pids) {
|
||||
if (verifyOwner && target === pid) continue;
|
||||
try {
|
||||
if (sameProcess(target)) signal(target, 'SIGTERM');
|
||||
} catch (error) {
|
||||
if (!withStopRequest || !verifyOwner) throw error;
|
||||
// Root TERM succeeded. Commit that fact even if a child needs a retry.
|
||||
deliveryError ??= error as Error;
|
||||
}
|
||||
}
|
||||
return deliveryError;
|
||||
};
|
||||
if (withStopRequest) {
|
||||
const claim = await withStopRequest(signalTree, [...births.values()]);
|
||||
if (claim) return finishStoppedTree(claim.targets, claim.signalledAt);
|
||||
} else signalTree();
|
||||
const alive = async (target: number) => {
|
||||
if (!sameProcess(target)) return false;
|
||||
try {
|
||||
process.kill(target, 0);
|
||||
} catch (error: any) {
|
||||
@@ -555,7 +606,9 @@ export async function killTask(pid: number, waitForExit = false) {
|
||||
};
|
||||
let remaining = await wait();
|
||||
if (!remaining.length) return;
|
||||
for (const target of remaining) signal(target, 'SIGKILL');
|
||||
for (const target of remaining) {
|
||||
if (sameProcess(target)) signal(target, 'SIGKILL');
|
||||
}
|
||||
remaining = await wait();
|
||||
if (remaining.length)
|
||||
throw new Error(`Task processes did not exit: ${remaining.join(', ')}`);
|
||||
@@ -612,17 +665,7 @@ export async function getUniqPath(
|
||||
suffix = `_${id}`;
|
||||
}
|
||||
|
||||
let items = command.split(/ +/);
|
||||
|
||||
const maxTimeCommandIndex = items.findIndex((x) => x === '-m');
|
||||
if (maxTimeCommandIndex !== -1) {
|
||||
items = items.slice(maxTimeCommandIndex + 2);
|
||||
}
|
||||
|
||||
let str = items[0];
|
||||
if (items[0] === TASK_COMMAND) {
|
||||
str = items[1];
|
||||
}
|
||||
let str = cronOperand(command) || 'task';
|
||||
|
||||
const dotIndex = str.lastIndexOf('.');
|
||||
|
||||
@@ -642,7 +685,8 @@ export async function getUniqPath(
|
||||
str = `${tempStr}_${str.slice(slashIndex + 1)}`;
|
||||
}
|
||||
|
||||
return `${str}${suffix}`;
|
||||
const base = str.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5.-]+/g, '_').slice(0, 100 - suffix.length);
|
||||
return `${base && !/^\.+$/.test(base) ? base : 'task'}${suffix}`;
|
||||
}
|
||||
|
||||
export function safeJSONParse(value?: string) {
|
||||
|
||||
+15
-1
@@ -16,7 +16,8 @@ export class Crontab {
|
||||
queued_token?: string | null;
|
||||
isPinned?: 1 | 0;
|
||||
labels?: string[];
|
||||
last_running_time?: number;
|
||||
last_instance_id?: number;
|
||||
last_running_time?: number | null;
|
||||
last_execution_time?: number;
|
||||
sub_id?: number;
|
||||
extra_schedules?: Array<{ schedule: string }>;
|
||||
@@ -24,6 +25,10 @@ export class Crontab {
|
||||
task_after?: string;
|
||||
log_name?: string;
|
||||
allow_multiple_instances?: 1 | 0;
|
||||
skip_if_pending?: boolean;
|
||||
max_queue_wait?: number;
|
||||
catchup_seconds?: number;
|
||||
recovery_from?: number;
|
||||
work_dir?: string;
|
||||
|
||||
constructor(options: Crontab) {
|
||||
@@ -51,6 +56,10 @@ 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.skip_if_pending = Boolean(options.skip_if_pending);
|
||||
this.max_queue_wait = options.max_queue_wait || 0;
|
||||
this.catchup_seconds = options.catchup_seconds || 0;
|
||||
this.recovery_from = options.recovery_from;
|
||||
this.work_dir = options.work_dir;
|
||||
}
|
||||
}
|
||||
@@ -86,6 +95,7 @@ export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
||||
log_path: DataTypes.STRING,
|
||||
queued_token: DataTypes.STRING,
|
||||
labels: DataTypes.JSON,
|
||||
last_instance_id: DataTypes.INTEGER,
|
||||
last_running_time: DataTypes.NUMBER,
|
||||
last_execution_time: DataTypes.NUMBER,
|
||||
sub_id: { type: DataTypes.NUMBER, allowNull: true },
|
||||
@@ -94,5 +104,9 @@ export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
||||
task_after: DataTypes.STRING,
|
||||
log_name: DataTypes.STRING,
|
||||
allow_multiple_instances: DataTypes.NUMBER,
|
||||
skip_if_pending: DataTypes.BOOLEAN,
|
||||
max_queue_wait: DataTypes.INTEGER,
|
||||
catchup_seconds: DataTypes.INTEGER,
|
||||
recovery_from: DataTypes.BIGINT,
|
||||
work_dir: DataTypes.STRING,
|
||||
});
|
||||
|
||||
@@ -8,8 +8,10 @@ export class CrontabStat {
|
||||
run_count?: number;
|
||||
success_count?: number;
|
||||
fail_count?: number;
|
||||
untimed_count?: number;
|
||||
total_time?: number;
|
||||
max_time?: number;
|
||||
fixed_max_time?: number | null;
|
||||
|
||||
constructor(options: CrontabStat) {
|
||||
this.id = options.id;
|
||||
@@ -18,6 +20,7 @@ export class CrontabStat {
|
||||
this.run_count = options.run_count || 0;
|
||||
this.success_count = options.success_count || 0;
|
||||
this.fail_count = options.fail_count || 0;
|
||||
this.untimed_count = options.untimed_count || 0;
|
||||
this.total_time = options.total_time || 0;
|
||||
this.max_time = options.max_time || 0;
|
||||
}
|
||||
@@ -53,10 +56,16 @@ export const CrontabStatModel = sequelize.define<CrontabStatInstance>(
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
untimed_count: {
|
||||
type: DataTypes.INTEGER,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
},
|
||||
total_time: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
fixed_max_time: { type: DataTypes.NUMBER, allowNull: true },
|
||||
max_time: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Sequelize, Transaction } from 'sequelize';
|
||||
import config from '../config/index';
|
||||
import type { Database } from 'sqlite3';
|
||||
import { join } from 'path';
|
||||
|
||||
export const sequelize = new Sequelize({
|
||||
@@ -20,4 +21,29 @@ export const sequelize = new Sequelize({
|
||||
transactionType: Transaction.TYPES.IMMEDIATE,
|
||||
});
|
||||
|
||||
// In DELETE journal mode, EXTRA flushes the unlink that makes a transaction
|
||||
// final. Sequelize opens a separate SQLite handle for each transaction.
|
||||
const initialized = new WeakMap<Database, Promise<void>>();
|
||||
sequelize.addHook('beforeQuery', async (_options, query) => {
|
||||
const connection = query.connection as Database;
|
||||
let ready = initialized.get(connection);
|
||||
if (!ready) {
|
||||
ready = new Promise<void>((resolve, reject) => {
|
||||
connection.run('PRAGMA synchronous=EXTRA', error => error ? reject(error) : resolve());
|
||||
}).catch(error => {
|
||||
initialized.delete(connection);
|
||||
throw error;
|
||||
});
|
||||
initialized.set(connection, ready);
|
||||
}
|
||||
await ready;
|
||||
});
|
||||
|
||||
// SQLite transactions use dedicated file handles outside Sequelize 6's pool.
|
||||
// Its default destroyConnection targets the pool on COMMIT/ROLLBACK errors,
|
||||
// leaving the native writer open. The SQLite release path closes that handle.
|
||||
sequelize.connectionManager.destroyConnection = async (connection) => {
|
||||
sequelize.connectionManager.releaseConnection(connection);
|
||||
};
|
||||
|
||||
export type ResponseType<T> = { code: number; data?: T; message?: string };
|
||||
|
||||
+19
-1
@@ -24,7 +24,25 @@ export interface AppToken {
|
||||
expiration: number;
|
||||
}
|
||||
|
||||
export type AppScope = 'envs' | 'crons' | 'configs' | 'scripts' | 'logs' | 'system' | 'dashboard';
|
||||
export type AppScope =
|
||||
| 'crons'
|
||||
| 'crons:read'
|
||||
| 'subscriptions'
|
||||
| 'subscriptions:read'
|
||||
| 'envs'
|
||||
| 'envs:read'
|
||||
| 'configs'
|
||||
| 'configs:read'
|
||||
| 'scripts'
|
||||
| 'scripts:read'
|
||||
| 'logs'
|
||||
| 'logs:read'
|
||||
| 'dependencies'
|
||||
| 'dependencies:read'
|
||||
| 'dashboard'
|
||||
| 'dashboard:read'
|
||||
| 'system'
|
||||
| 'apps';
|
||||
|
||||
export interface AppInstance extends Model<App, App>, App {}
|
||||
export const AppModel = sequelize.define<AppInstance>('App', {
|
||||
|
||||
@@ -6,6 +6,7 @@ export enum InstanceStatus {
|
||||
'finished' = 1,
|
||||
'stopped' = 2,
|
||||
'error' = 3,
|
||||
'unknown' = 4,
|
||||
}
|
||||
|
||||
export interface RunningInstanceAttributes {
|
||||
@@ -78,4 +79,5 @@ export const RunningInstanceModel = sequelize.define<RunningInstanceModel>(
|
||||
allowNull: true,
|
||||
},
|
||||
},
|
||||
{ indexes: [{ fields: ['cron_id', 'pid', 'started_at'] }, { fields: ['cron_id', 'id'] }] },
|
||||
);
|
||||
|
||||
+73
-38
@@ -16,6 +16,7 @@ import { t } from '../shared/i18n';
|
||||
import { AppScope } from '../data/open';
|
||||
import uniqueConstraintError from '../middlewares/uniqueConstraintError';
|
||||
import protectedPathCase from '../middlewares/protectedPathCase';
|
||||
import Logger from './logger';
|
||||
|
||||
function resolveTrustProxy(value = process.env.QL_TRUST_PROXY) {
|
||||
const setting = value?.trim();
|
||||
@@ -112,7 +113,43 @@ export default ({ app }: { app: Application }) => {
|
||||
const keyMatch = pathLower.match(/\/open\/([a-z]+)\/*/);
|
||||
const key = keyMatch && keyMatch[1];
|
||||
|
||||
if (!doc.scopes.includes(key as AppScope)) {
|
||||
const isReadRequest =
|
||||
(['GET', 'HEAD'].includes(req.method) &&
|
||||
!(
|
||||
key === 'crons' && /^\/open\/crons\/import\/?$/.test(pathLower)
|
||||
)) ||
|
||||
(['scripts', 'logs'].includes(key || '') &&
|
||||
req.method === 'POST' &&
|
||||
/^\/open\/(?:scripts|logs)\/(?:download|entries\/check)\/?$/.test(pathLower));
|
||||
const hasNamespaceScope =
|
||||
doc.scopes.includes(key as AppScope) ||
|
||||
([
|
||||
'crons',
|
||||
'subscriptions',
|
||||
'envs',
|
||||
'configs',
|
||||
'scripts',
|
||||
'logs',
|
||||
'dependencies',
|
||||
'dashboard',
|
||||
].includes(key || '') &&
|
||||
doc.scopes.includes(`${key}:read` as AppScope) &&
|
||||
isReadRequest);
|
||||
if (!hasNamespaceScope) {
|
||||
const err = new UnauthorizedError('credentials_bad_scheme', {
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
return next(err);
|
||||
}
|
||||
|
||||
// The built-in system app still needs its local CLI maintenance API.
|
||||
const appRouteAllowed =
|
||||
key !== 'system' ||
|
||||
doc.name === 'system' ||
|
||||
((req.method === 'GET' || req.method === 'HEAD') &&
|
||||
(pathLower === '/open/system' || pathLower === '/open/system/')) ||
|
||||
(req.method === 'PUT' && pathLower === '/open/system/notify');
|
||||
if (!appRouteAllowed) {
|
||||
const err = new UnauthorizedError('credentials_bad_scheme', {
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
@@ -155,14 +192,7 @@ export default ({ app }: { app: Application }) => {
|
||||
|
||||
app.use(async (req, res, next) => {
|
||||
const pathLower = req.path.toLowerCase();
|
||||
if (
|
||||
![
|
||||
'/api/user/init',
|
||||
'/api/user/notification/init',
|
||||
'/open/user/init',
|
||||
'/open/user/notification/init',
|
||||
].includes(pathLower)
|
||||
) {
|
||||
if (!['/api/user/init', '/open/user/init'].includes(pathLower)) {
|
||||
return next();
|
||||
}
|
||||
const authInfo = (await shareStore.getAuthInfo()) || ({} as AuthInfo);
|
||||
@@ -202,37 +232,23 @@ export default ({ app }: { app: Application }) => {
|
||||
|
||||
app.use(
|
||||
(
|
||||
err: Error & { status: number },
|
||||
err: Error & { status: number; code?: string },
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
if (err.name === 'UnauthorizedError') {
|
||||
return res
|
||||
.status(err.status)
|
||||
.send({ code: 401, message: err.message })
|
||||
.end();
|
||||
}
|
||||
return next(err);
|
||||
},
|
||||
);
|
||||
|
||||
app.use(
|
||||
(
|
||||
err: Error & { errors: any[] },
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
if (err.name.includes('Sequelize')) {
|
||||
return res
|
||||
.status(500)
|
||||
.send({
|
||||
code: 400,
|
||||
message: `${err.message}`,
|
||||
errors: err.errors,
|
||||
})
|
||||
.end();
|
||||
let message = err.message;
|
||||
if (!config.isDevelopment) {
|
||||
if (err.code === 'credentials_bad_scheme') {
|
||||
message = t('暂无权限');
|
||||
} else if (err.code === 'credentials_required') {
|
||||
message = t('请先登录');
|
||||
} else {
|
||||
message = t('Token 已失效');
|
||||
}
|
||||
}
|
||||
return res.status(401).send({ code: 401, message }).end();
|
||||
}
|
||||
return next(err);
|
||||
},
|
||||
@@ -245,10 +261,29 @@ export default ({ app }: { app: Application }) => {
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
res.status(err.status || 500);
|
||||
const status =
|
||||
Number.isInteger(err.status) && err.status >= 400 && err.status < 600
|
||||
? err.status
|
||||
: 500;
|
||||
if (status >= 500) {
|
||||
const route =
|
||||
typeof req.route?.path === 'string' ? req.route.path : '?';
|
||||
const errorName = /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(err.name)
|
||||
? err.name
|
||||
: 'Error';
|
||||
Logger.error(
|
||||
'HTTP request failed: status=%d method=%s route=%s type=%s',
|
||||
status,
|
||||
req.method,
|
||||
route,
|
||||
errorName,
|
||||
);
|
||||
}
|
||||
res.status(status);
|
||||
res.json({
|
||||
code: err.status || 500,
|
||||
message: err.message,
|
||||
code: status,
|
||||
message:
|
||||
!config.isDevelopment && status >= 500 ? t('未知错误') : err.message,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import type express from 'express';
|
||||
import config from '../config';
|
||||
|
||||
export async function createHttpApplication(): Promise<express.Application> {
|
||||
// Only the HTTP worker needs an Express application and its middleware.
|
||||
const [
|
||||
{ default: createExpress },
|
||||
{ default: helmet },
|
||||
{ default: cors },
|
||||
{ default: compression },
|
||||
{ monitoringMiddleware },
|
||||
] = await Promise.all([
|
||||
import('express'),
|
||||
import('helmet'),
|
||||
import('cors'),
|
||||
import('compression'),
|
||||
import('../middlewares/monitoring'),
|
||||
]);
|
||||
const app = createExpress();
|
||||
app.use((req, res, next) => {
|
||||
if (req.query.t) delete req.query.t;
|
||||
next();
|
||||
});
|
||||
app.use(
|
||||
helmet({
|
||||
contentSecurityPolicy: false,
|
||||
}),
|
||||
);
|
||||
app.use(cors(config.cors));
|
||||
app.use(compression());
|
||||
app.use(monitoringMiddleware);
|
||||
return app;
|
||||
}
|
||||
+10
-16
@@ -1,7 +1,7 @@
|
||||
import DependenceService from '../services/dependence';
|
||||
import { exec } from 'child_process';
|
||||
import { Container } from 'typedi';
|
||||
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
||||
import { Crontab, CrontabModel } from '../data/cron';
|
||||
import CronService from '../services/cron';
|
||||
import EnvService from '../services/env';
|
||||
import { DependenceModel, DependenceStatus } from '../data/dependence';
|
||||
@@ -18,7 +18,7 @@ import OpenService from '../services/open';
|
||||
import { shareStore } from '../shared/store';
|
||||
import Logger from './logger';
|
||||
import cronClient from '../schedule/client';
|
||||
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
||||
import { TriggerHistory } from '../shared/triggerHistory';
|
||||
import { setLang, systemLang } from '../shared/i18n';
|
||||
|
||||
export default async () => {
|
||||
@@ -121,18 +121,11 @@ export default async () => {
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化更新所有任务状态为空闲
|
||||
await CrontabModel.update({ status: CrontabStatus.idle }, { where: {} });
|
||||
|
||||
// 清空所有运行中的实例记录(服务重启后进程已不存在)
|
||||
await RunningInstanceModel.update(
|
||||
{
|
||||
status: InstanceStatus.stopped,
|
||||
finished_at: Math.floor(Date.now() / 1000),
|
||||
// The previous process's exit code cannot be recovered after a restart.
|
||||
},
|
||||
{ where: { status: InstanceStatus.running } },
|
||||
);
|
||||
const history = new TriggerHistory(CrontabModel.sequelize!);
|
||||
const pendingStops = await history.pendingStops();
|
||||
const pendingBatches = await history.pendingStopBatches();
|
||||
if (pendingStops.length || pendingBatches.length) await cronService.resumePendingStops(history, pendingStops, pendingBatches);
|
||||
await history.reconcileInstances();
|
||||
|
||||
// 初始化时执行一次所有的 ql repo 任务
|
||||
CrontabModel.findAll({
|
||||
@@ -222,6 +215,9 @@ export default async () => {
|
||||
}
|
||||
} catch { }
|
||||
|
||||
// Replace legacy task environment files before recovered tasks can run.
|
||||
await envService.set_envs();
|
||||
|
||||
// 初始化保存一次ck和定时任务数据
|
||||
cronClient.readiness.configure(async () => {
|
||||
await cronService.autosave_crontab(true);
|
||||
@@ -229,8 +225,6 @@ export default async () => {
|
||||
});
|
||||
await cronClient.readiness.recover();
|
||||
|
||||
await envService.set_envs();
|
||||
|
||||
const authInfo = await userService.getAuthInfo();
|
||||
await shareStore.updateAuthInfo(authInfo);
|
||||
await openService.refreshApps();
|
||||
|
||||
@@ -16,6 +16,10 @@ message ICron {
|
||||
string command = 3;
|
||||
repeated ISchedule extra_schedules = 4;
|
||||
string name = 5;
|
||||
optional uint32 max_queue_wait = 6;
|
||||
optional uint32 catchup_seconds = 7;
|
||||
optional int64 recovery_from = 8;
|
||||
optional bool skip_if_pending = 9;
|
||||
}
|
||||
|
||||
message AddCronRequest {
|
||||
|
||||
+91
-2
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.6.1
|
||||
// protoc v5.28.3
|
||||
// protoc v5.29.0
|
||||
// source: back/protos/cron.proto
|
||||
|
||||
/* eslint-disable */
|
||||
@@ -31,6 +31,10 @@ export interface ICron {
|
||||
command: string;
|
||||
extra_schedules: ISchedule[];
|
||||
name: string;
|
||||
max_queue_wait?: number | undefined;
|
||||
catchup_seconds?: number | undefined;
|
||||
recovery_from?: number | undefined;
|
||||
skip_if_pending?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface AddCronRequest {
|
||||
@@ -112,7 +116,17 @@ export const ISchedule: MessageFns<ISchedule> = {
|
||||
};
|
||||
|
||||
function createBaseICron(): ICron {
|
||||
return { id: "", schedule: "", command: "", extra_schedules: [], name: "" };
|
||||
return {
|
||||
id: "",
|
||||
schedule: "",
|
||||
command: "",
|
||||
extra_schedules: [],
|
||||
name: "",
|
||||
max_queue_wait: undefined,
|
||||
catchup_seconds: undefined,
|
||||
recovery_from: undefined,
|
||||
skip_if_pending: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export const ICron: MessageFns<ICron> = {
|
||||
@@ -132,6 +146,18 @@ export const ICron: MessageFns<ICron> = {
|
||||
if (message.name !== "") {
|
||||
writer.uint32(42).string(message.name);
|
||||
}
|
||||
if (message.max_queue_wait !== undefined) {
|
||||
writer.uint32(48).uint32(message.max_queue_wait);
|
||||
}
|
||||
if (message.catchup_seconds !== undefined) {
|
||||
writer.uint32(56).uint32(message.catchup_seconds);
|
||||
}
|
||||
if (message.recovery_from !== undefined) {
|
||||
writer.uint32(64).int64(message.recovery_from);
|
||||
}
|
||||
if (message.skip_if_pending !== undefined) {
|
||||
writer.uint32(72).bool(message.skip_if_pending);
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
@@ -182,6 +208,38 @@ export const ICron: MessageFns<ICron> = {
|
||||
message.name = reader.string();
|
||||
continue;
|
||||
}
|
||||
case 6: {
|
||||
if (tag !== 48) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.max_queue_wait = reader.uint32();
|
||||
continue;
|
||||
}
|
||||
case 7: {
|
||||
if (tag !== 56) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.catchup_seconds = reader.uint32();
|
||||
continue;
|
||||
}
|
||||
case 8: {
|
||||
if (tag !== 64) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.recovery_from = longToNumber(reader.int64());
|
||||
continue;
|
||||
}
|
||||
case 9: {
|
||||
if (tag !== 72) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.skip_if_pending = reader.bool();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
@@ -200,6 +258,10 @@ export const ICron: MessageFns<ICron> = {
|
||||
? object.extra_schedules.map((e: any) => ISchedule.fromJSON(e))
|
||||
: [],
|
||||
name: isSet(object.name) ? globalThis.String(object.name) : "",
|
||||
max_queue_wait: isSet(object.max_queue_wait) ? globalThis.Number(object.max_queue_wait) : undefined,
|
||||
catchup_seconds: isSet(object.catchup_seconds) ? globalThis.Number(object.catchup_seconds) : undefined,
|
||||
recovery_from: isSet(object.recovery_from) ? globalThis.Number(object.recovery_from) : undefined,
|
||||
skip_if_pending: isSet(object.skip_if_pending) ? globalThis.Boolean(object.skip_if_pending) : undefined,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -220,6 +282,18 @@ export const ICron: MessageFns<ICron> = {
|
||||
if (message.name !== "") {
|
||||
obj.name = message.name;
|
||||
}
|
||||
if (message.max_queue_wait !== undefined) {
|
||||
obj.max_queue_wait = Math.round(message.max_queue_wait);
|
||||
}
|
||||
if (message.catchup_seconds !== undefined) {
|
||||
obj.catchup_seconds = Math.round(message.catchup_seconds);
|
||||
}
|
||||
if (message.recovery_from !== undefined) {
|
||||
obj.recovery_from = Math.round(message.recovery_from);
|
||||
}
|
||||
if (message.skip_if_pending !== undefined) {
|
||||
obj.skip_if_pending = message.skip_if_pending;
|
||||
}
|
||||
return obj;
|
||||
},
|
||||
|
||||
@@ -233,6 +307,10 @@ export const ICron: MessageFns<ICron> = {
|
||||
message.command = object.command ?? "";
|
||||
message.extra_schedules = object.extra_schedules?.map((e) => ISchedule.fromPartial(e)) || [];
|
||||
message.name = object.name ?? "";
|
||||
message.max_queue_wait = object.max_queue_wait ?? undefined;
|
||||
message.catchup_seconds = object.catchup_seconds ?? undefined;
|
||||
message.recovery_from = object.recovery_from ?? undefined;
|
||||
message.skip_if_pending = object.skip_if_pending ?? undefined;
|
||||
return message;
|
||||
},
|
||||
};
|
||||
@@ -618,6 +696,17 @@ type KeysOfUnion<T> = T extends T ? keyof T : never;
|
||||
export type Exact<P, I extends P> = P extends Builtin ? P
|
||||
: P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };
|
||||
|
||||
function longToNumber(int64: { toString(): string }): number {
|
||||
const num = globalThis.Number(int64.toString());
|
||||
if (num > globalThis.Number.MAX_SAFE_INTEGER) {
|
||||
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
|
||||
}
|
||||
if (num < globalThis.Number.MIN_SAFE_INTEGER) {
|
||||
throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
function isSet(value: any): boolean {
|
||||
return value !== null && value !== undefined;
|
||||
}
|
||||
|
||||
+59
-28
@@ -3,6 +3,8 @@ import { AddCronRequest, AddCronResponse } from '../protos/cron';
|
||||
import { createCronJob, CronJob } from '../shared/cronScheduler';
|
||||
import { isValidCronSchedule } from '../shared/cronSchedule';
|
||||
import { scheduleStacks } from './data';
|
||||
import { latestMissedSlot } from '../shared/cronRecovery';
|
||||
import { slotId } from '../shared/triggerHistory';
|
||||
import { runCron } from '../shared/runCron';
|
||||
import Logger from '../loaders/logger';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
@@ -12,9 +14,12 @@ const isValidCronField = (cron: string): boolean => {
|
||||
return isValidCronSchedule(cron);
|
||||
};
|
||||
|
||||
const definitions = new WeakMap<CronJob[], string>();
|
||||
|
||||
const addCron = (
|
||||
call: ServerUnaryCall<AddCronRequest, AddCronResponse>,
|
||||
callback: sendUnaryData<AddCronResponse>,
|
||||
savePlan?: () => Promise<void>,
|
||||
) => {
|
||||
// ===== 第一遍:预校验所有 cron 表达式 =====
|
||||
const validationErrors: string[] = [];
|
||||
@@ -54,26 +59,41 @@ const addCron = (
|
||||
|
||||
// Prepare stopped jobs first: construction errors must preserve the old snapshot.
|
||||
const prepared = new Map<string, CronJob[]>();
|
||||
const desired = new Map(call.request.crons.map((item) => [item.id, item]));
|
||||
const recoveries: (() => Promise<void>)[] = [];
|
||||
try {
|
||||
for (const item of call.request.crons) {
|
||||
for (const item of desired.values()) {
|
||||
const signature = JSON.stringify([item.schedule, item.command,
|
||||
(item.extra_schedules || []).map((s) => s.schedule), item.max_queue_wait || 0,
|
||||
!!item.skip_if_pending, item.catchup_seconds || 0, item.catchup_seconds || item.skip_if_pending ? item.recovery_from : 0]);
|
||||
const current = scheduleStacks.get(item.id);
|
||||
if (current && definitions.get(current) === signature) continue;
|
||||
const jobs: CronJob[] = [];
|
||||
prepared.get(item.id)?.forEach((job) => job.cancel());
|
||||
definitions.set(jobs, signature);
|
||||
prepared.set(item.id, jobs);
|
||||
for (const schedule of [
|
||||
for (const [ruleIndex, schedule] of [
|
||||
item.schedule,
|
||||
...(item.extra_schedules || []).map((x) => x.schedule),
|
||||
]) {
|
||||
].entries()) {
|
||||
const fire = async (date: Date, source: 'node' | 'recovery' = 'node') => {
|
||||
const isCurrent = () => scheduleStacks.get(item.id) === jobs;
|
||||
if (!isCurrent()) return;
|
||||
await runCron(item.command, item, isCurrent, date && {
|
||||
id: slotId(item.id, ruleIndex, schedule, +date), time: +date, source,
|
||||
});
|
||||
};
|
||||
if (call.request.replace && item.catchup_seconds && item.recovery_from) {
|
||||
recoveries.push(async () => {
|
||||
const now = Date.now();
|
||||
const since = Math.max(item.recovery_from!, now - item.catchup_seconds! * 1000);
|
||||
const time = latestMissedSlot(schedule, since, now);
|
||||
if (time !== null) await fire(new Date(time), 'recovery');
|
||||
});
|
||||
}
|
||||
jobs.push(
|
||||
createCronJob(
|
||||
schedule,
|
||||
async () => {
|
||||
Logger.info(t('[schedule][准备运行任务] 命令: %s'), item.command);
|
||||
await runCron(
|
||||
item.command,
|
||||
item,
|
||||
() => scheduleStacks.get(item.id) === jobs,
|
||||
);
|
||||
},
|
||||
fire,
|
||||
{
|
||||
name: `${item.id}: ${item.name || ''}`,
|
||||
logger: Logger,
|
||||
@@ -94,23 +114,34 @@ const addCron = (
|
||||
return;
|
||||
}
|
||||
|
||||
if (call.request.replace) {
|
||||
for (const jobs of scheduleStacks.values())
|
||||
jobs.forEach((job) => job?.cancel());
|
||||
scheduleStacks.clear();
|
||||
}
|
||||
for (const [id, jobs] of prepared) {
|
||||
scheduleStacks.get(id)?.forEach((job) => job.cancel());
|
||||
scheduleStacks.set(id, jobs);
|
||||
jobs.forEach((job) => job.start());
|
||||
Logger.info(
|
||||
t('[schedule][创建定时任务] 任务ID: %s, 规则数: %s'),
|
||||
id,
|
||||
jobs.length,
|
||||
);
|
||||
}
|
||||
const activate = () => {
|
||||
if (call.request.replace) {
|
||||
for (const [id, jobs] of scheduleStacks) {
|
||||
if (desired.has(id)) continue;
|
||||
jobs.forEach((job) => job?.cancel());
|
||||
scheduleStacks.delete(id);
|
||||
}
|
||||
}
|
||||
for (const [id, jobs] of prepared) {
|
||||
scheduleStacks.get(id)?.forEach((job) => job.cancel());
|
||||
scheduleStacks.set(id, jobs);
|
||||
jobs.forEach((job) => job.start());
|
||||
Logger.info(
|
||||
t('[schedule][创建定时任务] 任务ID: %s, 规则数: %s'),
|
||||
id,
|
||||
jobs.length,
|
||||
);
|
||||
}
|
||||
|
||||
callback(null, null);
|
||||
callback(null, null);
|
||||
for (const recover of recoveries) setImmediate(() => recover().catch((err) => Logger.error(String(err))));
|
||||
};
|
||||
if (savePlan) {
|
||||
savePlan().then(activate).catch(error => {
|
||||
for (const jobs of prepared.values()) jobs.forEach(job => job.cancel());
|
||||
callback(error);
|
||||
});
|
||||
} else activate();
|
||||
};
|
||||
|
||||
export { addCron };
|
||||
|
||||
@@ -94,7 +94,7 @@ class Client {
|
||||
const registrationTimeoutMs = Math.min(120000, 5000 + ruleCount * 5);
|
||||
return new Promise((resolve, reject) => {
|
||||
this.client.addCron(
|
||||
{ crons: request, replace },
|
||||
AddCronRequest.fromPartial({ crons: request, replace }),
|
||||
new Metadata(),
|
||||
{ deadline: Date.now() + registrationTimeoutMs },
|
||||
(err, res) => {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { ServerUnaryCall, sendUnaryData } from '@grpc/grpc-js';
|
||||
import {
|
||||
AddCronRequest,
|
||||
AddCronResponse,
|
||||
DeleteCronRequest,
|
||||
DeleteCronResponse,
|
||||
} from '../protos/cron';
|
||||
import { addCron } from './addCron';
|
||||
import { delCron } from './delCron';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { saveSchedulePlan, confirmSchedulePlan } from '../shared/scheduleAudit';
|
||||
|
||||
// Keep acknowledgement, publication and timer replacement in request order,
|
||||
// even if the client times out and sends a replacement snapshot.
|
||||
let pending = Promise.resolve();
|
||||
function serialize(action: () => Promise<void>) {
|
||||
pending = pending.then(action, action);
|
||||
return pending;
|
||||
}
|
||||
|
||||
export function registeredAdd(
|
||||
call: ServerUnaryCall<AddCronRequest, AddCronResponse>,
|
||||
callback: sendUnaryData<AddCronResponse>,
|
||||
) {
|
||||
return serialize(async () => {
|
||||
const db = require('../data').sequelize;
|
||||
const token = randomUUID();
|
||||
let first = 0;
|
||||
const last = await new Promise<number>((resolve, reject) => {
|
||||
addCron(
|
||||
call,
|
||||
(error) => (error ? reject(error) : resolve(Date.now())),
|
||||
async () => {
|
||||
await saveSchedulePlan(db, call.request, undefined, token);
|
||||
first = Date.now();
|
||||
},
|
||||
);
|
||||
});
|
||||
await confirmSchedulePlan(db, token, first, last, call.request.replace);
|
||||
callback(null, null);
|
||||
}).catch((error) => callback(error));
|
||||
}
|
||||
|
||||
export function registeredDelete(
|
||||
call: ServerUnaryCall<DeleteCronRequest, DeleteCronResponse>,
|
||||
callback: sendUnaryData<DeleteCronResponse>,
|
||||
) {
|
||||
return serialize(async () => {
|
||||
const db = require('../data').sequelize;
|
||||
const token = randomUUID();
|
||||
await saveSchedulePlan(db, call.request, undefined, token);
|
||||
const first = Date.now();
|
||||
delCron(call, (error) => {
|
||||
if (error) throw error;
|
||||
});
|
||||
await confirmSchedulePlan(db, token, first, Date.now(), false);
|
||||
callback(null, null);
|
||||
}).catch((error) => callback(error));
|
||||
}
|
||||
+611
-285
File diff suppressed because it is too large
Load Diff
+76
-19
@@ -27,9 +27,20 @@ import taskLimit from '../shared/pLimit';
|
||||
import { detectOS } from '../config/util';
|
||||
import { LINUX_DEPENDENCE_COMMAND } from '../config/const';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
type RefreshType = 'nodejs' | 'python3';
|
||||
type RefreshJob = {
|
||||
id: string;
|
||||
type: RefreshType;
|
||||
state: 'running' | 'completed' | 'failed';
|
||||
};
|
||||
|
||||
@Service()
|
||||
export default class DependenceService {
|
||||
private activeRefreshJob?: RefreshJob;
|
||||
private refreshJobs = new Map<string, RefreshJob>();
|
||||
|
||||
constructor(
|
||||
@Inject('logger') private logger: winston.Logger,
|
||||
private sockService: SockService,
|
||||
@@ -118,11 +129,6 @@ export default class DependenceService {
|
||||
query: any = {},
|
||||
): Promise<Dependence[]> {
|
||||
let condition = query;
|
||||
const dependenceType =
|
||||
type && DependenceTypes[type] !== undefined
|
||||
? DependenceTypes[type]
|
||||
: undefined;
|
||||
await this.refreshInstalledStatuses(dependenceType);
|
||||
if (type && DependenceTypes[type] !== undefined) {
|
||||
condition.type = DependenceTypes[type];
|
||||
}
|
||||
@@ -145,6 +151,52 @@ export default class DependenceService {
|
||||
}
|
||||
}
|
||||
|
||||
public startRefresh(type: RefreshType): {
|
||||
job: RefreshJob;
|
||||
accepted: boolean;
|
||||
} {
|
||||
if (this.activeRefreshJob) {
|
||||
return {
|
||||
job: this.activeRefreshJob,
|
||||
accepted: this.activeRefreshJob.type === type,
|
||||
};
|
||||
}
|
||||
|
||||
const job: RefreshJob = { id: randomUUID(), type, state: 'running' };
|
||||
this.activeRefreshJob = job;
|
||||
this.refreshJobs.set(job.id, job);
|
||||
while (this.refreshJobs.size > 20) {
|
||||
const oldestId = this.refreshJobs.keys().next().value;
|
||||
this.refreshJobs.delete(oldestId);
|
||||
}
|
||||
|
||||
void this.refreshInstalledStatuses(DependenceTypes[type])
|
||||
.then(() => {
|
||||
job.state = 'completed';
|
||||
})
|
||||
.catch((error) => {
|
||||
this.logger.error('Dependency refresh failed: %o', error);
|
||||
job.state = 'failed';
|
||||
})
|
||||
.finally(() => {
|
||||
if (this.activeRefreshJob === job) {
|
||||
this.activeRefreshJob = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
return { job, accepted: true };
|
||||
}
|
||||
|
||||
public getRefreshJob(id: string): RefreshJob | undefined {
|
||||
return this.refreshJobs.get(id);
|
||||
}
|
||||
|
||||
public getActiveRefreshJob(): RefreshJob | undefined {
|
||||
return this.activeRefreshJob?.state === 'running'
|
||||
? this.activeRefreshJob
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private async refreshInstalledStatuses(type?: DependenceTypes) {
|
||||
const cacheDependenceTypes = [
|
||||
DependenceTypes.nodejs,
|
||||
@@ -160,26 +212,31 @@ export default class DependenceService {
|
||||
type: type === undefined ? { [Op.in]: cacheDependenceTypes } : type,
|
||||
},
|
||||
});
|
||||
const checkableDocs = docs.filter(
|
||||
(doc) =>
|
||||
doc.type !== DependenceTypes.python3 ||
|
||||
!isPythonSourceDependency(doc.name),
|
||||
);
|
||||
const checks = await concurrentRun(
|
||||
docs
|
||||
.filter(
|
||||
(doc) =>
|
||||
doc.type !== DependenceTypes.python3 ||
|
||||
!isPythonSourceDependency(doc.name),
|
||||
)
|
||||
.map((doc) => async () => {
|
||||
return (await this.isDependenceInstalled(doc)) ? undefined : doc.id;
|
||||
}),
|
||||
checkableDocs.map((doc) => async () => this.isDependenceInstalled(doc)),
|
||||
5,
|
||||
);
|
||||
const missingIds = (checks || []).filter(
|
||||
(id): id is number => id !== undefined,
|
||||
);
|
||||
|
||||
if (missingIds.length) {
|
||||
for (const [index, installed] of (checks || []).entries()) {
|
||||
if (installed) continue;
|
||||
const doc = checkableDocs[index];
|
||||
await DependenceModel.update(
|
||||
{ status: DependenceStatus.installFailed },
|
||||
{ where: { id: missingIds } },
|
||||
{
|
||||
where: {
|
||||
id: doc.id,
|
||||
status: DependenceStatus.installed,
|
||||
name: doc.name,
|
||||
type: doc.type,
|
||||
updatedAt: (doc as typeof doc & { updatedAt: Date }).updatedAt,
|
||||
// Sequelize's automatic timestamp is absent from Dependence's attribute type.
|
||||
} as any,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+22
-3
@@ -14,12 +14,17 @@ import {
|
||||
} from '../data/env';
|
||||
import { writeFileWithLock } from '../shared/utils';
|
||||
import { sequelize } from '../data';
|
||||
import {
|
||||
assertAllowedTaskEnvName,
|
||||
isAllowedTaskEnvName,
|
||||
} from '../shared/taskEnvName';
|
||||
|
||||
@Service()
|
||||
export default class EnvService {
|
||||
constructor(@Inject('logger') private logger: winston.Logger) { }
|
||||
|
||||
public async create(payloads: Env[]): Promise<Env[]> {
|
||||
payloads.forEach((payload) => assertAllowedTaskEnvName(payload.name));
|
||||
const envs = await this.envs();
|
||||
let position = initPosition;
|
||||
if (
|
||||
@@ -52,6 +57,7 @@ export default class EnvService {
|
||||
public async update(payload: Env): Promise<Env> {
|
||||
const doc = await this.getDb({ id: payload.id });
|
||||
const tab = new Env({ ...doc, ...payload });
|
||||
assertAllowedTaskEnvName(tab.name);
|
||||
const newDoc = await this.updateDb(tab);
|
||||
await this.set_envs();
|
||||
return newDoc;
|
||||
@@ -151,7 +157,10 @@ export default class EnvService {
|
||||
['position', 'DESC'],
|
||||
['createdAt', 'ASC'],
|
||||
]);
|
||||
return result;
|
||||
return result.map((env) => ({
|
||||
...env,
|
||||
securityBlocked: !isAllowedTaskEnvName(env.name),
|
||||
}));
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
@@ -182,11 +191,14 @@ export default class EnvService {
|
||||
}
|
||||
|
||||
public async enabled(ids: number[]) {
|
||||
const docs = await EnvModel.findAll({ where: { id: ids } });
|
||||
docs.forEach((doc) => assertAllowedTaskEnvName(doc.name));
|
||||
await EnvModel.update({ status: EnvStatus.normal }, { where: { id: ids } });
|
||||
await this.set_envs();
|
||||
}
|
||||
|
||||
public async updateNames({ ids, name }: { ids: number[]; name: string }) {
|
||||
assertAllowedTaskEnvName(name);
|
||||
await EnvModel.update({ name }, { where: { id: ids } });
|
||||
await this.set_envs();
|
||||
}
|
||||
@@ -242,6 +254,13 @@ export default class EnvService {
|
||||
name: { [Op.not]: null },
|
||||
status: EnvStatus.normal,
|
||||
});
|
||||
const invalid = envs.filter((env) => !isAllowedTaskEnvName(env.name));
|
||||
if (invalid.length > 0) {
|
||||
this.logger.warn(
|
||||
'Skipped reserved environment variables in task files: %s',
|
||||
JSON.stringify(invalid.map((env) => ({ id: env.id, name: env.name }))),
|
||||
);
|
||||
}
|
||||
const groups = groupBy(envs, 'name');
|
||||
let env_string = '';
|
||||
let js_env_string = '';
|
||||
@@ -250,8 +269,8 @@ export default class EnvService {
|
||||
if (Object.prototype.hasOwnProperty.call(groups, key)) {
|
||||
const group = groups[key];
|
||||
|
||||
// 忽略不符合bash要求的环境变量名称
|
||||
if (/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(key)) {
|
||||
// Ignore invalid and reserved names, including legacy database rows.
|
||||
if (isAllowedTaskEnvName(key)) {
|
||||
let value = group
|
||||
.map((x) => x.value)
|
||||
.join('&')
|
||||
|
||||
@@ -2,8 +2,7 @@ import { Server, ServerCredentials } from '@grpc/grpc-js';
|
||||
import { CronService } from '../protos/cron';
|
||||
import { HealthService } from '../protos/health';
|
||||
import { ApiService } from '../protos/api';
|
||||
import { addCron } from '../schedule/addCron';
|
||||
import { delCron } from '../schedule/delCron';
|
||||
import { registeredAdd, registeredDelete } from '../schedule/registeredPlans';
|
||||
import { setConcurrency } from '../schedule/setConcurrency';
|
||||
import { check } from '../schedule/health';
|
||||
import * as Api from '../schedule/api';
|
||||
@@ -28,7 +27,7 @@ export class GrpcServerService {
|
||||
async initialize() {
|
||||
try {
|
||||
this.server.addService(HealthService, { check });
|
||||
this.server.addService(CronService, { addCron, delCron, setConcurrency });
|
||||
this.server.addService(CronService, { addCron: registeredAdd, delCron: registeredDelete, setConcurrency });
|
||||
this.server.addService(ApiService, Api);
|
||||
|
||||
const tlsConfig = await initGrpcCerts();
|
||||
@@ -50,13 +49,13 @@ export class GrpcServerService {
|
||||
for (const host of hostsToTry) {
|
||||
try {
|
||||
const address = this.formatGrpcAddress(host, grpcPort);
|
||||
await bindAsync(address, credentials);
|
||||
const boundPort = 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;
|
||||
return boundPort;
|
||||
} catch (err) {
|
||||
lastError = err as Error;
|
||||
Logger.warn(`Failed to bind gRPC on ${host}:${grpcPort}, trying next...`, err);
|
||||
|
||||
@@ -8,6 +8,6 @@ export default class LogService {
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
public checkFilePath(filePath: string, fileName: string) {
|
||||
return resolveFileAccess(config.logPath, [filePath || '', fileName]);
|
||||
return resolveFileAccess(config.logPath, [filePath || '', fileName], ['.tmp']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +92,10 @@ export default class OpenService {
|
||||
|
||||
private async updateDb(payload: Partial<App>): Promise<App> {
|
||||
return this.withAppsLock(async () => {
|
||||
const target = await AppModel.findOne({ where: { id: payload.id } });
|
||||
if (target?.name === 'system' || payload.name === 'system') {
|
||||
throw Object.assign(new Error(t('暂无权限')), { status: 403 });
|
||||
}
|
||||
await AppModel.update(payload, { where: { id: payload.id } });
|
||||
const apps = await this.find({});
|
||||
await shareStore.updateApps(apps);
|
||||
@@ -109,6 +113,12 @@ export default class OpenService {
|
||||
|
||||
public async remove(ids: number[]) {
|
||||
return this.withAppsLock(async () => {
|
||||
const systemApp = await AppModel.findOne({
|
||||
where: { id: ids, name: 'system' },
|
||||
});
|
||||
if (systemApp) {
|
||||
throw Object.assign(new Error(t('暂无权限')), { status: 403 });
|
||||
}
|
||||
await AppModel.destroy({ where: { id: ids } });
|
||||
const apps = await this.find({});
|
||||
await shareStore.updateApps(apps);
|
||||
|
||||
+54
-23
@@ -1,11 +1,13 @@
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import dayjs from 'dayjs';
|
||||
import { Op } from 'sequelize';
|
||||
import { literal, Op } from 'sequelize';
|
||||
import { Service } from 'typedi';
|
||||
import config from '../config';
|
||||
import { CrontabStatModel } from '../data/cronStats';
|
||||
import { sequelize } from '../data';
|
||||
import { TriggerHistory } from '../shared/triggerHistory';
|
||||
import { prunedExitMigrationId } from '../shared/schemaMigrations';
|
||||
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
||||
import { AuthDataType, SystemModel } from '../data/system';
|
||||
import {
|
||||
@@ -21,10 +23,12 @@ export interface StorageCleanupRequest extends RetentionPolicy {
|
||||
compactDatabase?: boolean;
|
||||
}
|
||||
|
||||
function runningInstanceWhere(days: number) {
|
||||
const cutoff = dayjs().subtract(days, 'day').unix();
|
||||
function runningInstanceWhere(cutoffMs: number) {
|
||||
const cutoff = cutoffMs / 1000;
|
||||
return {
|
||||
status: { [Op.ne]: InstanceStatus.running },
|
||||
id: { [Op.notIn]: literal(`(SELECT instance_id FROM CronTriggers WHERE instance_id IS NOT NULL
|
||||
AND (exit_pending=1 OR state IN ('queued','running') OR finished_at IS NULL OR observed_at >= ${cutoffMs} OR finished_at >= ${cutoffMs}))`) },
|
||||
[Op.or]: [
|
||||
{ finished_at: { [Op.lt]: cutoff } },
|
||||
{
|
||||
@@ -35,9 +39,11 @@ function runningInstanceWhere(days: number) {
|
||||
};
|
||||
}
|
||||
|
||||
function cronStatWhere(days: number) {
|
||||
function retentionCutoffs(policy: RetentionPolicy) {
|
||||
const now = dayjs();
|
||||
return {
|
||||
date: { [Op.lt]: dayjs().subtract(days, 'day').format('YYYY-MM-DD') },
|
||||
history: now.subtract(policy.runningInstanceRetentionDays, 'day').startOf('second').valueOf(),
|
||||
firstDay: now.subtract(policy.cronStatRetentionDays, 'day').format('YYYY-MM-DD'),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -63,20 +69,20 @@ export default class RetentionService {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
public async preview(request: StorageCleanupRequest) {
|
||||
public async preview(request: StorageCleanupRequest, cutoffs = retentionCutoffs(normalizeRetentionPolicy(request))) {
|
||||
const policy = normalizeRetentionPolicy(request);
|
||||
const dependenceCacheTypes = (request.dependenceCacheTypes || []).filter(
|
||||
isDependenceCacheType,
|
||||
);
|
||||
const [runningInstances, cronStats, dependenceCaches] = await Promise.all([
|
||||
const [runningInstances, cronStats, dependenceCaches, triggers] = await Promise.all([
|
||||
policy.runningInstanceRetentionDays > 0
|
||||
? RunningInstanceModel.count({
|
||||
where: runningInstanceWhere(policy.runningInstanceRetentionDays),
|
||||
where: runningInstanceWhere(cutoffs.history),
|
||||
})
|
||||
: 0,
|
||||
policy.cronStatRetentionDays > 0
|
||||
? CrontabStatModel.count({
|
||||
where: cronStatWhere(policy.cronStatRetentionDays),
|
||||
where: { date: { [Op.lt]: cutoffs.firstDay } },
|
||||
})
|
||||
: 0,
|
||||
Promise.all(
|
||||
@@ -87,11 +93,15 @@ export default class RetentionService {
|
||||
),
|
||||
})),
|
||||
),
|
||||
policy.runningInstanceRetentionDays > 0
|
||||
? new TriggerHistory(sequelize).countExpired(cutoffs.history)
|
||||
: 0,
|
||||
]);
|
||||
|
||||
return {
|
||||
policy,
|
||||
runningInstances,
|
||||
triggers,
|
||||
cronStats,
|
||||
dependenceCaches,
|
||||
dependenceCacheBytes: dependenceCaches.reduce(
|
||||
@@ -103,25 +113,46 @@ export default class RetentionService {
|
||||
}
|
||||
|
||||
public async cleanup(request: StorageCleanupRequest) {
|
||||
const preview = await this.preview(request);
|
||||
const cutoffs = retentionCutoffs(normalizeRetentionPolicy(request));
|
||||
const preview = await this.preview(request, cutoffs);
|
||||
const deleted = await sequelize.transaction(async (transaction) => {
|
||||
const history = new TriggerHistory(sequelize);
|
||||
if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) {
|
||||
await history.replayPublishedExits(transaction);
|
||||
}
|
||||
const runningInstances =
|
||||
preview.policy.runningInstanceRetentionDays > 0
|
||||
? await RunningInstanceModel.destroy({
|
||||
where: runningInstanceWhere(
|
||||
preview.policy.runningInstanceRetentionDays,
|
||||
),
|
||||
where: runningInstanceWhere(cutoffs.history),
|
||||
transaction,
|
||||
})
|
||||
: 0;
|
||||
const cronStats =
|
||||
preview.policy.cronStatRetentionDays > 0
|
||||
? await CrontabStatModel.destroy({
|
||||
where: cronStatWhere(preview.policy.cronStatRetentionDays),
|
||||
transaction,
|
||||
})
|
||||
: 0;
|
||||
return { runningInstances, cronStats };
|
||||
let cronStats = 0;
|
||||
if (preview.policy.cronStatRetentionDays > 0) {
|
||||
const firstDay = cutoffs.firstDay;
|
||||
cronStats = await CrontabStatModel.destroy({ where: { date: { [Op.lt]: firstDay } }, transaction });
|
||||
await sequelize.query(`INSERT INTO CronStatRetention(id,first_day) VALUES (1,$firstDay)
|
||||
ON CONFLICT(id) DO UPDATE SET first_day=MAX(first_day,excluded.first_day)`,
|
||||
{ bind: { firstDay }, transaction });
|
||||
await sequelize.query(`DELETE FROM CronPrunedUnknownRuns WHERE last_possible_day <
|
||||
(SELECT first_day FROM CronStatRetention WHERE id=1)`, { transaction });
|
||||
}
|
||||
const triggers = preview.policy.runningInstanceRetentionDays > 0
|
||||
? await history.deleteExpired(cutoffs.history, transaction)
|
||||
: 0;
|
||||
if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) {
|
||||
// An unbound receipt's day can be wrong. A later bound receipt still
|
||||
// needs the execution-to-task link even after both visible histories expire.
|
||||
// A writer can also win the lock before an interrupted upgrade retries.
|
||||
// Keep its bound bookings until the proof-copy transaction has committed.
|
||||
await sequelize.query(`DELETE FROM CronLegacyExitBookings WHERE day <
|
||||
(SELECT first_day FROM CronStatRetention WHERE id=1)
|
||||
AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=CronLegacyExitBookings.trigger_id)
|
||||
AND ((bound=1 AND EXISTS (SELECT 1 FROM SchemaMigrations WHERE id=$proofMigration))
|
||||
OR (bound=0 AND NOT EXISTS (SELECT 1 FROM Crontabs WHERE id=CronLegacyExitBookings.cron_id)))`,
|
||||
{ bind: { proofMigration: prunedExitMigrationId }, transaction });
|
||||
}
|
||||
return { runningInstances, cronStats, triggers };
|
||||
});
|
||||
|
||||
const dependenceCaches = [];
|
||||
@@ -135,7 +166,7 @@ export default class RetentionService {
|
||||
|
||||
if (
|
||||
request.compactDatabase &&
|
||||
(deleted.runningInstances || deleted.cronStats)
|
||||
(deleted.runningInstances || deleted.cronStats || deleted.triggers)
|
||||
) {
|
||||
await sequelize.query('VACUUM');
|
||||
}
|
||||
@@ -148,7 +179,7 @@ export default class RetentionService {
|
||||
},
|
||||
compactedDatabase: Boolean(
|
||||
request.compactDatabase &&
|
||||
(deleted.runningInstances || deleted.cronStats),
|
||||
(deleted.runningInstances || deleted.cronStats || deleted.triggers),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -58,6 +58,10 @@ export default class SystemService {
|
||||
private sockService: SockService,
|
||||
) {}
|
||||
|
||||
public get cronConcurrency() {
|
||||
return taskLimit.cronConcurrency;
|
||||
}
|
||||
|
||||
public async getSystemConfig() {
|
||||
const doc = await this.getDb({ type: AuthDataType.systemConfig });
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import os from 'os';
|
||||
import { readFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
function read(file: string): string {
|
||||
try { return readFileSync(file, 'utf8').trim(); } catch { return ''; }
|
||||
}
|
||||
|
||||
// Walk ancestors too: a nested cgroup can inherit a tighter parent quota.
|
||||
export function containerResources(readValue = read, platform = process.platform) {
|
||||
const hostCpus = os.cpus().length;
|
||||
const hostMemory = os.totalmem();
|
||||
let cpus = hostCpus;
|
||||
let memTotal = hostMemory;
|
||||
let memFree = os.freemem();
|
||||
if (platform === 'linux') {
|
||||
const groups = readValue('/proc/self/cgroup').split('\n');
|
||||
for (const line of groups) {
|
||||
const match = /^\d+:([^:]*):(\/.*)$/.exec(line);
|
||||
if (!match) continue;
|
||||
const controllers = match[1].split(',');
|
||||
const unified = !match[1];
|
||||
for (const kind of ['cpu', 'memory', 'cpuset']) {
|
||||
if (!unified && !controllers.includes(kind)) continue;
|
||||
const roots = unified ? ['/sys/fs/cgroup'] : [...new Set([kind, match[1]].map(k => '/sys/fs/cgroup/' + k))];
|
||||
for (const root of roots) {
|
||||
let dir = path.join(root, path.normalize(match[2]));
|
||||
while (dir === root || dir.startsWith(root + '/')) {
|
||||
const value = (file: string) => readValue(path.join(dir, file));
|
||||
if (kind === 'cpu') {
|
||||
const [quota, period] = (unified ? value('cpu.max').split(/\s+/) :
|
||||
[value('cpu.cfs_quota_us'), value('cpu.cfs_period_us')]).map(Number);
|
||||
if (quota > 0 && period > 0) cpus = Math.min(cpus, quota / period);
|
||||
} else if (kind === 'cpuset') {
|
||||
const set = value(unified ? 'cpuset.cpus.effective' : 'cpuset.cpus');
|
||||
if (/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/.test(set)) {
|
||||
const count = set.split(',').reduce((n, range) => {
|
||||
const [lo, hi] = range.split('-').map(Number);
|
||||
return n + (hi ?? lo) - lo + 1;
|
||||
}, 0);
|
||||
if (count > 0) cpus = Math.min(cpus, count);
|
||||
}
|
||||
} else {
|
||||
const limit = Number(value(unified ? 'memory.max' : 'memory.limit_in_bytes'));
|
||||
if (limit > 0 && limit <= memTotal) {
|
||||
const usage = value(unified ? 'memory.current' : 'memory.usage_in_bytes');
|
||||
if (usage && Number.isFinite(Number(usage))) {
|
||||
memTotal = limit;
|
||||
memFree = Math.max(0, limit - Number(usage));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dir === root) break;
|
||||
dir = path.dirname(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { cpus, memTotal, memFree, hostCpus, hostMemory,
|
||||
memUsagePercent: ((1 - memFree / memTotal) * 100).toFixed(1) };
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { join } from 'path';
|
||||
import { existsSync } from 'fs';
|
||||
import { receiptPath } from './managedExit.cjs';
|
||||
import { spawn } from 'cross-spawn';
|
||||
import type { ChildProcessWithoutNullStreams } from 'child_process';
|
||||
import type { Readable } from 'stream';
|
||||
|
||||
// A managed command waits on its parent's pipe. EOF before authorization exits
|
||||
// without interpreting the command, even when the worker is killed by SIGKILL.
|
||||
export function spawnCronCommand(command: string, triggerId?: string, onCommandStart?: (at: number) => void) {
|
||||
if (!triggerId) return spawn(command, { shell: '/bin/bash' });
|
||||
const sourceScript = join(__dirname, '../../shell/cron-command.py');
|
||||
const supervisor = existsSync(sourceScript) ? sourceScript : join(process.env.QL_DIR!, 'shell/cron-command.py');
|
||||
const args = ['-I', '-S', supervisor, command, String(process.pid),
|
||||
receiptPath(triggerId) || '', process.execPath, join(__dirname, 'managedExit.cjs'),
|
||||
];
|
||||
if (onCommandStart) args.push('report-start');
|
||||
const child = spawn('python3', args, { env: { ...process.env, QL_TRIGGER_ID: triggerId },
|
||||
stdio: onCommandStart ? ['pipe', 'pipe', 'pipe', 'pipe'] : 'pipe' }) as ChildProcessWithoutNullStreams;
|
||||
if (onCommandStart && child.stdio[3]) {
|
||||
const timing = child.stdio[3] as Readable;
|
||||
let stamp = '';
|
||||
timing.setEncoding('ascii').on('data', chunk => { stamp += chunk; });
|
||||
timing.once('end', () => { if (/^\d{13}$/.test(stamp)) onCommandStart(Number(stamp)); });
|
||||
timing.on('error', () => {}); // Missing telemetry must not change the command result.
|
||||
}
|
||||
// A concurrent stop can close the pipe before the authorization write.
|
||||
child.stdin.on('error', () => {});
|
||||
return child;
|
||||
}
|
||||
|
||||
export function releaseCronCommand(child: ChildProcessWithoutNullStreams): Promise<void> {
|
||||
return new Promise((resolve, reject) =>
|
||||
child.stdin.end('run\n', (error?: Error) => error ? reject(error) : resolve()));
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Read literal shell words only. Never expand or execute a command to derive a
|
||||
// path. Adjacent quoted/unquoted fragments belong to the same argument.
|
||||
function words(command: string): string[] {
|
||||
const result: string[] = [];
|
||||
let value = '', quote = '', active = false;
|
||||
for (let i = 0; i < command.length; i++) {
|
||||
const c = command[i];
|
||||
if (quote && c === quote) { quote = ''; continue; }
|
||||
if (!quote && (c === "'" || c === '"')) { quote = c; active = true; continue; }
|
||||
if (c === '\\' && quote !== "'") {
|
||||
const next = command[++i];
|
||||
if (next === undefined) return [];
|
||||
if (quote === '"' && !/[$`"\\\n]/.test(next)) value += '\\';
|
||||
if (next !== '\n') { value += next; active = true; }
|
||||
continue;
|
||||
}
|
||||
if (!quote && /[;&|<>()\n]/.test(c)) break;
|
||||
if (!quote && /\s/.test(c)) {
|
||||
if (active) result.push(value);
|
||||
value = ''; active = false; continue;
|
||||
}
|
||||
if (!active && !quote && c === '#') break;
|
||||
value += c; active = true;
|
||||
}
|
||||
if (quote) return [];
|
||||
if (active) result.push(value);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function cronOperand(command: string, taskOnly = false): string | undefined {
|
||||
const args = words(command.trim());
|
||||
if (args[0] === 'task') args.shift();
|
||||
else if (taskOnly && args[0] === 'ql') return;
|
||||
while (args[0] === '-l' || args[0] === '-m') {
|
||||
if (args.shift() === '-m') args.shift();
|
||||
}
|
||||
if (args.length > 1 && /^(?:.*\/)?(?:node|python3?|bash|sh|ts-node(?:-transpile-only)?)$/.test(args[0])) args.shift();
|
||||
return args[0];
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { upcomingSlots } from './cronScheduler';
|
||||
|
||||
type Definition = {
|
||||
schedule?: string;
|
||||
extra_schedules?: { schedule: string }[];
|
||||
isDisabled?: number;
|
||||
saved?: boolean;
|
||||
};
|
||||
const cache = new Map<string, { after: number; times: number[] }>();
|
||||
|
||||
export function previewSchedule(
|
||||
schedule: string,
|
||||
count: number,
|
||||
now: number,
|
||||
): number[] {
|
||||
const key = JSON.stringify([
|
||||
Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
schedule,
|
||||
]);
|
||||
const cached = cache.get(key);
|
||||
if (cached && now >= cached.after) {
|
||||
const future = cached.times.filter((time) => time > now);
|
||||
if (future.length >= count) return future.slice(0, count);
|
||||
}
|
||||
const times = upcomingSlots(schedule, now, count);
|
||||
if (cache.size >= 512) cache.delete(cache.keys().next().value!);
|
||||
cache.set(key, { after: now, times });
|
||||
return times;
|
||||
}
|
||||
|
||||
export function withNextRun<T extends Definition>(cron: T) {
|
||||
let nextRunTime: number | null = null;
|
||||
if (
|
||||
cron.schedule &&
|
||||
!cron.isDisabled &&
|
||||
cron.saved !== false &&
|
||||
!cron.schedule.startsWith('@once') &&
|
||||
!cron.schedule.startsWith('@boot')
|
||||
) {
|
||||
try {
|
||||
const now = Date.now();
|
||||
nextRunTime = Math.min(
|
||||
...[
|
||||
cron.schedule,
|
||||
...(cron.extra_schedules || []).map((x) => x.schedule),
|
||||
].map((rule) => previewSchedule(rule, 1, now)[0]),
|
||||
);
|
||||
} catch {
|
||||
// Legacy invalid rows remain visible and editable.
|
||||
}
|
||||
}
|
||||
return { ...cron, nextRunTime };
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { execFileSync, spawnSync } from 'child_process';
|
||||
|
||||
// Legacy runs can outlive a scheduler restart without an active trigger receipt.
|
||||
export function hasLiveCronProcess(status?: number, pid?: number | null) {
|
||||
if (status !== 0 || !pid || pid < 0) return false; // CrontabStatus.running
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === 'ESRCH') return false;
|
||||
if (code === 'EPERM') return true;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function readBsdProcessField(pid: number, field: 'lstart' | 'ppid') {
|
||||
const result = spawnSync('ps', ['-p', String(pid), '-o', field + '='], {
|
||||
encoding: 'utf8', env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
|
||||
});
|
||||
// ENOENT from spawning ps refers to the executable, not the target PID.
|
||||
if (result.error) throw new Error('Cannot run ps: ' + result.error.message, { cause: result.error });
|
||||
const value = result.stdout.trim();
|
||||
if (result.status === 0 && value) return value;
|
||||
// BSD ps exits 1 without output when the selected PID has already exited.
|
||||
if (result.status === 1 && !value && !result.stderr.trim())
|
||||
throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
|
||||
throw new Error(`Cannot read ${field} for PID ${pid}: ${result.stderr.trim() || result.signal || 'ps status ' + result.status}`);
|
||||
}
|
||||
|
||||
export function systemOwner(pid: number) {
|
||||
if (process.platform !== 'linux') {
|
||||
// BSD crontab installations have no procfs. ps exposes the process birth time.
|
||||
process.kill(pid, 0);
|
||||
const birth = readBsdProcessField(pid, 'lstart');
|
||||
return `crond:${pid}:${birth}`;
|
||||
}
|
||||
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
||||
const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
||||
if (['Z', 'X', 'x'].includes(fields[0])) throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
|
||||
const startTicks = fields[19];
|
||||
const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
|
||||
return `crond:${pid}:${startTicks}:${boot}`;
|
||||
}
|
||||
|
||||
let linuxClockTicks: number | undefined;
|
||||
|
||||
// A start packet may arrive after its PID was recycled, before the replacement reports.
|
||||
export function legacyProcessOwner(pid: number, started: number): string | undefined {
|
||||
try {
|
||||
const identity = systemOwner(pid);
|
||||
const birth = identity.slice(`crond:${pid}:`.length);
|
||||
let bornAt: number;
|
||||
if (process.platform === 'linux') {
|
||||
linuxClockTicks ??= Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }));
|
||||
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
|
||||
if (!boot || !(linuxClockTicks > 0)) throw new Error('Cannot read process birth time');
|
||||
bornAt = Number(boot[1]) + Number(birth.split(':')[0]) / linuxClockTicks;
|
||||
} else {
|
||||
bornAt = Date.parse(birth + ' UTC') / 1000;
|
||||
}
|
||||
// Both the callback and Linux boot time have one-second precision.
|
||||
return Math.floor(bornAt) <= started + 1 ? identity : undefined;
|
||||
} catch (error) {
|
||||
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) return undefined;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// PID 1 survives worker restarts, but changes when a container or Linux host restarts.
|
||||
export function pidNamespaceOwner() {
|
||||
return process.platform === 'linux' ? systemOwner(1) : null;
|
||||
}
|
||||
|
||||
// psTree enumerates asynchronously. Reject a PID already reparented or recycled
|
||||
// between enumeration and the birth-token snapshot.
|
||||
export function isProcessDescendant(pid: number, root: number) {
|
||||
const seen = new Set<number>();
|
||||
while (pid > 1 && !seen.has(pid)) {
|
||||
if (pid === root) return true;
|
||||
seen.add(pid);
|
||||
if (process.platform === 'linux') {
|
||||
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
||||
pid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
|
||||
} else {
|
||||
pid = Number(readBsdProcessField(pid, 'ppid'));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// For an individual legacy instance the task ID alone also matches its siblings.
|
||||
export function verifyCronProcess(pid: number, cronId: number, identity?: string | null, started?: number,
|
||||
instance?: { logPath?: string }) {
|
||||
const conflict = () => Object.assign(new Error('Task process identity could not be verified'), { status: 409 });
|
||||
if (!Number.isInteger(pid) || pid <= 1) throw conflict();
|
||||
if (identity) {
|
||||
// A birth token for this PID proves the original process is gone if the
|
||||
// kernel now reports a different birth. Access errors remain retryable.
|
||||
if (!identity.startsWith(`crond:${pid}:`)) throw conflict();
|
||||
let current: string;
|
||||
try { current = systemOwner(pid); }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT')
|
||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
||||
throw error;
|
||||
}
|
||||
if (current !== identity) throw Object.assign(new Error('Command PID was reused'), { code: 'PID_REUSED', status: 409 });
|
||||
return current;
|
||||
}
|
||||
try {
|
||||
if (process.platform === 'linux') {
|
||||
const env = readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0');
|
||||
if (instance && (!instance.logPath || instance.logPath === '/dev/null' ||
|
||||
!env.includes('real_log_path=' + instance.logPath))) throw conflict();
|
||||
if (env.includes('ID=' + cronId) && started) {
|
||||
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
|
||||
const birth = systemOwner(pid);
|
||||
const ticks = Number(birth.split(':')[2]);
|
||||
const hz = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }));
|
||||
if (boot && hz > 0 && Math.floor(Number(boot[1]) + ticks / hz) <= started + 1) return birth;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) {
|
||||
// Distinguish a completed child whose receipt is still being written
|
||||
// from a live PID with an unverifiable identity.
|
||||
try { systemOwner(pid); } catch (probe) {
|
||||
if (['ENOENT', 'ESRCH'].includes((probe as NodeJS.ErrnoException).code!))
|
||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
||||
}
|
||||
}
|
||||
}
|
||||
throw conflict();
|
||||
}
|
||||
|
||||
// After a stop worker exits, descendants may already have been adopted by PID 1.
|
||||
// A saved birth identity still identifies them; walking the dead root no longer can.
|
||||
export async function finishStoppedTree(identities: string[], signalledAt?: number | null) {
|
||||
const surviving = () => identities.flatMap(identity => {
|
||||
const pid = Number(identity.split(':')[1]);
|
||||
if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error('Invalid saved process identity');
|
||||
try { return systemOwner(pid) === identity ? [pid] : []; }
|
||||
catch (error) {
|
||||
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) return [];
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
const remainingGrace = Math.min(1000, Math.max(0, (signalledAt ?? Date.now()) + 1000 - Date.now()));
|
||||
const graceDeadline = Date.now() + remainingGrace;
|
||||
while (surviving().length) {
|
||||
const remaining = graceDeadline - Date.now();
|
||||
if (remaining <= 0) break;
|
||||
await new Promise(resolve => setTimeout(resolve, Math.min(20, remaining)));
|
||||
}
|
||||
if (!surviving().length) return;
|
||||
// Revalidate each PID immediately before signalling, including after the grace period.
|
||||
for (const identity of identities) {
|
||||
const pid = Number(identity.split(':')[1]);
|
||||
try {
|
||||
if (systemOwner(pid) === identity) process.kill(pid, 'SIGKILL');
|
||||
} catch (error) {
|
||||
if (!['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) throw error;
|
||||
}
|
||||
}
|
||||
const deadline = Date.now() + 1000;
|
||||
while (surviving().length) {
|
||||
if (Date.now() >= deadline) throw new Error('Stopped process tree did not exit');
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { upcomingSlots } from './cronScheduler';
|
||||
|
||||
// Find only the latest eligible slot even for a second-level rule after hours
|
||||
// offline. Search by time, so cost is logarithmic in the configured window.
|
||||
export function latestMissedSlot(
|
||||
schedule: string,
|
||||
since: number,
|
||||
until: number,
|
||||
): number | null {
|
||||
let low = Math.floor(since / 1000);
|
||||
let high = Math.floor(until / 1000);
|
||||
let latest: number | null = null;
|
||||
while (low < high) {
|
||||
const middle = Math.floor((low + high) / 2);
|
||||
const [next] = upcomingSlots(schedule, middle * 1000);
|
||||
if (next > until) high = middle;
|
||||
else {
|
||||
latest = next;
|
||||
low = next / 1000;
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
@@ -12,6 +12,17 @@ export interface CronJob {
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
function acceptsSlot(parsed: ReturnType<typeof parseCronSchedule>, tasks: ScheduledTask[], index: number, date: Date) {
|
||||
if (tasks.length === 1) return true;
|
||||
// Preserve cron-parser 4's day/weekday OR semantics, including its
|
||||
// month-dependent full-day range and the global nth-week constraint.
|
||||
if (parsed.nthDay && Math.ceil(date.getDate() / 7) !== parsed.nthDay)
|
||||
return false;
|
||||
if (index === 1) return !tasks[0].match(date);
|
||||
const monthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
return parsed.dayCount < monthDays[date.getMonth()] || tasks[1].match(date);
|
||||
}
|
||||
|
||||
// node-cron owns timers and calendar calculation; Qinglong owns execution
|
||||
// concurrency and process lifetime. Missed in-process slots join that same queue.
|
||||
export function createCronJob(
|
||||
@@ -23,18 +34,8 @@ export function createCronJob(
|
||||
const tasks: ScheduledTask[] = [];
|
||||
let cancelled = false;
|
||||
let started = false;
|
||||
const accepts = (index: number, date: Date) => {
|
||||
if (tasks.length === 1) return true;
|
||||
// Preserve cron-parser 4's day/weekday OR semantics, including its
|
||||
// month-dependent full-day range and the global nth-week constraint.
|
||||
if (parsed.nthDay && Math.ceil(date.getDate() / 7) !== parsed.nthDay)
|
||||
return false;
|
||||
if (index === 1) return !tasks[0].match(date);
|
||||
const monthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
return parsed.dayCount < monthDays[date.getMonth()] || tasks[1].match(date);
|
||||
};
|
||||
const dispatch = async (index: number, date: Date, missed: boolean) => {
|
||||
if (cancelled || !started || !accepts(index, date)) return;
|
||||
if (cancelled || !started || !acceptsSlot(parsed, tasks, index, date)) return;
|
||||
if (missed) {
|
||||
options.logger.warn(
|
||||
t('[schedule][补执行迟到任务] 任务: %s, 计划时间: %s'),
|
||||
@@ -88,3 +89,54 @@ export function createCronJob(
|
||||
if (options.start !== false) job.start();
|
||||
return job;
|
||||
}
|
||||
|
||||
|
||||
// node-cron 4.6.0 exposes getNextRuns only from the wall clock. Its pinned
|
||||
// inline matcher also accepts an explicit cursor, needed for previews and recovery.
|
||||
export function upcomingSlots(schedule: string, after: number, count = 1, through?: number): number[] {
|
||||
const parsed = parseCronSchedule(schedule);
|
||||
const tasks: ScheduledTask[] = [];
|
||||
try {
|
||||
const matchers = parsed.patterns.map((pattern) => {
|
||||
const task = createTask(pattern, () => {});
|
||||
tasks.push(task);
|
||||
return (task as ScheduledTask & {
|
||||
timeMatcher: { getNextMatch(date: Date): Date; expressions: number[][] };
|
||||
}).timeMatcher;
|
||||
});
|
||||
const next = matchers.map((matcher) => matcher.getNextMatch(new Date(after)));
|
||||
// All calendar branches share their clock fields. For bounded audit ranges,
|
||||
// resolve each matching minute once, including the matcher's DST choice.
|
||||
const seconds = through == null ? [] : [...new Set(matchers[0].expressions[0])].sort((a,b) => a-b);
|
||||
const slots: number[] = [];
|
||||
let horizon = after + 366 * 100 * 86400000;
|
||||
while (slots.length < count) {
|
||||
const time = Math.min(...next.map(Number));
|
||||
if (through != null && time > through) break;
|
||||
if (!Number.isFinite(time) || time > horizon) throw new Error('No matching calendar date');
|
||||
let accepted = false;
|
||||
next.forEach((date, index) => {
|
||||
if (+date !== time) return;
|
||||
const valid = acceptsSlot(parsed, tasks, index, date);
|
||||
accepted ||= valid;
|
||||
// Both branches share the clock fields. Rejection applies to the
|
||||
// entire local day, including schedules that fire every second.
|
||||
const cursor = new Date(time);
|
||||
if (!valid) cursor.setHours(23, 59, 59, 999);
|
||||
else if (through != null) cursor.setTime(time - time % 60000 + 59999);
|
||||
next[index] = matchers[index].getNextMatch(cursor);
|
||||
});
|
||||
if (accepted) {
|
||||
if (through == null) slots.push(time);
|
||||
else for (const second of seconds) {
|
||||
const slot = time - time % 60000 + second * 1000;
|
||||
if (slot >= time && slot <= through && slots.length < count) slots.push(slot);
|
||||
}
|
||||
horizon = time + 366 * 100 * 86400000;
|
||||
}
|
||||
}
|
||||
return slots;
|
||||
} finally {
|
||||
tasks.forEach((task) => task.destroy());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
|
||||
// Hold the receipt claim and the daily increment in the same write transaction.
|
||||
export async function recordCronResult(
|
||||
database: Sequelize, cronId: number, _code: number, elapsedMs: number,
|
||||
finishedAt: number, triggerId: string, transaction?: Transaction,
|
||||
): Promise<void> {
|
||||
if (!triggerId) throw new Error('Execution identity required');
|
||||
if (!transaction) {
|
||||
return database.transaction((tx) =>
|
||||
recordCronResult(database, cronId, _code, elapsedMs, finishedAt, triggerId, tx));
|
||||
}
|
||||
const bind = { ref: cronId, id: triggerId };
|
||||
const claimed = await database.query(
|
||||
"UPDATE CronTriggers SET counted=1,exit_pending=NULL WHERE cron_id=$ref AND id=$id AND counted=0 AND started_at IS NOT NULL AND state IN ('finished','failed','stopped')",
|
||||
{ bind, type: QueryTypes.BULKUPDATE, transaction },
|
||||
);
|
||||
if (!claimed) {
|
||||
const rows = await database.query('SELECT 1 FROM CronTriggers WHERE cron_id=$ref AND id=$id',
|
||||
{ bind, type: QueryTypes.SELECT, transaction });
|
||||
if (!rows.length) throw new Error('Unknown trigger');
|
||||
return;
|
||||
}
|
||||
const [receipt] = await database.query<{ state: string; finished_at: number; reversible: number }>(
|
||||
`SELECT state,finished_at,EXISTS(SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=$id) AS reversible
|
||||
FROM CronTriggers WHERE cron_id=$ref AND id=$id`,
|
||||
{ bind, type: QueryTypes.SELECT, transaction });
|
||||
const day = dayjs(receipt.finished_at ?? finishedAt).format('YYYY-MM-DD');
|
||||
await addDailyExit(database, cronId, day, receipt.state, elapsedMs, Boolean(receipt.reversible), transaction);
|
||||
if (receipt.reversible) {
|
||||
await database.query(`UPDATE CronLegacyExitBookings SET stopped=$stopped,
|
||||
stat_id=(SELECT id FROM CrontabStats WHERE ref_id=$ref AND date=$day
|
||||
AND NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE id=1 AND first_day>$day))
|
||||
WHERE trigger_id=$id`, { bind: { ...bind, day, stopped: Number(receipt.state === 'stopped') }, transaction });
|
||||
}
|
||||
}
|
||||
|
||||
export async function addDailyExit(database: Sequelize, cronId: number, day: string, state: string,
|
||||
elapsedMs: number, reversible: boolean, transaction: Transaction) {
|
||||
await database.query(
|
||||
`INSERT INTO "CrontabStats"
|
||||
(ref_id, date, run_count, success_count, fail_count, total_time, max_time, fixed_max_time, createdAt, updatedAt)
|
||||
SELECT $id, $date, 1, $success, $fail, $elapsed, $elapsed, $fixedMax, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
WHERE NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE id=1 AND first_day>$date)
|
||||
ON CONFLICT(ref_id, date) DO UPDATE SET
|
||||
run_count = COALESCE(run_count, 0) + 1,
|
||||
success_count = COALESCE(success_count, 0) + excluded.success_count,
|
||||
fail_count = COALESCE(fail_count, 0) + excluded.fail_count,
|
||||
total_time = COALESCE(total_time, 0) + excluded.total_time,
|
||||
max_time = MAX(COALESCE(max_time, 0), excluded.max_time),
|
||||
fixed_max_time = MAX(COALESCE(fixed_max_time,max_time,0),excluded.fixed_max_time),
|
||||
updatedAt = excluded.updatedAt`,
|
||||
{ transaction, bind: { id: cronId, date: day, fixedMax: reversible ? 0 : elapsedMs,
|
||||
success: Number(state === 'finished'), fail: Number(state === 'failed'), elapsed: elapsedMs } },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { QueueAddOptions } from 'p-queue-cjs';
|
||||
|
||||
type Job = () => Promise<unknown>;
|
||||
export interface CronQueueOptions extends QueueAddOptions {
|
||||
waitingSignal?: EventEmitter;
|
||||
onRemoved?: () => void;
|
||||
}
|
||||
|
||||
// p-queue checks its signal only after dequeue. Remove expired waits while the
|
||||
// execution slots are still occupied, without aborting a running child.
|
||||
export class CronWaitQueue {
|
||||
private entries: { run: Job; priority: number; detach: () => void }[] = [];
|
||||
|
||||
get size() { return this.entries.length; }
|
||||
|
||||
enqueue(run: Job, options: Partial<CronQueueOptions> = {}) {
|
||||
const { priority = 0, waitingSignal, onRemoved } = options;
|
||||
const remove = () => {
|
||||
const index = this.entries.indexOf(entry);
|
||||
if (index < 0) return;
|
||||
this.entries.splice(index, 1);
|
||||
onRemoved?.();
|
||||
};
|
||||
const entry = { run, priority, detach: () => waitingSignal?.off('expired', remove) };
|
||||
const last = this.entries[this.size - 1];
|
||||
if (!last || last.priority >= priority) this.entries.push(entry);
|
||||
else this.entries.splice(this.entries.findIndex((job) => job.priority < priority), 0, entry);
|
||||
waitingSignal?.once('expired', remove);
|
||||
}
|
||||
|
||||
dequeue() {
|
||||
const next = this.entries.shift();
|
||||
next?.detach();
|
||||
return next?.run;
|
||||
}
|
||||
|
||||
filter(options: Partial<CronQueueOptions>) {
|
||||
return this.entries.filter((entry) => entry.priority === options.priority).map((entry) => entry.run);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { resolveFileAccess } from './fileAccess';
|
||||
|
||||
export type DirectoryVersion = [string, string | null];
|
||||
|
||||
function isGone(error: unknown) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
return code === 'ENOENT' || code === 'ENOTDIR';
|
||||
}
|
||||
|
||||
async function directoryVersion(root: string, parent: string, blacklist: string[]) {
|
||||
const dir = parent ? resolveFileAccess(root, [parent], blacklist) : root;
|
||||
const denied = () => Object.assign(new Error('Invalid directory'), { status: 403 });
|
||||
if (!dir) throw denied();
|
||||
try {
|
||||
if (await fs.realpath(dir) !== path.join(root, parent)) throw denied();
|
||||
const stat = await fs.lstat(dir, { bigint: true });
|
||||
return stat.isDirectory() ? [stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs].join(':') : null;
|
||||
} catch (error) {
|
||||
if (isGone(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkDirectoryVersions(root: string, blacklist: string[], versions: DirectoryVersion[]) {
|
||||
const realRoot = await fs.realpath(root);
|
||||
const matches = await Promise.all(versions.map(async ([parent, expected]) => {
|
||||
try {
|
||||
return await directoryVersion(realRoot, parent, blacklist) === expected;
|
||||
} catch (error) {
|
||||
// A formerly accessible directory may now be a symlink outside the root.
|
||||
if ((error as { status?: number }).status === 403) return false;
|
||||
throw error;
|
||||
}
|
||||
}));
|
||||
return matches.every(Boolean);
|
||||
}
|
||||
|
||||
export async function readDirectoryPage(root: string, blacklist: string[], directory: string, after: string,
|
||||
search: string, foldersOnly: boolean, newestFirst: boolean, limit = 50) {
|
||||
const blocked = new Set(blacklist.map(name => name.toLowerCase()));
|
||||
const realRoot = await fs.realpath(root);
|
||||
const versions: DirectoryVersion[] = [];
|
||||
async function entries(parent: string) {
|
||||
const version = await directoryVersion(realRoot, parent, blacklist);
|
||||
versions.push([parent, version]);
|
||||
if (version === null) return [];
|
||||
try {
|
||||
return (await fs.readdir(path.join(realRoot, parent), { withFileTypes: true })).filter(e =>
|
||||
!blocked.has(e.name.toLowerCase()) && (e.isDirectory() || (!foldersOnly && e.isFile())));
|
||||
} catch (error) {
|
||||
if (isGone(error)) return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
|
||||
const rows = [];
|
||||
let next: string | null = null;
|
||||
async function row(parent: string, title: string, directory: boolean) {
|
||||
const key = path.join(parent, title);
|
||||
if (directory) return { title, parent, key, type: 'directory', isLeaf: false };
|
||||
try {
|
||||
const stat = await fs.lstat(path.join(root, key));
|
||||
if (stat.isFile()) return { title, parent, key, type: 'file', isLeaf: true, size: stat.size };
|
||||
} catch (error) { if (!isGone(error)) throw error; }
|
||||
}
|
||||
if (!search) {
|
||||
const sorted = (await entries(directory)).sort((a,b) =>
|
||||
Number(b.isDirectory()) - Number(a.isDirectory()) ||
|
||||
compare(a.name, b.name) * (newestFirst && !a.isDirectory() ? -1 : 1));
|
||||
const selected = sorted.filter(e => {
|
||||
if (!after) return true;
|
||||
const group = e.isDirectory() ? '0' : '1';
|
||||
return group > after[0] || (group === after[0] &&
|
||||
compare(e.name, after.slice(1)) * (newestFirst && !e.isDirectory() ? -1 : 1) > 0);
|
||||
});
|
||||
const page = selected.slice(0, limit);
|
||||
const data = (await Promise.all(page.map(e => row(directory, e.name, e.isDirectory())))).filter(Boolean);
|
||||
if (selected.length > limit) {
|
||||
const last = page[page.length - 1];
|
||||
next = (last.isDirectory() ? '0' : '1') + last.name;
|
||||
}
|
||||
return { data, next, versions };
|
||||
}
|
||||
// Resume a depth-first search at the last visited entry, including on pages with zero matches.
|
||||
async function* walk(parent: string, resume: string[]): AsyncGenerator<{ parent: string; name: string; dir: boolean }> {
|
||||
const items = (await entries(parent)).sort((a,b) => compare(a.name,b.name));
|
||||
for (const item of items) {
|
||||
if (resume.length && item.name < resume[0]) continue;
|
||||
const same = item.name === resume[0];
|
||||
if (!same) yield { parent, name: item.name, dir: item.isDirectory() };
|
||||
if (item.isDirectory()) {
|
||||
try { yield* walk(path.join(parent, item.name), same ? resume.slice(1) : []); }
|
||||
catch (error) {
|
||||
if (!isGone(error) && (error as { status?: number }).status !== 403) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let visited = 0;
|
||||
for await (const entry of walk('', after ? after.split('/') : [])) {
|
||||
const key = path.join(entry.parent, entry.name);
|
||||
if (key.toLowerCase().includes(search.toLowerCase())) {
|
||||
const item = await row(entry.parent, entry.name, entry.dir);
|
||||
if (item) rows.push(item);
|
||||
}
|
||||
if (++visited >= 512 || rows.length === limit) { next = key; break; }
|
||||
}
|
||||
return { data: rows, next, versions };
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { checkDirectoryVersions, readDirectoryPage } from './directoryPage';
|
||||
|
||||
export function directoryCheckHandler(root: () => string, blacklist: string[]) {
|
||||
return [
|
||||
celebrate({ body: Joi.array().items(Joi.array().ordered(
|
||||
Joi.string().allow('').max(4096).required(), Joi.string().max(128).allow(null).required(),
|
||||
).length(2)).min(1).max(128).required() }),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const current = await checkDirectoryVersions(root(), blacklist, req.body);
|
||||
res.send({ code: 200, current });
|
||||
} catch (error) { next(error); }
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function directoryPageHandler(root: () => string, blacklist: string[], newestFirst: boolean) {
|
||||
return [
|
||||
celebrate({ query: Joi.object({
|
||||
path: Joi.string().allow(''), after: Joi.string().allow(''), search: Joi.string().allow(''),
|
||||
folders: Joi.boolean(), t: Joi.string(),
|
||||
}) }),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { path = '', after = '', search = '', folders } = req.query;
|
||||
const page = await readDirectoryPage(root(), blacklist, String(path), String(after),
|
||||
String(search), String(folders) === 'true', newestFirst);
|
||||
res.send({ code: 200, ...page });
|
||||
} catch (error) { next(error); }
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -2,3 +2,10 @@
|
||||
export function errStack(error: unknown): string {
|
||||
return error instanceof Error && error.stack ? error.stack : String(error);
|
||||
}
|
||||
|
||||
export class PendingCronInstall extends Error {
|
||||
readonly status = 503;
|
||||
constructor(readonly cronId: number, message: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// The original scheduled CLI wire format maps to its existing persisted trigger ID.
|
||||
export const executionIdPattern = /^(?:client-|legacy-system:\d{1,12}:)[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
|
||||
export function executionTriggerId(id: string) {
|
||||
return id.replace('legacy-system:', 'system-cli-').replace(':', '-');
|
||||
}
|
||||
|
||||
// A header lets upgraded clients keep the same identified body on older panels.
|
||||
export function receiptFinishTime(header?: string) {
|
||||
if (header && /^\d{1,13}$/.test(header)) {
|
||||
const time = Number(header);
|
||||
if (time > 0 && time <= Date.now()) return time;
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,11 @@ export function resolveFileAccess(
|
||||
const resolvedRoot = path.resolve(root);
|
||||
const target = path.resolve(resolvedRoot, ...parts);
|
||||
if (target === resolvedRoot || !isWithin(resolvedRoot, target)) return '';
|
||||
// File systems such as default APFS can resolve a differently cased spelling
|
||||
// of the same entry. Check every protected name without case sensitivity.
|
||||
const blockedNames = new Set(blacklist.map((part) => part.toLowerCase()));
|
||||
const isBlocked = (relative: string) =>
|
||||
relative.split(path.sep).some((part) => blacklist.includes(part));
|
||||
relative.split(path.sep).some((part) => blockedNames.has(part.toLowerCase()));
|
||||
if (isBlocked(path.relative(resolvedRoot, target))) return '';
|
||||
try {
|
||||
const realRoot = fs.realpathSync(resolvedRoot);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
const messages: Record<string, Record<string, string>> = {
|
||||
zh: {},
|
||||
en: {
|
||||
'系统定时规则安装失败,旧规则可能仍在运行,正在重试': 'System crontab installation failed. The previous rules may still run. Retrying.',
|
||||
'Cron表达式格式有误': 'Invalid cron expression',
|
||||
'升级任务启动失败,请检查日志后重试':
|
||||
'Failed to start the update. Check the logs and try again.',
|
||||
'[schedule][停止已运行任务] 任务ID: %s, PID: %s':
|
||||
@@ -23,6 +25,7 @@ const messages: Record<string, Record<string, string>> = {
|
||||
'代理层数不能超过 20': 'Proxy hop count cannot exceed 20',
|
||||
'环境变量 QL_TRUST_PROXY 已生效,系统设置不可覆盖':
|
||||
'QL_TRUST_PROXY is active and cannot be overridden by system settings',
|
||||
环境变量名称不可使用: 'Environment variable name is reserved or invalid',
|
||||
系统配置不存在: 'System configuration does not exist',
|
||||
'历史版本仅支持不超过 1 MiB 的 UTF-8 文本脚本':
|
||||
'Version history only supports UTF-8 text scripts up to 1 MiB',
|
||||
@@ -137,6 +140,7 @@ const messages: Record<string, Record<string, string>> = {
|
||||
验证失败: 'Verification failed',
|
||||
实例不存在或已停止: 'Instance does not exist or stopped',
|
||||
实例已停止: 'Instance stopped',
|
||||
实例已结束: 'Instance already ended',
|
||||
确认停止实例: 'Confirm to stop instance',
|
||||
确认停止运行实例: 'Confirm to stop running instance',
|
||||
确认停止: 'Confirm to stop',
|
||||
@@ -212,6 +216,9 @@ const messages: Record<string, Record<string, string>> = {
|
||||
日志设置为忽略: 'Log set to ignore',
|
||||
定时规则不能为空: 'Schedule rule cannot be empty',
|
||||
无效的定时规则: 'Invalid schedule rule',
|
||||
定时规则必须是字符串: 'Schedule rule must be a string',
|
||||
额外定时规则必须是对象: 'Extra schedule must be an object',
|
||||
额外定时规则必须是数组: 'Extra schedules must be an array',
|
||||
'日志名称只能包含中文、字母、数字、下划线、连字符、点和路径分隔符':
|
||||
'Log name can only contain Chinese characters, letters, numbers, underscores, hyphens, dots, and path separators',
|
||||
日志名称不能超过100个字符: 'Log name cannot exceed 100 characters',
|
||||
@@ -257,6 +264,8 @@ const messages: Record<string, Record<string, string>> = {
|
||||
'执行after命令...': 'Execute after command...',
|
||||
'## 执行结束... %s 耗时 %s 秒':
|
||||
'## Execution finished... %s elapsed %s seconds',
|
||||
'原调度未能恢复,正在重试': 'Could not restore the previous schedule. Retrying.',
|
||||
'任务已修改,请刷新后重试': 'The task has changed. Refresh and try again.',
|
||||
'调度器注册失败,任务创建已回滚':
|
||||
'Scheduler registration failed, task creation rolled back',
|
||||
'调度器注册失败,任务更新已回滚':
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
|
||||
type DayCounts = {
|
||||
cron_id: number;
|
||||
day: string;
|
||||
successes: number;
|
||||
failures: number;
|
||||
later_successes: number;
|
||||
later_failures: number;
|
||||
has_bookings: number;
|
||||
saved_successes: number;
|
||||
saved_failures: number;
|
||||
};
|
||||
|
||||
// Process one outcome, newest day first. Same-day receipts can only cover
|
||||
// eligible exits. Surplus becomes available to earlier days after this match.
|
||||
function matchDailyCounts(exits: number, saved: number, laterCredits: number, afterLastBooking = 0) {
|
||||
const localMatches = Math.min(saved, exits - afterLastBooking);
|
||||
const deficit = exits - localMatches;
|
||||
const borrowed = Math.min(deficit, laterCredits);
|
||||
return { missing: deficit - borrowed, remaining: laterCredits - borrowed + saved - localMatches };
|
||||
}
|
||||
|
||||
// A legacy terminal status needs a matching exit code. An identified supervisor
|
||||
// also knows a child failed when the OS returns a signal instead of a code.
|
||||
const confirmedResult = `t.started_at IS NOT NULL AND t.finished_at>=t.started_at
|
||||
AND t.state IN ('finished','failed')
|
||||
AND (t.source<>'legacy' OR (
|
||||
((t.state='finished' AND t.exit_code=0) OR (t.state='failed' AND t.exit_code<>0))
|
||||
AND NOT EXISTS (SELECT 1 FROM RunningInstances sibling
|
||||
LEFT JOIN CronTriggers linked ON linked.instance_id=sibling.id
|
||||
WHERE sibling.cron_id=i.cron_id AND sibling.pid=i.pid AND sibling.finished_at=i.finished_at
|
||||
AND sibling.id<>i.id AND sibling.status IN (1,3)
|
||||
AND (linked.id IS NULL OR (linked.source='legacy' AND linked.owner IS NULL))
|
||||
AND (sibling.started_at<>i.started_at OR COALESCE(sibling.log_path,'')<>COALESCE(i.log_path,'')
|
||||
OR sibling.status<>i.status OR sibling.exit_code IS NOT i.exit_code OR linked.id IS NOT NULL))))`;
|
||||
|
||||
export function readDailyResults(database: Sequelize, cronId: number) {
|
||||
const today = dayjs().startOf('day');
|
||||
const first = today.subtract(6, 'day');
|
||||
const next = today.add(1, 'day');
|
||||
return database.query<{
|
||||
day: string; exitSuccess: number; exitFail: number;
|
||||
bookedSuccess: number; bookedFail: number; supplement: number;
|
||||
}>(`WITH results AS (
|
||||
SELECT date(t.finished_at/1000,'unixepoch','localtime') AS day,
|
||||
SUM(t.state='finished') AS exitSuccess,SUM(t.state='failed') AS exitFail,
|
||||
0 AS bookedSuccess,0 AS bookedFail,0 AS supplement
|
||||
FROM CronTriggers t LEFT JOIN RunningInstances i ON i.id=t.instance_id
|
||||
WHERE t.cron_id=$id AND t.finished_at >= $start AND t.finished_at < $end
|
||||
AND t.reason IS NOT 'spawn' AND ${confirmedResult} GROUP BY day
|
||||
UNION ALL
|
||||
SELECT date,0,0,COALESCE(success_count,0),COALESCE(fail_count,0),untimed_count
|
||||
FROM CrontabStats WHERE ref_id=$id AND date >= $first AND date < $next
|
||||
) SELECT day,SUM(exitSuccess) AS exitSuccess,SUM(exitFail) AS exitFail,
|
||||
SUM(bookedSuccess) AS bookedSuccess,SUM(bookedFail) AS bookedFail,SUM(supplement) AS supplement
|
||||
FROM results GROUP BY day ORDER BY day DESC`, { type: QueryTypes.SELECT, bind: {
|
||||
id: cronId, start: first.valueOf(), end: next.valueOf(),
|
||||
first: first.format('YYYY-MM-DD'), next: next.format('YYYY-MM-DD'),
|
||||
} });
|
||||
}
|
||||
|
||||
// Run under the schema migration's write lock, before accepting new receipts.
|
||||
export async function repairLegacyDailyStatistics(database: Sequelize, transaction: Transaction, priorVersion: 0 | 1 | 2) {
|
||||
// Old panels updated every outstanding start with the reported PID. Identical
|
||||
// copies of a start prove only one exit; conflicting rows cannot identify it.
|
||||
const imported = await database.query(`WITH exits AS (
|
||||
SELECT MIN(i.id) AS instance FROM RunningInstances i
|
||||
JOIN Crontabs c ON c.id=i.cron_id
|
||||
LEFT JOIN CronTriggers linked ON linked.instance_id=i.id
|
||||
WHERE (linked.id IS NULL OR (linked.source='legacy' AND linked.owner IS NULL))
|
||||
AND i.status IN (1,3) AND i.pid>0 AND i.started_at>0 AND i.finished_at>=i.started_at
|
||||
AND i.finished_at*1000>=COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)
|
||||
GROUP BY i.cron_id,i.pid,i.finished_at
|
||||
HAVING MIN(i.started_at)=MAX(i.started_at)
|
||||
AND COUNT(DISTINCT COALESCE(i.log_path,''))=1 AND MIN(i.status)=MAX(i.status)
|
||||
AND COUNT(i.exit_code)=COUNT(*) AND MIN(i.exit_code)=MAX(i.exit_code)
|
||||
AND COUNT(linked.id)=0
|
||||
)
|
||||
INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,log_path,exit_code,counted)
|
||||
SELECT 'legacy-db-' || i.id,i.cron_id,'legacy',CASE i.status WHEN 1 THEN 'finished' ELSE 'failed' END,
|
||||
i.started_at*1000,i.started_at*1000,i.finished_at*1000,i.id,i.log_path,i.exit_code,1
|
||||
FROM exits JOIN RunningInstances i ON i.id=exits.instance
|
||||
WHERE (i.status=1 AND i.exit_code=0) OR (i.status=3 AND i.exit_code<>0)`,
|
||||
{ transaction, type: QueryTypes.BULKUPDATE });
|
||||
|
||||
// A newly imported last run must have the same owner it would acquire through
|
||||
// the normal handoff. An older exit must never replace a more recent start.
|
||||
if (imported) await database.query(`WITH ranked AS (
|
||||
SELECT cron_id,instance_id,started_at/1000 AS start,(finished_at-started_at)/1000 AS elapsed,
|
||||
ROW_NUMBER() OVER (PARTITION BY cron_id ORDER BY started_at DESC,instance_id DESC) AS position
|
||||
FROM CronTriggers WHERE source='legacy' AND id LIKE 'legacy-db-%'
|
||||
)
|
||||
UPDATE Crontabs AS c SET (last_instance_id,last_execution_time,last_running_time)=
|
||||
(SELECT instance_id,start,elapsed FROM ranked WHERE cron_id=c.id AND position=1)
|
||||
WHERE EXISTS (SELECT 1 FROM ranked r WHERE r.cron_id=c.id AND r.position=1 AND
|
||||
(c.last_execution_time IS NULL OR c.last_execution_time<r.start OR
|
||||
(c.last_execution_time=r.start AND (c.last_instance_id IS NULL OR c.last_instance_id<r.instance_id)))
|
||||
AND NOT EXISTS (SELECT 1 FROM RunningInstances i WHERE i.cron_id=c.id AND
|
||||
(i.started_at>r.start OR (i.started_at=r.start AND i.id>r.instance_id))))`,
|
||||
{ transaction });
|
||||
|
||||
// Statistics retention removes whole dates across tasks. When the old panel
|
||||
// retained no earlier totals, yesterday is the oldest date even a 1-day policy keeps.
|
||||
const yesterday = dayjs().subtract(1,'day').format('YYYY-MM-DD');
|
||||
const days = await database.query<DayCounts>(`WITH exits AS (
|
||||
SELECT t.cron_id,t.state,date(t.finished_at/1000,'unixepoch','localtime') AS day,
|
||||
t.started_at,i.createdAt,t.id
|
||||
FROM CronTriggers t LEFT JOIN RunningInstances i ON i.id=t.instance_id
|
||||
WHERE t.counted=1 AND ${confirmedResult}
|
||||
), ordered AS (
|
||||
SELECT e.*, CASE WHEN e.id LIKE 'legacy-db-%' AND s.untimed_count=0
|
||||
AND date(s.updatedAt,'localtime')=e.day AND julianday(s.createdAt)<=julianday(s.updatedAt)
|
||||
AND e.started_at/1000>CAST(strftime('%s',s.updatedAt) AS INTEGER)
|
||||
AND julianday(e.createdAt)>julianday(s.updatedAt) THEN 1 ELSE 0 END AS later
|
||||
FROM exits e LEFT JOIN CrontabStats s ON s.ref_id=e.cron_id AND s.date=e.day
|
||||
), evidence AS (
|
||||
SELECT cron_id,day,SUM(state='finished') AS successes,SUM(state='failed') AS failures,
|
||||
SUM(later*(state='finished')) AS later_successes,SUM(later*(state='failed')) AS later_failures,
|
||||
0 AS has_bookings,0 AS saved_successes,0 AS saved_failures FROM ordered GROUP BY cron_id,day
|
||||
UNION ALL
|
||||
SELECT ref_id,date,0,0,0,0,1,COALESCE(success_count,0),COALESCE(fail_count,0) FROM CrontabStats
|
||||
)
|
||||
SELECT cron_id,day,MAX(has_bookings) AS has_bookings,SUM(successes) AS successes,SUM(failures) AS failures,
|
||||
SUM(later_successes) AS later_successes,SUM(later_failures) AS later_failures,
|
||||
SUM(saved_successes) AS saved_successes,SUM(saved_failures) AS saved_failures
|
||||
FROM evidence WHERE day>=MIN($yesterday,COALESCE((SELECT MIN(date) FROM CrontabStats),$yesterday))
|
||||
AND day>=COALESCE((SELECT first_day FROM CronStatRetention WHERE id=1),'')
|
||||
GROUP BY cron_id,day ORDER BY cron_id,day DESC`, { type: QueryTypes.SELECT, transaction, bind:{ yesterday } });
|
||||
|
||||
// Anonymous receipts cannot identify a particular exit. Match nearest
|
||||
// eligible days first; never move already booked counts or elapsed samples.
|
||||
let task: number | undefined;
|
||||
let successCredit = 0, failureCredit = 0;
|
||||
let priorSuccessCredit = 0, priorFailureCredit = 0;
|
||||
for (const day of days) {
|
||||
if (day.cron_id !== task) {
|
||||
task = day.cron_id;
|
||||
successCredit = failureCredit = priorSuccessCredit = priorFailureCredit = 0;
|
||||
}
|
||||
const successes = matchDailyCounts(day.successes, day.saved_successes, successCredit, day.later_successes);
|
||||
const failures = matchDailyCounts(day.failures, day.saved_failures, failureCredit, day.later_failures);
|
||||
successCredit = successes.remaining;
|
||||
failureCredit = failures.remaining;
|
||||
let success = successes.missing, failure = failures.missing;
|
||||
if (priorVersion === 2) {
|
||||
// Replaying v2 on the current snapshot could resurrect a cleaned-up day.
|
||||
// Only the extra lower bound established by v3 is new evidence.
|
||||
const priorSuccess = matchDailyCounts(day.successes, day.saved_successes, priorSuccessCredit);
|
||||
const priorFailure = matchDailyCounts(day.failures, day.saved_failures, priorFailureCredit);
|
||||
priorSuccessCredit = priorSuccess.remaining;
|
||||
priorFailureCredit = priorFailure.remaining;
|
||||
success = Math.max(0, success - priorSuccess.missing);
|
||||
failure = Math.max(0, failure - priorFailure.missing);
|
||||
}
|
||||
// Old repairs did not journal deletions. An absent task/day could have
|
||||
// been cleared after a supplement. Preserve the gap on repeat upgrades.
|
||||
if (priorVersion && !day.has_bookings) continue;
|
||||
if (!success && !failure) continue;
|
||||
// Anonymous elapsed samples have no execution identity. Preserve measured
|
||||
// times; adding instance wall times here could count the same sample twice.
|
||||
await database.query(`INSERT INTO CrontabStats
|
||||
(ref_id,date,run_count,success_count,fail_count,untimed_count,total_time,max_time,createdAt,updatedAt)
|
||||
VALUES ($task,$day,$runs,$success,$failure,$runs,0,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(ref_id,date) DO UPDATE SET run_count=COALESCE(run_count,0)+excluded.run_count,
|
||||
success_count=COALESCE(success_count,0)+excluded.success_count,
|
||||
fail_count=COALESCE(fail_count,0)+excluded.fail_count,
|
||||
untimed_count=untimed_count+excluded.untimed_count,updatedAt=CURRENT_TIMESTAMP`,
|
||||
{ transaction, bind: { task,day:day.day,runs:success+failure,success,failure } });
|
||||
}
|
||||
}
|
||||
+56
-16
@@ -1,12 +1,18 @@
|
||||
import fs from 'fs/promises';
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
export const DEFAULT_LOG_CHUNK_BYTES = 256 * 1024;
|
||||
export const MAX_LOG_CHUNK_BYTES = 1024 * 1024;
|
||||
|
||||
// The viewer retains at most one Mi UTF-16 code units.
|
||||
const CURSOR_WINDOW_BYTES = 4 * MAX_LOG_CHUNK_BYTES;
|
||||
|
||||
export interface LogReadOptions {
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
tail?: boolean;
|
||||
follow?: boolean;
|
||||
cursor?: string;
|
||||
}
|
||||
|
||||
export interface LogChunk {
|
||||
@@ -15,6 +21,8 @@ export interface LogChunk {
|
||||
nextOffset: number;
|
||||
total: number;
|
||||
truncated: boolean;
|
||||
cursor?: string;
|
||||
reset?: boolean;
|
||||
}
|
||||
|
||||
function normalizeLimit(limit?: number) {
|
||||
@@ -49,6 +57,10 @@ function completeUtf8End(buffer: Buffer, start: number, end: number) {
|
||||
return end - sequenceStart < expectedLength ? sequenceStart : end;
|
||||
}
|
||||
|
||||
function logDigest(identity: string, from: number, bytes: Buffer) {
|
||||
return createHash('sha256').update(`${identity}:${from}:`).update(bytes).digest('hex');
|
||||
}
|
||||
|
||||
export async function readLogChunk(
|
||||
filePath: string,
|
||||
options: LogReadOptions = {},
|
||||
@@ -56,23 +68,43 @@ export async function readLogChunk(
|
||||
let handle: fs.FileHandle | undefined;
|
||||
try {
|
||||
handle = await fs.open(filePath, 'r');
|
||||
const { size: total } = await handle.stat();
|
||||
const stat = await handle.stat({ bigint: true });
|
||||
const total = Number(stat.size);
|
||||
const identity = `${stat.dev}:${stat.ino}`;
|
||||
const limit = normalizeLimit(options.limit);
|
||||
const requestedOffset = Number.isFinite(options.offset)
|
||||
? Math.trunc(options.offset!)
|
||||
? Math.max(0, Math.trunc(options.offset!))
|
||||
: undefined;
|
||||
const requestedStart =
|
||||
options.tail || requestedOffset === undefined
|
||||
? Math.max(total - limit, 0)
|
||||
: Math.min(Math.max(requestedOffset, 0), total);
|
||||
const length = Math.min(limit + 3, total - requestedStart);
|
||||
const buffer = Buffer.allocUnsafe(length);
|
||||
const { bytesRead } = await handle.read(
|
||||
buffer,
|
||||
0,
|
||||
length,
|
||||
requestedStart,
|
||||
);
|
||||
let start = options.tail || requestedOffset === undefined
|
||||
? Math.max(total - limit, 0)
|
||||
: Math.min(requestedOffset, total);
|
||||
const resume = options.cursor && !options.tail && requestedOffset !== undefined;
|
||||
const [fromText, digest] = resume ? options.cursor!.split('.') : [];
|
||||
let from = resume ? Number(fromText) : start;
|
||||
let reset = Boolean(resume && (
|
||||
requestedOffset !== start || !Number.isSafeInteger(from) ||
|
||||
from < 0 || from > start || start - from > CURSOR_WINDOW_BYTES
|
||||
));
|
||||
if (reset) from = start = 0;
|
||||
|
||||
// Read the previously displayed bytes and their continuation together.
|
||||
// A truncate followed by regrowth can leave both size and inode unchanged.
|
||||
const readWindow = async (position: number, end: number) => {
|
||||
const data = Buffer.allocUnsafe(Math.min(end, total) - position);
|
||||
const { bytesRead } = await handle!.read(data, 0, data.length, position);
|
||||
return data.subarray(0, bytesRead);
|
||||
};
|
||||
let window = await readWindow(from, start + limit + 3);
|
||||
if (resume && !reset) {
|
||||
const prefix = window.subarray(0, start - from);
|
||||
if (prefix.length !== start - from || logDigest(identity, from, prefix) !== digest) {
|
||||
reset = true;
|
||||
start = from = 0;
|
||||
window = await readWindow(0, limit + 3);
|
||||
}
|
||||
}
|
||||
const buffer = window.subarray(start - from);
|
||||
const bytesRead = buffer.length;
|
||||
let leadingBytes = 0;
|
||||
while (
|
||||
leadingBytes < bytesRead &&
|
||||
@@ -80,12 +112,20 @@ export async function readLogChunk(
|
||||
) {
|
||||
leadingBytes++;
|
||||
}
|
||||
const offset = requestedStart + leadingBytes;
|
||||
const offset = start + leadingBytes;
|
||||
const candidateEnd = Math.min(leadingBytes + limit, bytesRead);
|
||||
const contentEnd = completeUtf8End(buffer, leadingBytes, candidateEnd);
|
||||
const nextOffset = requestedStart + contentEnd;
|
||||
const nextOffset = start + contentEnd;
|
||||
|
||||
let cursor: string | undefined;
|
||||
if (options.follow || options.cursor) {
|
||||
const retainedFrom = Math.max(from, nextOffset - CURSOR_WINDOW_BYTES);
|
||||
cursor = resume && !reset && nextOffset === start ? options.cursor :
|
||||
`${retainedFrom}.${logDigest(identity, retainedFrom, window.subarray(retainedFrom - from, nextOffset - from))}`;
|
||||
}
|
||||
|
||||
return {
|
||||
...(cursor && { cursor, reset }),
|
||||
content: buffer.subarray(leadingBytes, contentEnd).toString('utf8'),
|
||||
offset,
|
||||
nextOffset,
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
// Keep the command's actual exit available until its SQLite transaction commits.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createHash, randomUUID } = require('node:crypto');
|
||||
|
||||
const idPattern = /^[a-z0-9-]{1,120}$/;
|
||||
|
||||
// A full data volume can still have room for a directory entry. In this format
|
||||
// the empty file publishes the tuple atomically, including its execution-bound
|
||||
// checksum. Keep the encoded name when moving it into a collector-private slot.
|
||||
const metadataName = /^\.pending\.([a-z0-9-]{1,120})\.full-(\d{1,3}|SIG[A-Z0-9]+)-(\d{1,16})-([0-9a-f]{64})-([a-zA-Z0-9_]+)$/;
|
||||
|
||||
// The digest only guards disposal of legacy bytes. It cannot establish an exit.
|
||||
const legacyCapture = /^\.pending\.([a-z0-9-]{1,120})\.l-([0-9a-f]{32})-[0-9a-f]{24}$/;
|
||||
const claimName = /^\.claim(-bound)?\.([a-z0-9-]{1,120})\.[a-zA-Z0-9]{6}$/;
|
||||
|
||||
function metadataReceipt(file) {
|
||||
const name = path.basename(file);
|
||||
return metadataName.exec(name === '.pending.claimed' ? path.basename(path.dirname(file)) : name);
|
||||
}
|
||||
|
||||
function storageFull(error) {
|
||||
const codes = [error?.code, error?.original?.code, error?.parent?.code];
|
||||
if (codes.some(code => ['ENOSPC', 'EDQUOT', 'SQLITE_FULL'].includes(code))) return true;
|
||||
const directory = receiptDirectory();
|
||||
if (directory && codes.includes('SQLITE_CANTOPEN')) {
|
||||
// SQLite maps a failed journal creation to CANTOPEN even when the kernel
|
||||
// reported ENOSPC. Other open failures keep their normal error semantics.
|
||||
try {
|
||||
const capacity = fs.statfsSync(path.dirname(directory));
|
||||
return capacity.bavail === 0 || (capacity.files > 0 && capacity.ffree === 0);
|
||||
} catch { return false; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function receiptDirectory() {
|
||||
const data = process.env.QL_DATA_DIR || (process.env.QL_DIR && path.join(process.env.QL_DIR, 'data'));
|
||||
if (data) return path.join(data, 'db', 'cron-exits');
|
||||
}
|
||||
|
||||
function receiptPath(id) {
|
||||
const directory = receiptDirectory();
|
||||
if (directory && typeof id === 'string' && idPattern.test(id)) return path.join(directory, id);
|
||||
}
|
||||
|
||||
async function listReceiptFiles(directory, prefix) {
|
||||
if (!directory) return [];
|
||||
try {
|
||||
const entries = await fs.promises.readdir(directory, { withFileTypes: true });
|
||||
const files = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() || !entry.name.startsWith(prefix)) continue;
|
||||
const id = entry.name.slice(prefix.length);
|
||||
if (idPattern.test(id)) files.push({ id, file: path.join(directory, entry.name) });
|
||||
}
|
||||
return files;
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function publishedExits() {
|
||||
return (await listReceiptFiles(receiptDirectory(), '')).map(entry => entry.id);
|
||||
}
|
||||
|
||||
// flock attaches to the open file description. The child inherits fd 3 and
|
||||
// exits immediately. Closing the panel's handle (including on SIGKILL)
|
||||
// releases the lock without leaving a lock file on a full volume.
|
||||
async function lockClaim(handle, shared) {
|
||||
const run = (program, args) => new Promise((resolve, reject) => {
|
||||
const child = require('node:child_process').spawn(program, args, {
|
||||
stdio: ['ignore', 'ignore', 'ignore', handle.fd],
|
||||
});
|
||||
child.once('error', reject);
|
||||
child.once('exit', (code, signal) => {
|
||||
if (code === 0 || code === 1) resolve(code === 0);
|
||||
else reject(new Error(`Receipt directory lock failed (${signal || code})`));
|
||||
});
|
||||
});
|
||||
try {
|
||||
return await run('flock', ['-n', shared ? '-s' : '-x', '3']);
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
// Python is also shipped with the task supervisor on minimal Linux images.
|
||||
const program = 'import fcntl,sys\ntry: fcntl.flock(3, fcntl.LOCK_NB | fcntl.LOCK_' +
|
||||
(shared ? 'SH' : 'EX') + ')\nexcept BlockingIOError: sys.exit(1)';
|
||||
return run('python3', ['-c', program]);
|
||||
}
|
||||
}
|
||||
|
||||
// Move the current directory entry to a fresh, recoverable name outside the
|
||||
// reusable claim directory. A writer can replace that entry without flock.
|
||||
// Only the bytes actually captured by this attempt authorize its final unlink.
|
||||
/** @param {string} id @param {string} file @param {{outcome: string, time: number}} [booked] */
|
||||
async function retireLegacyFile(id, file, booked) {
|
||||
const directory = receiptDirectory();
|
||||
const sourceDir = path.dirname(file);
|
||||
const slot = path.basename(file);
|
||||
const bound = /^\.(pending|published)\./.test(slot) && !legacyCapture.test(slot);
|
||||
const metadata = metadataReceipt(file);
|
||||
const parent = claimName.exec(path.basename(sourceDir));
|
||||
const privateSlot = path.dirname(sourceDir) === directory &&
|
||||
(parent?.[2] === id && slot === (parent[1] ? '.pending.claimed' : 'receipt') ||
|
||||
metadata?.[1] === id && slot === '.pending.claimed');
|
||||
if (!directory || !idPattern.test(id)) return;
|
||||
const dbDir = path.dirname(directory);
|
||||
const localBin = path.join(directory, '.reclaim');
|
||||
const fromBin = sourceDir === dbDir || sourceDir === localBin;
|
||||
if (sourceDir !== directory && !privateSlot && !(fromBin && captureId(slot) === id)) return;
|
||||
|
||||
const matches = exit => exit && !exit.namedExit && (exit.version === 1
|
||||
? booked && exit.time === booked.time && (exit.signal ?? String(exit.code)) === booked.outcome
|
||||
: !bound);
|
||||
let handle, binHandle;
|
||||
try {
|
||||
if ((privateSlot || sourceDir === localBin) && process.platform === 'linux') {
|
||||
handle = await fs.promises.open(sourceDir, fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
||||
if (privateSlot && !await lockClaim(handle, true)) return;
|
||||
}
|
||||
const source = handle ? `/proc/self/fd/${handle.fd}/${slot}` : file;
|
||||
// A canonical publication may only be readable after the move. For a
|
||||
// recovered copy, first avoid moving an unsettled witness on every scan.
|
||||
const previous = await readExit(id, source, file);
|
||||
if (slot !== id && !matches(previous)) return;
|
||||
const nonce = randomUUID();
|
||||
let name;
|
||||
if (metadata) {
|
||||
name = metadata[0].slice(0, -metadata[5].length) + 'r_' + nonce.replace(/-/g, '').slice(0, 16);
|
||||
} else if (bound || !previous || previous.version === 1) {
|
||||
name = `.pending.${id}.r-${nonce}`;
|
||||
} else {
|
||||
const digest = exitChecksum(id, previous.code, previous.signal, previous.time).slice(0, 32);
|
||||
name = `.pending.${id}.l-${digest}-${nonce.replace(/-/g, '').slice(0, 24)}`;
|
||||
}
|
||||
// The database directory is outside the writers' receipt namespace and
|
||||
// already exists even at zero free inodes. A separately mounted journal
|
||||
// requires a disposal directory on its own filesystem.
|
||||
let bin = sourceDir === localBin ? localBin : dbDir;
|
||||
const pinBin = async () => {
|
||||
binHandle = await fs.promises.open(localBin, fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
||||
return process.platform === 'linux' ? `/proc/self/fd/${binHandle.fd}/${name}` : path.join(localBin, name);
|
||||
};
|
||||
let captured = path.join(bin, name);
|
||||
if (bin === localBin) captured = handle ? path.join(path.dirname(source), name) : await pinBin();
|
||||
try {
|
||||
await fs.promises.rename(source, captured);
|
||||
} catch (error) {
|
||||
if (error.code !== 'EXDEV' || bin === localBin) throw error;
|
||||
await fs.promises.mkdir(localBin, { mode: 0o700, recursive: true });
|
||||
bin = localBin;
|
||||
captured = await pinBin();
|
||||
await fs.promises.rename(source, captured);
|
||||
}
|
||||
const actual = await readExit(id, captured, path.join(bin, name));
|
||||
// An unreadable source offers no authority to discard unbound bytes.
|
||||
const sameExit = previous && actual && actual.version === previous.version &&
|
||||
actual.code === previous.code && actual.signal === previous.signal && actual.time === previous.time;
|
||||
if (matches(actual) && (sameExit || (!previous && actual.version === 1))) {
|
||||
await fs.promises.unlink(captured);
|
||||
} else if (actual !== undefined) {
|
||||
// A differing, torn or unreadable file is evidence for another pass.
|
||||
// Persist its new directory entry before releasing the original directory.
|
||||
if (binHandle) await binHandle.sync();
|
||||
else if (bin !== sourceDir || !handle) syncDirectory(bin);
|
||||
if (bin === localBin) syncDirectory(directory);
|
||||
if (handle) await handle.sync();
|
||||
else if (sourceDir !== bin) syncDirectory(sourceDir);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
} finally {
|
||||
if (binHandle) await binHandle.close();
|
||||
if (handle) await handle.close();
|
||||
if (privateSlot) await fs.promises.rmdir(sourceDir).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
function captureId(name) {
|
||||
const marker = metadataName.exec(name);
|
||||
if (marker && /^r_[0-9a-f]{16}$/.test(marker[5])) return marker[1];
|
||||
const match = legacyCapture.exec(name) ??
|
||||
/^\.pending\.([a-z0-9-]{1,120})\.r-[0-9a-f-]{36}$/.exec(name);
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
async function receiptEntries(directory) {
|
||||
try { return await fs.promises.readdir(directory, { withFileTypes: true }); }
|
||||
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
||||
}
|
||||
|
||||
async function retiringExits() {
|
||||
const dir = receiptDirectory();
|
||||
if (!dir) return [];
|
||||
const files = [];
|
||||
const bins = [path.dirname(dir)];
|
||||
for (const entry of await receiptEntries(dir)) {
|
||||
if (entry.isDirectory() && entry.name === '.reclaim') {
|
||||
bins.push(path.join(dir, entry.name));
|
||||
continue;
|
||||
}
|
||||
const claim = claimName.exec(entry.name);
|
||||
const metadata = metadataName.exec(entry.name);
|
||||
if ((claim || metadata) && entry.isDirectory()) {
|
||||
const directory = path.join(dir, entry.name);
|
||||
try { await fs.promises.rmdir(directory); continue; } catch (error) {
|
||||
if (error.code === 'ENOENT') continue;
|
||||
}
|
||||
files.push({ id: metadata ? metadata[1] : claim[2], file: path.join(directory, metadata || claim[1] ? '.pending.claimed' : 'receipt') });
|
||||
continue;
|
||||
}
|
||||
const match = metadata ?? /^\.(?:retiring|collecting)\.([a-z0-9-]{1,120})\.[0-9a-f-]{36}$/.exec(entry.name)
|
||||
?? /^\.pending\.([a-z0-9-]{1,120})\.[a-z0-9_-]{1,64}$/.exec(entry.name)
|
||||
?? /^\.published\.([a-z0-9-]{1,120})\.[0-9a-f]{64}$/.exec(entry.name);
|
||||
if (entry.isFile() && match) files.push({ id:match[1], file:path.join(dir,entry.name) });
|
||||
}
|
||||
for (const bin of bins) {
|
||||
for (const entry of await receiptEntries(bin)) {
|
||||
const id = entry.isFile() && captureId(entry.name);
|
||||
if (id) files.push({ id, file:path.join(bin,entry.name) });
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
async function publishedScriptStarts() {
|
||||
const directory = process.env.QL_DIR && path.join(process.env.QL_DIR, '.tmp');
|
||||
try {
|
||||
return await listReceiptFiles(directory, 'cron-start-');
|
||||
} catch {
|
||||
// Optional entry instrumentation must not prevent exit recovery.
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function validExit(code, signal, time) {
|
||||
return Number.isSafeInteger(time) && time > 0 && Number.isFinite(new Date(time).getTime()) &&
|
||||
((Number.isInteger(code) && code >= 0 && code <= 255 && signal === null) ||
|
||||
(code === null && typeof signal === 'string' && /^SIG[A-Z0-9]+$/.test(signal)));
|
||||
}
|
||||
|
||||
// The Python supervisor uses the same compact JSON array of ASCII values.
|
||||
function exitChecksum(id, code, signal, time) {
|
||||
return createHash('sha256').update(JSON.stringify([id, code, signal, time])).digest('hex');
|
||||
}
|
||||
|
||||
function syncDirectory(directory) {
|
||||
const fd = fs.openSync(directory, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY);
|
||||
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
||||
}
|
||||
|
||||
function writeExit(id, code, signal, time) {
|
||||
if (!validExit(code, signal, time)) throw new TypeError('Invalid command exit receipt');
|
||||
const file = receiptPath(id);
|
||||
if (!file) return;
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
||||
const checksum = exitChecksum(id, code, signal, time);
|
||||
const receipt = JSON.stringify({ code, signal, time, version: 1, checksum });
|
||||
// Creation is the first durable observation. No data block is needed for
|
||||
// this witness. Keep the regular JSON publication for earlier readers.
|
||||
const directory = path.dirname(file);
|
||||
const prefix = '.pending.' + id + '.';
|
||||
const marker = prefix + 'full-' + (signal ?? code) + '-' + time + '-' + checksum + '-';
|
||||
const publish = (name, content) => {
|
||||
for (;;) {
|
||||
const target = path.join(directory, name + randomUUID().replace(/-/g, '').slice(0, 16));
|
||||
try {
|
||||
fs.writeFileSync(target, content, { flag: 'wx', mode: 0o600, flush: Boolean(content) });
|
||||
return target;
|
||||
} catch (error) {
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
publish(marker, '');
|
||||
// ext4 journals the empty inode and directory entry together. Also fence the
|
||||
// directory's own entry: another publisher may just have created it.
|
||||
syncDirectory(directory);
|
||||
syncDirectory(path.dirname(directory));
|
||||
try {
|
||||
if (fs.statfsSync(directory).bavail === 0) return;
|
||||
const source = publish(marker, receipt);
|
||||
try { fs.linkSync(source, file); }
|
||||
catch (error) {
|
||||
if (error.code === 'ENOENT') return;
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
// A panel from before metadata receipts can still discover this retry.
|
||||
for (;;) {
|
||||
try { fs.linkSync(source, path.join(directory, prefix + randomUUID())); break; }
|
||||
catch (linkError) {
|
||||
if (linkError.code === 'ENOENT') break;
|
||||
if (linkError.code !== 'EEXIST') throw linkError;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Older panels find the JSON only through this newly created link.
|
||||
syncDirectory(directory);
|
||||
} catch (error) {
|
||||
if (!storageFull(error)) throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function parseExit(id, value) {
|
||||
if (!value || !validExit(value.code, value.signal, value.time)) return null;
|
||||
const { code, signal, time, checksum, version } = value;
|
||||
if (version !== undefined || checksum !== undefined) {
|
||||
if (version !== 1 || checksum !== exitChecksum(id, code, signal, time)) return null;
|
||||
} else if (Object.keys(value).length !== 3) {
|
||||
return null;
|
||||
}
|
||||
return { code, signal, time, version };
|
||||
}
|
||||
|
||||
// undefined means no publication. null means a result cannot yet be trusted.
|
||||
async function readExit(id, file = receiptPath(id), publication = file) {
|
||||
if (!file) return;
|
||||
try {
|
||||
const handle = await fs.promises.open(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW);
|
||||
try {
|
||||
// Bound CPU and memory even if the damaged file is growing.
|
||||
const buffer = Buffer.alloc(1025);
|
||||
let size = 0;
|
||||
while (size < buffer.length) {
|
||||
const { bytesRead } = await handle.read(buffer, size, buffer.length - size, null);
|
||||
if (!bytesRead) break;
|
||||
size += bytesRead;
|
||||
}
|
||||
if (size === buffer.length) return null;
|
||||
const metadata = metadataReceipt(publication);
|
||||
const bytes = buffer.toString('utf8', 0, size);
|
||||
let namedExit;
|
||||
if (metadata && metadata[1] === id && (await handle.stat()).isFile()) {
|
||||
const [, , outcome, end, checksum] = metadata;
|
||||
const signal = outcome.startsWith('SIG') ? outcome : null;
|
||||
const value = { code: signal ? null : Number(outcome), signal, time: Number(end), version: 1, checksum };
|
||||
// Both current publishers serialize in this order. Accept a torn body
|
||||
// only when every byte matches the tuple independently published by
|
||||
// the filename. Validate replacement files on their own bytes below.
|
||||
namedExit = parseExit(id, value);
|
||||
const json = JSON.stringify(value);
|
||||
if (json.startsWith(bytes)) {
|
||||
return namedExit && { ...namedExit, file, namedExit: undefined };
|
||||
}
|
||||
}
|
||||
const exit = parseExit(id, JSON.parse(bytes));
|
||||
const guard = legacyCapture.exec(path.basename(publication));
|
||||
if (guard && exit && exit.version !== 1 && (guard[1] !== id ||
|
||||
guard[2] !== exitChecksum(id, exit.code, exit.signal, exit.time).slice(0, 32))) return null;
|
||||
const conflictingName = exit?.version === 1 && namedExit && (exit.time !== namedExit.time ||
|
||||
exit.code !== namedExit.code || exit.signal !== namedExit.signal);
|
||||
return exit && { ...exit, file, namedExit: conflictingName ? namedExit : undefined };
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return;
|
||||
if (error.code || error instanceof SyntaxError) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { isLegacyCapture: file => legacyCapture.test(path.basename(file)), isMetadataReceipt: file => Boolean(metadataReceipt(file)), receiptPath, publishedExits, publishedScriptStarts, readExit, writeExit, validExit, storageFull, retireLegacyFile, retiringExits };
|
||||
|
||||
if (require.main === module) {
|
||||
const id = process.env.QL_TRIGGER_ID;
|
||||
const exit = parseExit(id, JSON.parse(process.argv[2]));
|
||||
if (!idPattern.test(id || '') || !exit) throw new Error('Invalid supervisor exit receipt');
|
||||
const { code, signal, time } = exit;
|
||||
// An older supervisor may only have delivered this tuple in its message.
|
||||
// Journal it before waiting for the SQLite writer or loading the panel.
|
||||
let journaled = false;
|
||||
if (exit.version === 1) {
|
||||
try { writeExit(id, code, signal, time); journaled = Boolean(receiptPath(id)); }
|
||||
catch (error) { console.error('[scheduler] Could not journal supervisor message:', error); }
|
||||
}
|
||||
// Development workers run TypeScript directly. Released panels load the
|
||||
// compiled module without starting another runtime on ordinary exits.
|
||||
if (!fs.existsSync(path.join(__dirname, 'triggerHistory.js'))) {
|
||||
process.env.TS_NODE_PROJECT = path.join(__dirname, '../tsconfig.json');
|
||||
require('ts-node/register/transpile-only');
|
||||
}
|
||||
const { triggerHistory } = require('./triggerHistory');
|
||||
triggerHistory().complete(id, signal || code !== 0 ? 'failed' : 'finished',
|
||||
signal, code, time, exit.version === 1 ? exit : 'legacy').catch(error => {
|
||||
if (journaled && storageFull(error)) return;
|
||||
console.error('[scheduler] Failed to settle orphaned command:', error);
|
||||
process.exitCode = storageFull(error) ? 75 : 1;
|
||||
}).finally(() => require('../data').sequelize.close());
|
||||
}
|
||||
+43
-5
@@ -1,5 +1,9 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
|
||||
import os from 'os';
|
||||
import type { Sequelize } from 'sequelize';
|
||||
import { QueueOccupants, recordQueueAdmission } from './queueDiagnostics';
|
||||
import { CronWaitQueue, CronQueueOptions } from './cronWaitQueue';
|
||||
import { AuthDataType, SystemModel } from '../data/system';
|
||||
import Logger from '../loaders/logger';
|
||||
import { Dependence } from '../data/dependence';
|
||||
@@ -23,7 +27,11 @@ class TaskLimit {
|
||||
private queuedCrons = new Map<string, ICronFn<any>[]>();
|
||||
private repeatCronNotifyMap = new Map<string, number>();
|
||||
private updateLogLimit = new PQueue({ concurrency: 1 });
|
||||
private cronLimit = new PQueue({
|
||||
private warnSampling = (error: Error) => Logger.warn('[queue] Could not save occupancy: %s', error.message);
|
||||
private scheduledOccupants = new QueueOccupants('scheduled', () => this.cronLimit.concurrency, this.warnSampling);
|
||||
private manualOccupants = new QueueOccupants('manual', () => this.manualCronoLimit.concurrency, this.warnSampling);
|
||||
private cronLimit = new PQueue<CronWaitQueue, CronQueueOptions>({
|
||||
queueClass: CronWaitQueue,
|
||||
concurrency: Math.max(os.cpus().length, 4),
|
||||
});
|
||||
private manualCronoLimit = new PQueue({
|
||||
@@ -131,10 +139,16 @@ class TaskLimit {
|
||||
}
|
||||
}
|
||||
|
||||
public get cronConcurrency() {
|
||||
return this.manualCronoLimit.concurrency;
|
||||
}
|
||||
|
||||
public async setCustomLimit(limit?: number) {
|
||||
if (limit) {
|
||||
this.cronLimit.concurrency = limit;
|
||||
this.manualCronoLimit.concurrency = limit;
|
||||
this.scheduledOccupants.refresh();
|
||||
this.manualOccupants.refresh();
|
||||
return;
|
||||
}
|
||||
await SystemModel.sync();
|
||||
@@ -142,8 +156,7 @@ class TaskLimit {
|
||||
where: { type: AuthDataType.systemConfig },
|
||||
});
|
||||
if (doc?.info?.cronConcurrency) {
|
||||
this.cronLimit.concurrency = doc.info.cronConcurrency;
|
||||
this.manualCronoLimit.concurrency = doc.info.cronConcurrency;
|
||||
await this.setCustomLimit(doc.info.cronConcurrency);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +165,10 @@ class TaskLimit {
|
||||
fn: ICronFn<T>,
|
||||
options?: Partial<QueueAddOptions>,
|
||||
isCurrent: () => boolean = () => true,
|
||||
onPending?: () => void,
|
||||
waitingSignal?: EventEmitter,
|
||||
triggerId?: string,
|
||||
db?: Sequelize,
|
||||
): Promise<T | void> {
|
||||
if (!isCurrent()) return;
|
||||
fn.cron = cron;
|
||||
@@ -160,6 +177,10 @@ class TaskLimit {
|
||||
const runs = this.queuedCrons
|
||||
.get(cron.id)
|
||||
?.filter((run) => run.isCurrent?.() !== false);
|
||||
if (cron.skip_if_pending && runs?.length) {
|
||||
onPending?.();
|
||||
return;
|
||||
}
|
||||
const result = runs?.length ? [...runs, fn] : [fn];
|
||||
const repeatTimes = this.repeatCronNotifyMap.get(cron.id) || 0;
|
||||
if (result?.length > 5) {
|
||||
@@ -190,14 +211,31 @@ class TaskLimit {
|
||||
return;
|
||||
}
|
||||
this.queuedCrons.set(cron.id, result);
|
||||
return this.cronLimit.add(fn, options);
|
||||
const run = this.trackAdmission(this.scheduledOccupants, this.cronLimit.concurrency, fn,
|
||||
{ id: triggerId, name: cron.name || cron.id }, db);
|
||||
if (!waitingSignal) return this.cronLimit.add(run, options);
|
||||
return new Promise<T | void>((resolve, reject) => {
|
||||
this.cronLimit.add(run, { ...options, waitingSignal, onRemoved: () => { this.scheduledOccupants.forget(triggerId); resolve(); } }).then(resolve, reject);
|
||||
});
|
||||
}
|
||||
|
||||
private trackAdmission<T>(pool: QueueOccupants, limit: number, fn: () => Promise<T>, occupant: { id?: string; name: string }, db?: Sequelize) {
|
||||
const admission = pool.admission(limit);
|
||||
if (occupant.id && admission && db) {
|
||||
pool.watch(occupant.id, db);
|
||||
void recordQueueAdmission(db, occupant.id, admission)
|
||||
.catch(error => Logger.warn('[queue] Failed to record wait reason: %s', error.message));
|
||||
}
|
||||
return pool.track(fn, occupant, db);
|
||||
}
|
||||
|
||||
public async manualRunWithCronLimit<T>(
|
||||
fn: () => Promise<T>,
|
||||
options?: Partial<QueueAddOptions>,
|
||||
occupant: { id?: string; name: string } = { name: '—' },
|
||||
db?: Sequelize,
|
||||
): Promise<T | void> {
|
||||
return this.manualCronoLimit.add(fn, options);
|
||||
return this.manualCronoLimit.add(this.trackAdmission(this.manualOccupants, this.manualCronoLimit.concurrency, fn, occupant, db), options);
|
||||
}
|
||||
|
||||
public async runWithSubscriptionLimit<T>(
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { QueryTypes, Sequelize } from 'sequelize';
|
||||
|
||||
type Occupant = { id?: string; name: string };
|
||||
export type Admission = {
|
||||
queue: 'manual' | 'scheduled';
|
||||
limit: number;
|
||||
occupied: number;
|
||||
holders: Occupant[];
|
||||
};
|
||||
|
||||
// Each object belongs to exactly one execution pool in its owning process.
|
||||
export class QueueOccupants {
|
||||
private active = new Set<Occupant>();
|
||||
private waiting = new Map<string, Sequelize>();
|
||||
private writing = false;
|
||||
private changed = false;
|
||||
|
||||
constructor(
|
||||
private queue: Admission['queue'],
|
||||
private limit: () => number,
|
||||
private warn: (error: Error) => void,
|
||||
) {}
|
||||
|
||||
watch(id: string, db: Sequelize) {
|
||||
this.waiting.set(id, db);
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
forget(id?: string) {
|
||||
if (id) this.waiting.delete(id);
|
||||
}
|
||||
|
||||
refresh() {
|
||||
if (!this.waiting.size) return;
|
||||
this.changed = true;
|
||||
if (this.writing) return;
|
||||
this.writing = true;
|
||||
// Coalesce synchronous PQueue handoffs and keep SQLite writes in observation order.
|
||||
void Promise.resolve().then(async () => {
|
||||
try {
|
||||
while (this.changed) {
|
||||
this.changed = false;
|
||||
const context = JSON.stringify(this.snapshot(this.limit()));
|
||||
const groups = new Map<Sequelize, string[]>();
|
||||
for (const [id, db] of this.waiting) {
|
||||
const ids = groups.get(db);
|
||||
if (ids) ids.push(id);
|
||||
else groups.set(db, [id]);
|
||||
}
|
||||
for (const [db, ids] of groups) {
|
||||
await db
|
||||
.query(
|
||||
`UPDATE CronTriggers SET queue_live_context=$context
|
||||
WHERE state='queued' AND dequeued_at IS NULL AND id IN (SELECT value FROM json_each($ids))`,
|
||||
{ bind: { context, ids: JSON.stringify(ids) } },
|
||||
)
|
||||
.catch(this.warn);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.writing = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
admission(limit: number): Admission | undefined {
|
||||
return this.active.size >= limit ? this.snapshot(limit) : undefined;
|
||||
}
|
||||
|
||||
private snapshot(limit: number): Admission {
|
||||
return {
|
||||
queue: this.queue,
|
||||
limit,
|
||||
occupied: this.active.size,
|
||||
holders: [...this.active].slice(0, 8),
|
||||
};
|
||||
}
|
||||
|
||||
track<T>(job: () => Promise<T>, occupant: Occupant, db?: Sequelize) {
|
||||
return async () => {
|
||||
this.forget(occupant.id);
|
||||
this.active.add(occupant);
|
||||
this.refresh();
|
||||
if (occupant.id && db) {
|
||||
void db
|
||||
.query(
|
||||
'UPDATE CronTriggers SET dequeued_at=$at,queue_live_context=NULL WHERE id=$id AND queued_at <= $at AND dequeued_at IS NULL',
|
||||
{ bind: { id: occupant.id, at: Date.now() } },
|
||||
)
|
||||
.catch(this.warn);
|
||||
}
|
||||
try {
|
||||
return await job();
|
||||
} finally {
|
||||
this.active.delete(occupant);
|
||||
this.refresh();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function recordQueueAdmission(
|
||||
db: Sequelize,
|
||||
id: string,
|
||||
admission: Admission,
|
||||
) {
|
||||
return db.query(
|
||||
'UPDATE CronTriggers SET queue_context=$context WHERE id=$id AND queued_at <= $at AND queue_context IS NULL',
|
||||
{ bind: { id, at: Date.now(), context: JSON.stringify(admission) } },
|
||||
);
|
||||
}
|
||||
|
||||
export function oldestQueued(db: Sequelize) {
|
||||
return db.query<{
|
||||
id: string;
|
||||
name: string;
|
||||
source: string;
|
||||
queued_at: number;
|
||||
queue_context: string | null;
|
||||
queue_live_context: string | null;
|
||||
}>(
|
||||
`SELECT t.id, COALESCE(NULLIF(c.name,''), c.command, '#' || t.cron_id) AS name, t.source,t.queued_at,t.queue_context,t.queue_live_context
|
||||
FROM CronTriggers t LEFT JOIN Crontabs c ON c.id=t.cron_id
|
||||
WHERE t.state='queued' AND t.dequeued_at IS NULL AND t.queued_at IS NOT NULL ORDER BY t.queued_at,t.id LIMIT 25`,
|
||||
{ type: QueryTypes.SELECT },
|
||||
);
|
||||
}
|
||||
+180
-35
@@ -1,23 +1,63 @@
|
||||
import { hasLiveCronProcess } from './cronProcess';
|
||||
import { EventEmitter } from 'events';
|
||||
import PQueue from 'p-queue-cjs';
|
||||
import { triggerHistory, TriggerState } from './triggerHistory';
|
||||
import { t } from './i18n';
|
||||
import { spawn } from 'cross-spawn';
|
||||
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
|
||||
import taskLimit from './pLimit';
|
||||
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';
|
||||
import { observeChildProcess, asError } from './childProcess';
|
||||
|
||||
export function runCron(
|
||||
const waiting = new Map<string, () => void>();
|
||||
// A backlog of missed timers can otherwise open hundreds of competing SQLite
|
||||
// writer transactions on wake. Only serialize history writes, never commands.
|
||||
const historyWrites = new PQueue({ concurrency: 1 });
|
||||
export function cancelWaitingTriggers(ids: string[]) {
|
||||
for (const id of ids) waiting.get(id)?.();
|
||||
}
|
||||
|
||||
export async function runCron(
|
||||
cmd: string,
|
||||
cron: ICron,
|
||||
isCurrent: () => boolean = () => true,
|
||||
trigger?: { id: string; time: number; source: 'node' | 'recovery' },
|
||||
): Promise<number | void> {
|
||||
const history = trigger && triggerHistory();
|
||||
const queuedAt = Date.now();
|
||||
if (trigger && history) {
|
||||
const cronId = Number(cron.id);
|
||||
const admitted = await historyWrites.add(() => cron.skip_if_pending
|
||||
? history.enqueueUnlessPending(trigger.id, cronId, trigger.source, trigger.time, queuedAt, cron.recovery_from)
|
||||
: history.enqueue(trigger.id, cronId, trigger.source, trigger.time, queuedAt));
|
||||
if (!admitted) return;
|
||||
}
|
||||
let reason = 'capacity';
|
||||
let state: TriggerState = 'skipped';
|
||||
let exitCode: number | null = null;
|
||||
let claimed = false;
|
||||
const deadline = cron.max_queue_wait ? queuedAt + cron.max_queue_wait * 1000 : Infinity;
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const expiry = trigger ? new EventEmitter() : undefined;
|
||||
const alive = () => isCurrent() && Date.now() < deadline;
|
||||
if (trigger && expiry && Number.isFinite(deadline)) {
|
||||
timer = setTimeout(() => {
|
||||
reason = 'queue_timeout';
|
||||
taskLimit.removeQueuedCron(cron.id, execute);
|
||||
expiry.emit('expired');
|
||||
}, Math.max(0, deadline - Date.now()));
|
||||
timer.unref();
|
||||
}
|
||||
const execute = async () => {
|
||||
if (trigger) waiting.delete(trigger.id);
|
||||
reason = 'changed';
|
||||
try {
|
||||
if (!isCurrent()) return;
|
||||
// Check if the cron is already running and stop it (only if multiple instances are not allowed)
|
||||
if (!alive()) { reason = isCurrent() ? 'queue_timeout' : 'changed'; return; }
|
||||
let multiple = false;
|
||||
// A single-instance trigger must not interrupt work already in progress.
|
||||
try {
|
||||
const existingCron = await CrontabModel.findOne({
|
||||
where: { id: Number(cron.id) },
|
||||
@@ -27,38 +67,89 @@ export function runCron(
|
||||
if (!isCurrent() || !existingCron || existingCron.isDisabled) return;
|
||||
|
||||
// Default to single instance mode (0) for backward compatibility
|
||||
const allowSingleInstances =
|
||||
existingCron?.allow_multiple_instances === 0;
|
||||
multiple = existingCron.allow_multiple_instances === 1;
|
||||
|
||||
if (
|
||||
allowSingleInstances &&
|
||||
existingCron &&
|
||||
existingCron.pid &&
|
||||
(existingCron.status === CrontabStatus.running ||
|
||||
existingCron.status === CrontabStatus.queued)
|
||||
) {
|
||||
Logger.info(
|
||||
t('[schedule][停止已运行任务] 任务ID: %s, PID: %s'),
|
||||
cron.id,
|
||||
existingCron.pid,
|
||||
);
|
||||
await killTask(existingCron.pid, true);
|
||||
// Mark old running instances as stopped
|
||||
const stoppedAt = dayjs().unix();
|
||||
await RunningInstanceModel.update(
|
||||
{ status: InstanceStatus.stopped, finished_at: stoppedAt },
|
||||
{
|
||||
if (!multiple) {
|
||||
// A queued manual run is an active reservation, even if its stored PID
|
||||
// belongs to a previous execution.
|
||||
if (
|
||||
existingCron.status === CrontabStatus.queued &&
|
||||
existingCron.pid
|
||||
) {
|
||||
Logger.info(
|
||||
'[schedule][Skip queued single-instance task] Task ID: %s, PID: %s',
|
||||
cron.id,
|
||||
existingCron.pid,
|
||||
);
|
||||
reason = 'overlap';
|
||||
return;
|
||||
}
|
||||
if (
|
||||
existingCron.status === CrontabStatus.running &&
|
||||
existingCron.pid
|
||||
) {
|
||||
if (hasLiveCronProcess(existingCron.status, existingCron.pid)) {
|
||||
Logger.info(
|
||||
'[schedule][Skip active single-instance task] Task ID: %s, PID: %s',
|
||||
cron.id,
|
||||
existingCron.pid,
|
||||
);
|
||||
reason = 'overlap';
|
||||
return;
|
||||
}
|
||||
|
||||
// Capture old instance IDs before releasing the stale cron state so
|
||||
// a concurrent replacement cannot have its instance marked stopped.
|
||||
const staleInstances = await RunningInstanceModel.findAll({
|
||||
attributes: ['id'],
|
||||
where: {
|
||||
cron_id: Number(cron.id),
|
||||
pid: existingCron.pid,
|
||||
status: InstanceStatus.running,
|
||||
},
|
||||
},
|
||||
);
|
||||
// Update the status to idle after killing
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: undefined },
|
||||
{ where: { id: Number(cron.id) } },
|
||||
);
|
||||
});
|
||||
if (!isCurrent()) return;
|
||||
const [recovered] = await CrontabModel.update(
|
||||
{
|
||||
status: CrontabStatus.idle,
|
||||
pid: null,
|
||||
queued_token: null,
|
||||
} as any,
|
||||
{
|
||||
where: {
|
||||
id: Number(cron.id),
|
||||
pid: existingCron.pid,
|
||||
status: CrontabStatus.running,
|
||||
...(existingCron.log_path !== undefined
|
||||
? { log_path: existingCron.log_path }
|
||||
: {}),
|
||||
...(existingCron.queued_token !== undefined
|
||||
? { queued_token: existingCron.queued_token }
|
||||
: {}),
|
||||
...(existingCron.last_execution_time !== undefined
|
||||
? { last_execution_time: existingCron.last_execution_time }
|
||||
: {}),
|
||||
...(existingCron.isDisabled !== undefined
|
||||
? { isDisabled: existingCron.isDisabled }
|
||||
: {}),
|
||||
allow_multiple_instances: 0,
|
||||
},
|
||||
},
|
||||
);
|
||||
if (recovered !== 1) return;
|
||||
const staleIds = staleInstances.map((instance) => instance.id!);
|
||||
if (staleIds.length) {
|
||||
await RunningInstanceModel.update(
|
||||
{ status: InstanceStatus.stopped, finished_at: dayjs().unix() },
|
||||
{ where: { id: staleIds, status: InstanceStatus.running } },
|
||||
);
|
||||
}
|
||||
Logger.info(
|
||||
'[schedule][Recovered stale single-instance task] Task ID: %s, PID: %s',
|
||||
cron.id,
|
||||
existingCron.pid,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
Logger.error(
|
||||
@@ -69,7 +160,7 @@ export function runCron(
|
||||
throw error;
|
||||
}
|
||||
|
||||
// In particular, invalidation can happen while stopping a previous run.
|
||||
// Invalidation can happen during the asynchronous database check.
|
||||
if (!isCurrent()) return;
|
||||
Logger.info(
|
||||
t('[schedule][开始执行任务] 参数 %s'),
|
||||
@@ -78,9 +169,39 @@ export function runCron(
|
||||
command: cmd,
|
||||
}),
|
||||
);
|
||||
const cp = spawn(cmd, { shell: '/bin/bash' });
|
||||
clearTimeout(timer);
|
||||
if (Date.now() >= deadline) {
|
||||
reason = 'queue_timeout';
|
||||
return;
|
||||
}
|
||||
if (trigger) {
|
||||
claimed = await history!.start(trigger.id, Date.now(), multiple);
|
||||
if (!claimed) { reason = 'overlap'; return; }
|
||||
}
|
||||
if (!isCurrent() || Date.now() >= deadline) {
|
||||
reason = isCurrent() ? 'queue_timeout' : 'changed';
|
||||
return;
|
||||
}
|
||||
let saveStart: Promise<void> | undefined;
|
||||
const cp = spawnCronCommand(cmd, trigger?.id, trigger && history ? at => {
|
||||
saveStart = history.recordCommandStart(trigger.id, at).catch(error => {
|
||||
Logger.warn('[schedule] Could not record command start: %s', asError(error).message);
|
||||
});
|
||||
} : undefined);
|
||||
|
||||
let denied: string | undefined;
|
||||
const { completed } = observeChildProcess(cp, {
|
||||
onStart: async () => {
|
||||
if (!trigger) return;
|
||||
try {
|
||||
if (await history!.bindCommand(trigger.id, cp.pid!) && !await history!.shouldStop(trigger.id)) {
|
||||
if (!alive()) denied = isCurrent() ? 'queue_timeout' : 'changed';
|
||||
else await releaseCronCommand(cp);
|
||||
}
|
||||
} finally {
|
||||
cp.stdin.end();
|
||||
}
|
||||
},
|
||||
onStderr: async (message) => {
|
||||
Logger.info(
|
||||
t('[schedule][任务标准错误] 命令: %s, 信息: %s'),
|
||||
@@ -90,6 +211,11 @@ export function runCron(
|
||||
},
|
||||
});
|
||||
const result = await completed;
|
||||
await saveStart;
|
||||
if (denied) { reason = denied; return; }
|
||||
state = result.signal ? 'stopped' : result.error || result.code !== 0 ? 'failed' : 'finished';
|
||||
reason = result.error ? 'spawn' : result.signal || '';
|
||||
exitCode = result.code;
|
||||
if (result.error) {
|
||||
Logger.error(
|
||||
t('[schedule][执行任务失败] 命令: %s, 错误: %s'),
|
||||
@@ -104,6 +230,8 @@ export function runCron(
|
||||
);
|
||||
return { ...cron, command: cmd, pid: cp.pid, ...result } as any;
|
||||
} catch (error) {
|
||||
state = 'failed';
|
||||
reason = 'spawn';
|
||||
Logger.error(
|
||||
t('[schedule][创建任务失败] 命令: %s, 错误: %s'),
|
||||
cmd,
|
||||
@@ -113,5 +241,22 @@ export function runCron(
|
||||
taskLimit.removeQueuedCron(cron.id, execute);
|
||||
}
|
||||
};
|
||||
return taskLimit.runWithCronLimit(cron, execute, undefined, isCurrent);
|
||||
try {
|
||||
if (trigger && expiry) waiting.set(trigger.id, () => {
|
||||
taskLimit.removeQueuedCron(cron.id, execute);
|
||||
expiry.emit('expired');
|
||||
});
|
||||
return await taskLimit.runWithCronLimit(cron, execute, undefined, isCurrent, () => { reason = 'pending'; }, expiry, trigger?.id, CrontabModel.sequelize);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (trigger) waiting.delete(trigger.id);
|
||||
if (trigger && history) {
|
||||
const outcomeReason = state === 'skipped' && !isCurrent() ? 'changed' : reason;
|
||||
const finishedAt = Date.now();
|
||||
await historyWrites.add(() => state === 'skipped' && !claimed
|
||||
? history.skipQueued(trigger.id, outcomeReason, finishedAt)
|
||||
: history.complete(trigger.id, state, outcomeReason || null, exitCode, finishedAt),
|
||||
{ priority: 1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ const backend = read(path.resolve(__dirname, '../app.js'));
|
||||
const root = process.env.QL_DIR || path.resolve(__dirname, '../../..');
|
||||
const version = read(path.join(root, 'version.yaml'))
|
||||
?.toString()
|
||||
.match(/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+)/m)?.[1];
|
||||
.match(/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)/m)?.[1];
|
||||
|
||||
export const runtimeBuild = Object.freeze({
|
||||
instanceId: randomUUID(),
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
import { AddCronRequest, DeleteCronRequest } from '../protos/cron';
|
||||
import { upcomingSlots } from './cronScheduler';
|
||||
import { slotId } from './triggerHistory';
|
||||
|
||||
type Rule = {
|
||||
cron_id: string;
|
||||
rule_index: number;
|
||||
schedule: string;
|
||||
zone: string;
|
||||
since: number;
|
||||
until: number | null;
|
||||
open_latest: number;
|
||||
close_latest: number;
|
||||
};
|
||||
type Receipt = {
|
||||
id: string;
|
||||
cron_id: number;
|
||||
scheduled_at: number;
|
||||
observed_at: number;
|
||||
state: string;
|
||||
command_started_at: number | null;
|
||||
verified_exit: number;
|
||||
script_started_at: number | null;
|
||||
queued_at: number | null;
|
||||
started_at: number | null;
|
||||
};
|
||||
|
||||
export async function saveSchedulePlan(
|
||||
db: Sequelize,
|
||||
change: AddCronRequest | DeleteCronRequest,
|
||||
at?: number,
|
||||
token?: string,
|
||||
) {
|
||||
const rules =
|
||||
'crons' in change
|
||||
? [
|
||||
...new Map(change.crons.map((task) => [task.id, task])).values(),
|
||||
].flatMap((task) =>
|
||||
[
|
||||
task.schedule,
|
||||
...(task.extra_schedules || []).map((extra) => extra.schedule),
|
||||
].map((schedule, index) => ({ task: task.id, index, schedule })),
|
||||
)
|
||||
: [];
|
||||
const ids =
|
||||
'crons' in change ? change.crons.map((task) => task.id) : change.ids;
|
||||
const replace = 'replace' in change && change.replace;
|
||||
await db.transaction(async (transaction) => {
|
||||
const now = at ?? Date.now();
|
||||
const bind = {
|
||||
rules: JSON.stringify(rules),
|
||||
ids: JSON.stringify(ids),
|
||||
replace: Number(replace),
|
||||
zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
now,
|
||||
token: token ?? null,
|
||||
};
|
||||
if (token)
|
||||
await db.query(
|
||||
'INSERT INTO CronPlanSwitches(token,staged_at) VALUES($token,$now)',
|
||||
{ transaction, bind: { token, now } },
|
||||
);
|
||||
if (replace)
|
||||
await db.query(
|
||||
'INSERT OR IGNORE INTO CronPlanCoverage(id,since) VALUES(1,$now)',
|
||||
{ transaction, bind: { now } },
|
||||
);
|
||||
const desired = `WITH desired AS (SELECT json_extract(value,'$.task') AS task, json_extract(value,'$.index') AS idx,
|
||||
json_extract(value,'$.schedule') AS schedule FROM json_each($rules))`;
|
||||
await db.query(
|
||||
`${desired} UPDATE CronPlanRules SET until=$now,closed_by=$token WHERE until IS NULL
|
||||
AND ($replace OR cron_id IN (SELECT value FROM json_each($ids)))
|
||||
AND (cron_id,rule_index,schedule,zone) NOT IN (SELECT task,idx,schedule,$zone FROM desired)`,
|
||||
{ transaction, bind },
|
||||
);
|
||||
await db.query(
|
||||
`${desired} INSERT OR IGNORE INTO CronPlanRules(cron_id,rule_index,schedule,zone,since,opened_by)
|
||||
SELECT task,idx,schedule,$zone,$now,$token FROM desired`,
|
||||
{
|
||||
transaction,
|
||||
bind: { rules: bind.rules, zone: bind.zone, now, token: bind.token },
|
||||
},
|
||||
);
|
||||
// Only the current local day is displayed. Keep an extra day for zone changes.
|
||||
await db.query(
|
||||
`DELETE FROM CronPlanRules WHERE until < $now - 3*86400000 AND
|
||||
(closed_by IS NULL OR closed_by IN (SELECT token FROM CronPlanSwitches WHERE last_at < $now - 3*86400000))`,
|
||||
{ transaction, bind: { now } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Persisting intent and installing timers are separated by an asynchronous
|
||||
// SQLite commit. Only the synchronous timer swap defines the effective edges.
|
||||
export async function confirmSchedulePlan(
|
||||
db: Sequelize,
|
||||
token: string,
|
||||
first: number,
|
||||
last: number,
|
||||
replace: boolean,
|
||||
) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await db.query(
|
||||
`UPDATE CronPlanSwitches SET first_at=$first,last_at=$last
|
||||
WHERE token=$token AND last_at IS NULL`,
|
||||
{ transaction, bind: { token, first, last } },
|
||||
);
|
||||
if (replace) {
|
||||
// After a crash the former worker's switch time is unknowable. A complete
|
||||
// replacement establishes the latest possible edge for older requests.
|
||||
await db.query(
|
||||
`UPDATE CronPlanSwitches SET first_at=staged_at,last_at=$last
|
||||
WHERE last_at IS NULL AND seq<(SELECT seq FROM CronPlanSwitches WHERE token=$token)`,
|
||||
{ transaction, bind: { token, last } },
|
||||
);
|
||||
}
|
||||
await db.query(
|
||||
`DELETE FROM CronPlanSwitches WHERE last_at < $last - 3*86400000
|
||||
AND token NOT IN (SELECT opened_by FROM CronPlanRules WHERE opened_by IS NOT NULL)
|
||||
AND token NOT IN (SELECT closed_by FROM CronPlanRules WHERE closed_by IS NOT NULL)`,
|
||||
{ transaction, bind: { last } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export const blockSize = 15 * 60000;
|
||||
const calendar = new Map<string, number[]>();
|
||||
export function blockSlots(schedule: string, zone: string, block: number) {
|
||||
const key = JSON.stringify([zone, schedule, block]);
|
||||
let times = calendar.get(key);
|
||||
if (!times) {
|
||||
times = upcomingSlots(schedule, block - 1, Infinity, block + blockSize - 1);
|
||||
if (calendar.size >= 2048) calendar.delete(calendar.keys().next().value!);
|
||||
calendar.set(key, times);
|
||||
}
|
||||
return times;
|
||||
}
|
||||
|
||||
function lowerBound(times: number[], time: number) {
|
||||
let lo = 0,
|
||||
hi = times.length;
|
||||
while (lo < hi) {
|
||||
const mid = Math.floor((lo + hi) / 2);
|
||||
if (times[mid] < time) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
function p95(values: number[]) {
|
||||
return values.length
|
||||
? values.sort((a, b) => a - b)[Math.ceil(values.length * 0.95) - 1]
|
||||
: null;
|
||||
}
|
||||
|
||||
export async function auditSchedule(
|
||||
db: Sequelize,
|
||||
dayStart: number,
|
||||
now = Date.now(),
|
||||
) {
|
||||
// All counts use the same settled plan window and the same committed snapshot.
|
||||
const nextDay = new Date(dayStart);
|
||||
nextDay.setHours(24, 0, 0, 0);
|
||||
const through = Math.min(now - 5000, nextDay.getTime() - 1);
|
||||
const snapshot = await db.transaction(
|
||||
{ type: Transaction.TYPES.DEFERRED },
|
||||
async (transaction) => {
|
||||
const [coverage] = await db.query<{ since: number }>(
|
||||
`SELECT MAX(since,$dayStart,
|
||||
COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)) AS since FROM CronPlanCoverage WHERE id=1`,
|
||||
{ transaction, bind: { dayStart }, type: QueryTypes.SELECT },
|
||||
);
|
||||
if (!coverage || coverage.since > through) return;
|
||||
const bind = { since: coverage.since, through };
|
||||
const rules = await db.query<Rule>(
|
||||
`SELECT r.cron_id,r.rule_index,r.schedule,r.zone,COALESCE(o.first_at,r.since) AS since,
|
||||
CASE WHEN o.token IS NULL THEN r.since ELSE COALESCE(o.last_at,$through) END AS open_latest,
|
||||
COALESCE(c.first_at,r.until) AS until,
|
||||
CASE WHEN c.token IS NULL THEN COALESCE(r.until,$through) ELSE COALESCE(c.last_at,$through) END AS close_latest
|
||||
FROM CronPlanRules r LEFT JOIN CronPlanSwitches o ON o.token=r.opened_by
|
||||
LEFT JOIN CronPlanSwitches c ON c.token=r.closed_by
|
||||
WHERE r.since < $through AND close_latest >= $since`,
|
||||
{ transaction, bind, type: QueryTypes.SELECT },
|
||||
);
|
||||
const receipts = await db.query<Receipt>(
|
||||
`SELECT id,cron_id,scheduled_at,observed_at,state,
|
||||
command_started_at,script_started_at,queued_at,COALESCE(dequeued_at,started_at) AS started_at,
|
||||
EXISTS(SELECT 1 FROM CronLegacyExitBookings b WHERE b.trigger_id=CronTriggers.id AND b.bound=1) AS verified_exit FROM CronTriggers
|
||||
WHERE scheduled_at BETWEEN $since AND $through AND source IN ('node','recovery')`,
|
||||
{ transaction, bind, type: QueryTypes.SELECT },
|
||||
);
|
||||
return { since: coverage.since, rules, receipts };
|
||||
},
|
||||
);
|
||||
if (!snapshot) return null;
|
||||
const byTaskBlock = new Map<string, Receipt[]>();
|
||||
for (const row of snapshot.receipts) {
|
||||
const block = row.scheduled_at - (row.scheduled_at % blockSize);
|
||||
const key = row.cron_id + '/' + block;
|
||||
const group = byTaskBlock.get(key);
|
||||
if (group) group.push(row);
|
||||
else byTaskBlock.set(key, [row]);
|
||||
}
|
||||
const deviations: number[] = [],
|
||||
starts: number[] = [],
|
||||
entries: number[] = [],
|
||||
waits: number[] = [];
|
||||
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
let partial = false;
|
||||
let expected = 0,
|
||||
onTime = 0,
|
||||
skipped = 0,
|
||||
queued = 0,
|
||||
dispatched = 0;
|
||||
for (const rule of snapshot.rules) {
|
||||
const first = Math.max(snapshot.since, rule.since + 1);
|
||||
const last = Math.min(through, rule.close_latest);
|
||||
const certainFirst = Math.max(first, rule.open_latest + 1);
|
||||
const certainLast = Math.min(last, rule.until ?? last);
|
||||
if (first > last) continue;
|
||||
// A wall clock rule registered in another time zone cannot be replayed
|
||||
// against the current local calendar.
|
||||
if (rule.zone !== zone) return null;
|
||||
for (
|
||||
let block = first - (first % blockSize);
|
||||
block <= last;
|
||||
block += blockSize
|
||||
) {
|
||||
const times = blockSlots(rule.schedule, zone, block);
|
||||
const possible = lowerBound(times, last + 1) - lowerBound(times, first);
|
||||
const certain = Math.max(
|
||||
0,
|
||||
lowerBound(times, certainLast + 1) - lowerBound(times, certainFirst),
|
||||
);
|
||||
if (certain < possible) partial = true;
|
||||
expected += certain;
|
||||
for (const row of byTaskBlock.get(rule.cron_id + '/' + block) ?? []) {
|
||||
const time = row.scheduled_at;
|
||||
if (
|
||||
time < certainFirst ||
|
||||
time > certainLast ||
|
||||
times[lowerBound(times, time)] !== time ||
|
||||
row.id !== slotId(rule.cron_id, rule.rule_index, rule.schedule, time)
|
||||
)
|
||||
continue;
|
||||
const deviation = Math.abs(row.observed_at - time);
|
||||
deviations.push(deviation);
|
||||
if (deviation <= 5000) onTime++;
|
||||
if (
|
||||
row.command_started_at != null ||
|
||||
row.script_started_at != null ||
|
||||
row.verified_exit
|
||||
) {
|
||||
dispatched++;
|
||||
if (row.command_started_at != null && row.command_started_at >= time)
|
||||
starts.push(row.command_started_at - time);
|
||||
} else if (row.state === 'skipped') skipped++;
|
||||
else if (row.state === 'queued') queued++;
|
||||
if (row.script_started_at != null && row.script_started_at >= time)
|
||||
entries.push(row.script_started_at - time);
|
||||
if (row.started_at != null && row.queued_at != null && row.started_at >= row.queued_at)
|
||||
waits.push(row.started_at - row.queued_at);
|
||||
}
|
||||
}
|
||||
}
|
||||
const observed = deviations.length;
|
||||
return {
|
||||
since: snapshot.since,
|
||||
through,
|
||||
zone,
|
||||
partial,
|
||||
expected,
|
||||
observed,
|
||||
missing: expected - observed,
|
||||
onTime,
|
||||
skipped,
|
||||
queued,
|
||||
dispatched,
|
||||
commandSamples: starts.length,
|
||||
unconfirmed: observed - dispatched - skipped - queued,
|
||||
triggerDeviationP95: p95(deviations),
|
||||
waitP95: p95(waits),
|
||||
waitSamples: waits.length,
|
||||
commandStartP95: p95(starts),
|
||||
scriptStartP95: p95(entries),
|
||||
scriptSamples: entries.length,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { installTriggerHistory } from './triggerHistory';
|
||||
import { repairLegacyDailyStatistics } from './legacyDailyStatistics';
|
||||
import { QueryTypes, Sequelize } from 'sequelize';
|
||||
|
||||
export const prunedExitMigrationId = 'preserve-pruned-bound-exits-v1';
|
||||
|
||||
// Append new entries; IDs are persisted and must not be renumbered or reused.
|
||||
const columns = [
|
||||
{
|
||||
@@ -25,6 +30,13 @@ const columns = [
|
||||
{ table: 'Envs', column: 'isPinned', type: 'NUMBER' },
|
||||
{ table: 'Envs', column: 'labels', type: 'JSON' },
|
||||
{ table: 'Crontabs', column: 'queued_token', type: 'VARCHAR(255)' },
|
||||
{ table: 'Crontabs', column: 'max_queue_wait', type: 'INTEGER' },
|
||||
{ table: 'Crontabs', column: 'catchup_seconds', type: 'INTEGER' },
|
||||
{ table: 'Crontabs', column: 'skip_if_pending', type: 'BOOLEAN' },
|
||||
{ table: 'Crontabs', column: 'recovery_from', type: 'BIGINT' },
|
||||
{ table: 'Crontabs', column: 'last_instance_id', type: 'INTEGER' },
|
||||
{ table: 'CrontabStats', column: 'untimed_count', type: 'INTEGER NOT NULL DEFAULT 0' },
|
||||
{ table: 'CrontabStats', column: 'fixed_max_time', type: 'NUMBER' },
|
||||
];
|
||||
|
||||
export async function migrateSchema(database: Sequelize): Promise<void> {
|
||||
@@ -33,6 +45,7 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
|
||||
'CREATE TABLE IF NOT EXISTS "SchemaMigrations" ("id" TEXT PRIMARY KEY, "applied_at" TEXT NOT NULL)',
|
||||
{ transaction },
|
||||
);
|
||||
await installTriggerHistory(database, transaction);
|
||||
const applied = await database.query<{ id: string }>(
|
||||
'SELECT "id" FROM "SchemaMigrations"',
|
||||
{ type: QueryTypes.SELECT, transaction },
|
||||
@@ -66,5 +79,52 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const repairId = 'repair-legacy-daily-statistics-v3';
|
||||
const prior = appliedIds.has('repair-legacy-daily-statistics-v2') ? 2
|
||||
: appliedIds.has('repair-legacy-daily-statistics-v1') ? 1 : 0;
|
||||
const retentionId = 'preserve-cron-stat-retention-v1';
|
||||
if (!appliedIds.has(retentionId)) {
|
||||
if (prior || appliedIds.has(repairId)) {
|
||||
// Old cleanup removed complete date prefixes but kept no cutoff. Every
|
||||
// surviving date and yesterday (the minimum supported retention) is
|
||||
// safe to keep. Older empty dates cannot be distinguished from deletions.
|
||||
await database.query(`INSERT OR IGNORE INTO CronStatRetention(id,first_day)
|
||||
SELECT 1, MIN(COALESCE(MIN(date),$yesterday),$yesterday) FROM CrontabStats`,
|
||||
{ bind: { yesterday: dayjs().subtract(1,'day').format('YYYY-MM-DD') }, transaction });
|
||||
}
|
||||
await database.query('INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
|
||||
{ bind: { id: retentionId }, transaction });
|
||||
}
|
||||
if (!appliedIds.has(repairId)) {
|
||||
await repairLegacyDailyStatistics(database, transaction, prior);
|
||||
// This reconciliation includes v1 and v2. Record all on fresh installations
|
||||
// so rolling back and upgrading again cannot replay the superseded repair.
|
||||
await database.query(`INSERT OR IGNORE INTO SchemaMigrations(id,applied_at)
|
||||
VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP),('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP),($id,CURRENT_TIMESTAMP)`,
|
||||
{ transaction, bind: { id: repairId } });
|
||||
}
|
||||
|
||||
if (!appliedIds.has(prunedExitMigrationId)) {
|
||||
// Earlier versions could reclaim the last file before upgrading. The
|
||||
// surviving bound booking still identifies the original exit exactly.
|
||||
await database.query(`INSERT OR IGNORE INTO CronUnmatchedBoundExits(trigger_id,outcome,finished_at)
|
||||
SELECT b.trigger_id,b.outcome,b.finished_at FROM CronLegacyExitBookings b
|
||||
WHERE b.bound=1 AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=b.trigger_id)
|
||||
AND NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=b.trigger_id)`, { transaction });
|
||||
await database.query('INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
|
||||
{ bind: { id: prunedExitMigrationId }, transaction });
|
||||
}
|
||||
|
||||
// Older databases can contain non-JSON values in Envs.labels. Sequelize
|
||||
// parses this column on every environment read, including HTTP startup.
|
||||
await database.query(
|
||||
`UPDATE "Envs" SET "labels" = '[]'
|
||||
WHERE CASE WHEN json_valid("labels")
|
||||
THEN json_type("labels") <> 'array'
|
||||
ELSE 1
|
||||
END`,
|
||||
{ transaction },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
import { blockSize, blockSlots } from './scheduleAudit';
|
||||
|
||||
export type SystemRule = { id: number; schedule: string; name?: string };
|
||||
type Install = {
|
||||
id: number;
|
||||
staged: number;
|
||||
confirmed: number | null;
|
||||
zone: string;
|
||||
rules: string;
|
||||
};
|
||||
type Receipt = {
|
||||
id: string;
|
||||
cron_id: number;
|
||||
system_rule: string | null;
|
||||
observed_at: number;
|
||||
system_dispatch_at: number | null;
|
||||
launched: number;
|
||||
state: string;
|
||||
};
|
||||
|
||||
export async function stageSystemPlan(
|
||||
db: Sequelize,
|
||||
rules: SystemRule[],
|
||||
at = Date.now(),
|
||||
) {
|
||||
const bind = {
|
||||
at,
|
||||
zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
rules: JSON.stringify([...rules].sort((a, b) => a.id - b.id)),
|
||||
};
|
||||
return db.transaction(
|
||||
{ type: Transaction.TYPES.IMMEDIATE },
|
||||
async (transaction) => {
|
||||
const [pending] = await db.query<{ id: number }>(
|
||||
`SELECT id FROM (SELECT * FROM CronSystemPlans ORDER BY id DESC LIMIT 1)
|
||||
WHERE confirmed IS NULL AND zone=$zone AND rules=$rules`,
|
||||
{
|
||||
bind: { zone: bind.zone, rules: bind.rules },
|
||||
transaction,
|
||||
type: QueryTypes.SELECT,
|
||||
},
|
||||
);
|
||||
if (pending) return pending.id;
|
||||
const [id] = await db.query(
|
||||
'INSERT INTO CronSystemPlans(staged,zone,rules) VALUES ($at,$zone,$rules)',
|
||||
{ bind, transaction, type: QueryTypes.INSERT },
|
||||
);
|
||||
return id;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// On a switch to Node the service can no longer attest the installed daemon rules.
|
||||
export async function suspendSystemPlan(db: Sequelize) {
|
||||
await db.query(
|
||||
`INSERT INTO CronSystemPlans(staged,zone,rules)
|
||||
SELECT $now,zone,'[]' FROM (SELECT zone,confirmed FROM CronSystemPlans ORDER BY id DESC LIMIT 1)
|
||||
WHERE confirmed IS NOT NULL`,
|
||||
{ bind: { now: Date.now() } },
|
||||
);
|
||||
}
|
||||
|
||||
export async function confirmSystemPlan(
|
||||
db: Sequelize,
|
||||
id: number,
|
||||
at = Date.now(),
|
||||
) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await db.query(
|
||||
'UPDATE CronSystemPlans SET confirmed=$at WHERE id=$id AND confirmed IS NULL',
|
||||
{ transaction, bind: { id, at } },
|
||||
);
|
||||
// Keep the effective snapshot preceding the retention window.
|
||||
await db.query(
|
||||
'DELETE FROM CronSystemPlans WHERE id < (SELECT MAX(id) FROM CronSystemPlans WHERE staged < $cutoff AND confirmed IS NOT NULL)',
|
||||
{ transaction, bind: { cutoff: at - 3 * 86400000 } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function systemScheduleAudit(
|
||||
db: Sequelize,
|
||||
dayStart: number,
|
||||
now = Date.now(),
|
||||
) {
|
||||
const next = new Date(dayStart);
|
||||
next.setHours(24, 0, 0, 0);
|
||||
const through = Math.min(now - 5000, +next - 1);
|
||||
const { since, installs, receipts } = await db.transaction(
|
||||
{ type: Transaction.TYPES.DEFERRED },
|
||||
async (transaction) => {
|
||||
const [retention] = await db.query<{ since: number }>(
|
||||
'SELECT MAX($dayStart,COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)) AS since',
|
||||
{ transaction, bind: { dayStart }, type: QueryTypes.SELECT },
|
||||
);
|
||||
const since = retention.since;
|
||||
const installs = await db.query<Install>(
|
||||
`SELECT * FROM CronSystemPlans WHERE id >= COALESCE((SELECT MAX(id) FROM CronSystemPlans
|
||||
WHERE confirmed < $since - 60000),0) AND staged <= $now ORDER BY id`,
|
||||
{ transaction, bind: { since, now }, type: QueryTypes.SELECT },
|
||||
);
|
||||
const receipts = await db.query<Receipt>(
|
||||
`SELECT id,cron_id,system_rule,system_dispatch_at,observed_at,state,
|
||||
(command_started_at IS NOT NULL OR script_started_at IS NOT NULL OR
|
||||
(started_at IS NOT NULL AND EXISTS (SELECT 1 FROM CronLegacyExitBookings b
|
||||
WHERE b.trigger_id=CronTriggers.id AND b.bound=1 AND b.disputed=0))) AS launched
|
||||
FROM CronTriggers
|
||||
WHERE source='system' AND COALESCE(system_dispatch_at,observed_at) >= $since
|
||||
AND COALESCE(system_dispatch_at,observed_at) < $end ORDER BY observed_at,id`,
|
||||
{
|
||||
transaction,
|
||||
bind: {
|
||||
since,
|
||||
end: Math.min(
|
||||
+next,
|
||||
Math.floor(through / 60000) * 60000 + 60000,
|
||||
now + 1,
|
||||
),
|
||||
},
|
||||
type: QueryTypes.SELECT,
|
||||
},
|
||||
);
|
||||
return { since, installs, receipts };
|
||||
},
|
||||
);
|
||||
if (!installs.length && !receipts.length) return null;
|
||||
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
const minute = 60000;
|
||||
const plans = installs.map((plan) => ({
|
||||
...plan,
|
||||
tasks: new Map(
|
||||
(JSON.parse(plan.rules) as SystemRule[]).map((rule) => [rule.id, rule]),
|
||||
),
|
||||
}));
|
||||
const groups = new Map<string, Receipt[]>();
|
||||
const dispatchedTasks = new Set<string>();
|
||||
const legacyThrough = new Map<string, number>();
|
||||
const receiptKey = (task: number, rule: string | null, time: number) =>
|
||||
JSON.stringify([task, rule, time]);
|
||||
for (const row of receipts) {
|
||||
if (row.system_dispatch_at == null || !row.system_rule) {
|
||||
const key = JSON.stringify([row.cron_id, row.system_rule]);
|
||||
legacyThrough.set(
|
||||
key,
|
||||
Math.max(legacyThrough.get(key) ?? 0, row.observed_at),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
dispatchedTasks.add(
|
||||
row.cron_id + '/' + Math.floor(row.system_dispatch_at / minute),
|
||||
);
|
||||
const key = receiptKey(
|
||||
row.cron_id,
|
||||
row.system_rule,
|
||||
Math.floor(row.system_dispatch_at / minute) * minute,
|
||||
);
|
||||
const group = groups.get(key) ?? [];
|
||||
group.push(row);
|
||||
groups.set(key, group);
|
||||
}
|
||||
let expected = 0,
|
||||
observed = 0,
|
||||
dispatched = 0,
|
||||
skipped = 0,
|
||||
missing = 0,
|
||||
duplicates = 0,
|
||||
matchedReceipts = 0;
|
||||
let uncertain = 0,
|
||||
awaiting = 0,
|
||||
switchSlots = 0,
|
||||
partial = false;
|
||||
type Slot = {
|
||||
time: number;
|
||||
task: number;
|
||||
name?: string;
|
||||
status: string;
|
||||
triggerCount: number;
|
||||
startCount: number;
|
||||
skipCount: number;
|
||||
unknownExitCount: number;
|
||||
id?: string;
|
||||
};
|
||||
const recent: Slot[] = [];
|
||||
const dst =
|
||||
new Date(dayStart).getTimezoneOffset() !==
|
||||
new Date(+next - 1).getTimezoneOffset();
|
||||
let baseline = -1,
|
||||
last = -1;
|
||||
const calendar = new Map<string, Set<number>>();
|
||||
for (
|
||||
let time =
|
||||
Math.ceil(Math.max(since, plans[0]?.staged ?? since) / minute) * minute;
|
||||
time <= through;
|
||||
time += minute
|
||||
) {
|
||||
// A successful crontab install acknowledges the file. crond reads changes at
|
||||
// its minute tick. Around that tick either file can still explain a callback.
|
||||
while (last + 1 < plans.length && plans[last + 1].staged <= time + 5000)
|
||||
last++;
|
||||
while (baseline + 1 <= last) {
|
||||
let confirmed = baseline + 1;
|
||||
while (confirmed <= last && plans[confirmed].confirmed == null)
|
||||
confirmed++;
|
||||
if (confirmed > last || plans[confirmed].confirmed! >= time - minute)
|
||||
break;
|
||||
baseline = confirmed;
|
||||
}
|
||||
if (last < 0) continue;
|
||||
const possible = plans.slice(Math.max(0, baseline), last + 1);
|
||||
if (dst || possible.some((plan) => plan.zone !== zone)) {
|
||||
partial = true;
|
||||
continue;
|
||||
}
|
||||
const tasks = new Set<number>();
|
||||
for (const plan of possible)
|
||||
for (const id of plan.tasks.keys()) tasks.add(id);
|
||||
const block = time - (time % blockSize);
|
||||
if (time === block) calendar.clear();
|
||||
const entries: Slot[] = [];
|
||||
for (const task of tasks) {
|
||||
const schedules = new Set<string>();
|
||||
let name: string | undefined;
|
||||
for (const plan of possible) {
|
||||
const rule = plan.tasks.get(task);
|
||||
if (!rule) continue;
|
||||
name = rule.name;
|
||||
let times = calendar.get(rule.schedule);
|
||||
if (!times) {
|
||||
times = new Set(blockSlots(rule.schedule, zone, block));
|
||||
calendar.set(rule.schedule, times);
|
||||
}
|
||||
if (times.has(time)) schedules.add(rule.schedule);
|
||||
}
|
||||
if (!schedules.size) continue;
|
||||
const [schedule] = schedules;
|
||||
const stable =
|
||||
baseline >= 0 &&
|
||||
schedules.size === 1 &&
|
||||
possible.every(
|
||||
(plan) =>
|
||||
plan.confirmed != null &&
|
||||
plan.tasks.get(task)?.schedule === schedule,
|
||||
);
|
||||
const group = [...schedules].flatMap(
|
||||
(rule) => groups.get(receiptKey(task, rule, time)) ?? [],
|
||||
);
|
||||
let status: string;
|
||||
const launched = group.find((row) => row.launched === 1);
|
||||
const skip = group.find((row) => row.state === 'skipped');
|
||||
if (group.length) {
|
||||
++expected;
|
||||
++observed;
|
||||
matchedReceipts += group.length;
|
||||
duplicates += group.length - 1;
|
||||
if (launched) ++dispatched;
|
||||
else if (skip) ++skipped;
|
||||
status = launched ? 'started' : skip ? 'skipped' : 'unconfirmed';
|
||||
} else if (!stable) {
|
||||
++switchSlots;
|
||||
partial = true;
|
||||
status = 'switch';
|
||||
} else {
|
||||
++expected;
|
||||
const lastUndated = Math.max(
|
||||
legacyThrough.get(JSON.stringify([task, null])) ?? 0,
|
||||
legacyThrough.get(JSON.stringify([task, schedule])) ?? 0,
|
||||
);
|
||||
if (
|
||||
time <= lastUndated ||
|
||||
dispatchedTasks.has(task + '/' + time / minute)
|
||||
) {
|
||||
++uncertain;
|
||||
status = 'uncertain';
|
||||
} else if (time + minute > now) {
|
||||
++awaiting;
|
||||
status = 'awaiting';
|
||||
} else {
|
||||
++missing;
|
||||
status = 'missing';
|
||||
}
|
||||
}
|
||||
entries.push({
|
||||
time,
|
||||
task,
|
||||
name,
|
||||
status,
|
||||
triggerCount: group.length,
|
||||
startCount: group.filter((row) => row.launched === 1).length,
|
||||
skipCount: group.filter((row) => row.state === 'skipped').length,
|
||||
unknownExitCount: group.filter((row) => row.launched === 1 && row.state === 'unknown').length,
|
||||
id: (launched || skip || group[0])?.id,
|
||||
});
|
||||
}
|
||||
if (entries.length)
|
||||
recent.unshift(...entries.sort((a, b) => a.task - b.task).slice(0, 25));
|
||||
recent.splice(25);
|
||||
}
|
||||
return {
|
||||
since: Math.max(since, plans[0]?.staged ?? since),
|
||||
through,
|
||||
confirmedAt:
|
||||
[...plans].reverse().find((p) => p.confirmed != null)?.confirmed ?? null,
|
||||
pending: plans.at(-1)?.confirmed == null,
|
||||
partial,
|
||||
expected,
|
||||
observed,
|
||||
dispatched,
|
||||
skipped,
|
||||
missing,
|
||||
duplicates,
|
||||
uncertain,
|
||||
awaiting,
|
||||
switchSlots,
|
||||
actualSkips: receipts.filter((row) => row.state === 'skipped').length,
|
||||
actualStarts: receipts.filter((row) => row.launched === 1).length,
|
||||
unmatched: receipts.length - matchedReceipts,
|
||||
recent,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { t } from './i18n';
|
||||
|
||||
// These names control the task runner or the interpreters it starts. Values
|
||||
// managed through the environment API must remain task data, not executable
|
||||
// configuration.
|
||||
const reservedNames = new Set([
|
||||
'TASK_BEFORE',
|
||||
'TASK_AFTER',
|
||||
'WORK_DIR',
|
||||
'TASK_SHELL_PARAMS',
|
||||
'SCRIPT_PARAMS',
|
||||
'WHICH_PROGRAM',
|
||||
'ISJSORPYTHONFILE',
|
||||
'EXPORTED_VARIABLES',
|
||||
'FOUND_DOUBLE_DASH',
|
||||
'LOG_DIR',
|
||||
'LOG_PATH',
|
||||
'ID',
|
||||
'BEGIN_TIMESTAMP',
|
||||
'TIME_FORMAT',
|
||||
'MTIME_FORMAT',
|
||||
'IS_MACOS',
|
||||
'RANDOMDELAY',
|
||||
'RANDOMDELAYFILEEXTENSIONS',
|
||||
'RANDOMDELAYIGNOREDMINUTES',
|
||||
'COMMAND_TIMEOUT_TIME',
|
||||
'SET_U_ON',
|
||||
'_TASK_EXIT_CODE',
|
||||
'PATH',
|
||||
'HOME',
|
||||
'SHELL',
|
||||
'ENV',
|
||||
'BASH_ENV',
|
||||
'BASHOPTS',
|
||||
'SHELLOPTS',
|
||||
'IFS',
|
||||
'CDPATH',
|
||||
'GLOBIGNORE',
|
||||
'PROMPT_COMMAND',
|
||||
'PS4',
|
||||
'NODE_OPTIONS',
|
||||
'NODE_PATH',
|
||||
'PREV_NODE_OPTIONS',
|
||||
'PREV_NODE_PATH',
|
||||
'PREV_PYTHONPATH',
|
||||
'GIT_SSH',
|
||||
'GIT_SSH_COMMAND',
|
||||
'GIT_ASKPASS',
|
||||
'GIT_EXEC_PATH',
|
||||
'GIT_TEMPLATE_DIR',
|
||||
'SSH_ASKPASS',
|
||||
]);
|
||||
|
||||
export function isAllowedTaskEnvName(name: unknown): name is string {
|
||||
if (typeof name !== 'string' || !/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(name)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const upper = name.toUpperCase();
|
||||
return (
|
||||
!reservedNames.has(upper) &&
|
||||
!upper.startsWith('BASH_') &&
|
||||
!upper.startsWith('QL') &&
|
||||
!upper.startsWith('FILE_') &&
|
||||
!upper.startsWith('DIR_') &&
|
||||
!upper.startsWith('LD_') &&
|
||||
!upper.startsWith('DYLD_') &&
|
||||
!upper.startsWith('PYTHON') &&
|
||||
!upper.startsWith('GIT_CONFIG_')
|
||||
);
|
||||
}
|
||||
|
||||
export function assertAllowedTaskEnvName(name: unknown): asserts name is string {
|
||||
if (!isAllowedTaskEnvName(name)) {
|
||||
throw Object.assign(new Error(t('环境变量名称不可使用')), {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -20,8 +20,10 @@ export const scheduleSchema = Joi.string()
|
||||
.required()
|
||||
.custom(validateSchedule)
|
||||
.messages({
|
||||
'any.required': '定时规则不能为空',
|
||||
'any.invalid': '无效的定时规则',
|
||||
'string.empty': '定时规则不能为空',
|
||||
'string.base': '定时规则必须是字符串',
|
||||
});
|
||||
|
||||
export const commonCronSchema = {
|
||||
@@ -30,7 +32,27 @@ export const commonCronSchema = {
|
||||
schedule: scheduleSchema,
|
||||
labels: Joi.array().optional().allow(null),
|
||||
sub_id: Joi.number().optional().allow(null),
|
||||
extra_schedules: Joi.array().optional().allow(null),
|
||||
extra_schedules: Joi.array()
|
||||
.items(
|
||||
Joi.object({
|
||||
schedule: Joi.string()
|
||||
.required()
|
||||
.custom((value, helpers) =>
|
||||
isValidCronSchedule(value) ? value : helpers.error('any.invalid'),
|
||||
)
|
||||
.messages({
|
||||
'any.required': '定时规则不能为空',
|
||||
'any.invalid': '无效的定时规则',
|
||||
'string.empty': '定时规则不能为空',
|
||||
'string.base': '定时规则必须是字符串',
|
||||
}),
|
||||
})
|
||||
.unknown(true)
|
||||
.messages({ 'object.base': '额外定时规则必须是对象' }),
|
||||
)
|
||||
.optional()
|
||||
.allow(null)
|
||||
.messages({ 'array.base': '额外定时规则必须是数组' }),
|
||||
task_before: Joi.string().optional().allow('').allow(null),
|
||||
task_after: Joi.string().optional().allow('').allow(null),
|
||||
log_name: Joi.string()
|
||||
@@ -48,14 +70,10 @@ export const commonCronSchema = {
|
||||
}
|
||||
|
||||
// For other absolute paths, ensure they are within the safe log directory
|
||||
const normalizedValue = path.normalize(value);
|
||||
const normalizedLogPath = path.normalize(config.logPath);
|
||||
|
||||
if (!normalizedValue.startsWith(normalizedLogPath)) {
|
||||
const relative = path.relative(config.logPath, value);
|
||||
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {
|
||||
return helpers.error('string.unsafePath');
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -75,6 +93,9 @@ export const commonCronSchema = {
|
||||
'string.max': '日志名称不能超过100个字符',
|
||||
'string.unsafePath': '绝对路径必须在日志目录内或使用 /dev/null',
|
||||
}),
|
||||
skip_if_pending: Joi.boolean().optional().allow(null),
|
||||
max_queue_wait: Joi.number().integer().min(0).max(86400).allow(null),
|
||||
catchup_seconds: Joi.number().integer().min(0).max(86400).allow(null),
|
||||
allow_multiple_instances: Joi.number().optional().valid(0, 1).allow(null),
|
||||
work_dir: Joi.string().optional().allow('').allow(null),
|
||||
};
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ check installs dependencies, repairs and reloads; inspect its before/after obser
|
||||
|
||||
On a panel containing the selection loader, set `QL_CLI_ROOT=/absolute/path/to/built/cli` to the internal build directory containing the full dist tree, **not an npm installation**. Restart to create private ~/bin ql/task/cron wrappers and prioritize them for panel processes. Independent terminals should use the selected absolute path. Unset the variable and restart to restore Shell entries. Invalid paths report errors without silent fallback. Original Shell entries remain the default.
|
||||
|
||||
dist/startup.js retains startup/reload compatibility; dist/compat.js and dist/subscription-worker.js are internal adapters, not npm commands. Lifecycle fields follow the installed panel version; customized versions may select QL_CLI_LIFECYCLE=legacy|extended.
|
||||
dist/startup.js retains startup/reload compatibility; dist/compat.js and dist/subscription-worker.js are internal adapters, not npm commands. The CLI negotiates receipt fields with the running panel. Set `QL_CLI_LIFECYCLE=legacy` to force the legacy format.
|
||||
|
||||
The separate [qinglong-local skill](skills/qinglong-local/SKILL.md) covers execution and maintenance. Use qinglong-cli for remote API management. QL_LANG=en selects English help/messages while JSON fields remain stable.
|
||||
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ repo/raw 沿用位置参数,使用 QL_DIR/QL_DATA_DIR,不接受 --root/--jso
|
||||
|
||||
包含选择加载器的面板设置 `QL_CLI_ROOT=/absolute/path/to/built/cli`,指向包含完整 dist 的面板工具构建目录,**不能指向 npm 包**。重启后加载器在 ~/bin 创建私有 ql/task/cron 包装器,并为面板进程优先使用它们;独立终端应显式使用该路径。清除变量并重启恢复原 Shell 入口。无效路径报错,不静默降级。默认仍保留旧 Shell 入口。
|
||||
|
||||
`dist/startup.js` 兼容旧启动/reload;`dist/compat.js` 与 `dist/subscription-worker.js` 保留内部适配用途,不注册为 npm 命令。生命周期根据已安装面板版本选择字段,定制版本可设置 QL_CLI_LIFECYCLE=legacy|extended。
|
||||
`dist/startup.js` 兼容旧启动/reload;`dist/compat.js` 与 `dist/subscription-worker.js` 保留内部适配用途,不注册为 npm 命令。CLI 根据运行中的面板对回执字段的校验结果选择协议。设置 `QL_CLI_LIFECYCLE=legacy` 可强制使用旧格式。
|
||||
|
||||
独立 Skill 位于 [skills/qinglong-local](skills/qinglong-local/SKILL.md),包含完整执行与维护参考。远程管理另用 qinglong-cli Skill。`QL_LANG=en` 切换帮助和执行提示;JSON 字段保持一致。
|
||||
|
||||
|
||||
+7
-7
@@ -43,12 +43,12 @@ Use command `--help` and `QL_LANG=en` for English. Command names and JSON fields
|
||||
|
||||
## Complete OpenAPI management
|
||||
|
||||
The CLI also supports task/subscription CRUD, application and secret management, environment variables, configuration, scripts, logs, dependencies, system, dashboard and user APIs. `ql api routes --json` lists all 143 active routes; three retired file-reading endpoints are excluded. CI compares the catalogue against backend routes. See the [complete bilingual reference](skills/qinglong-cli/references/openapi.md) for every command and payload.
|
||||
The CLI also supports task/subscription CRUD, application and secret management, environment variables, configuration, scripts, logs, dependencies, system, dashboard and user APIs. `ql api routes --json` lists the active routes; three retired file-reading endpoints are excluded. CI compares the catalogue against backend routes. See the [complete bilingual reference](skills/qinglong-cli/references/openapi.md) for every command and payload.
|
||||
|
||||
```sh
|
||||
ql task create --name demo --command 'task demo.js' --schedule '0 0 * * *' --json
|
||||
ql subscription create --type public-repo --url https://example.com/repo.git --alias demo --schedule-type crontab --schedule '0 0 * * *' --json
|
||||
ql app create --name agent --scopes crons,subscriptions --show-secrets --json
|
||||
ql app create --name agent --scopes crons,subscriptions,envs --show-secrets --json
|
||||
ql env create --data @envs.json --json
|
||||
ql api request PUT /open/crons/run --data '[12,13]' --json
|
||||
```
|
||||
@@ -68,7 +68,7 @@ Protected requests use `Authorization: Bearer <token>`. Two credential sources a
|
||||
|
||||
### Application login
|
||||
|
||||
Create a dedicated panel application with the required scopes, such as crons, subscriptions or envs. `login` and `auth login` are equivalent. Interactive login hides the Client Secret; secret command-line arguments are not supported.
|
||||
Create a dedicated panel application with the required scopes. Existing scopes retain their original permissions. For read-only access, use `crons:read`, `subscriptions:read`, `envs:read`, `configs:read`, `scripts:read`, `dependencies:read`, `logs:read`, or `dashboard:read`. Script and log read-only scopes also allow downloads and directory version checks via POST. `GET /crons/import` writes tasks and is excluded from `crons:read`. `login` and `auth login` are equivalent. Interactive login hides the Client Secret; secret command-line arguments are not supported.
|
||||
|
||||
```sh
|
||||
ql login --url https://ql.example.com
|
||||
@@ -76,7 +76,7 @@ ql auth status --scope crons --json
|
||||
# For automation, inject QL_CLIENT_ID and QL_CLIENT_SECRET before the same login command
|
||||
```
|
||||
|
||||
Credentials/token are stored in `~/.config/qinglong/cli.json`, a plaintext file owned by the current user with mode 0600. `QL_CLI_CONFIG` selects another file. Login validates application credentials, not every resource permission.
|
||||
Credentials/token are stored in `~/.config/qinglong/cli.json` as plaintext. The CLI requests mode `0600` when creating the file and rejects symlinks and non-regular files when reading it. Windows, WSL mounts, and some network or device filesystems do not reliably report POSIX permissions, so reads do not depend on mode bits or UID. Keep the config in a location accessible only to your user and protect it with the filesystem's actual permissions or ACLs; use the direct-token environment variables below if that cannot be guaranteed. `QL_CLI_CONFIG` selects another file. Login validates application credentials, not every resource permission.
|
||||
|
||||
### Direct access token
|
||||
|
||||
@@ -128,11 +128,11 @@ npm run test:cli
|
||||
node cli/scripts/verify-package.cjs
|
||||
```
|
||||
|
||||
Tests cover requests, token refresh, output, errors, no automatic retries, permissions and isolated installation. Package verification installs the archive offline, verifies the sole ql executable and rejects local commands.
|
||||
Tests cover requests, token refresh, output, errors, no automatic retries, config file type and isolated installation. Package verification installs the archive offline, verifies the sole ql executable and rejects local commands.
|
||||
|
||||
The CLI package workflow checks, builds and tests Node 22.12/24 on relevant PRs, develop/master pushes and manual runs. Node 24 uploads the archive verified by offline installation as `qinglong-cli-<commit>`. After both matrix jobs succeed, master pushes publish that exact archive to npm as latest, using GitHub Actions OIDC trusted publishing without an NPM_TOKEN secret. Manual runs publish only when run on master with publish enabled; PRs, develop and forks never publish. Configure the npm Trusted Publisher for repository `whyour/qinglong`, workflow `cli-package.yml`, with `npm publish` allowed. The panel package `@whyour/qinglong` separately trusts `build-docker-image.yml`. Publishing uses Node 24 with `id-token: write` granted only to the publish job. New packages need an initial publication before configuring their trusted publisher.
|
||||
The CLI package workflow checks, builds and tests Node 22.12/24 on relevant PRs, develop/master pushes and manual runs, and verifies saved login and command reads on real Windows and Linux ARM64 filesystems. Node 24 uploads the archive verified by offline installation as `qinglong-cli-<commit>`. After all validation jobs succeed, master pushes publish that exact archive to npm as `latest`; a manual run on master with `publish` enabled can also publish a stable release. Develop pushes only verify. A manual run on develop with `publish` enabled and `prerelease_version` set (for example `0.1.5-beta.0`) publishes under the matching `alpha`, `beta` or `rc` tag. PRs and forks never publish. CLI-only changes do not trigger the main image build, except for the few internal CLI upgrade files used by the image. Configure the npm Trusted Publisher for repository `whyour/qinglong`, workflow `cli-package.yml`, with `npm publish` allowed. The panel package `@whyour/qinglong` separately trusts `build-docker-image.yml`. The publish job uses Node 24 and GitHub Actions OIDC without an `NPM_TOKEN` secret, with `id-token: write` granted only to that job. New packages need an initial publication before configuring their trusted publisher.
|
||||
|
||||
The CLI has an independent stable version in cli/package.json and cli/package-lock.json. Before releasing changes, run `npm version patch --prefix cli --no-git-tag-version` (or minor/major) and commit both files. Existing versions are skipped with a notice; registry failures stop publication. Only stable X.Y.Z versions are published by this workflow. Publication does not rebuild the verified archive or run package lifecycle scripts.
|
||||
The CLI stable version is maintained independently in cli/package.json and cli/package-lock.json. Before releasing changes, run `npm version patch --prefix cli --no-git-tag-version` (or minor/major) and commit both files. A develop prerelease version is set only in the workflow run and is not written back to the repository. An existing stable version is skipped with a notice; a duplicate prerelease version fails, as does a registry lookup error. The publish job does not rebuild the verified archive or run package lifecycle scripts.
|
||||
|
||||
## Panel-internal tools
|
||||
|
||||
|
||||
+7
-7
@@ -43,12 +43,12 @@ ql auth logout --json
|
||||
|
||||
## 全量 OpenAPI 管理
|
||||
|
||||
现在还支持任务/订阅创建、修改、删除,应用管理与密钥重置,以及环境变量、配置、脚本、日志、依赖、系统、仪表盘和用户管理。`ql api routes --json` 列出全部 143 条有效路由;3 条已下线文件读取接口不包含在内。新增命令在 [完整双语参考](skills/qinglong-cli/references/openapi.md) 中逐项列出,路由覆盖由 CI 与后端代码核对。
|
||||
现在还支持任务/订阅创建、修改、删除,应用管理与密钥重置,以及环境变量、配置、脚本、日志、依赖、系统、仪表盘和用户管理。`ql api routes --json` 列出当前版本的有效路由;3 条已下线文件读取接口不包含在内。新增命令在 [完整双语参考](skills/qinglong-cli/references/openapi.md) 中逐项列出,路由覆盖由 CI 与后端代码核对。
|
||||
|
||||
```sh
|
||||
ql task create --name demo --command 'task demo.js' --schedule '0 0 * * *' --json
|
||||
ql subscription create --type public-repo --url https://example.com/repo.git --alias demo --schedule-type crontab --schedule '0 0 * * *' --json
|
||||
ql app create --name agent --scopes crons,subscriptions --show-secrets --json
|
||||
ql app create --name agent --scopes crons,subscriptions,envs --show-secrets --json
|
||||
ql env create --data @envs.json --json
|
||||
ql api request PUT /open/crons/run --data '[12,13]' --json
|
||||
```
|
||||
@@ -68,7 +68,7 @@ ql api request PUT /open/crons/run --data '[12,13]' --json
|
||||
|
||||
### 应用凭据登录
|
||||
|
||||
在面板创建专用应用,按需授予 crons、subscriptions、envs 等权限。`login` 与 `auth login` 等价;交互输入 Client ID 和不回显的 Client Secret,密钥不支持命令行参数。
|
||||
在面板创建专用应用,按需授予 crons、subscriptions 等权限。旧 scope 保留原有权限;仅读取时可选用 `crons:read`、`subscriptions:read`、`envs:read`、`configs:read`、`scripts:read`、`dependencies:read`、`logs:read`、`dashboard:read`。脚本和日志的只读权限也允许通过 POST 下载文件和校验目录版本;`GET /crons/import` 会写入任务,不属于只读操作。`login` 与 `auth login` 等价;交互输入 Client ID 和不回显的 Client Secret,密钥不支持命令行参数。
|
||||
|
||||
```sh
|
||||
ql login --url https://ql.example.com
|
||||
@@ -76,7 +76,7 @@ ql auth status --scope crons --json
|
||||
# 自动化环境事先注入 QL_CLIENT_ID 和 QL_CLIENT_SECRET,再运行同一 login 命令
|
||||
```
|
||||
|
||||
凭据和 token 保存到 `~/.config/qinglong/cli.json`,为当前用户所有的 0600 明文文件。`QL_CLI_CONFIG` 可选择其他配置文件。登录只验证应用凭据,不意味着具备所有资源权限。
|
||||
凭据和 token 保存到 `~/.config/qinglong/cli.json` 明文文件。CLI 创建文件时会请求 `0600` 权限,并在读取时拒绝符号链接和非普通文件;由于 Windows、WSL 挂载盘及部分网络或设备文件系统不能可靠提供 POSIX 权限位,读取时不以权限位或 UID 为准。请将配置保存在仅当前用户可访问的位置,并按实际文件系统的权限或 ACL 保护它;无法保证时可使用下述环境令牌方式。`QL_CLI_CONFIG` 可选择其他配置文件。登录只验证应用凭据,不意味着具备所有资源权限。
|
||||
|
||||
### 直接使用访问令牌
|
||||
|
||||
@@ -128,11 +128,11 @@ npm run test:cli
|
||||
node cli/scripts/verify-package.cjs
|
||||
```
|
||||
|
||||
测试覆盖请求格式、认证刷新、输出、错误、禁止自动重试、权限和独立安装。打包验证会离线安装 tgz,并确认唯一入口是 `ql`,本机命令不可调用。
|
||||
测试覆盖请求格式、认证刷新、输出、错误、禁止自动重试、配置文件类型和独立安装。打包验证会离线安装 tgz,并确认唯一入口是 `ql`,本机命令不可调用。
|
||||
|
||||
CLI package 工作流在相关 PR、develop/master 推送和手动触发时执行 Node 22.12/24 类型检查、构建及测试。Node 24 上传通过离线安装验证的 `qinglong-cli-<commit>` artifact。两个矩阵任务成功后,master 推送会将这份已验证的 tgz 发布到 npm 的 latest 标签,通过 GitHub Actions OIDC 可信发布,无需 `NPM_TOKEN` Secret。手动运行需选择 master 并勾选 publish;PR、develop 和 fork 不发布。npm 的 Trusted Publisher 需绑定仓库 `whyour/qinglong` 和工作流 `cli-package.yml`,允许 `npm publish`;面板包 `@whyour/qinglong` 单独绑定 `build-docker-image.yml`。发布 job 使用 Node 24,并仅在该 job 授予 `id-token: write`。新包需先完成首次发布,再配置对应包的可信发布关系。
|
||||
CLI package 工作流在相关 PR、develop/master 推送和手动触发时执行 Node 22.12/24 类型检查、构建及测试,并在 Windows 与 Linux ARM64 上用真实文件系统验证登录和命令读取。Node 24 上传通过离线安装验证的 `qinglong-cli-<commit>` artifact。全部验证成功后,master 推送会将这份 tgz 发布到 npm 的 `latest` 标签;手动在 master 勾选 `publish` 也可发布稳定版。develop 推送只验证;手动在 develop 勾选 `publish` 并填写 `prerelease_version`(例如 `0.1.5-beta.0`)可发布到对应的 `alpha`、`beta` 或 `rc` 标签。PR 和 fork 不发布。CLI 专属改动不会触发主镜像构建,少数被镜像使用的 CLI 内部升级文件除外。npm 的 Trusted Publisher 需绑定仓库 `whyour/qinglong` 和工作流 `cli-package.yml`,允许 `npm publish`;面板包 `@whyour/qinglong` 单独绑定 `build-docker-image.yml`。发布 job 使用 Node 24 和 GitHub Actions OIDC,无需 `NPM_TOKEN` Secret,仅该 job 授予 `id-token: write`。新包需先完成首次发布,再配置对应包的可信发布关系。
|
||||
|
||||
CLI 版本独立维护在 cli/package.json 和 cli/package-lock.json。发布改动前执行 `npm version patch --prefix cli --no-git-tag-version`(也可用 minor/major),提交这两个文件。已发布的版本会提示并跳过;registry 查询失败则停止发布。该流程仅发布 X.Y.Z 稳定版本,不重新构建产物或执行包生命周期脚本。
|
||||
CLI 稳定版版本号独立维护在 cli/package.json 和 cli/package-lock.json。发布改动前执行 `npm version patch --prefix cli --no-git-tag-version`(也可用 minor/major),提交这两个文件。develop 预发布版版本号仅在工作流运行时设置,不写回仓库。已发布的稳定版版本号会提示并跳过;重复的预发布版版本号会报错,registry 查询失败也会停止发布。发布 job 不重新构建产物或执行包生命周期脚本。
|
||||
|
||||
## 面板内部工具
|
||||
|
||||
|
||||
Generated
+78
-4
@@ -1,12 +1,13 @@
|
||||
{
|
||||
"name": "@whyour/qinglong-cli",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@whyour/qinglong-cli",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.4",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"ql": "dist/npm/ql.js"
|
||||
},
|
||||
@@ -14,12 +15,12 @@
|
||||
"@types/node": "22.19.0",
|
||||
"commander": "15.0.0",
|
||||
"esbuild": "0.28.2",
|
||||
"tar": "7.5.20",
|
||||
"typescript": "5.2.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
},
|
||||
"license": "Apache-2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.28.2",
|
||||
@@ -463,6 +464,19 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@isaacs/fs-minipass": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
|
||||
"integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"minipass": "^7.0.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.19.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.0.tgz",
|
||||
@@ -473,6 +487,16 @@
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/chownr": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
|
||||
"integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/commander": {
|
||||
"version": "15.0.0",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-15.0.0.tgz",
|
||||
@@ -525,6 +549,46 @@
|
||||
"@esbuild/win32-x64": "0.28.2"
|
||||
}
|
||||
},
|
||||
"node_modules/minipass": {
|
||||
"version": "7.1.3",
|
||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
|
||||
"integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/minizlib": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz",
|
||||
"integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"minipass": "^7.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 18"
|
||||
}
|
||||
},
|
||||
"node_modules/tar": {
|
||||
"version": "7.5.20",
|
||||
"resolved": "https://registry.npmjs.org/tar/-/tar-7.5.20.tgz",
|
||||
"integrity": "sha512-9FcyK4PA6+WbzlTM9WhQm6vB5W7cP7dUiPsv1g7YDwEQnQ1CGpK3MGlKk/ITVWMk05kHZuBhmVhiv8LZoy/PFQ==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"@isaacs/fs-minipass": "^4.0.0",
|
||||
"chownr": "^3.0.0",
|
||||
"minipass": "^7.1.2",
|
||||
"minizlib": "^3.1.0",
|
||||
"yallist": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.2.2",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz",
|
||||
@@ -545,6 +609,16 @@
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
|
||||
"integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@whyour/qinglong-cli",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.4",
|
||||
"description": "Authenticated remote management CLI for QingLong 2.x",
|
||||
"type": "commonjs",
|
||||
"bin": {
|
||||
@@ -26,7 +26,8 @@
|
||||
"commander": "15.0.0",
|
||||
"esbuild": "0.28.2",
|
||||
"typescript": "5.2.2",
|
||||
"@types/node": "22.19.0"
|
||||
"@types/node": "22.19.0",
|
||||
"tar": "7.5.20"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
|
||||
@@ -17,6 +17,25 @@ fs.copyFileSync(
|
||||
path.join(root, 'src/internal/maintenance/upgradeArtifacts.cjs'),
|
||||
path.join(root, 'dist/internal/maintenance/upgradeArtifacts.cjs'),
|
||||
);
|
||||
fs.copyFileSync(
|
||||
path.join(root, 'src/internal/maintenance/panelUpgrade.cjs'),
|
||||
path.join(root, 'dist/internal/maintenance/panelUpgrade.cjs'),
|
||||
);
|
||||
fs.copyFileSync(
|
||||
path.join(root, 'src/internal/maintenance/nodeRuntime.cjs'),
|
||||
path.join(root, 'dist/internal/maintenance/nodeRuntime.cjs'),
|
||||
);
|
||||
// The operational CLI may live outside the panel and has no panel node_modules.
|
||||
require('esbuild').buildSync({
|
||||
entryPoints: [path.join(root, 'src/internal/maintenance/platformBundle.cjs')],
|
||||
outfile: path.join(root, 'dist/internal/maintenance/platformBundle.cjs'),
|
||||
bundle: true,
|
||||
platform: 'node',
|
||||
format: 'cjs',
|
||||
target: 'node20',
|
||||
minify: true,
|
||||
legalComments: 'inline',
|
||||
});
|
||||
require('esbuild').buildSync({
|
||||
entryPoints: [path.join(root, 'src/shared/cli/commander.ts')],
|
||||
outfile: path.join(root, 'dist/shared/cli/commander.js'),
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
# OpenAPI 全量参考 / Complete OpenAPI reference
|
||||
|
||||
CLI 对应本版本后端的 146 条有效路由。通过 `ql api routes --json` 查看方法、路径、对应命令、位置参数、请求体与上传字段;CLI 测试与 back/api 路由逐项核对。GET configs/:file、scripts/:file、logs/:file 已返回 410,改用 detail 命令,不再暴露旧入口。旧版面板可能没有新路由,以服务端响应为准。
|
||||
CLI 对应本版本后端的有效路由。通过 `ql api routes --json` 查看方法、路径、对应命令、位置参数、请求体与上传字段;CLI 测试与 back/api 路由逐项核对。GET configs/:file、scripts/:file、logs/:file 已返回 410,改用 detail 命令,不再暴露旧入口。旧版面板可能没有新路由,以服务端响应为准。
|
||||
|
||||
The catalogue covers 146 active routes in the current backend. `ql api routes --json` lists methods, paths, commands, positional parameters, bodies and upload fields. A route-coverage test detects drift. Three retired GET :file routes return 410; use detail-based commands. Older panel versions may not implement newer routes.
|
||||
The catalogue covers the active routes in the current backend. `ql api routes --json` lists methods, paths, commands, positional parameters, bodies and upload fields. A route-coverage test detects drift. Three retired GET :file routes return 410; use detail-based commands. Older panel versions may not implement newer routes.
|
||||
|
||||
日志和脚本分页返回 `versions`。应用可将已浏览目录的版本按每组 1 到 128 项交给同一资源的 `entries-check --data`。返回 `current: false` 时,从第一页重新读取。
|
||||
|
||||
Log and script pages return `versions`. Pass the visited directories’ versions to the matching `entries-check --data` command in groups of 1 to 128. Restart pagination when it returns `current: false`.
|
||||
|
||||
`ql task instances <id>` 默认返回该任务的完整运行历史,按启动时间倒序。显式传 `--query '{"paged":true,"limit":25}'` 后按实例 ID 倒序分页(默认 25,最多 100),将返回的 `next` 作为下一页的 `before`,直到 `next` 为 `null`。刷新指定实例可传 `{"paged":true,"ids":"12,13"}`。触发记录使用独立的 `task triggers` 接口,日志和脚本目录分页使用 `log entries` 和 `script entries`。
|
||||
|
||||
`ql task instances <id>` returns the full history ordered by start time by default. Opt in with `--query '{"paged":true,"limit":25}'` to page by descending instance ID (default 25, maximum 100). Pass `next` as `before` until `next` is `null`. Use `{"paged":true,"ids":"12,13"}` to refresh specific rows. Trigger history and directory pagination use separate endpoints.
|
||||
|
||||
直接调用 `PUT /open/crons/stop` 时,请求体为任务 ID 数组。需要安全重试的调用方应在首次发送前生成 UUID,放入 `Idempotency-Key` 请求头,并在该操作的所有重试中复用。相同键只处理第一次受理时的实例和排队记录,换用不同任务集合会返回 409。主动发起新的停止操作时使用新键。未携带键的旧客户端每次调用都会停止当前任务实例。
|
||||
|
||||
## 认证与权限 / Authentication and permissions
|
||||
|
||||
常规使用 `ql login` 的应用凭据。scope 是 /open 后首个路径段:crons、subscriptions、envs、configs、scripts、logs、dependencies、system、dashboard 等。应用管理需要 apps;user、health、update 等路由同样接受服务端权限校验。面板 UI 当前没有列出全部这些 scope,不能把路由存在理解成现有应用已获授权。
|
||||
常规使用 `ql login` 的应用凭据。scope 通常对应 /open 后首个路径段:crons、subscriptions、envs、configs、scripts、logs、dependencies、system、dashboard 等。旧 scope 保留原有权限;上述资源除 system 外可选用对应的 `:read` scope。`crons:read` 不包含会写入任务的 `GET /crons/import`;`scripts:read`、`logs:read` 包含使用 POST 的下载和目录版本校验,不包含写入、删除或执行。`dashboard:read` 不允许 POST 统计上报。外部应用的 `system` scope 仅允许读取系统状态和发送通知。应用管理需要 apps;`GET /apps` 会返回 Client Secret,因此不提供 `apps:read`。user、health、update 等路由同样接受服务端权限校验。路由存在不代表现有应用已获授权。
|
||||
|
||||
认证步骤、环境变量优先级、应用登录、面板会话与双因素验证、退出行为,统一见 [认证参考](panel.md#authentication)。应用管理可用 apps 权限的应用或授权面板会话;QL_URL/QL_ACCESS_TOKEN 不保存、不刷新,不自动退回应用配置。
|
||||
认证步骤、环境变量优先级、应用登录、面板会话与双因素验证、退出行为,统一见 [认证参考](panel.md#authentication)。应用管理可用已有 apps 权限的应用或授权面板会话;后端创建和更新应用时拒绝授予 apps 权限。QL_URL/QL_ACCESS_TOKEN 不保存、不刷新,不自动退回应用配置。
|
||||
|
||||
See the [authentication reference](panel.md#authentication) for application login, direct-token precedence, owner sessions/2FA and logout. App management accepts apps-scoped credentials or an authorized owner session. Direct tokens are not saved/refreshed and never fall back to application configuration.
|
||||
See the [authentication reference](panel.md#authentication) for application login, direct-token precedence, owner sessions/2FA and logout. App management accepts existing apps-scoped credentials or an authorized owner session; the backend rejects granting apps scope when creating or updating an application. Direct tokens are not saved/refreshed and never fall back to application configuration.
|
||||
|
||||
Existing scopes retain their original access. Use the resource's `:read` scope for read-only access to crons, subscriptions, envs, configs, scripts, dependencies, logs, or dashboard. `crons:read` excludes the mutating `GET /crons/import`; `scripts:read` and `logs:read` include downloads and directory version checks (POST), but exclude writes, deletion, and execution. `dashboard:read` excludes statistics reporting (POST). External `system` applications may only read system status and send notifications. `GET /apps` returns Client Secrets, so there is no `apps:read` scope.
|
||||
|
||||
`auth status --scope <scope>` tests a representative read; update has no read endpoint and is not offered by status. This does not prove permission for every write. `app list/create/update/reset-secret` 默认隐藏 client_secret/tokens;只有明确需要凭据时才加 --show-secrets,并避免把输出记录到共享日志。其他资源/通用请求可能含环境值、配置、脚本、订阅凭据和会话,按敏感数据处理。
|
||||
|
||||
@@ -49,16 +61,24 @@ ql script get --query '{"file":"demo.js","path":""}' --json
|
||||
ql script history-list --query '{"filename":"demo.js","path":""}' --json
|
||||
ql script history-detail --query '{"filename":"demo.js","path":"","id":"VERSION_UUID"}' --json
|
||||
ql script history-restore --data '{"filename":"demo.js","path":"","id":"VERSION_UUID","expectedHash":"CURRENT_SHA256"}' --json
|
||||
# Requires the full configs scope or a panel session token.
|
||||
ql config save --data '{"name":"example.sh","content":"# example"}' --json
|
||||
ql config get --query '{"path":"example.sh"}' --json
|
||||
ql log download --data '{"filename":"example.log","path":"example"}' --output ./example.log --json
|
||||
ql dependency create --data '[{"name":"example-package","type":0}]' --json
|
||||
ql dependency refresh --data '{"type":"python3"}' --json
|
||||
ql dependency refresh-active --json
|
||||
ql dependency refresh-status <JOB_UUID> --json
|
||||
ql system data-export --data '{}' --output ./panel.tgz --json
|
||||
ql system data-import --file ./panel.tgz --json
|
||||
ql api request PUT /open/crons/run --data '[12,13]' --json
|
||||
ql api request GET /open/crons --query '{"page":1,"size":100,"searchValue":"demo"}' --json
|
||||
```
|
||||
|
||||
依赖 refresh 的 type 为 nodejs 或 python3,立即返回后台任务 id 与 state;用 refresh-status 查询该 UUID,直到 completed 或 failed。refresh-active 返回运行中的任务或 null,普通 list 不触发检查。
|
||||
|
||||
Dependency refresh accepts type nodejs or python3 and immediately returns a background job id and state. Poll refresh-status with that UUID until completed or failed. refresh-active returns the running job or null; listing dependencies does not trigger checks.
|
||||
|
||||
任务 create/update 需要 command/schedule;name、labels、sub_id、extra_schedules、task_before/after、log_name、allow_multiple_instances、work_dir 等字段可通过 --data 提交。订阅 create 需要 type/url/alias/schedule_type,update 需要 id/type/url/alias;interval_schedule、pull_option、dependences、extensions、sub_before/after、proxy、autoAddCron/autoDelCron 等用 --data。private-repo 凭据仅通过受保护文件或 stdin 提供。环境变量与依赖 create 接受对象数组,应用 scopes 为字符串数组。其余准确字段/枚举由当前后端 Joi schema 校验:见 [back/api](https://github.com/whyour/qinglong/tree/develop/back/api) 和 [定时规则 schema](https://github.com/whyour/qinglong/blob/develop/back/validation/schedule.ts)。
|
||||
|
||||
Task creation/update needs command/schedule; additional fields use --data. Subscription creation needs type/url/alias/schedule_type; updates need id/type/url/alias. Interval schedules, private repository credentials, filters, hooks and booleans use --data. Env/dependency creation accepts arrays; application scopes is a string array. The server validates field types/enums; the linked backend schemas are authoritative.
|
||||
@@ -80,6 +100,7 @@ System/user operations below execute remotely through the panel API. They do not
|
||||
| `ql task view-enable <id...>` | PUT | `crons/views/enable` | --query |
|
||||
| `ql task list ` | GET | `crons` | --query via api request |
|
||||
| `ql task detail ` | GET | `crons/detail` | --query |
|
||||
| `ql task preview` | GET | `crons/preview` | --query '{"schedule":"0 6 * * *"}' |
|
||||
| `ql task create ` | POST | `crons` | --data, --query |
|
||||
| `ql task run <id...>` | PUT | `crons/run` | --query via api request |
|
||||
| `ql task stop <id...>` | PUT | `crons/stop` | --query via api request |
|
||||
@@ -95,6 +116,8 @@ System/user operations below execute remotely through the panel API. They do not
|
||||
| `ql task import ` | GET | `crons/import` | --query |
|
||||
| `ql task get <id>` | GET | `crons/:id` | --query via api request |
|
||||
| `ql task status ` | PUT | `crons/status` | --data, --query |
|
||||
| `ql task daily-results <id>` | GET | `crons/:id/daily-results` | Verified exits and booked results for the last seven days |
|
||||
| `ql task triggers <id>` | GET | `crons/:id/triggers` | --query '{"offset":0}' |
|
||||
| `ql task instances <id>` | GET | `crons/:id/instances` | --query |
|
||||
| `ql task instance-stop <id> <instanceId>` | POST | `crons/:id/instances/:instanceId/stop` | --query |
|
||||
| `ql task log-files <id>` | GET | `crons/:id/logs` | --query |
|
||||
@@ -136,6 +159,8 @@ System/user operations below execute remotely through the panel API. They do not
|
||||
| `ql config save ` | POST | `configs/save` | --data, --query |
|
||||
| `ql script list ` | GET | `scripts` | --query |
|
||||
| `ql script get ` | GET | `scripts/detail` | --query |
|
||||
| `ql script entries ` | GET | `scripts/entries` | --query |
|
||||
| `ql script entries-check ` | POST | `scripts/entries/check` | --data, --query |
|
||||
| `ql script history-list ` | GET | `scripts/history` | --query |
|
||||
| `ql script history-detail ` | GET | `scripts/history/detail` | --query |
|
||||
| `ql script history-restore ` | PUT | `scripts/history/restore` | --data, --query |
|
||||
@@ -148,9 +173,14 @@ System/user operations below execute remotely through the panel API. They do not
|
||||
| `ql script rename ` | PUT | `scripts/rename` | --data, --query |
|
||||
| `ql log list ` | GET | `logs` | --query |
|
||||
| `ql log get ` | GET | `logs/detail` | --query |
|
||||
| `ql log entries ` | GET | `logs/entries` | --query |
|
||||
| `ql log entries-check ` | POST | `logs/entries/check` | --data, --query |
|
||||
| `ql log delete ` | DELETE | `logs` | --data, --query |
|
||||
| `ql log download ` | POST | `logs/download` | --data, --output, --query |
|
||||
| `ql dependency list ` | GET | `dependencies` | --query |
|
||||
| `ql dependency refresh ` | POST | `dependencies/refresh` | --data, --query |
|
||||
| `ql dependency refresh-active ` | GET | `dependencies/refresh/active` | --query |
|
||||
| `ql dependency refresh-status <id>` | GET | `dependencies/refresh/:id` | --query |
|
||||
| `ql dependency create ` | POST | `dependencies` | --data, --query |
|
||||
| `ql dependency update <id>` | PUT | `dependencies` | --data, --query |
|
||||
| `ql dependency delete <id...>` | DELETE | `dependencies` | --query |
|
||||
@@ -211,7 +241,6 @@ System/user operations below execute remotely through the panel API. They do not
|
||||
| `ql user notification-get ` | GET | `user/notification` | --query |
|
||||
| `ql user notification-set ` | PUT | `user/notification` | --data, --query |
|
||||
| `ql user init ` | PUT | `user/init` | --data, --query |
|
||||
| `ql user notification-init ` | PUT | `user/notification/init` | --data, --query |
|
||||
| `ql user avatar ` | PUT | `user/avatar` | --data, --file (avatar), --query |
|
||||
| `ql system apply-reload ` | PUT | `update/reload` | --query |
|
||||
| `ql system apply-system ` | PUT | `update/system` | --query |
|
||||
|
||||
@@ -18,9 +18,11 @@ export const nodePreloadSource: string = [
|
||||
' return;',
|
||||
' }',
|
||||
'',
|
||||
" const clientModule = require.cache[require.resolve('./client.js')];",
|
||||
' const originalResolveFilename = Module._resolveFilename;',
|
||||
' Module._resolveFilename = function (request, parent, isMain, options) {',
|
||||
' if (',
|
||||
' !clientModule.loadingPanelDependencies &&',
|
||||
' !Module.builtinModules.includes(request) &&',
|
||||
" !request.startsWith('node:') &&",
|
||||
" !request.startsWith('.') &&",
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { extendedLifecycle } from '../runtime/lifecycle';
|
||||
import { LifecycleReceipt } from '../runtime/lifecycle';
|
||||
import fs from 'node:fs/promises';
|
||||
import { writeSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { randomInt, randomUUID } from 'node:crypto';
|
||||
import { randomInt } from 'node:crypto';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import type { LocalContext } from '../runtime/context';
|
||||
import { sourceEnvironment } from '../runtime/context';
|
||||
import { LocalApi } from '../runtime/api';
|
||||
import { cancellationExitCode, runProcess } from '../runtime/process';
|
||||
import { within } from '../runtime/files';
|
||||
import { fail } from '../../shared/errors';
|
||||
@@ -207,11 +206,8 @@ export async function executeTask(
|
||||
const started = Math.floor(start / 1000);
|
||||
const first = options.argv[0]!;
|
||||
const taskId = await taskIdentity(context, first);
|
||||
const extended = await extendedLifecycle(context);
|
||||
const executionId =
|
||||
extended && context.env.QL_EXECUTION_ORIGIN === 'scheduled_system'
|
||||
? `legacy-system:${started}:${randomUUID()}`
|
||||
: undefined;
|
||||
const receipt = new LifecycleReceipt(context, started);
|
||||
const triggerId = receipt.triggerId;
|
||||
const fileName = path.basename(first, path.extname(first));
|
||||
const parent = first.includes('/') ? path.basename(path.dirname(first)) : '';
|
||||
const folder =
|
||||
@@ -221,7 +217,7 @@ export async function executeTask(
|
||||
folder === '/dev/null'
|
||||
? '/dev/null'
|
||||
: context.env.real_log_path ||
|
||||
path.join(folder, `${timestamp(new Date(start))}.log`);
|
||||
path.join(folder, `${timestamp(new Date(start))}${triggerId ? "-" + triggerId : ""}.log`);
|
||||
const fullLog =
|
||||
logPath === '/dev/null'
|
||||
? logPath
|
||||
@@ -245,20 +241,17 @@ export async function executeTask(
|
||||
process.stderr.write(value);
|
||||
})
|
||||
: undefined;
|
||||
const api = new LocalApi(context);
|
||||
const report = async (final: boolean, code = 0, duration = 0) => {
|
||||
if (!taskId) return;
|
||||
try {
|
||||
await api.call('crons/status', 'PUT', {
|
||||
await receipt.status({
|
||||
ids: [taskId],
|
||||
status: final ? '1' : '0',
|
||||
pid: String(process.pid),
|
||||
log_path: logPath,
|
||||
last_execution_time: started,
|
||||
last_running_time: duration,
|
||||
...(final && extended ? { exit_code: code } : {}),
|
||||
...(executionId ? { execution_id: executionId } : {}),
|
||||
});
|
||||
}, final ? code : undefined);
|
||||
} catch {
|
||||
output(
|
||||
Buffer.from(
|
||||
@@ -266,13 +259,9 @@ export async function executeTask(
|
||||
),
|
||||
);
|
||||
}
|
||||
if (final && extended) {
|
||||
if (final) {
|
||||
try {
|
||||
await api.call('dashboard/record', 'POST', {
|
||||
ref_id: taskId,
|
||||
code,
|
||||
elapsed: duration,
|
||||
});
|
||||
await receipt.statistics(taskId, code, duration);
|
||||
} catch {
|
||||
output(
|
||||
Buffer.from(
|
||||
@@ -282,6 +271,7 @@ export async function executeTask(
|
||||
}
|
||||
}
|
||||
};
|
||||
let durationSeconds = 0;
|
||||
let exitCode = 1,
|
||||
timedOut = false;
|
||||
let languageDirectory: string | undefined;
|
||||
@@ -504,7 +494,7 @@ export async function executeTask(
|
||||
} finally {
|
||||
if (languageDirectory)
|
||||
await fs.rm(languageDirectory, { recursive: true, force: true });
|
||||
const durationSeconds = Math.max(
|
||||
durationSeconds = Math.max(
|
||||
1,
|
||||
Math.floor((Date.now() - start) / 1000),
|
||||
);
|
||||
@@ -534,8 +524,8 @@ export async function executeTask(
|
||||
return {
|
||||
exitCode,
|
||||
logPath,
|
||||
durationSeconds: Math.max(1, Math.floor((Date.now() - start) / 1000)),
|
||||
executionId,
|
||||
durationSeconds,
|
||||
executionId: taskId ? receipt.executionId : undefined,
|
||||
taskId,
|
||||
timedOut,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// Node 24's ARMv6 JS compiler tiers can trap on ARM1176. Keep WebAssembly
|
||||
// enabled for fetch/undici; --jitless disables their HTTP parser as well.
|
||||
const armv6ServerArgs = Object.freeze([
|
||||
'--no-opt',
|
||||
'--no-sparkplug',
|
||||
'--no-maglev',
|
||||
]);
|
||||
function serverRuntimeArgs(runtime = process) {
|
||||
return runtime.arch === 'arm' &&
|
||||
Number(runtime.config.variables.arm_version) === 6 &&
|
||||
Number(runtime.versions.node.split('.')[0]) >= 24
|
||||
? [...armv6ServerArgs]
|
||||
: [];
|
||||
}
|
||||
|
||||
module.exports = { serverRuntimeArgs, armv6ServerArgs };
|
||||
if (require.main === module)
|
||||
process.stdout.write(serverRuntimeArgs().join(' '));
|
||||
@@ -7,6 +7,10 @@ import type { LocalContext } from '../runtime/context';
|
||||
import { atomicWrite } from '../runtime/files';
|
||||
import { runProcess, checkedProcess } from '../runtime/process';
|
||||
import { findDirectBackendPids } from '../runtime/backendProcesses';
|
||||
const { serverRuntimeArgs, armv6ServerArgs } = require('./nodeRuntime.cjs') as {
|
||||
serverRuntimeArgs(): string[];
|
||||
armv6ServerArgs: readonly string[];
|
||||
};
|
||||
|
||||
export async function repairConfiguration(
|
||||
context: LocalContext,
|
||||
@@ -117,7 +121,11 @@ async function stopDirectBackend(context: LocalContext): Promise<void> {
|
||||
for (const line of result.stdout.split('\n')) {
|
||||
const match = line.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);
|
||||
if (!match || !/^node(?:\d+)?$/.test(path.basename(match[2]!))) continue;
|
||||
if (match[3] !== entry) continue;
|
||||
if (
|
||||
match[3] !== entry &&
|
||||
match[3] !== `${armv6ServerArgs.join(' ')} ${entry}`
|
||||
)
|
||||
continue;
|
||||
const pid = Number(match[1]);
|
||||
if (pid === process.pid) continue;
|
||||
try {
|
||||
@@ -150,6 +158,14 @@ export async function startPanel(
|
||||
GRPC_PORT: context.env.QlGrpcPort || '5500',
|
||||
},
|
||||
};
|
||||
// Archive selection and launcher ownership apply only to the upgrade worker.
|
||||
// Retaining them in PM2 would pin the next online update to an offline file.
|
||||
for (const name of [
|
||||
'QL_UPGRADE_FILE',
|
||||
'QL_UPGRADE_REPAIR_DEPS',
|
||||
'QL_UPGRADE_LAUNCHER_PID',
|
||||
])
|
||||
delete options.env[name as keyof typeof options.env];
|
||||
if (await executableAvailable('pm2', context.env)) {
|
||||
const flushed = await runProcess('pm2', ['flush'], options);
|
||||
if (flushed.code === 0) {
|
||||
@@ -171,7 +187,7 @@ export async function startPanel(
|
||||
0o600,
|
||||
);
|
||||
try {
|
||||
const child = spawn(process.execPath, [entry], {
|
||||
const child = spawn(process.execPath, [...serverRuntimeArgs(), entry], {
|
||||
...options,
|
||||
detached: true,
|
||||
stdio: ['ignore', log.fd, log.fd],
|
||||
|
||||
@@ -6,6 +6,7 @@ const { spawn } = require('node:child_process');
|
||||
const http = require('node:http');
|
||||
const { setTimeout: delay } = require('node:timers/promises');
|
||||
const artifacts = require('./upgradeArtifacts.cjs');
|
||||
const { nodeRuntimeArgs } = require('./platformBundle.cjs');
|
||||
|
||||
const active = new Set(['starting', 'running', 'restarting']);
|
||||
const stateFile = (tmp) => path.join(tmp, 'panel-upgrade.json');
|
||||
@@ -60,7 +61,9 @@ async function withPanelLifecycle(root, tmp, env, operation, signal) {
|
||||
|
||||
async function targetVersion(source) {
|
||||
const text = await fs.readFile(path.join(source, 'version.yaml'), 'utf8');
|
||||
const version = text.match(/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+)/m)?.[1];
|
||||
const version = text.match(
|
||||
/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)/m,
|
||||
)?.[1];
|
||||
if (!version) throw new Error('Invalid update version');
|
||||
return version;
|
||||
}
|
||||
@@ -164,7 +167,7 @@ async function readState(tmp) {
|
||||
}
|
||||
|
||||
async function getStatus(tmp) {
|
||||
const state = await readState(tmp);
|
||||
let state = await readState(tmp);
|
||||
if (active.has(state.status)) {
|
||||
let alive = false;
|
||||
if (Number.isSafeInteger(state.pid) && state.pid > 0) {
|
||||
@@ -176,8 +179,14 @@ async function getStatus(tmp) {
|
||||
}
|
||||
} else alive = Date.now() - state.startedAt < 10000;
|
||||
if (!alive) {
|
||||
state.status = 'failed';
|
||||
state.error = '升级任务意外中断,请重试';
|
||||
// The worker can publish its terminal state and exit after our first read.
|
||||
const previous = state;
|
||||
state = await readState(tmp);
|
||||
if (active.has(state.status) && state.id === previous.id &&
|
||||
state.pid === previous.pid && state.startedAt === previous.startedAt) {
|
||||
state.status = 'failed';
|
||||
state.error = '升级任务意外中断,请重试';
|
||||
}
|
||||
}
|
||||
}
|
||||
// Bound reads even when an installer produces a very large log.
|
||||
@@ -200,6 +209,93 @@ async function getStatus(tmp) {
|
||||
return state;
|
||||
}
|
||||
|
||||
// Manual restarts accept the currently prepared package, including one retained
|
||||
// after a failed preparation. Legacy installs without jobs keep their old path;
|
||||
// complete-bundle installs always verify and record the actual running build.
|
||||
async function withPreparedJob(tmp, env, selected, operation) {
|
||||
const previous = await getStatus(tmp);
|
||||
if (active.has(previous.status)) throw new Error('已有更新或重载正在执行。');
|
||||
const hasRecord = await fs
|
||||
.access(stateFile(tmp))
|
||||
.then(() => true)
|
||||
.catch((error) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
return false;
|
||||
});
|
||||
if (!hasRecord) {
|
||||
const pkg = env.QL_DIR
|
||||
? JSON.parse(
|
||||
await fs
|
||||
.readFile(path.join(env.QL_DIR, 'package.json'), 'utf8')
|
||||
.catch((error) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
return '{}';
|
||||
}),
|
||||
)
|
||||
: {};
|
||||
if (pkg.qinglongUpgradeFormat !== 2) return operation();
|
||||
}
|
||||
return artifacts.withUpgradeLock(
|
||||
path.join(tmp, 'panel-job-launch'),
|
||||
async () => {
|
||||
const current = await getStatus(tmp);
|
||||
if (active.has(current.status))
|
||||
throw new Error('已有更新或重载正在执行。');
|
||||
const prepared = await artifacts.selectedUpgrade(
|
||||
tmp,
|
||||
artifacts.releaseBranch(env),
|
||||
env,
|
||||
{ metadataOnly: true },
|
||||
);
|
||||
if (
|
||||
prepared.source !== selected.source ||
|
||||
prepared.static !== selected.static
|
||||
)
|
||||
throw new Error('暂存更新已变化,请重新下载更新。');
|
||||
const metadata = await stagedMetadata(selected);
|
||||
const previousBuild = await readRunningBuild(env).catch(() => undefined);
|
||||
const { log, error, ...record } = current;
|
||||
let state = {
|
||||
...record,
|
||||
...metadata,
|
||||
id: randomUUID(),
|
||||
action: 'apply',
|
||||
status: 'running',
|
||||
phase: 'verifying',
|
||||
startedAt: Date.now(),
|
||||
pid: process.pid,
|
||||
};
|
||||
const report = async (patch) => {
|
||||
state = { ...state, ...patch, updatedAt: Date.now() };
|
||||
await save(tmp, state);
|
||||
};
|
||||
await fs.writeFile(
|
||||
logFile(tmp),
|
||||
'Manual application of prepared update\n',
|
||||
{
|
||||
mode: 0o600,
|
||||
},
|
||||
);
|
||||
await report({});
|
||||
try {
|
||||
const result = await operation({
|
||||
onStop: () => report({ status: 'restarting', phase: 'restarting' }),
|
||||
onStart: (recover) =>
|
||||
recover
|
||||
? undefined
|
||||
: verifyRunningVersion(env, state, previousBuild),
|
||||
});
|
||||
await report({ status: 'completed', phase: 'completed' });
|
||||
return result;
|
||||
} catch (error) {
|
||||
await report({ status: 'failed', error: error.message });
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
env,
|
||||
);
|
||||
}
|
||||
|
||||
async function startJob({ root, tmp, env = process.env }, action) {
|
||||
if (!['download', 'apply'].includes(action))
|
||||
throw new Error('Invalid upgrade action');
|
||||
@@ -220,12 +316,14 @@ async function startJob({ root, tmp, env = process.env }, action) {
|
||||
let selected;
|
||||
let metadata;
|
||||
if (action === 'apply') {
|
||||
// Fail before launching a process or stopping the working panel.
|
||||
// Keep requests short on slow devices. The detached worker performs
|
||||
// complete file/dependency verification before it can stop the panel.
|
||||
try {
|
||||
selected = await artifacts.selectedUpgrade(
|
||||
tmp,
|
||||
artifacts.releaseBranch(env),
|
||||
env,
|
||||
{ metadataOnly: true },
|
||||
);
|
||||
metadata = await stagedMetadata(selected);
|
||||
if (previous.status === 'ready')
|
||||
@@ -390,7 +488,7 @@ async function runJob({ root, tmp, env = process.env }, id) {
|
||||
);
|
||||
await artifacts.waitForHealth(
|
||||
env,
|
||||
60000,
|
||||
undefined,
|
||||
recover ? undefined : controller.signal,
|
||||
);
|
||||
if (!recover)
|
||||
@@ -429,16 +527,30 @@ async function runJob({ root, tmp, env = process.env }, id) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { getStatus, startJob, runJob };
|
||||
module.exports = {
|
||||
getStatus,
|
||||
saveState: save,
|
||||
startJob,
|
||||
runJob,
|
||||
withPanelLifecycle,
|
||||
readRunningBuild,
|
||||
verifyRunningVersion,
|
||||
stagedMetadata,
|
||||
withPreparedJob,
|
||||
};
|
||||
async function launchWorker(id) {
|
||||
// detached creates a session but keeps the original parent. PM2 kills the
|
||||
// backend's entire descendant tree, so an intermediate launcher must exit
|
||||
// before the worker is allowed to stop that backend.
|
||||
const child = spawn(process.execPath, [__filename, 'worker', id], {
|
||||
env: { ...process.env, QL_UPGRADE_LAUNCHER_PID: String(process.pid) },
|
||||
detached: true,
|
||||
stdio: 'inherit',
|
||||
});
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[...nodeRuntimeArgs(), __filename, 'worker', id],
|
||||
{
|
||||
env: { ...process.env, QL_UPGRADE_LAUNCHER_PID: String(process.pid) },
|
||||
detached: true,
|
||||
stdio: 'inherit',
|
||||
},
|
||||
);
|
||||
await new Promise((resolve, reject) => {
|
||||
child.once('spawn', resolve);
|
||||
child.once('error', reject);
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
// One installed verifier handles release downloads and local offline archives.
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const os = require('node:os');
|
||||
const { execFile } = require('node:child_process');
|
||||
const { promisify } = require('node:util');
|
||||
const tar = require('tar');
|
||||
const { serverRuntimeArgs } = require('./nodeRuntime.cjs');
|
||||
const {
|
||||
prestartBackend,
|
||||
dependencyFailure,
|
||||
repairDependencies,
|
||||
} = require('./upgradePrestart.cjs');
|
||||
const execute = promisify(execFile);
|
||||
// Heavy archive parsing can hit unsupported V8 JIT paths on ARM1176. Keep
|
||||
// upgrade workers interpreted without changing the installed Node or server.
|
||||
const nodeRuntimeArgs = (runtime = process) =>
|
||||
runtime.arch === 'arm' && Number(runtime.config.variables.arm_version) === 6
|
||||
? ['--jitless']
|
||||
: [];
|
||||
const sha256 = (bytes) =>
|
||||
crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
const inside = (root, filename) => {
|
||||
const relative = path.relative(root, filename);
|
||||
return (
|
||||
relative !== '..' &&
|
||||
!relative.startsWith(`..${path.sep}`) &&
|
||||
!path.isAbsolute(relative)
|
||||
);
|
||||
};
|
||||
const versionParts = (v) => String(v).replace(/^v/, '').split('.').map(Number);
|
||||
function atLeast(actual, minimum) {
|
||||
const a = versionParts(actual),
|
||||
b = versionParts(minimum);
|
||||
return (
|
||||
b.every((n) => Number.isFinite(n)) &&
|
||||
a.every((n) => Number.isFinite(n)) &&
|
||||
(a[0] > b[0] ||
|
||||
(a[0] === b[0] &&
|
||||
(a[1] > b[1] || (a[1] === b[1] && (a[2] || 0) >= (b[2] || 0)))))
|
||||
);
|
||||
}
|
||||
|
||||
async function runtimeTarget() {
|
||||
let libc, libcVersion;
|
||||
if (process.platform === 'linux') {
|
||||
const header = process.report.getReport().header;
|
||||
if (header.glibcVersionRuntime) {
|
||||
libc = 'glibc';
|
||||
libcVersion = header.glibcVersionRuntime;
|
||||
} else {
|
||||
let text = '';
|
||||
try {
|
||||
text = (await execute('ldd', ['--version'])).stdout;
|
||||
} catch (error) {
|
||||
text = `${error.stdout || ''}\n${error.stderr || ''}`;
|
||||
}
|
||||
const match = text.match(/musl[\s\S]*?Version\s+(\d+\.\d+\.\d+)/i);
|
||||
if (!match)
|
||||
throw new Error(
|
||||
'Cannot identify Linux libc; refusing a native dependency bundle',
|
||||
);
|
||||
libc = 'musl';
|
||||
libcVersion = match[1];
|
||||
}
|
||||
}
|
||||
const armVersion =
|
||||
process.arch === 'arm'
|
||||
? Number(process.config.variables.arm_version)
|
||||
: undefined;
|
||||
if (process.arch === 'arm' && ![6, 7, 8].includes(armVersion))
|
||||
throw new Error('Cannot identify ARM instruction set');
|
||||
const arch =
|
||||
process.arch === 'arm' ? `armv${armVersion >= 7 ? 7 : 6}` : process.arch;
|
||||
const armFloatAbi =
|
||||
process.arch === 'arm' ? process.config.variables.arm_float_abi : undefined;
|
||||
if (
|
||||
process.arch === 'arm' &&
|
||||
!['hard', 'soft', 'softfp'].includes(armFloatAbi)
|
||||
)
|
||||
throw new Error('Cannot identify ARM floating-point ABI');
|
||||
return {
|
||||
platform: process.platform,
|
||||
arch,
|
||||
libc,
|
||||
libcVersion,
|
||||
endianness: os.endianness(),
|
||||
armFloatAbi,
|
||||
};
|
||||
}
|
||||
|
||||
function targetKey(target) {
|
||||
return [target.platform, target.arch, target.libc].filter(Boolean).join('-');
|
||||
}
|
||||
|
||||
function assertCompatible(manifest, target, node = process.versions.node) {
|
||||
if (
|
||||
manifest.format !== 2 ||
|
||||
!/^[a-f0-9]{40}$/.test(manifest.sourceCommit) ||
|
||||
!/^[a-f0-9]{64}$/.test(manifest.lockfileSha256) ||
|
||||
!manifest.files ||
|
||||
typeof manifest.files !== 'object' ||
|
||||
Array.isArray(manifest.files) ||
|
||||
!Number.isSafeInteger(manifest.nodeApi) ||
|
||||
manifest.nodeApi < 6
|
||||
)
|
||||
throw new Error('Invalid platform bundle manifest');
|
||||
if (targetKey(manifest.target || {}) !== targetKey(target))
|
||||
throw new Error(`Bundle platform mismatch: need ${targetKey(target)}`);
|
||||
if (
|
||||
!atLeast(node, manifest.nodeMinimum) ||
|
||||
Number(process.versions.napi) < manifest.nodeApi
|
||||
)
|
||||
throw new Error(
|
||||
`Bundle requires Node >= ${manifest.nodeMinimum} and Node-API ${manifest.nodeApi}; the existing Node is retained`,
|
||||
);
|
||||
if (
|
||||
manifest.target.endianness !== target.endianness ||
|
||||
manifest.target.armFloatAbi !== target.armFloatAbi
|
||||
)
|
||||
throw new Error(
|
||||
'Bundle native byte order or ARM floating-point ABI mismatch',
|
||||
);
|
||||
if (target.libc && !atLeast(target.libcVersion, manifest.target.libcMinimum))
|
||||
throw new Error(
|
||||
`Bundle requires ${target.libc} >= ${manifest.target.libcMinimum}`,
|
||||
);
|
||||
}
|
||||
|
||||
async function inventory(roots) {
|
||||
const files = {};
|
||||
async function visit(directory, prefix) {
|
||||
for (const name of (await fs.readdir(directory)).sort()) {
|
||||
const filename = path.join(directory, name),
|
||||
relative = `${prefix}/${name}`;
|
||||
const stat = await fs.lstat(filename);
|
||||
if (stat.isDirectory()) await visit(filename, relative);
|
||||
else if (stat.isFile())
|
||||
files[relative] = {
|
||||
type: 'file',
|
||||
mode: stat.mode & 0o777,
|
||||
sha256: sha256(await fs.readFile(filename)),
|
||||
};
|
||||
else if (stat.isSymbolicLink()) {
|
||||
const link = await fs.readlink(filename);
|
||||
const boundary = roots[prefix.split('/')[0]];
|
||||
if (
|
||||
path.isAbsolute(link) ||
|
||||
!inside(boundary, path.resolve(path.dirname(filename), link)) ||
|
||||
!inside(await fs.realpath(boundary), await fs.realpath(filename))
|
||||
)
|
||||
throw new Error(`Bundle link escapes its payload: ${relative}`);
|
||||
files[relative] = { type: 'link', link };
|
||||
} else throw new Error(`Unsupported bundle entry: ${relative}`);
|
||||
}
|
||||
}
|
||||
for (const [name, root] of Object.entries(roots)) await visit(root, name);
|
||||
return files;
|
||||
}
|
||||
|
||||
async function verifyPayload(selected, manifest, target) {
|
||||
assertCompatible(manifest, target);
|
||||
for (const name of ['data', '.tmp', '.git', '.env', 'static']) {
|
||||
if (
|
||||
await fs.lstat(path.join(selected.source, name)).catch((error) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
return null;
|
||||
})
|
||||
)
|
||||
throw new Error(`Reserved installation path in bundle: ${name}`);
|
||||
}
|
||||
const actual = await inventory({
|
||||
source: selected.source,
|
||||
static: selected.static,
|
||||
});
|
||||
const names = Object.keys(actual).sort(),
|
||||
expected = Object.keys(manifest.files).sort();
|
||||
if (
|
||||
JSON.stringify(names) !== JSON.stringify(expected) ||
|
||||
names.some(
|
||||
(name) =>
|
||||
JSON.stringify(actual[name]) !== JSON.stringify(manifest.files[name]),
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
'Platform bundle files or dependency checksums do not match',
|
||||
);
|
||||
if (
|
||||
sha256(await fs.readFile(path.join(selected.source, 'pnpm-lock.yaml'))) !==
|
||||
manifest.lockfileSha256
|
||||
)
|
||||
throw new Error('Platform bundle lockfile mismatch');
|
||||
await fs.access(
|
||||
path.join(selected.source, 'node_modules/sqlite3/package.json'),
|
||||
);
|
||||
}
|
||||
|
||||
async function smokeDependencies(source, signal) {
|
||||
// This probe is installed verifier code, never a verifier supplied by an archive.
|
||||
const probe = `
|
||||
const path = require('node:path'),fs = require('node:fs');
|
||||
const root = fs.realpathSync(process.cwd());
|
||||
const r = require('node:module').createRequire(path.join(root,'package.json'));
|
||||
for (const name of ['sqlite3','sequelize','cron-parser','@grpc/grpc-js','undici']) {
|
||||
if (!fs.realpathSync(r.resolve(name)).startsWith(root + path.sep)) throw new Error('Dependency outside staged payload: '+name);
|
||||
r(name);
|
||||
}
|
||||
const sqlite=r('sqlite3'), db=new sqlite.Database(':memory:');
|
||||
db.serialize(()=>{db.run('CREATE TABLE verify_bundle(value INTEGER)');db.run('INSERT INTO verify_bundle VALUES(42)');
|
||||
db.get('SELECT value FROM verify_bundle',(err,row)=>{if(err||row.value!==42){console.error(err||'SQLite readback failed');process.exitCode=1;}db.close();});});
|
||||
`;
|
||||
// Match the server's normal runtime. Node 20.18's built-in HTTP parser needs
|
||||
// WebAssembly, which --jitless disables; only archive workers need that flag.
|
||||
await execute(process.execPath, [...serverRuntimeArgs(process), '-e', probe], {
|
||||
cwd: source,
|
||||
env: { ...process.env, NODE_PATH: '', NODE_OPTIONS: '' },
|
||||
// ARM1176 devices need the same startup allowance as the backend probe.
|
||||
// Keep this bounded and cancellable without forcing an unnecessary repair.
|
||||
timeout: nodeRuntimeArgs().length ? 300000 : 30000,
|
||||
signal,
|
||||
});
|
||||
}
|
||||
|
||||
async function extractArchive(archive, destination) {
|
||||
const entries = new Map(),
|
||||
links = new Set();
|
||||
let unpacked = 0,
|
||||
invalid;
|
||||
await tar.t({
|
||||
file: archive,
|
||||
strict: true,
|
||||
onReadEntry(entry) {
|
||||
try {
|
||||
const name = entry.path.replace(/\/$/, '');
|
||||
if (
|
||||
!name ||
|
||||
name.includes('\\') ||
|
||||
/[\x00-\x1f\x7f]/.test(name) ||
|
||||
name.split('/').some((p) => !p || p === '.' || p === '..') ||
|
||||
!(name === 'qinglong' || name.startsWith('qinglong/')) ||
|
||||
entries.has(name) ||
|
||||
!['File', 'OldFile', 'Directory', 'SymbolicLink'].includes(entry.type)
|
||||
)
|
||||
throw new Error(`Unsafe bundle archive entry: ${name}`);
|
||||
unpacked += entry.size;
|
||||
if (unpacked > 2 * 1024 ** 3 || entries.size > 200000)
|
||||
throw new Error('Bundle archive exceeds extraction limits');
|
||||
entries.set(name, entry.type);
|
||||
if (entry.type === 'SymbolicLink') {
|
||||
if (
|
||||
path.posix.isAbsolute(entry.linkpath) ||
|
||||
entry.linkpath.includes('\\') ||
|
||||
!inside(
|
||||
'/qinglong',
|
||||
path.posix.resolve('/', path.posix.dirname(name), entry.linkpath),
|
||||
)
|
||||
)
|
||||
throw new Error('Unsafe bundle symlink');
|
||||
links.add(name);
|
||||
}
|
||||
} catch (error) {
|
||||
invalid ||= error;
|
||||
}
|
||||
},
|
||||
});
|
||||
if (invalid) throw invalid;
|
||||
for (const name of entries.keys()) {
|
||||
let parent = path.posix.dirname(name);
|
||||
while (parent !== '.') {
|
||||
if (links.has(parent))
|
||||
throw new Error('Archive writes through a symlink');
|
||||
parent = path.posix.dirname(parent);
|
||||
}
|
||||
}
|
||||
await tar.x({
|
||||
file: archive,
|
||||
cwd: destination,
|
||||
strict: true,
|
||||
preservePaths: false,
|
||||
noChown: true,
|
||||
umask: 0,
|
||||
});
|
||||
}
|
||||
|
||||
async function stageBundle({
|
||||
root,
|
||||
tmp,
|
||||
env,
|
||||
run,
|
||||
signal,
|
||||
onProgress,
|
||||
verifyStatic,
|
||||
download,
|
||||
probe = smokeDependencies,
|
||||
prestart = prestartBackend,
|
||||
repair = repairDependencies,
|
||||
}) {
|
||||
let local = env.QL_UPGRADE_FILE;
|
||||
if (!local) {
|
||||
const current = JSON.parse(
|
||||
await fs
|
||||
.readFile(path.join(root, 'package.json'), 'utf8')
|
||||
.catch((error) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
return '{}';
|
||||
}),
|
||||
);
|
||||
if (current.qinglongUpgradeFormat !== 2) return null; // One-time compatibility path for older releases.
|
||||
}
|
||||
const target = await runtimeTarget();
|
||||
const branch = ['develop', 'debian-dev'].includes(env.QL_BRANCH)
|
||||
? 'develop'
|
||||
: 'master';
|
||||
const workspace = await fs.mkdtemp(path.join(tmp, 'upgrade-'));
|
||||
const report = onProgress || (async () => {});
|
||||
try {
|
||||
const archive = path.join(workspace, 'bundle.tar.gz');
|
||||
let expectedCommit;
|
||||
if (local) {
|
||||
if (!path.isAbsolute(local))
|
||||
throw new Error('Offline bundle path must be absolute');
|
||||
// Snapshot the local input so replacing it cannot race validation/extraction.
|
||||
await fs.copyFile(local, archive);
|
||||
} else {
|
||||
const indexUrl =
|
||||
env.QL_UPGRADE_INDEX_URL ||
|
||||
`https://github.com/whyour/qinglong/releases/download/upgrade-${branch}/latest.json`;
|
||||
const checkUrl = (url) => {
|
||||
const parsed = new URL(url);
|
||||
if (
|
||||
parsed.protocol !== 'https:' &&
|
||||
!(
|
||||
parsed.protocol === 'http:' &&
|
||||
['127.0.0.1', '[::1]'].includes(parsed.hostname)
|
||||
)
|
||||
)
|
||||
throw new Error('Upgrade URLs require HTTPS');
|
||||
};
|
||||
checkUrl(indexUrl);
|
||||
const indexFile = path.join(workspace, 'index.json');
|
||||
await run('curl', [
|
||||
'--fail',
|
||||
'--silent',
|
||||
'--show-error',
|
||||
'--location',
|
||||
'--proto',
|
||||
new URL(indexUrl).protocol === 'http:' ? '=http,https' : '=https',
|
||||
'--proto-redir',
|
||||
'=https',
|
||||
'--header',
|
||||
'Cache-Control: no-cache',
|
||||
'--connect-timeout',
|
||||
'10',
|
||||
'--max-time',
|
||||
'30',
|
||||
'--max-filesize',
|
||||
'1048576',
|
||||
'--output',
|
||||
indexFile,
|
||||
indexUrl,
|
||||
]);
|
||||
const index = JSON.parse(await fs.readFile(indexFile, 'utf8'));
|
||||
const entry = index.packages?.[targetKey(target)];
|
||||
if (
|
||||
index.format !== 2 ||
|
||||
!/^[a-f0-9]{40}$/.test(index.sourceCommit) ||
|
||||
!entry ||
|
||||
!Number.isSafeInteger(entry.size) ||
|
||||
entry.size <= 0 ||
|
||||
entry.size > 512 * 1024 ** 2 ||
|
||||
!/^[a-f0-9]{64}$/.test(entry.sha256)
|
||||
)
|
||||
throw new Error(`No verified update bundle for ${targetKey(target)}`);
|
||||
checkUrl(entry.url);
|
||||
expectedCommit = index.sourceCommit;
|
||||
await report({
|
||||
phase: 'downloading',
|
||||
artifact: 'qinglong-bundle',
|
||||
downloadedBytes: 0,
|
||||
totalBytes: entry.size,
|
||||
percent: 0,
|
||||
});
|
||||
await download(
|
||||
run,
|
||||
archive,
|
||||
entry.url,
|
||||
'qinglong-bundle',
|
||||
report,
|
||||
true,
|
||||
entry,
|
||||
);
|
||||
}
|
||||
if ((await fs.stat(archive)).size > 512 * 1024 ** 2)
|
||||
throw new Error('Bundle is too large');
|
||||
await report({
|
||||
phase: 'extracting',
|
||||
artifact: 'qinglong-bundle',
|
||||
percent: null,
|
||||
});
|
||||
await extractArchive(archive, workspace);
|
||||
const incoming = path.join(workspace, 'qinglong');
|
||||
const manifest = JSON.parse(
|
||||
await fs.readFile(path.join(incoming, 'bundle.json'), 'utf8'),
|
||||
);
|
||||
if (expectedCommit && manifest.sourceCommit !== expectedCommit)
|
||||
throw new Error('Update index and bundle commit differ');
|
||||
const selected = {
|
||||
source: path.join(workspace, `qinglong-${branch}`),
|
||||
static: path.join(workspace, `qinglong-static-${branch}`),
|
||||
};
|
||||
await fs.rename(path.join(incoming, 'source'), selected.source);
|
||||
await fs.rename(path.join(incoming, 'static'), selected.static);
|
||||
await report({ phase: 'verifying', percent: null });
|
||||
await verifyPayload(selected, manifest, target);
|
||||
const build = await verifyStatic(selected.source, selected.static, env);
|
||||
if (build.sourceCommit !== manifest.sourceCommit)
|
||||
throw new Error('Bundle and build commit differ');
|
||||
await report({ phase: 'dependencies', percent: null });
|
||||
let dependencyFiles;
|
||||
const testCandidate = async () => {
|
||||
await probe(selected.source, signal);
|
||||
await report({ phase: 'prestarting', percent: null });
|
||||
return prestart(selected, { target, signal });
|
||||
};
|
||||
try {
|
||||
await testCandidate();
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
if (!dependencyFailure(error)) throw error;
|
||||
if (local && env.QL_UPGRADE_REPAIR_DEPS !== '1')
|
||||
throw new Error(
|
||||
`Offline dependency check failed; no network access attempted. Use --repair-deps to allow one repair. ${error.message}`,
|
||||
);
|
||||
await report({ phase: 'repairing', percent: null });
|
||||
await repair(selected.source, { target, signal, env });
|
||||
const repaired = await inventory({
|
||||
source: selected.source,
|
||||
static: selected.static,
|
||||
});
|
||||
dependencyFiles = Object.fromEntries(
|
||||
Object.entries(repaired).filter(([name]) =>
|
||||
name.startsWith('source/node_modules/'),
|
||||
),
|
||||
);
|
||||
// A repair may change only dependencies, never bless changed application code.
|
||||
await verifyPayload(
|
||||
selected,
|
||||
manifestWithDependencies(manifest, dependencyFiles),
|
||||
target,
|
||||
);
|
||||
await verifyStatic(selected.source, selected.static, env);
|
||||
await testCandidate(); // Exactly one repair; this failure propagates.
|
||||
}
|
||||
await fs.writeFile(
|
||||
path.join(workspace, 'prestart.json'),
|
||||
JSON.stringify({
|
||||
format: 1,
|
||||
sourceCommit: manifest.sourceCommit,
|
||||
manifestSha256: sha256(Buffer.from(JSON.stringify(manifest))),
|
||||
node: process.version,
|
||||
execPath: process.execPath,
|
||||
completedAt: Date.now(),
|
||||
...(dependencyFiles ? { dependencyFiles } : {}),
|
||||
}),
|
||||
{ flag: 'wx', mode: 0o600 },
|
||||
);
|
||||
await fs.writeFile(
|
||||
path.join(workspace, 'bundle.json'),
|
||||
JSON.stringify(manifest),
|
||||
{ flag: 'wx', mode: 0o600 },
|
||||
);
|
||||
await fs.writeFile(
|
||||
path.join(workspace, 'ready.json'),
|
||||
JSON.stringify({
|
||||
...selected,
|
||||
root: path.resolve(root),
|
||||
sourceCommit: manifest.sourceCommit,
|
||||
dependenciesChanged: true,
|
||||
bundle: true,
|
||||
}),
|
||||
{ flag: 'wx', mode: 0o600 },
|
||||
);
|
||||
const pointer = path.join(workspace, 'pointer.json');
|
||||
await fs.writeFile(
|
||||
pointer,
|
||||
JSON.stringify({ directory: path.basename(workspace) }),
|
||||
{ flag: 'wx', mode: 0o600 },
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
const readyPointer = path.join(tmp, `upgrade-ready-${branch}.json`);
|
||||
const previous = await fs
|
||||
.readFile(readyPointer, 'utf8')
|
||||
.catch(() => 'null');
|
||||
await fs.rename(pointer, readyPointer);
|
||||
try {
|
||||
const old = JSON.parse(previous)?.directory;
|
||||
if (
|
||||
/^upgrade-[A-Za-z0-9_-]+$/.test(old) &&
|
||||
old !== path.basename(workspace)
|
||||
)
|
||||
await fs.rm(path.join(tmp, old), { recursive: true, force: true });
|
||||
} catch {
|
||||
/* Committed readiness must survive cleanup failure. */
|
||||
}
|
||||
return selected;
|
||||
} catch (error) {
|
||||
await fs.rm(workspace, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function manifestWithDependencies(manifest, dependencyFiles) {
|
||||
if (!dependencyFiles) return manifest;
|
||||
if (
|
||||
typeof dependencyFiles !== 'object' ||
|
||||
Array.isArray(dependencyFiles) ||
|
||||
!Object.keys(dependencyFiles).length ||
|
||||
Object.keys(dependencyFiles).some(
|
||||
(name) => !name.startsWith('source/node_modules/'),
|
||||
)
|
||||
)
|
||||
throw new Error('Invalid repaired dependency inventory');
|
||||
return {
|
||||
...manifest,
|
||||
files: {
|
||||
...Object.fromEntries(
|
||||
Object.entries(manifest.files).filter(
|
||||
([name]) => !name.startsWith('source/node_modules/'),
|
||||
),
|
||||
),
|
||||
...dependencyFiles,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function verifyStagedBundle(selected) {
|
||||
const manifest = JSON.parse(
|
||||
await fs.readFile(
|
||||
path.join(path.dirname(selected.source), 'bundle.json'),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const prestart = JSON.parse(
|
||||
await fs.readFile(
|
||||
path.join(path.dirname(selected.source), 'prestart.json'),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
if (
|
||||
prestart.format !== 1 ||
|
||||
prestart.sourceCommit !== manifest.sourceCommit ||
|
||||
prestart.manifestSha256 !== sha256(Buffer.from(JSON.stringify(manifest))) ||
|
||||
prestart.node !== process.version ||
|
||||
prestart.execPath !== process.execPath ||
|
||||
!Number.isSafeInteger(prestart.completedAt)
|
||||
)
|
||||
throw new Error(
|
||||
'Upgrade prestart receipt is missing or stale; prepare the update again',
|
||||
);
|
||||
await verifyPayload(
|
||||
selected,
|
||||
manifestWithDependencies(manifest, prestart.dependencyFiles),
|
||||
await runtimeTarget(),
|
||||
);
|
||||
await smokeDependencies(selected.source);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
nodeRuntimeArgs,
|
||||
atLeast,
|
||||
runtimeTarget,
|
||||
targetKey,
|
||||
assertCompatible,
|
||||
inventory,
|
||||
verifyPayload,
|
||||
smokeDependencies,
|
||||
extractArchive,
|
||||
stageBundle,
|
||||
verifyStagedBundle,
|
||||
sha256,
|
||||
};
|
||||
@@ -107,7 +107,7 @@ async function selectedUpgrade(
|
||||
|
||||
export interface ReloadLifecycle {
|
||||
stop(context: LocalContext): Promise<void>;
|
||||
start(context: LocalContext): Promise<unknown>;
|
||||
start(context: LocalContext, recover?: boolean): Promise<unknown>;
|
||||
}
|
||||
|
||||
// All old entries stay on the same filesystem until service start succeeds.
|
||||
@@ -202,7 +202,7 @@ export async function replaceAndReload(
|
||||
if (item.existed) await fs.rename(item.backup, item.target);
|
||||
}
|
||||
try {
|
||||
await lifecycle.start(context);
|
||||
await lifecycle.start(context, true);
|
||||
} catch {
|
||||
throw new Error(
|
||||
translate(
|
||||
@@ -300,14 +300,31 @@ export async function reloadPanel(
|
||||
return await artifacts.withUpgradeLock(
|
||||
context.paths.dir_tmp!,
|
||||
() =>
|
||||
replaceAndReload(context, replacements, {
|
||||
stop: stopPanel,
|
||||
start: async (ctx) => {
|
||||
const service = await startPanel(ctx);
|
||||
await artifacts.waitForHealth(ctx.env, 60000, operationSignal());
|
||||
return service;
|
||||
},
|
||||
}),
|
||||
require('./panelUpgrade.cjs').withPreparedJob(
|
||||
context.paths.dir_tmp!,
|
||||
context.env,
|
||||
selected,
|
||||
(job?: {
|
||||
onStop(): Promise<void>;
|
||||
onStart(recover?: boolean): Promise<void> | undefined;
|
||||
}) =>
|
||||
replaceAndReload(context, replacements, {
|
||||
stop: async (ctx) => {
|
||||
await job?.onStop();
|
||||
await stopPanel(ctx);
|
||||
},
|
||||
start: async (ctx, recover) => {
|
||||
const service = await startPanel(ctx);
|
||||
await artifacts.waitForHealth(
|
||||
ctx.env,
|
||||
undefined,
|
||||
operationSignal(),
|
||||
);
|
||||
await job?.onStart(recover);
|
||||
return service;
|
||||
},
|
||||
}),
|
||||
),
|
||||
context.env,
|
||||
);
|
||||
} finally {
|
||||
|
||||
@@ -218,13 +218,19 @@ async function downloadWithProgress(
|
||||
'--location',
|
||||
...(quiet ? ['--silent', '--show-error'] : []),
|
||||
'--proto',
|
||||
'=https',
|
||||
/^http:\/\/(?:127\.0\.0\.1|\[::1\])(?::\d+)?\//.test(url)
|
||||
? '=http,https'
|
||||
: '=https',
|
||||
'--proto-redir',
|
||||
'=https',
|
||||
'--connect-timeout',
|
||||
'30',
|
||||
'--max-time',
|
||||
'600',
|
||||
String(
|
||||
artifact === 'qinglong-bundle' && expected?.size
|
||||
? Math.max(600, Math.min(7200, Math.ceil(expected.size / 8192) + 120))
|
||||
: 600,
|
||||
),
|
||||
'--speed-limit',
|
||||
'1024',
|
||||
'--speed-time',
|
||||
@@ -260,6 +266,26 @@ async function stageUpgrade({
|
||||
signal,
|
||||
onProgress,
|
||||
}) {
|
||||
const currentPackage = JSON.parse(
|
||||
await fs
|
||||
.readFile(path.join(root, 'package.json'), 'utf8')
|
||||
.catch((error) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
return '{}';
|
||||
}),
|
||||
);
|
||||
if (env.QL_UPGRADE_FILE || currentPackage.qinglongUpgradeFormat === 2) {
|
||||
return require('./platformBundle.cjs').stageBundle({
|
||||
root,
|
||||
tmp,
|
||||
env,
|
||||
run,
|
||||
signal,
|
||||
onProgress,
|
||||
verifyStatic: verifyUpgrade,
|
||||
download: downloadWithProgress,
|
||||
});
|
||||
}
|
||||
const report = onProgress || (async () => {});
|
||||
const workspace = await fs.mkdtemp(path.join(tmp, 'upgrade-'));
|
||||
const branch = releaseBranch(env);
|
||||
@@ -469,7 +495,12 @@ async function stageUpgrade({
|
||||
}
|
||||
}
|
||||
|
||||
async function selectedUpgrade(tmp, branch, env = process.env) {
|
||||
async function selectedUpgrade(
|
||||
tmp,
|
||||
branch,
|
||||
env = process.env,
|
||||
{ metadataOnly = false } = {},
|
||||
) {
|
||||
const pointer = JSON.parse(
|
||||
await fs.readFile(path.join(tmp, `upgrade-ready-${branch}.json`), 'utf8'),
|
||||
);
|
||||
@@ -493,9 +524,13 @@ async function selectedUpgrade(tmp, branch, env = process.env) {
|
||||
);
|
||||
if (ready.source !== selected.source || ready.static !== selected.static)
|
||||
throw new Error(upgradeMessage('暂存升级就绪记录不匹配。', env));
|
||||
const manifest = await verifyUpgrade(selected.source, selected.static, env);
|
||||
const manifest = metadataOnly
|
||||
? await manifestAt(selected.static, env)
|
||||
: await verifyUpgrade(selected.source, selected.static, env);
|
||||
if (ready.sourceCommit !== manifest.sourceCommit)
|
||||
throw new Error(upgradeMessage('暂存升级就绪记录不匹配。', env));
|
||||
if (ready.bundle && !metadataOnly)
|
||||
await require('./platformBundle.cjs').verifyStagedBundle(selected);
|
||||
if (ready.dependenciesChanged)
|
||||
await fs.access(path.join(selected.source, 'node_modules'));
|
||||
else {
|
||||
@@ -571,7 +606,7 @@ async function replaceAndReload(replacements, lifecycle, env = process.env) {
|
||||
} catch (error) {
|
||||
// Do not modify files under a still-running failed startup. Keep backups
|
||||
// for recovery if stopping the new process itself fails.
|
||||
if (attemptedStart) await lifecycle.stop();
|
||||
if (attemptedStart) await lifecycle.stop(true);
|
||||
for (const item of changed.reverse()) {
|
||||
await fs.rm(item.target, { recursive: true, force: true });
|
||||
if (item.existed) {
|
||||
@@ -640,7 +675,16 @@ async function reloadSystem({
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
async function waitForHealth(env, timeout = 60000, signal) {
|
||||
function startupHealthTimeout(runtime = process) {
|
||||
// ARMv6 starts the database, scheduler and HTTP workers sequentially. Give
|
||||
// slow devices time to become healthy before deciding to restore a backup.
|
||||
return runtime.arch === 'arm' &&
|
||||
Number(runtime.config.variables.arm_version) === 6
|
||||
? 300000
|
||||
: 60000;
|
||||
}
|
||||
|
||||
async function waitForHealth(env, timeout = startupHealthTimeout(), signal) {
|
||||
const port = Number(env.QlPort || 5700);
|
||||
let base = env.QlBaseUrl || '';
|
||||
if (base && !base.startsWith('/')) base = `/${base}`;
|
||||
@@ -786,9 +830,18 @@ esac
|
||||
mode: 0o600,
|
||||
},
|
||||
);
|
||||
// Offline selection and worker ownership belong to this operation only.
|
||||
// Passing them to PM2 would pin future online updates to the old local file.
|
||||
const lifecycleEnv = { ...env };
|
||||
for (const name of [
|
||||
'QL_UPGRADE_FILE',
|
||||
'QL_UPGRADE_REPAIR_DEPS',
|
||||
'QL_UPGRADE_LAUNCHER_PID',
|
||||
])
|
||||
delete lifecycleEnv[name];
|
||||
const hook = (operation, args = [], signal) =>
|
||||
runProcess(
|
||||
env,
|
||||
lifecycleEnv,
|
||||
'bash',
|
||||
['--', snapshot, operation, ...args],
|
||||
false,
|
||||
@@ -821,16 +874,21 @@ async function main() {
|
||||
tmp,
|
||||
() =>
|
||||
withLifecycleHooks(root, tmp, env, async (hook) => {
|
||||
let job;
|
||||
const lifecycle = {
|
||||
signal: controller.signal,
|
||||
stop: () => hook('stop'),
|
||||
stop: async () => {
|
||||
await job?.onStop();
|
||||
await hook('stop');
|
||||
},
|
||||
start: async (recover) => {
|
||||
await hook('start', [], recover ? undefined : controller.signal);
|
||||
await waitForHealth(
|
||||
env,
|
||||
60000,
|
||||
undefined,
|
||||
recover ? undefined : controller.signal,
|
||||
);
|
||||
await job?.onStart(recover);
|
||||
},
|
||||
};
|
||||
if (process.argv[2] === 'update') {
|
||||
@@ -850,15 +908,48 @@ async function main() {
|
||||
if (process.argv[4] !== 'true') return;
|
||||
} else if (process.argv[2] !== 'reload')
|
||||
throw new Error('Unknown upgrade command.');
|
||||
await reloadSystem({
|
||||
root,
|
||||
tmp,
|
||||
env,
|
||||
data: env.dir_data || path.join(root, 'data'),
|
||||
staticRoot: env.dir_static || path.join(root, 'static'),
|
||||
config: env.dir_config || path.join(root, 'data/config'),
|
||||
lifecycle,
|
||||
});
|
||||
const apply = async (preparedJob) => {
|
||||
job = preparedJob;
|
||||
await reloadSystem({
|
||||
root,
|
||||
tmp,
|
||||
env,
|
||||
data: env.dir_data || path.join(root, 'data'),
|
||||
staticRoot: env.dir_static || path.join(root, 'static'),
|
||||
config: env.dir_config || path.join(root, 'data/config'),
|
||||
lifecycle,
|
||||
});
|
||||
};
|
||||
// Legacy reloads can carry only this self-contained Bash verifier.
|
||||
// Complete-bundle installs also track manual applies without a job file.
|
||||
const hasPanelJob = await fs
|
||||
.access(path.join(tmp, 'panel-upgrade.json'))
|
||||
.then(() => true)
|
||||
.catch((error) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
return false;
|
||||
});
|
||||
const packageInfo = hasPanelJob
|
||||
? {}
|
||||
: JSON.parse(
|
||||
await fs
|
||||
.readFile(path.join(root, 'package.json'), 'utf8')
|
||||
.catch((error) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
return '{}';
|
||||
}),
|
||||
);
|
||||
if (hasPanelJob || packageInfo.qinglongUpgradeFormat === 2) {
|
||||
const selected = await selectedUpgrade(tmp, releaseBranch(env), env, {
|
||||
metadataOnly: true,
|
||||
});
|
||||
await require('./panelUpgrade.cjs').withPreparedJob(
|
||||
tmp,
|
||||
env,
|
||||
selected,
|
||||
apply,
|
||||
);
|
||||
} else await apply();
|
||||
console.log(upgradeMessage('更新及启动检查成功...', env));
|
||||
}),
|
||||
env,
|
||||
@@ -875,6 +966,7 @@ module.exports = {
|
||||
selectedUpgrade,
|
||||
replaceAndReload,
|
||||
reloadSystem,
|
||||
startupHealthTimeout,
|
||||
waitForHealth,
|
||||
runProcess,
|
||||
withLifecycleHooks,
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { spawn } = require('node:child_process');
|
||||
const crypto = require('node:crypto');
|
||||
const os = require('node:os');
|
||||
const { serverRuntimeArgs } = require('./nodeRuntime.cjs');
|
||||
|
||||
function probeLimits(target) {
|
||||
const small = target.arch === 'armv6';
|
||||
return { heapMb: small ? 128 : 192, timeoutMs: small ? 300000 : 60000 };
|
||||
}
|
||||
|
||||
function dependencyFailure(error) {
|
||||
const text = `${error.message || ''}\n${error.stack || ''}\n${
|
||||
error.stderr || ''
|
||||
}`;
|
||||
if (error.signal || /timed out|heap out of memory|ENOMEM/i.test(text))
|
||||
return false;
|
||||
if (
|
||||
/ERR_DLOPEN_FAILED/.test(`${error.code} ${text}`) &&
|
||||
/node_modules[/\\]/.test(text)
|
||||
)
|
||||
return true;
|
||||
const missing = /Cannot find (?:module|package) ['"]([^'"]+)['"]/.exec(
|
||||
text,
|
||||
)?.[1];
|
||||
const importer = /Require stack:\r?\n-\s+([^\r\n]+)/.exec(text)?.[1];
|
||||
const inDependencies = (filename) =>
|
||||
/(?:^|[/\\])node_modules[/\\]/.test(filename || '');
|
||||
// Node reports a missing package entry as an absolute path and missing
|
||||
// package-internal imports as relative paths. Neither is an app source error.
|
||||
const dependencyMissing =
|
||||
missing &&
|
||||
((!missing.startsWith('.') &&
|
||||
!path.isAbsolute(missing) &&
|
||||
!missing.startsWith('node:')) ||
|
||||
inDependencies(missing) ||
|
||||
inDependencies(importer));
|
||||
// Missing backend files, bad config and database errors must never trigger npm.
|
||||
return (
|
||||
(/MODULE_NOT_FOUND/.test(`${error.code} ${text}`) &&
|
||||
Boolean(dependencyMissing)) ||
|
||||
(/Could not locate the bindings file/.test(text) &&
|
||||
/node_modules[/\\]/.test(text))
|
||||
);
|
||||
}
|
||||
|
||||
// Once the group has received its final signal, its numeric ID can be reused.
|
||||
function childGroupSignaler(child) {
|
||||
let finished = false;
|
||||
return (signal) => {
|
||||
if (finished) return;
|
||||
try {
|
||||
if (process.platform !== 'win32' && child.pid) process.kill(-child.pid, signal);
|
||||
else child.kill(signal);
|
||||
if (signal === 'SIGKILL') finished = true;
|
||||
} catch (error) {
|
||||
if (error.code !== 'ESRCH') throw error;
|
||||
finished = true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function prestartBackend(
|
||||
selected,
|
||||
{ target, signal, limits = probeLimits(target) },
|
||||
) {
|
||||
signal?.throwIfAborted();
|
||||
const workspace = await fs.mkdtemp(
|
||||
path.join(path.dirname(selected.source), 'prestart-'),
|
||||
);
|
||||
try {
|
||||
const data = path.join(workspace, 'data');
|
||||
for (const name of ['db', 'config', 'syslog', 'log', 'scripts', 'upload'])
|
||||
await fs.mkdir(path.join(data, name), { recursive: true });
|
||||
// Copy only backend code/metadata, never all frontend assets or node_modules.
|
||||
await fs.mkdir(path.join(workspace, 'static'));
|
||||
await fs.cp(
|
||||
path.join(selected.static, 'build'),
|
||||
path.join(workspace, 'static/build'),
|
||||
{ recursive: true },
|
||||
);
|
||||
await fs.copyFile(
|
||||
path.join(selected.static, 'build-info.json'),
|
||||
path.join(workspace, 'static/build-info.json'),
|
||||
);
|
||||
await fs.copyFile(
|
||||
path.join(selected.source, 'version.yaml'),
|
||||
path.join(workspace, 'version.yaml'),
|
||||
);
|
||||
await fs.symlink(
|
||||
path.join(selected.source, 'node_modules'),
|
||||
path.join(workspace, 'node_modules'),
|
||||
'dir',
|
||||
);
|
||||
await fs.writeFile(path.join(workspace, '.env'), '', { mode: 0o600 });
|
||||
const entry = path.join(
|
||||
workspace,
|
||||
'static/build/bootstrap/upgradeProbe.js',
|
||||
);
|
||||
await fs.access(entry);
|
||||
const expected = JSON.parse(
|
||||
await fs.readFile(path.join(selected.static, 'build-info.json')),
|
||||
);
|
||||
const backendSha256 = crypto
|
||||
.createHash('sha256')
|
||||
.update(await fs.readFile(path.join(selected.static, 'build/app.js')))
|
||||
.digest('hex');
|
||||
const version = (
|
||||
await fs.readFile(path.join(selected.source, 'version.yaml'), 'utf8')
|
||||
).match(
|
||||
/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)/m,
|
||||
)?.[1];
|
||||
// An allowlist prevents NODE_OPTIONS, startup hooks, real data paths and
|
||||
// package-manager settings from escaping into the disposable backend.
|
||||
const env = {
|
||||
PATH: process.env.PATH,
|
||||
LANG: process.env.LANG || 'C.UTF-8',
|
||||
HOME: workspace,
|
||||
TMPDIR: workspace,
|
||||
NODE_ENV: 'production',
|
||||
QL_DIR: workspace,
|
||||
QL_DATA_DIR: data,
|
||||
QL_UPGRADE_PROBE: '1',
|
||||
BACK_PORT: '0',
|
||||
GRPC_PORT: '0',
|
||||
BIND_HOST: '127.0.0.1',
|
||||
BIND_HOST_GRPC: '127.0.0.1',
|
||||
QlBaseUrl: '/',
|
||||
NODE_PATH: '',
|
||||
NODE_OPTIONS: '',
|
||||
UV_THREADPOOL_SIZE: '1',
|
||||
};
|
||||
return await new Promise((resolve, reject) => {
|
||||
let report,
|
||||
failure,
|
||||
output = '',
|
||||
finished = false,
|
||||
killTimer;
|
||||
// No PM2/cluster workers. OpenSSL key generation is sequential in this
|
||||
// one backend process. Keep normal V8 mode for Node 20's HTTP/WASM support.
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[...serverRuntimeArgs(), `--max-old-space-size=${limits.heapMb}`, entry],
|
||||
{
|
||||
cwd: workspace,
|
||||
env,
|
||||
detached: process.platform !== 'win32',
|
||||
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
|
||||
},
|
||||
);
|
||||
try {
|
||||
if (child.pid) os.setPriority(child.pid, 10);
|
||||
} catch {}
|
||||
const signalGroup = childGroupSignaler(child);
|
||||
const kill = (signalName) => {
|
||||
try { signalGroup(signalName); } catch (error) { failure ||= error; }
|
||||
};
|
||||
const stop = (error) => {
|
||||
failure ||= error;
|
||||
kill('SIGTERM');
|
||||
killTimer ||= setTimeout(() => kill('SIGKILL'), 1500);
|
||||
};
|
||||
const abort = () =>
|
||||
stop(signal.reason || new Error('Upgrade prestart aborted'));
|
||||
const timer = setTimeout(
|
||||
() => stop(new Error('Upgrade prestart timed out')),
|
||||
limits.timeoutMs,
|
||||
);
|
||||
child.stdout.on('data', (chunk) => {
|
||||
output = (output + chunk).slice(-32768);
|
||||
});
|
||||
child.stderr.on('data', (chunk) => {
|
||||
output = (output + chunk).slice(-32768);
|
||||
});
|
||||
child.on('message', (message) => {
|
||||
if (message?.type === 'upgrade-probe') report = message;
|
||||
});
|
||||
const finish = (error) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(timer);
|
||||
clearTimeout(killTimer);
|
||||
signal?.removeEventListener('abort', abort);
|
||||
if (error) reject(error);
|
||||
else resolve(report);
|
||||
};
|
||||
child.on('error', (error) => finish(error));
|
||||
// Descendants can retain our output pipes after their parent exits.
|
||||
// Reap the group on exit rather than waiting for those pipes to close.
|
||||
child.once('exit', () => kill('SIGKILL'));
|
||||
child.on('close', (code, exitSignal) => {
|
||||
if (failure) return finish(failure);
|
||||
if (code !== 0 || !report?.ok)
|
||||
return finish(
|
||||
Object.assign(
|
||||
new Error(
|
||||
report?.message ||
|
||||
`Upgrade prestart exited: ${exitSignal || code}\n${output}`,
|
||||
),
|
||||
{
|
||||
code: report?.code,
|
||||
stack: report?.stack || output,
|
||||
signal: exitSignal,
|
||||
},
|
||||
),
|
||||
);
|
||||
if (
|
||||
report.build?.sourceCommit !== expected.sourceCommit ||
|
||||
report.build?.backendSha256 !== backendSha256 ||
|
||||
report.build?.version !== version
|
||||
)
|
||||
return finish(new Error('Upgrade prestart build identity mismatch'));
|
||||
finish();
|
||||
});
|
||||
signal?.addEventListener('abort', abort, { once: true });
|
||||
if (signal?.aborted) abort();
|
||||
});
|
||||
} finally {
|
||||
await fs.rm(workspace, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function repairDependencies(source, { target, signal, env }) {
|
||||
const workspace = await fs.mkdtemp(
|
||||
path.join(path.dirname(source), 'repair-'),
|
||||
);
|
||||
try {
|
||||
const pkg = JSON.parse(
|
||||
await fs.readFile(path.join(source, 'package.json')),
|
||||
);
|
||||
if (pkg.packageManager !== 'pnpm@8.3.1')
|
||||
throw new Error('Unsupported frozen-lockfile package manager');
|
||||
// Install apart from the verified application: lifecycle scripts cannot
|
||||
// rewrite source/static files or use the old installation's node_modules.
|
||||
await fs.writeFile(
|
||||
path.join(workspace, 'package.json'),
|
||||
JSON.stringify({ ...pkg, scripts: {} }),
|
||||
);
|
||||
await fs.copyFile(
|
||||
path.join(source, 'pnpm-lock.yaml'),
|
||||
path.join(workspace, 'pnpm-lock.yaml'),
|
||||
);
|
||||
const small = target.arch === 'armv6';
|
||||
const childEnv = {
|
||||
PATH: env.PATH || process.env.PATH,
|
||||
HOME: workspace,
|
||||
TMPDIR: workspace,
|
||||
NODE_OPTIONS: `${small ? '--jitless ' : ''}--max-old-space-size=${
|
||||
small ? 256 : 384
|
||||
}`,
|
||||
NODE_PATH: '',
|
||||
CI: 'true',
|
||||
npm_config_jobs: '1',
|
||||
MAKEFLAGS: '-j1',
|
||||
...(small
|
||||
? {
|
||||
npm_config_build_from_source: 'true',
|
||||
npm_config_force_process_config: 'true',
|
||||
CFLAGS: '-march=armv6 -mfpu=vfp -mfloat-abi=hard',
|
||||
CXXFLAGS: '-march=armv6 -mfpu=vfp -mfloat-abi=hard',
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
// Preserve network routing without inheriting Node/preload/compiler settings.
|
||||
for (const name of [
|
||||
'HTTP_PROXY',
|
||||
'HTTPS_PROXY',
|
||||
'ALL_PROXY',
|
||||
'NO_PROXY',
|
||||
'http_proxy',
|
||||
'https_proxy',
|
||||
'all_proxy',
|
||||
'no_proxy',
|
||||
])
|
||||
if (typeof env[name] === 'string') childEnv[name] = env[name];
|
||||
// Reuse matching installed headers on small devices; never inherit a
|
||||
// caller's nodedir or accidentally compile against a different Node ABI.
|
||||
const prefix = path.resolve(path.dirname(process.execPath), '..');
|
||||
const header = await fs
|
||||
.readFile(path.join(prefix, 'include/node/node_version.h'), 'utf8')
|
||||
.catch(() => '');
|
||||
const headerVersion = ['MAJOR', 'MINOR', 'PATCH']
|
||||
.map(
|
||||
(part) =>
|
||||
header.match(
|
||||
new RegExp(`#define\\s+NODE_${part}_VERSION\\s+(\\d+)`),
|
||||
)?.[1],
|
||||
)
|
||||
.join('.');
|
||||
if (headerVersion === process.versions.node) {
|
||||
childEnv.npm_config_nodedir = prefix;
|
||||
childEnv.npm_config_force_process_config = 'true';
|
||||
}
|
||||
const run = (args) =>
|
||||
runRepair('pnpm', args, {
|
||||
cwd: workspace,
|
||||
env: childEnv,
|
||||
signal,
|
||||
timeoutMs: small ? 1800000 : 600000,
|
||||
});
|
||||
const version = await run(['--version']);
|
||||
if (version.trim() !== '8.3.1')
|
||||
throw new Error('Dependency repair requires existing pnpm 8.3.1');
|
||||
await run([
|
||||
'install',
|
||||
'--prod',
|
||||
'--frozen-lockfile',
|
||||
'--ignore-scripts',
|
||||
'--child-concurrency=1',
|
||||
'--network-concurrency=2',
|
||||
]);
|
||||
await run(['rebuild', 'sqlite3', '@whyour/sqlite3']);
|
||||
if (
|
||||
!(await fs.readFile(path.join(source, 'pnpm-lock.yaml'))).equals(
|
||||
await fs.readFile(path.join(workspace, 'pnpm-lock.yaml')),
|
||||
)
|
||||
)
|
||||
throw new Error('Dependency repair changed the frozen lockfile');
|
||||
await fs.rm(path.join(source, 'node_modules'), {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
await fs.rename(
|
||||
path.join(workspace, 'node_modules'),
|
||||
path.join(source, 'node_modules'),
|
||||
);
|
||||
} finally {
|
||||
await fs.rm(workspace, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
// Bound output, wall time and the entire npm/node-gyp process group.
|
||||
async function runRepair(program, args, options) {
|
||||
return new Promise((resolve, reject) => {
|
||||
options.signal?.throwIfAborted();
|
||||
let output = '',
|
||||
stdout = '',
|
||||
failure,
|
||||
killTimer;
|
||||
const child = spawn(program, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
detached: process.platform !== 'win32',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
const signalGroup = childGroupSignaler(child);
|
||||
const kill = (sig) => {
|
||||
try { signalGroup(sig); } catch {}
|
||||
};
|
||||
const stop = (error) => {
|
||||
failure ||= error;
|
||||
kill('SIGTERM');
|
||||
killTimer ||= setTimeout(() => kill('SIGKILL'), 1500);
|
||||
};
|
||||
const abort = () =>
|
||||
stop(options.signal.reason || new Error('Dependency repair aborted'));
|
||||
const timer = setTimeout(
|
||||
() => stop(new Error('Dependency repair timed out')),
|
||||
options.timeoutMs,
|
||||
);
|
||||
const capture = (chunk) => {
|
||||
output = (output + chunk).slice(-32768);
|
||||
};
|
||||
child.stdout.on('data', (chunk) => {
|
||||
stdout = (stdout + chunk).slice(-32768);
|
||||
capture(chunk);
|
||||
});
|
||||
child.stderr.on('data', capture);
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
clearTimeout(killTimer);
|
||||
options.signal?.removeEventListener('abort', abort);
|
||||
};
|
||||
child.on('error', (error) => {
|
||||
kill('SIGKILL');
|
||||
cleanup();
|
||||
reject(error);
|
||||
});
|
||||
child.once('exit', () => kill('SIGKILL'));
|
||||
child.on('close', (code, signal) => {
|
||||
cleanup();
|
||||
if (failure || code !== 0)
|
||||
reject(
|
||||
failure ||
|
||||
new Error(
|
||||
`Dependency repair failed (${signal || code}): ${output}`,
|
||||
),
|
||||
);
|
||||
else resolve(stdout);
|
||||
});
|
||||
options.signal?.addEventListener('abort', abort, { once: true });
|
||||
if (options.signal?.aborted) abort();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
prestartBackend,
|
||||
dependencyFailure,
|
||||
repairDependencies,
|
||||
probeLimits,
|
||||
};
|
||||
@@ -7,6 +7,12 @@ import { fail } from '../../shared/errors';
|
||||
import { isRecord } from '../../shared/record';
|
||||
import { operationSignal, requestCancellation } from './cancellation';
|
||||
|
||||
export class ReceiptValidationError extends Error {
|
||||
constructor(readonly field: string) {
|
||||
super('The running panel rejected the lifecycle field ' + field);
|
||||
}
|
||||
}
|
||||
|
||||
export class LocalApi {
|
||||
private token?: string;
|
||||
constructor(private readonly context: LocalContext) {}
|
||||
@@ -65,50 +71,71 @@ export class LocalApi {
|
||||
endpoint: string,
|
||||
method = 'GET',
|
||||
body?: unknown,
|
||||
finishedAt?: number,
|
||||
): Promise<Record<string, unknown>> {
|
||||
operationSignal()?.throwIfAborted();
|
||||
const token = await this.credential();
|
||||
const port = this.context.env.QlPort || '5700';
|
||||
if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535)
|
||||
fail(translate(this.context.env, '本机面板端口无效。'), 2);
|
||||
const request = requestCancellation(30000);
|
||||
const retryReceipt = isRecord(body) && !!(body.execution_id || body.trigger_id) &&
|
||||
((method === 'PUT' && endpoint === 'crons/status') ||
|
||||
(method === 'POST' && endpoint === 'dashboard/record'));
|
||||
const payload = body === undefined ? undefined : JSON.stringify(body);
|
||||
let result: unknown;
|
||||
try {
|
||||
const response = await fetch(
|
||||
`http://127.0.0.1:${port}/open/${endpoint}`,
|
||||
{
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(body !== undefined
|
||||
? { 'Content-Type': 'application/json' }
|
||||
: {}),
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const request = requestCancellation(30000);
|
||||
try {
|
||||
const response = await fetch(
|
||||
`http://127.0.0.1:${port}/open/${endpoint}`,
|
||||
{
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(finishedAt !== undefined && { 'X-QL-Finished-At': String(finishedAt) }),
|
||||
...(body !== undefined
|
||||
? { 'Content-Type': 'application/json' }
|
||||
: {}),
|
||||
},
|
||||
body: payload,
|
||||
redirect: 'error',
|
||||
signal: request.signal,
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
redirect: 'error',
|
||||
signal: request.signal,
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
);
|
||||
if (!response.ok) {
|
||||
if (attempt === 0 && method === 'PUT' && endpoint === 'crons/status' && response.status === 400) {
|
||||
const rejection: unknown = await response.json();
|
||||
const validation = isRecord(rejection) && rejection.validation;
|
||||
const detail = isRecord(validation) && validation.body;
|
||||
if (isRecord(detail) && detail.source === 'body' && Array.isArray(detail.keys) &&
|
||||
detail.keys.length === 1 && ['trigger_id', 'execution_id', 'exit_code'].includes(detail.keys[0])) {
|
||||
throw new ReceiptValidationError(detail.keys[0]);
|
||||
}
|
||||
} else {
|
||||
await response.body?.cancel();
|
||||
}
|
||||
fail(
|
||||
translate(
|
||||
this.context.env,
|
||||
'本机 API 拒绝请求(HTTP %s)。',
|
||||
response.status,
|
||||
),
|
||||
);
|
||||
}
|
||||
result = await response.json();
|
||||
break;
|
||||
} catch (error) {
|
||||
if (error instanceof ReceiptValidationError) throw error;
|
||||
if (attempt === 0 && retryReceipt && request.signal.aborted && !operationSignal()?.aborted) continue;
|
||||
fail(
|
||||
translate(
|
||||
this.context.env,
|
||||
'本机 API 拒绝请求(HTTP %s)。',
|
||||
response.status,
|
||||
'本机 API 请求失败;请先检查操作结果,不要直接重试写入。',
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
request.dispose();
|
||||
}
|
||||
result = await response.json();
|
||||
} catch {
|
||||
fail(
|
||||
translate(
|
||||
this.context.env,
|
||||
'本机 API 请求失败;请先检查操作结果,不要直接重试写入。',
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
request.dispose();
|
||||
}
|
||||
if (!isRecord(result) || result.code !== 200)
|
||||
fail(
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
const { armv6ServerArgs } = require('../maintenance/nodeRuntime.cjs') as {
|
||||
armv6ServerArgs: readonly string[];
|
||||
};
|
||||
|
||||
// Linux preserves argv boundaries in cmdline. Resolve relative entrypoints from
|
||||
// each process's cwd, not from the operator's cwd or a broad ps substring match.
|
||||
@@ -27,11 +30,18 @@ export async function findDirectBackendPids(
|
||||
);
|
||||
const args = command.split('\0');
|
||||
if (args.at(-1) === '') args.pop();
|
||||
// Both the legacy fallback and the TS fallback launch one script without
|
||||
// Node flags or application arguments. Reject other command shapes.
|
||||
if (args.length !== 2 || !/^node(?:\d+)?$/.test(path.basename(args[0]!)))
|
||||
// Accept only the two launch shapes we own. Never treat eval, preload or
|
||||
// application arguments containing this path as a running backend.
|
||||
const scriptIndex =
|
||||
args.length === 2
|
||||
? 1
|
||||
: args.length === armv6ServerArgs.length + 2 &&
|
||||
armv6ServerArgs.every((flag, i) => args[i + 1] === flag)
|
||||
? args.length - 1
|
||||
: -1;
|
||||
if (scriptIndex < 0 || !/^node(?:\d+)?$/.test(path.basename(args[0]!)))
|
||||
continue;
|
||||
const script = args[1]!;
|
||||
const script = args[scriptIndex]!;
|
||||
if (!script) continue;
|
||||
const absolute = path.isAbsolute(script)
|
||||
? script
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { translate } from '../../shared/i18n/index';
|
||||
import { extendedLifecycle } from './lifecycle';
|
||||
import { LifecycleReceipt } from './lifecycle';
|
||||
import { within } from './files';
|
||||
import fs from 'node:fs/promises';
|
||||
import { writeSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { LocalContext } from './context';
|
||||
import { LocalApi } from './api';
|
||||
import { CliError } from '../../shared/errors';
|
||||
import { withOperationOutput } from './output';
|
||||
import { cancellableOperation, interruptedCode } from './cancellation';
|
||||
@@ -32,7 +30,9 @@ export async function loggedOperation<T>(
|
||||
]
|
||||
.map((value) => String(value).padStart(2, '0'))
|
||||
.join('-');
|
||||
const logPath = context.env.real_log_path || `${action}/${stamp}.log`;
|
||||
const receipt = new LifecycleReceipt(context, started);
|
||||
const triggerId = receipt.triggerId;
|
||||
const logPath = context.env.real_log_path || `${action}/${stamp}${triggerId ? '-' + triggerId : ''}.log`;
|
||||
const file = within(context.paths.dir_log!, logPath, context.env);
|
||||
const persist = context.env.real_time !== 'true';
|
||||
if (persist) await fs.mkdir(path.dirname(file), { recursive: true });
|
||||
@@ -45,25 +45,17 @@ export async function loggedOperation<T>(
|
||||
process.stderr.write(chunk);
|
||||
};
|
||||
const id = Number(context.env.ID);
|
||||
const extended = await extendedLifecycle(context);
|
||||
const executionId =
|
||||
extended && context.env.QL_EXECUTION_ORIGIN === 'scheduled_system'
|
||||
? `legacy-system:${started}:${randomUUID()}`
|
||||
: undefined;
|
||||
const api = new LocalApi(context);
|
||||
const report = async (final: boolean, code: number) => {
|
||||
if (!Number.isSafeInteger(id) || id <= 0) return;
|
||||
try {
|
||||
await api.call('crons/status', 'PUT', {
|
||||
await receipt.status({
|
||||
ids: [id],
|
||||
status: final ? '1' : '0',
|
||||
pid: String(process.pid),
|
||||
log_path: logPath,
|
||||
last_execution_time: started,
|
||||
last_running_time: final ? Math.floor((Date.now() - start) / 1000) : 0,
|
||||
...(final && extended ? { exit_code: code } : {}),
|
||||
...(executionId ? { execution_id: executionId } : {}),
|
||||
});
|
||||
}, final ? code : undefined);
|
||||
} catch {
|
||||
output(
|
||||
Buffer.from(
|
||||
|
||||
@@ -1,51 +1,63 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { LocalContext } from './context';
|
||||
import { LocalApi, ReceiptValidationError } from './api';
|
||||
|
||||
// The released 2.20 API rejects unknown lifecycle fields and has no dashboard record API.
|
||||
// Read the installed panel version, never the independently versioned CLI package.
|
||||
export async function extendedLifecycle(
|
||||
context: LocalContext,
|
||||
): Promise<boolean> {
|
||||
if (context.env.QL_CLI_LIFECYCLE === 'legacy') return false;
|
||||
if (context.env.QL_CLI_LIFECYCLE === 'extended') return true;
|
||||
let version: string | undefined;
|
||||
try {
|
||||
const manifest: unknown = JSON.parse(
|
||||
await fs.readFile(path.join(context.root, 'package.json'), 'utf8'),
|
||||
);
|
||||
if (
|
||||
manifest &&
|
||||
typeof manifest === 'object' &&
|
||||
'version' in manifest &&
|
||||
typeof manifest.version === 'string'
|
||||
)
|
||||
version = manifest.version;
|
||||
} catch {}
|
||||
if (version === undefined) {
|
||||
try {
|
||||
// Official 2.x images may omit package.version. Read only the top-level
|
||||
// scalar release field; no YAML dependency or expression evaluation.
|
||||
const release = await fs.readFile(
|
||||
path.join(context.root, 'version.yaml'),
|
||||
'utf8',
|
||||
);
|
||||
const entries = release
|
||||
.replace(/^\uFEFF/, '')
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => /^version:/.test(line));
|
||||
if (entries.length !== 1) return false;
|
||||
const scalar =
|
||||
/^version:[ \t]*(?:"([^"]+)"|'([^']+)'|([^\s#]+))[ \t]*(?:#.*)?$/.exec(
|
||||
entries[0]!,
|
||||
);
|
||||
version = scalar?.[1] ?? scalar?.[2] ?? scalar?.[3];
|
||||
} catch {
|
||||
return false;
|
||||
// Negotiate with the worker that validates the real receipt. Keep the agreed
|
||||
// wire format for this execution, even if the panel changes before it exits.
|
||||
export class LifecycleReceipt {
|
||||
private readonly api: LocalApi;
|
||||
private identity?: { trigger_id: string } | { execution_id: string };
|
||||
private extended: boolean;
|
||||
private startAttempted = false;
|
||||
private acceptedStart = false;
|
||||
private finishedAt?: number;
|
||||
readonly triggerId?: string;
|
||||
|
||||
constructor(context: LocalContext, started: number) {
|
||||
this.api = new LocalApi(context);
|
||||
this.extended = context.env.QL_CLI_LIFECYCLE !== 'legacy';
|
||||
const parent = context.env.QL_TRIGGER_ID;
|
||||
if (!this.extended) return;
|
||||
if (parent && /^[a-z0-9-]{1,120}$/.test(parent)) {
|
||||
this.triggerId = parent;
|
||||
this.identity = { trigger_id: parent };
|
||||
} else {
|
||||
const prefix = context.env.QL_EXECUTION_ORIGIN === 'scheduled_system'
|
||||
? `legacy-system:${started}:` : 'client-';
|
||||
this.identity = { execution_id: prefix + randomUUID() };
|
||||
}
|
||||
}
|
||||
const match = /^2\.(\d+)\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(
|
||||
version ?? '',
|
||||
);
|
||||
return !!match && Number(match[1]) >= 21;
|
||||
|
||||
get executionId() {
|
||||
return this.identity && 'execution_id' in this.identity ? this.identity.execution_id : undefined;
|
||||
}
|
||||
|
||||
async status(body: Record<string, unknown>, exitCode?: number) {
|
||||
const starting = exitCode === undefined;
|
||||
const firstStart = starting && !this.startAttempted;
|
||||
if (starting) this.startAttempted = true;
|
||||
if (!starting && this.identity) this.finishedAt ??= Date.now();
|
||||
try {
|
||||
await this.api.call('crons/status', 'PUT', {
|
||||
...body, ...this.identity, ...(!starting && this.extended && { exit_code: exitCode }),
|
||||
}, starting ? undefined : this.finishedAt);
|
||||
} catch (error) {
|
||||
if (!(error instanceof ReceiptValidationError)) throw error;
|
||||
if (firstStart && this.identity && error.field in this.identity) {
|
||||
// The old schema rejected this start before its handler could write.
|
||||
this.identity = undefined;
|
||||
} else if (!starting && !this.identity && this.extended && error.field === 'exit_code') {
|
||||
this.extended = false;
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
await this.api.call('crons/status', 'PUT', body);
|
||||
}
|
||||
if (starting) this.acceptedStart = true;
|
||||
}
|
||||
|
||||
async statistics(refId: number, code: number, elapsed: number) {
|
||||
if (this.extended && (this.identity || this.acceptedStart))
|
||||
await this.api.call('dashboard/record', 'POST', { ref_id: refId, code, elapsed, ...this.identity }, this.finishedAt);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +199,8 @@ async function reconcile(
|
||||
await api.call(
|
||||
'crons',
|
||||
'DELETE',
|
||||
obsolete.map((row) => row.id),
|
||||
obsolete.map((row) => ({ id: row.id, command: row.command, script: taskPath(row.command), sub_id: row.sub_id ?? null,
|
||||
...(typeof row.recovery_from === 'number' && { revision: row.recovery_from }) })),
|
||||
);
|
||||
for (const row of obsolete) {
|
||||
await fs.rm(
|
||||
@@ -236,6 +237,22 @@ async function reconcile(
|
||||
return { added, removed };
|
||||
}
|
||||
|
||||
// Branches can contain slashes. Reject a linked namespace component before
|
||||
// reading an old checkout or moving the staged tree into place.
|
||||
async function checkNamespace(root: string, name: string, env: NodeJS.ProcessEnv) {
|
||||
let current = root;
|
||||
for (const part of name.split('/')) {
|
||||
current = path.join(current, part);
|
||||
try {
|
||||
if ((await fs.lstat(current)).isSymbolicLink())
|
||||
fail(translate(env, '路径必须位于其管理目录内部。'), 2);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncRepository(
|
||||
context: LocalContext,
|
||||
input: SubscriptionInput,
|
||||
@@ -243,6 +260,9 @@ export async function syncRepository(
|
||||
const name = repositoryName(input.url, input.branch, context.env);
|
||||
const destination = within(context.paths.dir_scripts!, name, context.env);
|
||||
const repoDestination = within(context.paths.dir_repo!, name, context.env);
|
||||
const checkPaths = () => Promise.all([context.paths.dir_scripts!, context.paths.dir_repo!]
|
||||
.map(root => checkNamespace(root, name, context.env)));
|
||||
await checkPaths();
|
||||
const extensions = (
|
||||
input.extensions ||
|
||||
context.env.RepoFileExtensions ||
|
||||
@@ -325,6 +345,7 @@ export async function syncRepository(
|
||||
path.join(checkout, file),
|
||||
within(scripts, file, context.env),
|
||||
);
|
||||
await checkPaths();
|
||||
await replaceDirectory(scripts, destination);
|
||||
await replaceDirectory(checkout, repoDestination);
|
||||
const relativePaths = selected.map((file) =>
|
||||
|
||||
@@ -5,6 +5,7 @@ export interface OpenOperation {
|
||||
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
path: string;
|
||||
params?: string[];
|
||||
uuidParams?: string[];
|
||||
body?: 'ids' | 'json' | 'object-id';
|
||||
upload?: string;
|
||||
download?: boolean;
|
||||
@@ -58,6 +59,7 @@ export const openOperations: readonly OpenOperation[] = [
|
||||
},
|
||||
{ name: 'task list', method: 'GET', path: 'crons', existing: true },
|
||||
{ name: 'task detail', method: 'GET', path: 'crons/detail' },
|
||||
{ name: 'task preview', method: 'GET', path: 'crons/preview' },
|
||||
{ name: 'task create', method: 'POST', path: 'crons', body: 'json' },
|
||||
{
|
||||
name: 'task run',
|
||||
@@ -113,6 +115,13 @@ export const openOperations: readonly OpenOperation[] = [
|
||||
existing: true,
|
||||
},
|
||||
{ name: 'task status', method: 'PUT', path: 'crons/status', body: 'json' },
|
||||
{ name: 'task daily-results', method: 'GET', path: 'crons/:id/daily-results', params: ['id'] },
|
||||
{
|
||||
name: 'task triggers',
|
||||
method: 'GET',
|
||||
path: 'crons/:id/triggers',
|
||||
params: ['id'],
|
||||
},
|
||||
{
|
||||
name: 'task instances',
|
||||
method: 'GET',
|
||||
@@ -281,6 +290,8 @@ export const openOperations: readonly OpenOperation[] = [
|
||||
{ name: 'config save', method: 'POST', path: 'configs/save', body: 'json' },
|
||||
{ name: 'script list', method: 'GET', path: 'scripts' },
|
||||
{ name: 'script get', method: 'GET', path: 'scripts/detail' },
|
||||
{ name: 'script entries', method: 'GET', path: 'scripts/entries' },
|
||||
{ name: 'script entries-check', method: 'POST', path: 'scripts/entries/check', body: 'json' },
|
||||
{ name: 'script history-list', method: 'GET', path: 'scripts/history' },
|
||||
{
|
||||
name: 'script history-detail',
|
||||
@@ -325,6 +336,8 @@ export const openOperations: readonly OpenOperation[] = [
|
||||
},
|
||||
{ name: 'log list', method: 'GET', path: 'logs' },
|
||||
{ name: 'log get', method: 'GET', path: 'logs/detail' },
|
||||
{ name: 'log entries', method: 'GET', path: 'logs/entries' },
|
||||
{ name: 'log entries-check', method: 'POST', path: 'logs/entries/check', body: 'json' },
|
||||
{ name: 'log delete', method: 'DELETE', path: 'logs', body: 'json' },
|
||||
{
|
||||
name: 'log download',
|
||||
@@ -334,6 +347,24 @@ export const openOperations: readonly OpenOperation[] = [
|
||||
download: true,
|
||||
},
|
||||
{ name: 'dependency list', method: 'GET', path: 'dependencies' },
|
||||
{
|
||||
name: 'dependency refresh',
|
||||
method: 'POST',
|
||||
path: 'dependencies/refresh',
|
||||
body: 'json',
|
||||
},
|
||||
{
|
||||
name: 'dependency refresh-active',
|
||||
method: 'GET',
|
||||
path: 'dependencies/refresh/active',
|
||||
},
|
||||
{
|
||||
name: 'dependency refresh-status',
|
||||
method: 'GET',
|
||||
path: 'dependencies/refresh/:id',
|
||||
params: ['id'],
|
||||
uuidParams: ['id'],
|
||||
},
|
||||
{
|
||||
name: 'dependency create',
|
||||
method: 'POST',
|
||||
@@ -589,13 +620,6 @@ export const openOperations: readonly OpenOperation[] = [
|
||||
body: 'json',
|
||||
anonymous: true,
|
||||
},
|
||||
{
|
||||
name: 'user notification-init',
|
||||
method: 'PUT',
|
||||
path: 'user/notification/init',
|
||||
body: 'json',
|
||||
anonymous: true,
|
||||
},
|
||||
{
|
||||
name: 'user avatar',
|
||||
method: 'PUT',
|
||||
|
||||
@@ -17,20 +17,28 @@ export function configPath(): string {
|
||||
export function readConfig(): StoredConfig {
|
||||
let fd: number | undefined;
|
||||
try {
|
||||
fd = fs.openSync(
|
||||
configPath(),
|
||||
fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW,
|
||||
);
|
||||
const file = configPath();
|
||||
const pathStat = fs.lstatSync(file);
|
||||
if (!pathStat.isFile())
|
||||
fail(
|
||||
translate(
|
||||
process.env,
|
||||
'CLI 配置必须是普通文件,且不能是符号链接。',
|
||||
),
|
||||
);
|
||||
// Not every platform or filesystem implements POSIX mode bits or O_NOFOLLOW.
|
||||
const noFollow = fs.constants.O_NOFOLLOW ?? 0;
|
||||
fd = fs.openSync(file, fs.constants.O_RDONLY | noFollow);
|
||||
const stat = fs.fstatSync(fd);
|
||||
if (
|
||||
!stat.isFile() ||
|
||||
stat.mode & 0o077 ||
|
||||
(process.getuid && stat.uid !== process.getuid())
|
||||
pathStat.dev !== stat.dev ||
|
||||
pathStat.ino !== stat.ino
|
||||
) {
|
||||
fail(
|
||||
translate(
|
||||
process.env,
|
||||
'CLI 配置必须是当前用户拥有的私有普通文件(0600)。',
|
||||
'CLI 配置必须是普通文件,且不能是符号链接。',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -107,6 +107,14 @@ export async function auth(
|
||||
{
|
||||
crons: 'crons?page=1&size=1',
|
||||
configs: 'configs/files',
|
||||
'envs:read': 'envs',
|
||||
'configs:read': 'configs/files',
|
||||
'scripts:read': 'scripts',
|
||||
'crons:read': 'crons?page=1&size=1',
|
||||
'subscriptions:read': 'subscriptions',
|
||||
'dependencies:read': 'dependencies',
|
||||
'logs:read': 'logs',
|
||||
'dashboard:read': 'dashboard/overview',
|
||||
dashboard: 'dashboard/overview',
|
||||
} as Record<string, string>
|
||||
)[scope] ?? scope,
|
||||
|
||||
@@ -49,12 +49,19 @@ async function input(value: string | boolean | undefined): Promise<unknown> {
|
||||
}
|
||||
}
|
||||
|
||||
const UUID_PATTERN =
|
||||
'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
|
||||
|
||||
function route(method: string, path: string): OpenOperation {
|
||||
const match = openOperations.find(
|
||||
(op) =>
|
||||
op.method === method &&
|
||||
new RegExp(
|
||||
'^' + op.path.replace(/:[A-Za-z]+/g, '[1-9][0-9]*') + '$',
|
||||
'^' +
|
||||
op.path.replace(/:([A-Za-z]+)/g, (_match, name) =>
|
||||
op.uuidParams?.includes(name) ? UUID_PATTERN : '[1-9][0-9]*',
|
||||
) +
|
||||
'$',
|
||||
).test(path),
|
||||
);
|
||||
if (!match)
|
||||
@@ -63,7 +70,8 @@ function route(method: string, path: string): OpenOperation {
|
||||
'Method/path is not a supported OpenAPI route.',
|
||||
);
|
||||
for (const [index, part] of match.path.split('/').entries())
|
||||
if (part.startsWith(':')) integer(path.split('/')[index]!);
|
||||
if (part.startsWith(':') && !match.uuidParams?.includes(part.slice(1)))
|
||||
integer(path.split('/')[index]!);
|
||||
return match;
|
||||
}
|
||||
|
||||
@@ -107,7 +115,11 @@ export async function openCommand(
|
||||
if (!generic) {
|
||||
endpoint = op.path;
|
||||
for (const [index, name] of (op.params ?? []).entries()) {
|
||||
const value = integer(command.positionals[index]!);
|
||||
const positional = command.positionals[index]!;
|
||||
const isUuid = op.uuidParams?.includes(name);
|
||||
if (isUuid && !new RegExp(`^${UUID_PATTERN}$`).test(positional))
|
||||
usage('任务 ID 必须为 UUID。', 'Job ID must be a UUID.');
|
||||
const value = isUuid ? positional : integer(positional);
|
||||
endpoint = endpoint.replace(`:${name}`, String(value));
|
||||
if (op.body === 'object-id') {
|
||||
if (body !== undefined && !isRecord(body))
|
||||
|
||||
@@ -26,6 +26,14 @@ export const commands: readonly CommandSpec[] = [
|
||||
default: 'crons',
|
||||
choices: [
|
||||
...new Set(openOperations.map((op) => op.path.split('/')[0]!)),
|
||||
'envs:read',
|
||||
'configs:read',
|
||||
'scripts:read',
|
||||
'crons:read',
|
||||
'subscriptions:read',
|
||||
'dependencies:read',
|
||||
'logs:read',
|
||||
'dashboard:read',
|
||||
].filter((scope) => !['auth', 'update'].includes(scope)),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -175,8 +175,8 @@ export const english: Record<string, string> = {
|
||||
'Request failed or returned invalid JSON. Check the instance URL, network and TLS certificate.',
|
||||
'API 请求被拒绝(code %s),请检查%s。':
|
||||
'API request rejected (code %s). Check %s.',
|
||||
'CLI 配置必须是当前用户拥有的私有普通文件(0600)。':
|
||||
'CLI config must be an owned private regular file (0600).',
|
||||
'CLI 配置必须是普通文件,且不能是符号链接。':
|
||||
'CLI config must be a regular file, not a symbolic link.',
|
||||
'CLI 配置无效,请运行 ql login。': 'Invalid CLI config. Run ql login.',
|
||||
'尚未登录,请运行 ql login。': 'Not logged in. Run ql login.',
|
||||
'无法读取 CLI 配置,请检查文件权限并运行 ql login。':
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
const vm = require('node:vm');
|
||||
const { createRequire } = require('node:module');
|
||||
const { createContext } = require('../../dist/internal/runtime/context');
|
||||
const { replaceAndReload } = require('../../dist/internal/maintenance/upgrade');
|
||||
const runtime = require('../../dist/internal/maintenance/nodeRuntime.cjs');
|
||||
|
||||
// Change only runtime selection; execute the compiled operator, actual child
|
||||
// Node and process discovery, without pretending the host CPU is ARM.
|
||||
async function operatorFor(arch, armVersion, node) {
|
||||
const filename = require.resolve('../../dist/internal/maintenance/operator');
|
||||
const localRequire = createRequire(filename);
|
||||
const module = { exports: {} };
|
||||
const flags = runtime.serverRuntimeArgs({
|
||||
arch,
|
||||
config: { variables: { arm_version: armVersion } },
|
||||
versions: { node },
|
||||
});
|
||||
vm.runInNewContext(
|
||||
await fs.readFile(filename, 'utf8'),
|
||||
{
|
||||
module,
|
||||
exports: module.exports,
|
||||
process,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
require(name) {
|
||||
return name === './nodeRuntime.cjs'
|
||||
? { ...runtime, serverRuntimeArgs: () => [...flags] }
|
||||
: localRequire(name);
|
||||
},
|
||||
},
|
||||
{ filename },
|
||||
);
|
||||
return { ...module.exports, flags };
|
||||
}
|
||||
|
||||
for (const [arch, arm, node] of [
|
||||
['arm', 6, '24.18.1'],
|
||||
['arm', 6, '20.18.1'],
|
||||
['arm', 6, '22.20.0'],
|
||||
['arm', 7, '24.18.1'],
|
||||
['arm64', undefined, '24.18.1'],
|
||||
['x64', undefined, '24.18.1'],
|
||||
])
|
||||
test(`CLI direct startup and stop use compatible arguments: ${arch}/${arm}/${node}`, async (t) => {
|
||||
const operator = await operatorFor(arch, arm, node);
|
||||
const root = await fs.realpath(
|
||||
await fs.mkdtemp(path.join(os.tmpdir(), 'ql-runtime-start-')),
|
||||
);
|
||||
const context = createContext(
|
||||
{ root },
|
||||
{ PATH: process.platform === 'linux' ? '' : '/usr/bin:/bin', QL_LANG: 'en' },
|
||||
);
|
||||
const entry = path.join(context.paths.dir_static, 'build/app.js');
|
||||
let pid;
|
||||
t.after(async () => {
|
||||
if (pid) {
|
||||
try {
|
||||
process.kill(pid, 'SIGKILL');
|
||||
} catch {}
|
||||
}
|
||||
await fs.rm(root, { recursive: true, force: true });
|
||||
});
|
||||
await fs.mkdir(path.dirname(entry), { recursive: true });
|
||||
await fs.writeFile(
|
||||
entry,
|
||||
`require('fs').writeFileSync(${JSON.stringify(
|
||||
path.join(root, 'runtime.json'),
|
||||
)}, JSON.stringify({args:process.execArgv,pid:process.pid}));setInterval(()=>{},1000);`,
|
||||
);
|
||||
const started = await operator.startPanel(context);
|
||||
pid = started.pid;
|
||||
const report = JSON.parse(
|
||||
await fs.readFile(path.join(root, 'runtime.json')),
|
||||
);
|
||||
assert.equal(started.manager, 'node');
|
||||
assert.deepEqual(report.args, operator.flags);
|
||||
assert.equal(report.pid, pid);
|
||||
await operator.stopPanel(context);
|
||||
for (let n = 0; n < 100; n++) {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
} catch (e) {
|
||||
if (e.code === 'ESRCH') {
|
||||
pid = undefined;
|
||||
break;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
assert.equal(
|
||||
pid,
|
||||
undefined,
|
||||
'the exact backend must stop even with Node flags',
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'ARMv6 CLI replacement stops flagged new backend before restoring old backend and data',
|
||||
{
|
||||
skip: process.platform !== 'linux',
|
||||
timeout: 20000,
|
||||
},
|
||||
async (t) => {
|
||||
const operator = await operatorFor('arm', 6, '24.18.1');
|
||||
const root = await fs.realpath(
|
||||
await fs.mkdtemp(path.join(os.tmpdir(), 'ql-arm-rollback-')),
|
||||
);
|
||||
const context = createContext({ root }, { PATH: '', QL_LANG: 'en' });
|
||||
const entry = path.join(context.paths.dir_static, 'build/app.js');
|
||||
const incoming = path.join(root, 'incoming.js'),
|
||||
journal = path.join(root, 'journal.jsonl');
|
||||
const record = (version) =>
|
||||
`const fs=require('fs');fs.appendFileSync(${JSON.stringify(
|
||||
journal,
|
||||
)},JSON.stringify({version:${JSON.stringify(
|
||||
version,
|
||||
)},pid:process.pid,args:process.execArgv})+'\\n');setInterval(()=>{},1000);`;
|
||||
await fs.mkdir(path.dirname(entry), { recursive: true });
|
||||
await fs.mkdir(context.data, { recursive: true });
|
||||
await fs.writeFile(path.join(root, '.env'), 'KEEP=custom\n', {
|
||||
mode: 0o600,
|
||||
});
|
||||
await fs.writeFile(path.join(context.data, 'keep'), 'old data');
|
||||
await fs.writeFile(entry, record('old'));
|
||||
await fs.writeFile(incoming, record('new'));
|
||||
const pids = [];
|
||||
t.after(async () => {
|
||||
for (const pid of pids) {
|
||||
try {
|
||||
process.kill(pid, 'SIGKILL');
|
||||
} catch {}
|
||||
}
|
||||
await fs.rm(root, { recursive: true, force: true });
|
||||
});
|
||||
pids.push((await operator.startPanel(context)).pid);
|
||||
await assert.rejects(
|
||||
replaceAndReload(context, [{ source: incoming, target: entry }], {
|
||||
stop: (ctx) => operator.stopPanel(ctx),
|
||||
start: async (ctx, recover) => {
|
||||
const result = await operator.startPanel(ctx);
|
||||
pids.push(result.pid);
|
||||
if (!recover) throw new Error('injected new-version health failure');
|
||||
},
|
||||
}),
|
||||
/injected new-version health failure/,
|
||||
);
|
||||
const launches = (await fs.readFile(journal, 'utf8'))
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map(JSON.parse);
|
||||
assert.deepEqual(
|
||||
launches.map((x) => x.version),
|
||||
['old', 'new', 'old'],
|
||||
);
|
||||
for (const row of launches) assert.deepEqual(row.args, operator.flags);
|
||||
for (const row of launches.slice(0, -1))
|
||||
assert.throws(() => process.kill(row.pid, 0), { code: 'ESRCH' });
|
||||
process.kill(launches.at(-1).pid, 0);
|
||||
assert.equal(
|
||||
await fs.readFile(path.join(root, '.env'), 'utf8'),
|
||||
'KEEP=custom\n',
|
||||
);
|
||||
assert.equal((await fs.stat(path.join(root, '.env'))).mode & 0o777, 0o600);
|
||||
assert.equal(
|
||||
await fs.readFile(path.join(context.data, 'keep'), 'utf8'),
|
||||
'old data',
|
||||
);
|
||||
assert.equal(await fs.readFile(entry, 'utf8'), record('old'));
|
||||
assert.ok(
|
||||
!(await fs.readdir(path.dirname(entry))).some((x) =>
|
||||
x.includes('ql-backup'),
|
||||
),
|
||||
);
|
||||
await operator.stopPanel(context);
|
||||
},
|
||||
);
|
||||
@@ -3,7 +3,46 @@ const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
const { findDirectBackendPids } = require('../../dist/internal/runtime/backendProcesses');
|
||||
const {
|
||||
findDirectBackendPids,
|
||||
} = require('../../dist/internal/runtime/backendProcesses');
|
||||
|
||||
test('backend discovery accepts only owned compatibility flags and the exact installation entry', async (t) => {
|
||||
const root = await fs.realpath(
|
||||
await fs.mkdtemp(path.join(os.tmpdir(), 'ql-flagged-proc-')),
|
||||
);
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
const proc = path.join(root, 'proc'),
|
||||
panel = path.join(root, 'panel with spaces');
|
||||
const other = path.join(root, 'other/static/build/app.js');
|
||||
const entry = path.join(panel, 'static/build/app.js');
|
||||
for (const file of [entry, other]) {
|
||||
await fs.mkdir(path.dirname(file), { recursive: true });
|
||||
await fs.writeFile(file, '');
|
||||
}
|
||||
const flags = ['--no-opt', '--no-sparkplug', '--no-maglev'];
|
||||
const cases = [
|
||||
[['/usr/bin/node', ...flags, entry], true],
|
||||
[['node24', ...flags, 'static/build/app.js'], true],
|
||||
[['node', ...flags, other], false],
|
||||
[['node', '-e', entry], false],
|
||||
[['node', '-r', entry], false],
|
||||
[['node', ...flags, entry, 'argument'], false],
|
||||
[['node', '--no-opt', entry], false],
|
||||
[['bash', ...flags, entry], false],
|
||||
[['node', ...flags, '-e', entry], false],
|
||||
];
|
||||
const expected = [];
|
||||
for (const [i, [args, matches]] of cases.entries()) {
|
||||
const pid = 910001 + i,
|
||||
directory = path.join(proc, String(pid));
|
||||
await fs.mkdir(directory, { recursive: true });
|
||||
await fs.writeFile(path.join(directory, 'cmdline'), args.join('\0') + '\0');
|
||||
await fs.symlink(panel, path.join(directory, 'cwd'));
|
||||
if (matches) expected.push(pid);
|
||||
}
|
||||
assert.deepEqual((await findDirectBackendPids(entry, proc)).sort(), expected);
|
||||
});
|
||||
|
||||
test('Linux backend discovery scopes legacy relative and absolute commands to one installation', async (t) => {
|
||||
const root = await fs.realpath(
|
||||
@@ -64,7 +103,10 @@ test(
|
||||
const { spawn } = require('node:child_process');
|
||||
const { once } = require('node:events');
|
||||
const { createContext } = require('../../dist/internal/runtime/context');
|
||||
const { stopPanel, startPanel } = require('../../dist/internal/maintenance/operator');
|
||||
const {
|
||||
stopPanel,
|
||||
startPanel,
|
||||
} = require('../../dist/internal/maintenance/operator');
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-live-proc-'));
|
||||
const children = [];
|
||||
let fallbackPid;
|
||||
@@ -223,7 +265,9 @@ for (const language of ['zh', 'en', 'unsupported']) {
|
||||
);
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
const { createContext } = require('../../dist/internal/runtime/context');
|
||||
const { startPanel } = require('../../dist/internal/maintenance/operator');
|
||||
const {
|
||||
startPanel,
|
||||
} = require('../../dist/internal/maintenance/operator');
|
||||
const context = createContext({ root }, { PATH: '', QL_LANG: language });
|
||||
const entry = path.join(context.paths.dir_static, 'build/app.js');
|
||||
await fs.mkdir(path.dirname(entry), { recursive: true });
|
||||
|
||||
@@ -4,33 +4,8 @@ const fs = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { createContext } = require('../../dist/internal/runtime/context');
|
||||
const { extendedLifecycle } = require('../../dist/internal/runtime/lifecycle');
|
||||
const { loggedOperation } = require('../../dist/internal/runtime/commandLog');
|
||||
|
||||
test('installed panel version selects lifecycle schema and unknown versions stay conservative', async (t) => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-lifecycle-'));
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
const context = createContext({ root }, {});
|
||||
assert.equal(await extendedLifecycle(context), false);
|
||||
for (const [version, expected] of [
|
||||
['2.20.1', false],
|
||||
['2.19.0', false],
|
||||
['2.21.0-14', true],
|
||||
['3.0.0', false],
|
||||
['invalid', false],
|
||||
]) {
|
||||
await fs.writeFile(
|
||||
path.join(root, 'package.json'),
|
||||
JSON.stringify({ version }),
|
||||
);
|
||||
assert.equal(await extendedLifecycle(context), expected);
|
||||
}
|
||||
context.env.QL_CLI_LIFECYCLE = 'extended';
|
||||
assert.equal(await extendedLifecycle(context), true);
|
||||
context.env.QL_CLI_LIFECYCLE = 'legacy';
|
||||
assert.equal(await extendedLifecycle(context), false);
|
||||
});
|
||||
|
||||
test('command log preserves scheduler path and rejects escaping the log directory', async (t) => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-scheduler-log-'));
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
@@ -50,85 +25,82 @@ test('command log preserves scheduler path and rejects escaping the log director
|
||||
);
|
||||
});
|
||||
|
||||
test('released version.yaml selects lifecycle only when package version is absent', async (t) => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-release-version-'));
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
const context = createContext({ root }, {});
|
||||
await fs.writeFile(
|
||||
path.join(root, 'package.json'),
|
||||
'{"name":"released-panel"}',
|
||||
);
|
||||
for (const [release, expected] of [
|
||||
['version: 2.20.1\nchangeLog: |\n version: 2.99.0\n', false],
|
||||
['version: 2.21.0-14\npublishTime: 2026-09-25\n', true],
|
||||
['version: "2.21.1" # release\n', true],
|
||||
["\ufeffversion: '2.22.0'\r\n", true],
|
||||
['version: 3.0.0\n', false],
|
||||
['version: 2.21.invalid\n', false],
|
||||
['version: 2.21.0\nversion: 2.20.1\n', false],
|
||||
['changeLog: |\n version: 2.21.0\n', false],
|
||||
['version: !custom 2.21.0\n', false],
|
||||
]) {
|
||||
await fs.writeFile(path.join(root, 'version.yaml'), release);
|
||||
assert.equal(await extendedLifecycle(context), expected, release);
|
||||
}
|
||||
await fs.writeFile(path.join(root, 'version.yaml'), 'version: 2.21.1\n');
|
||||
await fs.writeFile(path.join(root, 'package.json'), '{"version":"2.20.1"}');
|
||||
assert.equal(await extendedLifecycle(context), false);
|
||||
context.env.QL_CLI_LIFECYCLE = 'extended';
|
||||
assert.equal(await extendedLifecycle(context), true);
|
||||
context.env.QL_CLI_LIFECYCLE = 'legacy';
|
||||
assert.equal(await extendedLifecycle(context), false);
|
||||
delete context.env.QL_CLI_LIFECYCLE;
|
||||
await fs.rm(path.join(root, 'package.json'));
|
||||
assert.equal(await extendedLifecycle(context), true);
|
||||
await fs.rm(path.join(root, 'version.yaml'));
|
||||
assert.equal(await extendedLifecycle(context), false);
|
||||
});
|
||||
|
||||
test('release-only version metadata controls actual task and maintenance status payloads', async (t) => {
|
||||
test('managed CLI tasks and maintenance commands report against the parent receipt', async t => {
|
||||
const { LocalApi } = require('../../dist/internal/runtime/api');
|
||||
const { executeTask } = require('../../dist/internal/execution/taskRunner');
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-release-payload-'));
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-managed-cli-'));
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
const context = createContext(
|
||||
{ root },
|
||||
{ PATH: process.env.PATH, ID: '7', no_tee: 'true' },
|
||||
);
|
||||
const id = 'parent-receipt-7';
|
||||
const context = createContext({ root }, {
|
||||
PATH: process.env.PATH, ID: '7', no_tee: 'true', QL_TRIGGER_ID: id,
|
||||
QL_CLI_LIFECYCLE: 'extended', QL_EXECUTION_ORIGIN: 'scheduled_system',
|
||||
});
|
||||
await fs.mkdir(context.paths.dir_scripts, { recursive: true });
|
||||
await fs.writeFile(
|
||||
path.join(context.paths.dir_scripts, 'fixture.sh'),
|
||||
'return 7',
|
||||
);
|
||||
await fs.writeFile(path.join(context.paths.dir_scripts, 'fixture.sh'), 'return 7');
|
||||
const calls = [];
|
||||
t.mock.method(LocalApi.prototype, 'call', async (endpoint, method, body) => {
|
||||
calls.push({ endpoint, body });
|
||||
return { code: 200 };
|
||||
});
|
||||
for (const version of ['2.20.1', '2.21.0-14']) {
|
||||
await fs.writeFile(
|
||||
path.join(root, 'version.yaml'),
|
||||
`version: ${version}\n`,
|
||||
);
|
||||
calls.length = 0;
|
||||
const result = await executeTask(context, {
|
||||
argv: ['fixture.sh'],
|
||||
mode: 'now',
|
||||
});
|
||||
assert.equal(result.exitCode, 7);
|
||||
const final = calls
|
||||
.filter((row) => row.endpoint === 'crons/status')
|
||||
.at(-1).body;
|
||||
assert.equal(final.exit_code, version === '2.20.1' ? undefined : 7);
|
||||
assert.equal(
|
||||
calls.some((row) => row.endpoint === 'dashboard/record'),
|
||||
version !== '2.20.1',
|
||||
);
|
||||
calls.length = 0;
|
||||
await loggedOperation(context, 'extra', async () => true);
|
||||
assert.equal(
|
||||
calls.at(-1).body.exit_code,
|
||||
version === '2.20.1' ? undefined : 0,
|
||||
);
|
||||
const result = await executeTask(context, { argv: ['fixture.sh'], mode: 'now' });
|
||||
assert.equal(result.exitCode, 7);
|
||||
assert.deepEqual(calls.map(r => r.endpoint), ['crons/status', 'crons/status', 'dashboard/record']);
|
||||
await loggedOperation(context, 'extra', async () => true);
|
||||
assert.equal(calls.length, 5);
|
||||
for (const { body } of calls) {
|
||||
assert.equal(body.trigger_id, id);
|
||||
assert.equal(body.execution_id, undefined);
|
||||
}
|
||||
calls.length = 0;
|
||||
context.env.QL_CLI_LIFECYCLE = 'legacy';
|
||||
await loggedOperation(context, 'extra', async () => true);
|
||||
assert.ok(calls.length);
|
||||
assert.ok(calls.every(r => !('trigger_id' in r.body)));
|
||||
});
|
||||
|
||||
test('distinct managed triggers in the same clock tick have separate maintenance and task logs', async t => {
|
||||
const { executeTask } = require('../../dist/internal/execution/taskRunner');
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-same-tick-'));
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
t.mock.method(Date, 'now', () => 1800000000000);
|
||||
const run = async id => {
|
||||
const context = createContext({ root }, { QL_CLI_LIFECYCLE: 'extended', QL_TRIGGER_ID: id,
|
||||
PATH: process.env.PATH, no_tee: 'true', log_name: 'shared' });
|
||||
await fs.mkdir(context.paths.dir_scripts, { recursive: true });
|
||||
await fs.writeFile(path.join(context.paths.dir_scripts, id + '.sh'), 'echo ' + id);
|
||||
const command = await loggedOperation(context, 'extra', async () => {});
|
||||
const task = await executeTask(context, { argv: [id + '.sh'], mode: 'now' });
|
||||
return { command: command.logPath, file: task.logPath,
|
||||
content: await fs.readFile(path.join(context.paths.dir_log, task.logPath), 'utf8') };
|
||||
};
|
||||
const [a, b] = await Promise.all([run('marker-alpha'), run('marker-bravo')]);
|
||||
assert.notEqual(a.command, b.command);
|
||||
assert.notEqual(a.file, b.file);
|
||||
assert.match(a.content, /marker-alpha/);
|
||||
assert.doesNotMatch(a.content, /marker-bravo/);
|
||||
assert.match(b.content, /marker-bravo/);
|
||||
assert.doesNotMatch(b.content, /marker-alpha/);
|
||||
});
|
||||
|
||||
test('same-tick standalone tasks and commands share a receipt only within one invocation', async t => {
|
||||
const { LocalApi } = require('../../dist/internal/runtime/api');
|
||||
const { executeTask } = require('../../dist/internal/execution/taskRunner');
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-client-receipts-'));
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
t.mock.method(Date, 'now', () => 1800000000000);
|
||||
const context = createContext({root}, {ID:'5', QL_CLI_LIFECYCLE:'extended', no_tee:'true',
|
||||
real_log_path:'shared.log', PATH:process.env.PATH});
|
||||
await fs.mkdir(context.paths.dir_scripts, {recursive:true});
|
||||
await fs.writeFile(path.join(context.paths.dir_scripts, 'receipt.sh'), 'exit 0');
|
||||
const groups = new Map();
|
||||
t.mock.method(LocalApi.prototype, 'call', async (endpoint, method, body) => {
|
||||
const id = body.execution_id;
|
||||
assert.match(id, /^client-[0-9a-f-]{36}$/);
|
||||
groups.set(id, [...(groups.get(id) || []), body.status ?? 'stat']);
|
||||
return {code:200};
|
||||
});
|
||||
await Promise.all([executeTask(context, {argv:['receipt.sh'], mode:'now'}),
|
||||
executeTask(context, {argv:['receipt.sh'], mode:'now'}),
|
||||
loggedOperation(context, 'extra', async () => {})]);
|
||||
assert.deepEqual([...groups.values()].map(sequence => sequence.join(',')).sort(), ['0,1','0,1,stat','0,1,stat']);
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user