mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 01:23:53 +08:00
feat: harden cron execution recovery and expose scheduling diagnostics
Reconcile scheduled and system cron triggers, isolate concurrent executions and retain verifiable exit statistics across restarts. Add paged task history, log and script browsing, dashboard timing details and regression coverage.
This commit is contained in:
1 parent
3b6a873520
commit
8a9e70e90b
166 files changed
+18942
-1800
No files matched your search
+58
-8
@@ -38,7 +38,7 @@ ql_api_request() {
|
||||
-H "Authorization: Bearer ${__ql_token__}" \
|
||||
-H "Content-Type: application/json;charset=UTF-8" \
|
||||
"$@" \
|
||||
--compressed)
|
||||
--compressed) || return $?
|
||||
if [[ "$attempt" == 2 || "$api" == '{"code":200}' ]] ||
|
||||
[[ "$(jq -r '.code' <<< "$api" 2>/dev/null)" != 401 ]]; then
|
||||
break
|
||||
@@ -99,6 +99,7 @@ add_cron_api() {
|
||||
t '%s -> 添加成功' "$name"
|
||||
else
|
||||
t '%s -> 添加失败(%s)' "$name" "$message"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -165,16 +166,43 @@ del_cron_api() {
|
||||
local api=$(ql_api_request \
|
||||
"http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \
|
||||
-X DELETE \
|
||||
--data-raw "[$ids]")
|
||||
--data-raw "${2:-[$ids]}")
|
||||
code=$(echo "$api" | jq -r .code)
|
||||
message=$(echo "$api" | jq -r .message)
|
||||
if [[ $code == 200 ]]; then
|
||||
t '成功'
|
||||
else
|
||||
t '失败(%s)' "$message"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Initialize once in the wrapper, before any pipeline, signal handler or receipt.
|
||||
init_execution_id() {
|
||||
ql_execution_id=""
|
||||
[[ -n ${QL_TRIGGER_ID:-} || ! ${ID:-} =~ ^[1-9][0-9]*$ ]] && return 0
|
||||
local uuid
|
||||
if [[ -r /proc/sys/kernel/random/uuid ]]; then
|
||||
IFS= read -r uuid < /proc/sys/kernel/random/uuid || return 1
|
||||
else
|
||||
uuid=$(node -p "require('crypto').randomUUID()") || return 1
|
||||
fi
|
||||
ql_execution_id="client-$uuid"
|
||||
}
|
||||
|
||||
# Only an identified receipt can safely repeat a write after curl times out.
|
||||
ql_receipt_request() {
|
||||
if [[ -z ${QL_TRIGGER_ID:-}${ql_execution_id:-} ]]; then
|
||||
ql_api_request "$@"
|
||||
return
|
||||
fi
|
||||
local response status
|
||||
response=$(ql_api_request --max-time 30 "$@") && { printf '%s' "$response"; return; }
|
||||
status=$?
|
||||
[[ $status == 28 ]] || return "$status"
|
||||
ql_api_request --max-time 30 "$@"
|
||||
}
|
||||
|
||||
update_cron() {
|
||||
local ids="$1"
|
||||
local status="$2"
|
||||
@@ -183,15 +211,31 @@ update_cron() {
|
||||
local lastExecutingTime="${5:-0}"
|
||||
local runningTime="${6:-0}"
|
||||
local exitCode="${7:-}"
|
||||
local finish_header=()
|
||||
if [[ ${8:-} =~ ^[0-9]{1,10}$ ]]; then finish_header=(-H "X-QL-Finished-At: ${8}000"); fi
|
||||
local trigger_id=${QL_TRIGGER_ID:-}
|
||||
local currentTimeStamp=${EPOCHSECONDS:-$(date +%s)}
|
||||
local dataRaw="{\"ids\":[$ids],\"status\":\"$status\",\"pid\":\"$pid\",\"log_path\":\"$logPath\",\"last_execution_time\":$lastExecutingTime,\"last_running_time\":$runningTime"
|
||||
# Preserve the no-fork fast path for generated names; legacy paths may need JSON escaping.
|
||||
local jsonLog
|
||||
if [[ $logPath =~ ^[a-zA-Z0-9_./-]+$ ]]; then
|
||||
jsonLog="\"$logPath\""
|
||||
else
|
||||
jsonLog=$(jq -Rn --arg path "$logPath" '$path') || return 1
|
||||
fi
|
||||
local dataRaw="{\"ids\":[$ids],\"status\":\"$status\",\"pid\":\"$pid\",\"log_path\":$jsonLog,\"last_execution_time\":$lastExecutingTime,\"last_running_time\":$runningTime"
|
||||
if [[ -n $exitCode ]]; then
|
||||
dataRaw="${dataRaw},\"exit_code\":$exitCode"
|
||||
fi
|
||||
if [[ $trigger_id =~ ^[a-z0-9-]{1,120}$ ]]; then
|
||||
dataRaw="${dataRaw},\"trigger_id\":\"$trigger_id\""
|
||||
elif [[ -n ${ql_execution_id:-} ]]; then
|
||||
dataRaw="${dataRaw},\"execution_id\":\"$ql_execution_id\""
|
||||
fi
|
||||
if [[ ${MANUAL:-} == true && -n $trigger_id${ql_execution_id:-} ]]; then dataRaw="${dataRaw},\"trigger_stopped\":true"; fi
|
||||
dataRaw="${dataRaw}}"
|
||||
local api=$(ql_api_request \
|
||||
local api=$(ql_receipt_request \
|
||||
"http://localhost:${ql_port}/open/crons/status?t=$currentTimeStamp" \
|
||||
-X PUT \
|
||||
${finish_header[@]+"${finish_header[@]}"} -X PUT \
|
||||
--data-raw "$dataRaw")
|
||||
ql_parse_status_response "$api" || true
|
||||
if [[ $code != 200 ]]; then
|
||||
@@ -257,10 +301,16 @@ record_cron_stat() {
|
||||
local elapsed="${3:-0}"
|
||||
[[ $ref_id ]] && [[ $ref_id -gt 0 ]] 2>/dev/null || return
|
||||
|
||||
local api=$(ql_api_request \
|
||||
local finish_header=()
|
||||
if [[ ${4:-} =~ ^[0-9]{1,10}$ ]]; then finish_header=(-H "X-QL-Finished-At: ${4}000"); fi
|
||||
local trigger_id=${QL_TRIGGER_ID:-}
|
||||
local extra=""
|
||||
if [[ $trigger_id =~ ^[a-z0-9-]{1,120}$ ]]; then extra=",\"trigger_id\":\"$trigger_id\""
|
||||
elif [[ -n ${ql_execution_id:-} ]]; then extra=",\"execution_id\":\"$ql_execution_id\""; fi
|
||||
local api=$(ql_receipt_request \
|
||||
"http://localhost:${ql_port:-5700}/open/dashboard/record" \
|
||||
-X POST \
|
||||
--data-raw "{\"ref_id\":$ref_id,\"code\":$exit_code,\"elapsed\":$elapsed}")
|
||||
${finish_header[@]+"${finish_header[@]}"} -X POST \
|
||||
--data-raw "{\"ref_id\":$ref_id,\"code\":$exit_code,\"elapsed\":$elapsed$extra}")
|
||||
ql_parse_status_response "$api" || true
|
||||
if [[ $code != 200 ]]; then
|
||||
if [[ ! $message ]]; then
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Wait for launch authorization, then preserve a command's exit across worker restarts."""
|
||||
import errno
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
def relay(source, destination):
|
||||
with source:
|
||||
for chunk in iter(lambda: os.read(source.fileno(), 65536), b''):
|
||||
if destination is None:
|
||||
continue
|
||||
remaining = memoryview(chunk)
|
||||
try:
|
||||
while remaining:
|
||||
remaining = remaining[os.write(destination, remaining):]
|
||||
except OSError:
|
||||
# The worker stopped reading. Continue draining so the user's
|
||||
# command and its log wrapper can still report their real exit.
|
||||
destination = None
|
||||
|
||||
|
||||
def sync_directory(directory):
|
||||
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def main():
|
||||
command, owner, marker, node, reporter = sys.argv[1:6]
|
||||
if sys.stdin.buffer.read() != b'run\n':
|
||||
return 125
|
||||
child = subprocess.Popen(['/bin/bash', '-c', command], stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
if sys.argv[6:] == ['report-start']:
|
||||
try:
|
||||
with os.fdopen(3, 'wb', buffering=0) as timing:
|
||||
timing.write(str(time.time_ns() // 1000000).encode('ascii'))
|
||||
except OSError:
|
||||
pass
|
||||
streams = [threading.Thread(target=relay, args=(child.stdout, 1)),
|
||||
threading.Thread(target=relay, args=(child.stderr, 2))]
|
||||
for stream in streams:
|
||||
stream.start()
|
||||
status = child.wait()
|
||||
finished = time.time_ns() // 1000000
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import signal
|
||||
|
||||
signame = None
|
||||
if status < 0:
|
||||
try:
|
||||
signame = signal.Signals(-status).name
|
||||
except ValueError:
|
||||
signame = 'SIG' + str(-status)
|
||||
code = status if status >= 0 else None
|
||||
fields = [os.environ.get('QL_TRIGGER_ID'), code, signame, finished]
|
||||
checksum = hashlib.sha256(json.dumps(fields, separators=(',', ':')).encode('ascii')).hexdigest()
|
||||
receipt = json.dumps({'code': code, 'signal': signame, 'time': finished,
|
||||
'version': 1, 'checksum': checksum}, separators=(',', ':'))
|
||||
needs_report = False
|
||||
if marker:
|
||||
try:
|
||||
os.makedirs(os.path.dirname(marker), mode=0o700, exist_ok=True)
|
||||
import tempfile
|
||||
prefix = '.pending.' + os.path.basename(marker) + '.'
|
||||
directory = os.path.dirname(marker)
|
||||
stamp = prefix + 'full-' + str(signame or code) + '-' + str(finished) + '-' + checksum + '-'
|
||||
# An empty file publishes the verified result in one directory
|
||||
# operation, before any JSON body can be interrupted or run short.
|
||||
with tempfile.NamedTemporaryFile(dir=directory, prefix=stamp, delete=False):
|
||||
pass
|
||||
# Sync the new entry and the entry for cron-exits itself before
|
||||
# treating the marker as published or suppressing a full-volume error.
|
||||
sync_directory(directory)
|
||||
sync_directory(os.path.dirname(directory))
|
||||
try:
|
||||
if os.statvfs(directory).f_bavail:
|
||||
with tempfile.NamedTemporaryFile(dir=directory, prefix=stamp, mode='w', delete=False) as out:
|
||||
out.write(receipt)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
try:
|
||||
os.link(out.name, marker)
|
||||
except FileExistsError:
|
||||
import secrets
|
||||
while True:
|
||||
try:
|
||||
os.link(out.name, os.path.join(directory, prefix + secrets.token_hex(16)))
|
||||
break
|
||||
except FileExistsError:
|
||||
continue
|
||||
except FileNotFoundError:
|
||||
break
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
sync_directory(directory)
|
||||
except OSError as error:
|
||||
if error.errno not in (errno.ENOSPC, errno.EDQUOT):
|
||||
raise
|
||||
except OSError as error:
|
||||
needs_report = True
|
||||
print('[scheduler] Could not save command exit:', error, file=sys.stderr)
|
||||
if needs_report or os.getppid() != int(owner):
|
||||
env = os.environ.copy()
|
||||
env.pop('NODE_OPTIONS', None)
|
||||
# Even with a live parent its child-close callback has no exit timestamp.
|
||||
# Keep the observed tuple while both the journal and SQLite are full.
|
||||
while subprocess.run([node, reporter, receipt], env=env, check=False).returncode == 75 and needs_report:
|
||||
time.sleep(2)
|
||||
for stream in streams:
|
||||
stream.join()
|
||||
if status < 0:
|
||||
if -status not in (signal.SIGKILL, signal.SIGSTOP):
|
||||
signal.signal(-status, signal.SIG_DFL)
|
||||
os.kill(os.getpid(), -status)
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
+2
-1
@@ -190,7 +190,7 @@ run_concurrent() {
|
||||
|
||||
handle_env_split
|
||||
time=$(date "+$mtime_format")
|
||||
single_log_time=$(format_log_time "$mtime_format" "$time")
|
||||
local single_log_time="$(format_log_time "$mtime_format" "$time")-$$"
|
||||
|
||||
enter_script_workdir || return $?
|
||||
|
||||
@@ -389,3 +389,4 @@ fi
|
||||
run_task_after "${task_shell_params[@]}"
|
||||
clear_env
|
||||
handle_task_end "${task_shell_params[@]}"
|
||||
return "$_task_exit_code"
|
||||
+18
-10
@@ -1,5 +1,3 @@
|
||||
const grpc = require('@grpc/grpc-js');
|
||||
const protoLoader = require('@grpc/proto-loader');
|
||||
const { readFileSync } = require('fs');
|
||||
const { join } = require('path');
|
||||
|
||||
@@ -9,7 +7,7 @@ class GrpcClient {
|
||||
'config/grpc',
|
||||
);
|
||||
|
||||
static #loadTlsCredentials() {
|
||||
static #loadTlsCredentials(grpc) {
|
||||
try {
|
||||
return grpc.credentials.createSsl(
|
||||
readFileSync(join(GrpcClient.#certDir, 'ca.crt')),
|
||||
@@ -60,15 +58,22 @@ class GrpcClient {
|
||||
];
|
||||
|
||||
#client;
|
||||
#Metadata;
|
||||
#closed = false;
|
||||
#api = {};
|
||||
|
||||
constructor() {
|
||||
this.#initializeClient();
|
||||
this.#bindMethods();
|
||||
}
|
||||
|
||||
#initializeClient() {
|
||||
// The panel dependencies resolve as they did before the task's global-path hook.
|
||||
module.loadingPanelDependencies = true;
|
||||
try {
|
||||
// Resolve explicitly: Node can cache a previous task require by parent directory.
|
||||
const grpc = require(require.resolve('@grpc/grpc-js'));
|
||||
const protoLoader = require(require.resolve('@grpc/proto-loader'));
|
||||
this.#Metadata = grpc.Metadata;
|
||||
const { protoPath, protoOptions, serverAddress, grpcOptions } =
|
||||
GrpcClient.#config;
|
||||
|
||||
@@ -77,28 +82,30 @@ class GrpcClient {
|
||||
|
||||
this.#client = new apiProto.Api(
|
||||
serverAddress,
|
||||
GrpcClient.#loadTlsCredentials(),
|
||||
GrpcClient.#loadTlsCredentials(grpc),
|
||||
grpcOptions,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize gRPC client:', error);
|
||||
process.exit(1);
|
||||
throw new Error('Failed to initialize gRPC client: ' + error.message, { cause: error });
|
||||
} finally {
|
||||
module.loadingPanelDependencies = false;
|
||||
}
|
||||
}
|
||||
|
||||
#promisifyMethod(methodName) {
|
||||
const capitalizedMethod =
|
||||
methodName.charAt(0).toUpperCase() + methodName.slice(1);
|
||||
const method = this.#client[capitalizedMethod].bind(this.#client);
|
||||
|
||||
return async (params = {}) => {
|
||||
if (this.#closed) throw new Error('Channel has been shut down');
|
||||
if (!this.#client) this.#initializeClient();
|
||||
return new Promise((resolve, reject) => {
|
||||
const metadata = new grpc.Metadata();
|
||||
const metadata = new this.#Metadata();
|
||||
const deadline = new Date(
|
||||
Date.now() + GrpcClient.#config.defaultTimeout,
|
||||
);
|
||||
|
||||
method(params, metadata, { deadline }, (error, response) => {
|
||||
this.#client[capitalizedMethod](params, metadata, { deadline }, (error, response) => {
|
||||
if (error) {
|
||||
return reject(error);
|
||||
}
|
||||
@@ -122,6 +129,7 @@ class GrpcClient {
|
||||
}
|
||||
|
||||
close() {
|
||||
this.#closed = true;
|
||||
if (this.#client) {
|
||||
this.#client.close();
|
||||
this.#client = null;
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Observe the first executable location in the entry file. Preloads, the TS
|
||||
// compiler and ESM dependency evaluation can all run before that location.
|
||||
const { Session, url } = require('inspector');
|
||||
const { pathToFileURL } = require('url');
|
||||
const { writeFileSync } = require('fs');
|
||||
|
||||
module.exports = function observeScriptStart(entry, marker) {
|
||||
if (!entry || !marker || url()) return;
|
||||
const session = new Session();
|
||||
try {
|
||||
session.connect();
|
||||
const target = pathToFileURL(entry).href;
|
||||
session.post('Debugger.enable');
|
||||
session.post('Debugger.setBreakpointByUrl', { url: target, lineNumber: 0 }, (err, bp) => {
|
||||
if (err || !bp) { session.disconnect(); return; }
|
||||
session.on('Debugger.paused', ({ params }) => {
|
||||
if (params.hitBreakpoints?.includes(bp.breakpointId)) {
|
||||
try { writeFileSync(marker, String(Date.now()), { flag: 'wx', mode: 0o600 }); } catch {}
|
||||
session.disconnect();
|
||||
} else {
|
||||
session.post('Debugger.resume');
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch { try { session.disconnect(); } catch {} }
|
||||
};
|
||||
@@ -15,9 +15,11 @@ function preferGlobalNodeModules() {
|
||||
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('.') &&
|
||||
@@ -171,3 +173,7 @@ try {
|
||||
} catch (error) {
|
||||
console.log(`run builtin code error: `, error, '\n');
|
||||
}
|
||||
|
||||
if (process.env.QL_SCRIPT_ENTRY && process.env.QL_SCRIPT_START_FILE) {
|
||||
require('./script-start.cjs')(process.env.QL_SCRIPT_ENTRY, process.env.QL_SCRIPT_START_FILE);
|
||||
}
|
||||
@@ -141,3 +141,28 @@ try:
|
||||
builtins.QLAPI = QLAPI
|
||||
except Exception as error:
|
||||
print(f"run builtin code error: {error}\n")
|
||||
|
||||
|
||||
# A line event in the entry module occurs after interpreter startup, imports
|
||||
# performed by this preload, and the configured before hook.
|
||||
def observe_script_start(target, marker):
|
||||
if sys.gettrace() is not None:
|
||||
return
|
||||
def first_line(frame, event, arg):
|
||||
if event == 'line':
|
||||
import time
|
||||
try:
|
||||
with open(marker, 'x') as receipt:
|
||||
receipt.write(str(time.time_ns() // 1000000))
|
||||
except OSError:
|
||||
pass
|
||||
sys.settrace(None)
|
||||
return first_line
|
||||
def enter(frame, event, arg):
|
||||
if event == 'call' and frame.f_code.co_name == '<module>' and os.path.realpath(frame.f_code.co_filename) == target:
|
||||
return first_line
|
||||
return None
|
||||
sys.settrace(enter)
|
||||
|
||||
if os.getenv('QL_SCRIPT_ENTRY') and os.getenv('QL_SCRIPT_START_FILE'):
|
||||
observe_script_start(os.environ['QL_SCRIPT_ENTRY'], os.environ['QL_SCRIPT_START_FILE'])
|
||||
+3
-3
@@ -274,7 +274,7 @@ git_clone_scripts() {
|
||||
|
||||
set_proxy "$proxy"
|
||||
|
||||
git clone -q --depth=1 "${branch_args[@]}" "$url" "$dir"
|
||||
git clone -q --depth=1 "${branch_args[@]}" -- "$url" "$dir"
|
||||
exit_status=$?
|
||||
|
||||
unset_proxy
|
||||
@@ -448,13 +448,13 @@ handle_task_end() {
|
||||
[[ "$diff_time" == 0 ]] && diff_time=1
|
||||
|
||||
if [[ $ID ]]; then
|
||||
local error=$(update_cron "\"$ID\"" "1" "$$" "$log_path" "$begin_timestamp" "$diff_time" "$exit_code")
|
||||
local error=$(update_cron "\"$ID\"" "1" "$$" "$log_path" "$begin_timestamp" "$diff_time" "$exit_code" "$end_timestamp")
|
||||
if [[ $error ]]; then
|
||||
error_message=$(t ', 状态更新失败(%s)' "$error")
|
||||
fi
|
||||
fi
|
||||
|
||||
record_cron_stat "$ID" "${exit_code:-0}" "$diff_time"
|
||||
record_cron_stat "$ID" "${exit_code:-0}" "$diff_time" "$end_timestamp"
|
||||
|
||||
if [[ "${MANUAL:=}" == "true" ]]; then
|
||||
t '\n## 已停止 🛑... %s 耗时 %s 秒%s' "$end_time" "$diff_time" "${error_message:=} "
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Install subscription files without following links under the scripts root."""
|
||||
import contextlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def parts(relative):
|
||||
names = relative.split('/')
|
||||
if any(name in ('', '.', '..') or re.search(r'[\x00-\x1f\x7f]', name) for name in names):
|
||||
raise ValueError('invalid relative path: ' + repr(relative))
|
||||
return names
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def directory(root, names, create=False):
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root, flags)
|
||||
try:
|
||||
for name in names:
|
||||
if create:
|
||||
try:
|
||||
os.mkdir(name, dir_fd=fd)
|
||||
except FileExistsError:
|
||||
pass
|
||||
child = os.open(name, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
yield fd
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def install(source, root, relative):
|
||||
*parents, name = parts(relative)
|
||||
with directory(root, parents, True) as fd:
|
||||
try:
|
||||
existing = os.stat(name, dir_fd=fd, follow_symlinks=False)
|
||||
except FileNotFoundError:
|
||||
existing = None
|
||||
if existing and not stat.S_ISREG(existing.st_mode):
|
||||
raise ValueError('destination is not a regular file: ' + relative)
|
||||
temp = '.ql-copy-' + secrets.token_hex(12)
|
||||
with open(source, 'rb') as src:
|
||||
out = os.open(temp, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600, dir_fd=fd)
|
||||
try:
|
||||
with os.fdopen(out, 'wb') as dst:
|
||||
shutil.copyfileobj(src, dst)
|
||||
os.fchmod(dst.fileno(), os.fstat(src.fileno()).st_mode & 0o777)
|
||||
# Replace rather than modifying an inode that may also have external hard links.
|
||||
os.replace(temp, name, src_dir_fd=fd, dst_dir_fd=fd)
|
||||
finally:
|
||||
try:
|
||||
os.unlink(temp, dir_fd=fd)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def regular_files(base):
|
||||
def failed(error):
|
||||
raise error
|
||||
for parent, dirs, files in os.walk(base, followlinks=False, onerror=failed):
|
||||
dirs[:] = [d for d in dirs if d != '.git']
|
||||
for name in files:
|
||||
source = Path(parent, name)
|
||||
if stat.S_ISREG(source.lstat().st_mode):
|
||||
relative = str(source.relative_to(base))
|
||||
parts(relative)
|
||||
yield relative
|
||||
|
||||
|
||||
def filtered(files, pattern, exclude=False):
|
||||
if not pattern:
|
||||
return files
|
||||
data = ''.join(file + '\n' for file in files)
|
||||
cmd = ['grep', '-E'] + (['-v'] if exclude else []) + ['-e', pattern]
|
||||
result = subprocess.run(cmd, input=os.fsencode(data), stdout=subprocess.PIPE)
|
||||
if result.returncode not in (0, 1):
|
||||
raise ValueError('invalid subscription filter: ' + pattern)
|
||||
return list(filter(None, os.fsdecode(result.stdout).split('\n')))
|
||||
|
||||
|
||||
def repository(repo, scripts, namespace, listing, deps, js, py, include, exclude, dependency, extensions):
|
||||
parts(namespace)
|
||||
suffixes = tuple('.' + ext for ext in re.split(r'[|\s]+', extensions) if ext)
|
||||
candidates = sorted(f for f in regular_files(repo) if f.endswith(suffixes))
|
||||
selected = filtered(filtered(candidates, include), exclude, True)
|
||||
needed = filtered(candidates, dependency) if dependency else []
|
||||
# Evaluate every filter and collect the complete source list before touching any destination.
|
||||
files = [(Path(p), Path(p).name) for p in (js, py) if p and Path(p).is_file()]
|
||||
files += [(Path(repo, f), f) for f in needed]
|
||||
if deps and Path(deps).is_dir() and not Path(deps).is_symlink():
|
||||
files += [(Path(deps, f), f) for f in regular_files(deps)]
|
||||
files += [(Path(repo, f), f) for f in selected]
|
||||
with directory(scripts, parts(namespace), True):
|
||||
pass
|
||||
for source, file in files:
|
||||
install(source, scripts, namespace + '/' + file)
|
||||
Path(listing).write_text(''.join(namespace + '/' + f + '\n' for f in selected))
|
||||
|
||||
|
||||
def unlink(root, relative):
|
||||
*parents, name = parts(relative)
|
||||
try:
|
||||
with directory(root, parents) as fd:
|
||||
if stat.S_ISREG(os.stat(name, dir_fd=fd, follow_symlinks=False).st_mode):
|
||||
os.unlink(name, dir_fd=fd)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def registered(listing, task, namespace, kind):
|
||||
def decode(line):
|
||||
try:
|
||||
return shlex.split(line, comments=False)
|
||||
except ValueError:
|
||||
return []
|
||||
with open(listing) as stream:
|
||||
for line in stream:
|
||||
args = decode(line)
|
||||
index = next((i for i, arg in enumerate(args) if re.fullmatch(r'ID=[1-9][0-9]*', arg)), None)
|
||||
if index is None:
|
||||
continue
|
||||
ident = args[index]
|
||||
prefix, args = args[:index], args[index + 1:]
|
||||
if len(args) == 4 and args[:3] == ['QL_TRIGGER_SOURCE=system', 'bash', '$QL_DIR/shell/system-cron.sh']:
|
||||
args = decode(args[3])
|
||||
prefix = []
|
||||
while args and re.match(r'^\w+=', args[0]) and not args[0].startswith('ID='):
|
||||
prefix.append(args.pop(0))
|
||||
if not args or args.pop(0) != ident:
|
||||
continue
|
||||
revision = next((a.split('=')[1] for a in prefix if re.fullmatch(r'QL_CRON_REVISION=[0-9]+', a)), '')
|
||||
while args and re.match(r'^\w+=', args[0]):
|
||||
args.pop(0)
|
||||
if not args or args.pop(0) != task:
|
||||
continue
|
||||
while args and args[0] in ('-m', '-l'):
|
||||
if args.pop(0) == '-m' and args:
|
||||
args.pop(0)
|
||||
if args and re.fullmatch(r'(?:.*/)?(?:node|python3?|bash|sh|ts-node(?:-transpile-only)?)', args[0]):
|
||||
args.pop(0)
|
||||
if not args:
|
||||
continue
|
||||
file = args[0]
|
||||
try:
|
||||
parts(file)
|
||||
except ValueError:
|
||||
continue
|
||||
owned = file == namespace if kind == 'raw' else (
|
||||
file.startswith(namespace + '/') or (file.startswith(namespace + '_') and '/' not in file))
|
||||
if owned:
|
||||
print(ident[3:], file, revision, sep='\t')
|
||||
|
||||
|
||||
def prepare(root, relative):
|
||||
with directory(root, parts(relative)[:-1], True):
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
{'registered': registered, 'parent': prepare, 'repo': repository, 'copy': install, 'unlink': unlink}[sys.argv[1]](*sys.argv[2:])
|
||||
except (ValueError, OSError) as error:
|
||||
sys.exit('subscription: ' + str(error))
|
||||
@@ -0,0 +1,42 @@
|
||||
# crond's supervisor survives the command to publish its actual exit code.
|
||||
system_receipt_cli="$QL_DIR/static/build/bootstrap/systemCron.js"
|
||||
if (( ${#BASH_SOURCE[@]} == 1 )); then
|
||||
entered=${EPOCHREALTIME:-}
|
||||
entered=${entered/./}
|
||||
if [[ ! $entered =~ ^[0-9]{13,}$ ]]; then entered="$(date +%s)000"; fi
|
||||
export QL_SYSTEM_ENTERED="${entered:0:13}"
|
||||
if ! IFS= read -r uuid 2>/dev/null < /proc/sys/kernel/random/uuid; then
|
||||
uuid=$(node -p 'require("crypto").randomUUID()') || exit 1
|
||||
fi
|
||||
export QL_TRIGGER_ID="system-$ID-$uuid"
|
||||
# Keep the claim acknowledgement separate from both task output and the
|
||||
# exit code: 75 can also be the actual exit code of a launched command.
|
||||
{
|
||||
claimed=$(exec /bin/bash -c '
|
||||
node "$1" start "$ID" "$PPID" "$QL_TRIGGER_ID" "$$" || {
|
||||
status=$?; [ "$status" = 75 ] && exit 0; exit "$status"
|
||||
}
|
||||
echo claimed >&3
|
||||
exec 3>&-
|
||||
command=$2
|
||||
shift 2
|
||||
eval "$command"
|
||||
' bash "$system_receipt_cli" "$@" 3>&1 >&4 4>&-)
|
||||
status=$?
|
||||
} 4>&1
|
||||
[[ $claimed == claimed ]] || exit "$status"
|
||||
# Capture the command end before launching Node or waiting for a SQLite writer.
|
||||
ended=${EPOCHREALTIME:-}
|
||||
ended=${ended/./}
|
||||
if [[ ! $ended =~ ^[0-9]{13,}$ ]]; then ended="$(date +%s)000"; fi
|
||||
while :; do
|
||||
node "$system_receipt_cli" finish "$ID" "$$" "$QL_TRIGGER_ID" "$status" "${ended:0:13}" && break
|
||||
[[ $? == 75 ]] || break
|
||||
sleep 2
|
||||
done
|
||||
exit "$status"
|
||||
fi
|
||||
|
||||
# Old crontabs enter via task.sh or update.sh. Replay their exact arguments
|
||||
# through the same supervisor; the exported trigger ID prevents recursion.
|
||||
exec /bin/bash "${BASH_SOURCE[0]}" 'exec /bin/bash "$@"' "${BASH_SOURCE[1]}" "$@"
|
||||
+19
-1
@@ -3,6 +3,20 @@
|
||||
# Fork from the current Bash state: an external `bash -c` would lose private
|
||||
# before-hook variables, arrays and functions used by sourced Shell scripts.
|
||||
run_task_command() {
|
||||
# Only the user command receives this identity. Helper interpreters started by
|
||||
# before hooks or a package manager must not report their own startup.
|
||||
local target=${2:-}
|
||||
if [[ -n ${QL_TRIGGER_ID:-} && ${QL_TRIGGER_ID} =~ ^[a-z0-9-]{1,120}$ && -n ${dir_tmp:-} ]]; then
|
||||
case "${1##*/}" in
|
||||
run_shell_script|node|python3|ts-node-transpile-only)
|
||||
if [[ -f $target ]]; then
|
||||
local -x QL_SCRIPT_START_FILE="$dir_tmp/cron-start-$QL_TRIGGER_ID"
|
||||
local -x QL_SCRIPT_ENTRY
|
||||
QL_SCRIPT_ENTRY=$(realpath "$target" 2>/dev/null) || QL_SCRIPT_ENTRY=""
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
local timeout_seconds
|
||||
if [[ -z ${command_timeout_time:-} ]]; then
|
||||
"$@"
|
||||
@@ -27,8 +41,12 @@ run_task_command() {
|
||||
timeout_worker=$!
|
||||
(
|
||||
set +m
|
||||
# Start the timer before allowing cleanup to signal its process group.
|
||||
# Otherwise a short task can finish while the watchdog is forking sleep.
|
||||
sleep "$timeout_seconds" &
|
||||
timeout_sleeper=$!
|
||||
: > "$timeout_dir/ready"
|
||||
sleep "$timeout_seconds" || exit 125
|
||||
wait "$timeout_sleeper" || exit 125
|
||||
: > "$timeout_dir/expired"
|
||||
kill -TERM -- "-$timeout_worker" 2>/dev/null || :
|
||||
sleep 0.5
|
||||
|
||||
+25
-3
@@ -1,6 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
dir_shell=$QL_DIR/shell
|
||||
if [[ ${QL_TRIGGER_SOURCE:-} == system && -z ${QL_TRIGGER_ID:-} && ${ID:-} =~ ^[0-9]+$ ]]; then
|
||||
. "$dir_shell/system-cron.sh"
|
||||
fi
|
||||
. "$dir_shell/share.sh"
|
||||
. "$dir_shell/api.sh"
|
||||
. "$dir_shell/task-timeout.sh"
|
||||
@@ -22,7 +25,20 @@ single_hanle() {
|
||||
run_shell_script() {
|
||||
# Preserve inherited variables/functions, but contain exit, exec and shell
|
||||
# options so the task wrapper can run after hooks and report completion.
|
||||
( . "$@" )
|
||||
(
|
||||
if [[ -n ${QL_SCRIPT_START_FILE:-} && -r $1 ]]; then
|
||||
local stamp=${EPOCHREALTIME:-}
|
||||
if [[ $stamp == *.* ]]; then
|
||||
stamp=${stamp/./}; stamp=${stamp:0:13}
|
||||
else
|
||||
stamp=$(date +%s%3N)
|
||||
fi
|
||||
if [[ $stamp =~ ^[0-9]{13}$ ]]; then
|
||||
( set -C; printf '%s' "$stamp" > "$QL_SCRIPT_START_FILE" ) 2>/dev/null || :
|
||||
fi
|
||||
fi
|
||||
. "$@"
|
||||
)
|
||||
}
|
||||
|
||||
define_program() {
|
||||
@@ -83,7 +99,9 @@ handle_log_path() {
|
||||
else
|
||||
log_dir="$log_name"
|
||||
fi
|
||||
log_path="$log_dir/$log_time.log"
|
||||
local run_suffix=""
|
||||
[[ ${QL_TRIGGER_ID:-} =~ ^[a-z0-9-]{1,120}$ ]] && run_suffix="-$QL_TRIGGER_ID"
|
||||
log_path="$log_dir/$log_time$run_suffix.log"
|
||||
|
||||
if [[ ${real_log_path:=} ]]; then
|
||||
log_path="$real_log_path"
|
||||
@@ -160,7 +178,11 @@ fi
|
||||
format_params "$@"
|
||||
define_program "${task_shell_params[@]}"
|
||||
handle_log_path "${task_shell_params[@]}"
|
||||
if [[ -n $ID && -z ${QL_TRIGGER_ID:-} ]]; then init_execution_id || exit 1; fi
|
||||
init_begin_time
|
||||
|
||||
eval '. "$dir_shell/otask.sh"' "$cmd"
|
||||
eval '. "$dir_shell/otask.sh"' "$cmd" '; task_status=${PIPESTATUS[0]}'
|
||||
if [[ -n ${QL_TRIGGER_ID:-} || ${QL_TRIGGER_SOURCE:-} == system ]]; then
|
||||
exit "$task_status"
|
||||
fi
|
||||
exit 0
|
||||
+115
-147
@@ -1,6 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
dir_shell=$QL_DIR/shell
|
||||
if [[ ${QL_TRIGGER_SOURCE:-} == system && -z ${QL_TRIGGER_ID:-} && ${ID:-} =~ ^[0-9]+$ ]]; then
|
||||
. "$dir_shell/system-cron.sh"
|
||||
fi
|
||||
. "$dir_shell/share.sh"
|
||||
. "$dir_shell/api.sh"
|
||||
load_ql_envs
|
||||
@@ -14,17 +17,15 @@ diff_cron() {
|
||||
local list_task="$2"
|
||||
local list_add="$3"
|
||||
local list_drop="$4"
|
||||
if [[ -s $list_task ]] && [[ -s $list_scripts ]]; then
|
||||
grep -vwf $list_task $list_scripts >$list_add
|
||||
grep -vwf $list_scripts $list_task >$list_drop
|
||||
fi
|
||||
|
||||
if [[ ! -s $list_task ]] && [[ -s $list_scripts ]]; then
|
||||
cp -f $list_scripts $list_add
|
||||
fi
|
||||
|
||||
if [[ ! -s $list_scripts ]] && [[ -s $list_task ]]; then
|
||||
cp -f $list_task $list_drop
|
||||
: > "$list_add"
|
||||
: > "$list_drop"
|
||||
if [[ -s $list_task && -s $list_scripts ]]; then
|
||||
grep -Fvx -f "$list_task" "$list_scripts" > "$list_add" || [[ $? == 1 ]] || return 1
|
||||
grep -Fvx -f "$list_scripts" "$list_task" > "$list_drop" || [[ $? == 1 ]] || return 1
|
||||
elif [[ -s $list_scripts ]]; then
|
||||
cp -f "$list_scripts" "$list_add"
|
||||
elif [[ -s $list_task ]]; then
|
||||
cp -f "$list_task" "$list_drop"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -34,7 +35,7 @@ output_list_add_drop() {
|
||||
local type=$(t "$2")
|
||||
if [[ -s $list ]]; then
|
||||
t '检测到有%s的定时任务:' "$type"
|
||||
cat $list
|
||||
cat "$list"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -46,27 +47,36 @@ del_cron() {
|
||||
local detail=""
|
||||
local ids=""
|
||||
t '\n开始尝试自动删除失效的定时任务...'
|
||||
for cron in $(cat $list_drop); do
|
||||
local id=$(cat $list_crontab_user | grep -E "$cmd_task.* $cron" | perl -pe "s|.*ID=(.*) $cmd_task.* $cron\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
if [[ $ids ]]; then
|
||||
ids="$ids,\"$id\""
|
||||
else
|
||||
ids="\"$id\""
|
||||
local script_root repo_root cron id file resolved revision result payload records=""
|
||||
local -a removed=()
|
||||
script_root=$(cd "$dir_scripts" && pwd -P) || return 1
|
||||
repo_root="$script_root/$path"
|
||||
while IFS=$'\t' read -r id cron revision; do
|
||||
[[ $id =~ ^[1-9][0-9]*$ ]] || continue
|
||||
grep -Fxq -e "$cron" "$list_drop" || continue
|
||||
file="$script_root/$cron"
|
||||
if [[ -e $file || -L $file ]]; then
|
||||
resolved=$(realpath "$file") || continue
|
||||
# Compare against the lexical subscription root too: a symlink in
|
||||
# any directory component must not redirect cleanup to another repo.
|
||||
case "$cron" in
|
||||
"$path"/*) [[ $resolved == "$repo_root/"* ]] || continue ;;
|
||||
"$path"_*) [[ $cron != */* && $resolved == "$file" ]] || continue ;;
|
||||
*) continue ;;
|
||||
esac
|
||||
[[ -f $file ]] || continue
|
||||
removed+=("$cron")
|
||||
fi
|
||||
cron_file="$dir_scripts/${cron}"
|
||||
if [[ -f $cron_file ]]; then
|
||||
cron_name=$(grep "new Env" $cron_file | awk -F "\(" '{print $2}' | awk -F "\)" '{print $1}' | sed 's:.*\('\''\|"\)\([^"'\'']*\)\('\''\|"\).*:\2:' | sed 's:"::g' | sed "s:'::g" | head -1)
|
||||
rm -f $cron_file
|
||||
fi
|
||||
[[ -z $cron_name ]] && cron_name="$cron"
|
||||
if [[ $detail ]]; then
|
||||
detail="${detail}\n${cron_name}"
|
||||
else
|
||||
detail="${cron_name}"
|
||||
fi
|
||||
done
|
||||
records+="$id"$'\t'"$cron"$'\t'"$revision"$'\n'
|
||||
ids="${ids:+$ids,}$id"
|
||||
detail="${detail:+$detail\n}$cron"
|
||||
done < "$dir_list_tmp/${path}_registered.list"
|
||||
if [[ $ids ]]; then
|
||||
result=$(del_cron_api "$ids")
|
||||
payload=$(printf '%s' "$records" | jq -Rn '[inputs | split("\t") | {id:(.[0]|tonumber), script:.[1]} + (if .[2] != "" then {revision:(.[2]|tonumber)} else {} end)]') || return 1
|
||||
result=$(del_cron_api "$ids" "$payload") || { printf '%s\n' "$result" >&2; return 1; }
|
||||
for cron in "${removed[@]}"; do
|
||||
python3 "${dir_shell:-$QL_DIR/shell}/subscription-files.py" unlink "$script_root" "$cron" || return 1
|
||||
done
|
||||
notify_api "$(t '%s 删除任务%s' "$path" "$result")" "$detail"
|
||||
fi
|
||||
}
|
||||
@@ -78,30 +88,31 @@ add_cron() {
|
||||
local path=$2
|
||||
t '\n开始尝试自动添加定时任务...'
|
||||
local detail=""
|
||||
cd $dir_scripts
|
||||
for file in $(cat $list_add); do
|
||||
local file_name=${file/${path}\//}
|
||||
file_name=${file_name/${path}\_/}
|
||||
local file operand
|
||||
cd "$dir_scripts" || return 1
|
||||
while IFS= read -r file; do
|
||||
local file_name=${file#"$path"/}
|
||||
file_name=${file_name#"$path"_}
|
||||
if [[ -f $file ]]; then
|
||||
cron_line=$(
|
||||
perl -ne "{
|
||||
print if /.*([\d\*]*[\*-\/,\d]*[\d\*] ){4,5}[\d\*]*[\*-\/,\d]*[\d\*]( |,|\").*$file_name/
|
||||
}" $file 2>/dev/null |
|
||||
perl -pe "{
|
||||
s|[^\d\*]*(([\d\*]*[\*-\/,\d]*[\d\*] ){4,5}[\d\*]*[\*-\/,\d]*[\d\*])( \|,\|\").*/?$file_name.*|\1|g;
|
||||
s|\*([\d\*])(.*)|\1\2|g;
|
||||
s| | |g;
|
||||
}" 2>/dev/null | sort -u | head -1
|
||||
QL_SCRIPT_NAME="$file_name" perl -ne '
|
||||
print "$1\n" if /((?:[\d*][\d*\/,\-]* ){4,5}[\d*][\d*\/,\-]*)(?: |,|").*\Q$ENV{QL_SCRIPT_NAME}\E/;
|
||||
' -- "$file" | sort -u | head -1
|
||||
)
|
||||
[[ -z $cron_line ]] && cron_line=$(grep "cron:" $file | awk -F ":" '{print $2}' | head -1 | xargs)
|
||||
[[ -z $cron_line ]] && cron_line=$(grep "cron " $file | awk -F "cron \"" '{print $2}' | awk -F "\" " '{print $1}' | head -1 | xargs)
|
||||
[[ -z $cron_line ]] && cron_line=$(grep "cron:" "$file" | awk -F ":" '{print $2}' | head -1 | xargs)
|
||||
[[ -z $cron_line ]] && cron_line=$(grep "cron " "$file" | awk -F "cron \"" '{print $2}' | awk -F "\" " '{print $1}' | head -1 | xargs)
|
||||
[[ -z $cron_line ]] && cron_line="$default_cron"
|
||||
cron_name=$(grep "new Env" $file | awk -F "\(" '{print $2}' | awk -F "\)" '{print $1}' | sed 's:.*\('\''\|"\)\([^"'\'']*\)\('\''\|"\).*:\2:' | sed 's:"::g' | sed "s:'::g" | head -1)
|
||||
[[ -z $cron_name ]] && cron_name=$(grep "name:" $file | awk -F ":" '{print $2}' | head -1 | xargs)
|
||||
cron_name=$(grep "new Env" "$file" | awk -F "\(" '{print $2}' | awk -F "\)" '{print $1}' | sed 's:.*\('\''\|"\)\([^"'\'']*\)\('\''\|"\).*:\2:' | sed 's:"::g' | sed "s:'::g" | head -1)
|
||||
[[ -z $cron_name ]] && cron_name=$(grep "name:" "$file" | awk -F ":" '{print $2}' | head -1 | xargs)
|
||||
[[ -z $cron_name ]] && cron_name=$(basename "$file_name")
|
||||
cron_name=${cron_name//$'\r'/}
|
||||
cron_line=${cron_line//$'\r'/}
|
||||
result=$(add_cron_api "$cron_line" "${cmd_task} ${file}" "$cron_name" "$SUB_ID")
|
||||
operand=$file
|
||||
if [[ ! $file =~ ^[[:alnum:]_./-]+$ ]]; then
|
||||
local escaped_quote="'\\''"
|
||||
operand="'${file//\'/$escaped_quote}'"
|
||||
fi
|
||||
result=$(add_cron_api "$cron_line" "${cmd_task} ${operand}" "$cron_name" "$SUB_ID") || { printf '%s\n' "$result" >&2; return 1; }
|
||||
echo -e "$result"
|
||||
if [[ $detail ]]; then
|
||||
detail="${detail}${result}\n"
|
||||
@@ -109,7 +120,7 @@ add_cron() {
|
||||
detail="${result}\n"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
done < "$list_add"
|
||||
notify_api "$(t '%s 新增任务' "$path")" "$detail"
|
||||
}
|
||||
|
||||
@@ -131,17 +142,18 @@ update_repo() {
|
||||
|
||||
local repo_path="${dir_repo}/${uniq_path}"
|
||||
|
||||
make_dir "${dir_scripts}/${uniq_path}"
|
||||
python3 "${dir_shell:-$QL_DIR/shell}/subscription-files.py" parent "$dir_repo" "$uniq_path" || return 1
|
||||
|
||||
local formatUrl="$url"
|
||||
rm -rf ${repo_path} &>/dev/null
|
||||
git_clone_scripts "${formatUrl}" ${repo_path} "${branch}" "${proxy}"
|
||||
rm -rf -- "$repo_path" || return 1
|
||||
git_clone_scripts "${formatUrl}" "$repo_path" "${branch}" "${proxy}"
|
||||
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
t '拉取 %s 成功...\n' "${uniq_path}"
|
||||
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions" "$autoAddCron" "$autoDelCron"
|
||||
else
|
||||
t '拉取 %s 失败,请检查日志...\n' "${uniq_path}"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -164,8 +176,11 @@ update_raw() {
|
||||
local raw_file_name="${uniq_path}.${suffix}"
|
||||
t '开始下载:%s 保存路径:%s\n' "${raw_url}" "$dir_raw/${raw_file_name}"
|
||||
|
||||
[[ $raw_file_name != */* && $raw_file_name != .* ]] || return 1
|
||||
local incoming
|
||||
incoming=$(mktemp "$dir_raw/.ql-download.XXXXXXXX") || return 1
|
||||
set_proxy "$proxy"
|
||||
if wget -q --no-check-certificate -O "$dir_raw/${raw_file_name}.new" "$raw_url"; then
|
||||
if wget -q --no-check-certificate -O "$incoming" "$raw_url"; then
|
||||
exit_status=0
|
||||
else
|
||||
exit_status=$?
|
||||
@@ -173,38 +188,30 @@ update_raw() {
|
||||
unset_proxy
|
||||
|
||||
if [[ $exit_status -eq 0 ]]; then
|
||||
mv "$dir_raw/${raw_file_name}.new" "$dir_raw/${raw_file_name}" || return $?
|
||||
python3 "${dir_shell:-$QL_DIR/shell}/subscription-files.py" copy "$incoming" "$dir_raw" "$raw_file_name" || { rm -f -- "$incoming"; return 1; }
|
||||
rm -f -- "$incoming"
|
||||
t '下载 %s 成功...\n' "${raw_file_name}"
|
||||
cd "$dir_raw" || return $?
|
||||
local filename="raw_${raw_file_name}"
|
||||
local cron_id=$(cat "$list_crontab_user" | grep -E "$cmd_task.* $filename" | perl -pe "s|.*ID=(.*) $cmd_task.* $filename\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
cp -f "$raw_file_name" "$dir_scripts/${filename}" || return $?
|
||||
if [[ -z $cron_id ]] && [[ ${autoAddCron} == true ]]; then
|
||||
cron_line=$(
|
||||
perl -ne "{
|
||||
print if /.*([\d\*]*[\*-\/,\d]*[\d\*] ){4,5}[\d\*]*[\*-\/,\d]*[\d\*]( |,|\").*$raw_file_name/
|
||||
}" $raw_file_name |
|
||||
perl -pe "{
|
||||
s|[^\d\*]*(([\d\*]*[\*-\/,\d]*[\d\*] ){4,5}[\d\*]*[\*-\/,\d]*[\d\*])( \|,\|\").*/?$raw_file_name.*|\1|g;
|
||||
s|\*([\d\*])(.*)|\1\2|g;
|
||||
s| | |g;
|
||||
}" | sort -u | head -1
|
||||
python3 "${dir_shell:-$QL_DIR/shell}/subscription-files.py" copy "$raw_file_name" "$dir_scripts" "$filename" || return 1
|
||||
if [[ ${autoAddCron} == true ]]; then
|
||||
local work
|
||||
work=$(mktemp -d "$dir_raw/.ql-register.XXXXXXXX") || return 1
|
||||
(
|
||||
# Reuse the repository operand decoder and metadata extraction. Do not
|
||||
# interpolate a filename into Perl, grep, or a shell command.
|
||||
python3 "${dir_shell:-$QL_DIR/shell}/subscription-files.py" registered "$list_crontab_user" "$cmd_task" "$filename" raw > "$work/registered" || exit 1
|
||||
[[ -s $work/registered ]] && exit 0
|
||||
printf '%s\n' "$filename" > "$work/added" || exit 1
|
||||
add_cron "$work/added" raw
|
||||
)
|
||||
cron_name=$(grep "new Env" $raw_file_name | awk -F "\(" '{print $2}' | awk -F "\)" '{print $1}' | sed 's:.*\('\''\|"\)\([^"'\'']*\)\('\''\|"\).*:\2:' | sed 's:"::g' | sed "s:'::g" | head -1)
|
||||
[[ -z $cron_name ]] && cron_name="$raw_file_name"
|
||||
[[ -z $cron_line ]] && cron_line=$(grep "cron:" $raw_file_name | awk -F ":" '{print $2}' | head -1 | xargs)
|
||||
[[ -z $cron_line ]] && cron_line=$(grep "cron " $raw_file_name | awk -F "cron \"" '{print $2}' | awk -F "\" " '{print $1}' | head -1 | xargs)
|
||||
[[ -z $cron_line ]] && cron_line="$default_cron"
|
||||
cron_name=${cron_name//$'\r'/}
|
||||
cron_line=${cron_line//$'\r'/}
|
||||
result=$(add_cron_api "$cron_line" "${cmd_task} ${filename}" "$cron_name" "$SUB_ID")
|
||||
echo -e "$result\n"
|
||||
notify_api "$(t '新增任务通知')" "\n$result"
|
||||
# update_cron_api "$cron_line:$cmd_task $filename:$cron_name:$cron_id"
|
||||
local status=$?
|
||||
rm -r -- "$work"
|
||||
return "$status"
|
||||
fi
|
||||
else
|
||||
t '下载 %s 失败,保留之前正常下载的版本...\n' "${raw_file_name}"
|
||||
[[ -f "$dir_raw/${raw_file_name}.new" ]] && rm -f "$dir_raw/${raw_file_name}.new"
|
||||
[[ -f "$incoming" ]] && rm -f "$incoming"
|
||||
return "$exit_status"
|
||||
fi
|
||||
|
||||
@@ -321,13 +328,15 @@ update_qinglong() {
|
||||
|
||||
# Preserve the updater's status through both tee and the final timing output.
|
||||
run_update_logged() (
|
||||
set -o pipefail
|
||||
if [[ "$real_time" == 'true' ]]; then
|
||||
"$@"
|
||||
elif [[ "$no_tee" == 'true' ]]; then
|
||||
"$@" >>"$file_path" 2>&1
|
||||
else
|
||||
"$@" 2>&1 | tee -a "$file_path"
|
||||
local statuses=("${PIPESTATUS[@]}")
|
||||
if [[ ${statuses[0]} -ne 0 ]]; then return "${statuses[0]}"; fi
|
||||
return "${statuses[1]}"
|
||||
fi
|
||||
)
|
||||
|
||||
@@ -350,25 +359,25 @@ diff_scripts() {
|
||||
autoDelCron=${AutoDelCron}
|
||||
fi
|
||||
|
||||
gen_list_repo "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions"
|
||||
gen_list_repo "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions" || return 1
|
||||
|
||||
local list_add="$dir_list_tmp/${uniq_path}_add.list"
|
||||
local list_drop="$dir_list_tmp/${uniq_path}_drop.list"
|
||||
diff_cron "$dir_list_tmp/${uniq_path}_scripts.list" "$dir_list_tmp/${uniq_path}_user.list" $list_add $list_drop
|
||||
diff_cron "$dir_list_tmp/${uniq_path}_scripts.list" "$dir_list_tmp/${uniq_path}_user.list" "$list_add" "$list_drop" || return 1
|
||||
|
||||
if [[ -s $list_drop ]]; then
|
||||
output_list_add_drop $list_drop "失效"
|
||||
output_list_add_drop "$list_drop" "失效"
|
||||
if [[ ${autoDelCron} == true ]]; then
|
||||
del_cron $list_drop $uniq_path
|
||||
del_cron "$list_drop" "$uniq_path" || return 1
|
||||
fi
|
||||
fi
|
||||
if [[ -s $list_add ]]; then
|
||||
output_list_add_drop $list_add "新"
|
||||
output_list_add_drop "$list_add" "新"
|
||||
if [[ ${autoAddCron} == true ]]; then
|
||||
add_cron $list_add $uniq_path
|
||||
add_cron "$list_add" "$uniq_path" || return 1
|
||||
fi
|
||||
fi
|
||||
cd $dir_current
|
||||
cd "$dir_current"
|
||||
}
|
||||
|
||||
## 生成脚本的路径清单文件
|
||||
@@ -380,64 +389,14 @@ gen_list_repo() {
|
||||
local blackword="$4"
|
||||
local dependence="$5"
|
||||
|
||||
rm -f $dir_list_tmp/${uniq_path}*.list &>/dev/null
|
||||
|
||||
cd ${repo_path}
|
||||
|
||||
local extension_string="${6:-$file_extensions}"
|
||||
extension_string="${extension_string//|/ }"
|
||||
extension_string="${extension_string//$'\n'/ }"
|
||||
local -a extensions=() find_args=()
|
||||
IFS=$' \t\n' read -r -a extensions <<< "$extension_string"
|
||||
local extension
|
||||
for extension in "${extensions[@]}"; do
|
||||
if [[ ${#find_args[@]} -gt 0 ]]; then
|
||||
find_args+=(-o)
|
||||
fi
|
||||
find_args+=(-name "*.${extension}")
|
||||
done
|
||||
files=$(find . "${find_args[@]}" | sed 's/^..//')
|
||||
if [[ $path ]]; then
|
||||
files=$(echo "$files" | egrep "$path")
|
||||
fi
|
||||
if [[ $blackword ]]; then
|
||||
files=$(echo "$files" | egrep -v "$blackword")
|
||||
fi
|
||||
|
||||
cp -f $file_notify_js "${dir_scripts}/${uniq_path}"
|
||||
cp -f $file_notify_py "${dir_scripts}/${uniq_path}"
|
||||
|
||||
if [[ $dependence ]]; then
|
||||
cd ${repo_path}
|
||||
results=$(find . "${find_args[@]}" | sed 's/^..//' | egrep "$dependence")
|
||||
for _file in ${results}; do
|
||||
file_path=$(dirname $_file)
|
||||
make_dir "${dir_scripts}/${uniq_path}/${file_path}"
|
||||
cp -f $_file "${dir_scripts}/${uniq_path}/${file_path}"
|
||||
done
|
||||
fi
|
||||
|
||||
if [[ -d $dir_dep ]]; then
|
||||
cp -rf $dir_dep/* "${dir_scripts}/${uniq_path}" &>/dev/null
|
||||
fi
|
||||
|
||||
for file in ${files}; do
|
||||
dirPath=$(dirname "$file")
|
||||
filename=$(basename "$file")
|
||||
filePath="${uniq_path}/${filename}"
|
||||
if [[ $dirPath ]] && [[ $dirPath != '.' ]]; then
|
||||
mkdir -p "${dir_scripts}/${uniq_path}/${dirPath}"
|
||||
filePath="${uniq_path}/${dirPath}/${filename}"
|
||||
fi
|
||||
cp -f $file "${dir_scripts}/$filePath"
|
||||
echo "$filePath" >>"$dir_list_tmp/${uniq_path}_scripts.list"
|
||||
# cron_id=$(cat $list_crontab_user | grep -E "$cmd_task.* ${uniq_path}_${filename}" | perl -pe "s|.*ID=(.*) $cmd_task.* ${uniq_path}_${filename}\.*|\1|" | head -1 | awk -F " " '{print $1}')
|
||||
# if [[ $cron_id ]]; then
|
||||
# result=$(update_cron_command_api "$cmd_task ${uniq_path}/${filename}:$cron_id")
|
||||
# fi
|
||||
done
|
||||
grep -E "${cmd_task}.* ${uniq_path}" ${list_crontab_user} | perl -pe "s|.*ID=(.*) ${cmd_task}.* (${uniq_path}.*)\.*|\2|" | awk -F " " '{print $1}' | sort -u >"$dir_list_tmp/${uniq_path}_user.list"
|
||||
cd $dir_current
|
||||
local scripts_list="$dir_list_tmp/${uniq_path}_scripts.list"
|
||||
mkdir -p "$(dirname "$scripts_list")" || return 1
|
||||
python3 "${dir_shell:-$QL_DIR/shell}/subscription-files.py" repo "$repo_path" "$dir_scripts" "$uniq_path" "$scripts_list" \
|
||||
"$dir_dep" "$file_notify_js" "$file_notify_py" "$path" "$blackword" "$dependence" "${6:-$file_extensions}" || return 1
|
||||
python3 "${dir_shell:-$QL_DIR/shell}/subscription-files.py" registered "$list_crontab_user" "$cmd_task" "$uniq_path" repo \
|
||||
> "$dir_list_tmp/${uniq_path}_registered.list" || return 1
|
||||
cut -f2 "$dir_list_tmp/${uniq_path}_registered.list" | sort -u > "$dir_list_tmp/${uniq_path}_user.list" || return 1
|
||||
cd "$dir_current"
|
||||
}
|
||||
|
||||
get_uniq_path() {
|
||||
@@ -486,7 +445,9 @@ main() {
|
||||
local log_dir="${p1}"
|
||||
make_dir "$dir_log/$log_dir"
|
||||
local log_time=$(date "+%Y-%m-%d-%H-%M-%S")
|
||||
local log_path="${log_dir}/${log_time}.log"
|
||||
local run_suffix=""
|
||||
[[ ${QL_TRIGGER_ID:-} =~ ^[a-z0-9-]{1,120}$ ]] && run_suffix="-$QL_TRIGGER_ID"
|
||||
local log_path="${real_log_path:-${log_dir}/${log_time}${run_suffix}.log}"
|
||||
local file_path="$dir_log/$log_path"
|
||||
|
||||
printf -v cmd '2>&1 | tee -a %q' "$file_path"
|
||||
@@ -509,6 +470,8 @@ main() {
|
||||
eval "printf '%s\n' $start_message $cmd"
|
||||
fi
|
||||
|
||||
local ql_execution_id=""
|
||||
if [[ -n $ID && -z ${QL_TRIGGER_ID:-} ]]; then init_execution_id || return 1; fi
|
||||
[[ $ID ]] && update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp"
|
||||
|
||||
local command_status=0
|
||||
@@ -524,12 +487,14 @@ main() {
|
||||
command_status=$?
|
||||
;;
|
||||
extra)
|
||||
eval run_extra_shell $cmd
|
||||
run_update_logged run_extra_shell
|
||||
command_status=$?
|
||||
;;
|
||||
repo)
|
||||
get_uniq_path "$p2" "$p6"
|
||||
if [[ -n $p2 ]]; then
|
||||
update_repo "$p2" "$p3" "$p4" "$p5" "$p6" "$p7" "$p8" "$p9" "$p10"
|
||||
command_status=$?
|
||||
else
|
||||
t '命令输入错误...\n'
|
||||
eval usage $cmd
|
||||
@@ -576,7 +541,10 @@ main() {
|
||||
local end_time=$(format_time "$time_format" "$etime")
|
||||
local end_timestamp=$(format_timestamp "$time_format" "$etime")
|
||||
local diff_time=$(($end_timestamp - $begin_timestamp))
|
||||
[[ $ID ]] && update_cron "\"$ID\"" "1" "$$" "$log_path" "$begin_timestamp" "$diff_time"
|
||||
if [[ $ID ]]; then
|
||||
update_cron "\"$ID\"" "1" "$$" "$log_path" "$begin_timestamp" "$diff_time" "$command_status" "$end_timestamp"
|
||||
record_cron_stat "$ID" "$command_status" "$diff_time" "$end_timestamp"
|
||||
fi
|
||||
|
||||
if [[ "$p1" != "repo" ]] && [[ "$p1" != "raw" ]]; then
|
||||
local end_message
|
||||
|
||||
Reference in new issue
Block a user