fix: preserve task logs and refine editor controls

This commit is contained in:
whyour committed 2026-11-21 01:11:44 +08:00
1 parent 4b3c31c0a7
commit a65d56a980
10 files changed
+356 -49

No files matched your search

+12 -3
View File
@@ -1007,8 +1007,15 @@ export default class CronService {
return;
}
}
const launchCommand = `real_log_path=${shellValue(logPath)} no_delay=true ${this.makeCommand(cron, true)}`;
// Let the independent supervisor own the log, while the command keeps
// writing to a drained pipe even if the worker dies or the log fills up.
const supervisedLog = Boolean(triggerId && outputPath);
const cp = spawnCronCommand(
`real_log_path=${shellValue(logPath)} no_delay=true ${this.makeCommand(cron, true)}`, triggerId,
launchCommand,
triggerId,
undefined,
outputPath,
);
// Install observers before the first await: very short children may already exit.
const { completed } = observeChildProcess(cp, {
@@ -1051,8 +1058,10 @@ export default class CronService {
throw error;
}
},
onStdout: outputPath ? (message) => logStreamManager.write(outputPath, message) : undefined,
onStderr: outputPath ? (message) => logStreamManager.write(outputPath, message) : undefined,
onStdout: outputPath && !supervisedLog ? (message) => logStreamManager.write(outputPath, message) : undefined,
onStderr: supervisedLog
? async (message) => { this.logger.error('[panel][Command supervisor] Task ID: %s, %s', id, message.trim()); }
: outputPath ? (message) => logStreamManager.write(outputPath, message) : undefined,
});
const result = await completed;
state = result.signal ? 'stopped' : result.error || result.code !== 0 ? 'failed' : 'finished';
+2 -1
View File
@@ -7,7 +7,7 @@ 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) {
export function spawnCronCommand(command: string, triggerId?: string, onCommandStart?: (at: number) => void, outputPath?: string) {
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');
@@ -15,6 +15,7 @@ export function spawnCronCommand(command: string, triggerId?: string, onCommandS
receiptPath(triggerId) || '', process.execPath, join(__dirname, 'managedExit.cjs'),
];
if (onCommandStart) args.push('report-start');
if (outputPath) args.push('log-output', outputPath);
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]) {
+41 -6
View File
@@ -7,7 +7,7 @@ import threading
import time
def relay(source, destination):
def relay(source, destination, on_error=None):
with source:
for chunk in iter(lambda: os.read(source.fileno(), 65536), b''):
if destination is None:
@@ -16,10 +16,38 @@ def relay(source, destination):
try:
while remaining:
remaining = remaining[os.write(destination, remaining):]
except OSError:
except OSError as error:
# The worker stopped reading. Continue draining so the user's
# command and its log wrapper can still report their real exit.
destination = None
if on_error is not None:
on_error(error)
def report_log_error(error):
# A missing HTTP worker must not turn an output failure into a task failure.
try:
os.write(2, ('[scheduler] Could not write command log: ' + str(error) + '\n').encode('utf-8'))
except OSError:
pass
def relay_log(source, log_path):
destination = None
try:
try:
destination = os.open(log_path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o666)
except OSError as error:
report_log_error(error)
# Do not forward these bytes to the worker: that would duplicate the log
# and reintroduce a dependency on the worker continuing to read stdout.
relay(source, destination, report_log_error)
finally:
if destination is not None:
try:
os.close(destination)
except OSError as error:
report_log_error(error)
def sync_directory(directory):
@@ -34,16 +62,23 @@ def main():
command, owner, marker, node, reporter = sys.argv[1:6]
if sys.stdin.buffer.read() != b'run\n':
return 125
options = sys.argv[6:]
report_start = options[:1] == ['report-start']
if report_start:
options = options[1:]
log_path = options[1] if len(options) == 2 and options[0] == 'log-output' else None
child = subprocess.Popen(['/bin/bash', '-c', command], stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if sys.argv[6:] == ['report-start']:
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT if log_path else subprocess.PIPE)
if 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))]
streams = ([threading.Thread(target=relay_log, args=(child.stdout, log_path))]
if log_path else [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()
+86 -4
View File
@@ -156,6 +156,37 @@ body {
}
}
.editor-wrap-setting {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 4px 8px;
border: 1px solid @border-color-base;
border-radius: 6px;
background: @component-background;
white-space: nowrap;
}
.editor-wrap-label {
color: @text-color-secondary;
font-size: 12px;
}
body[data-mode='phone'] {
.ql-container-wrapper .ant-page-header-heading-extra {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
}
.config-wrapper .config-select {
width: min(38vw, 140px);
}
}
.ant-tree {
.ant-tree-treenode {
width: 100%;
@@ -413,15 +444,19 @@ body[data-mode='phone'] .side-menu-user-wrapper {
.ant-pro-sider-logo {
padding-inline: 5px !important;
.title {
.brand-title {
display: flex;
flex: 1;
align-items: center;
min-width: 0;
height: 32px;
margin: 0 5px;
font-weight: 600;
font-size: 16px;
line-height: 32px;
vertical-align: middle;
line-height: 18px;
white-space: nowrap;
animation: pro-layout-title-hide 0.3s;
gap: 6px;
a {
display: inline-flex;
@@ -429,12 +464,55 @@ body[data-mode='phone'] .side-menu-user-wrapper {
}
}
.brand-name {
flex: 0 0 auto;
font-size: 18px;
line-height: 22px;
}
> a {
min-width: 0;
width: 100%;
}
.ant-image {
flex-shrink: 0;
}
img {
width: 32px !important;
border-radius: 52% !important;
}
}
.brand-version-link {
display: inline-flex;
flex: 0 1 auto;
align-items: center;
min-width: 0;
max-width: 100px;
padding-right: 4px;
cursor: pointer;
line-height: 14px;
.ant-badge {
min-width: 0;
max-width: 100%;
}
}
.brand-version {
display: block;
overflow: hidden;
text-overflow: ellipsis;
color: #595959;
font-size: 11px;
font-weight: 400;
line-height: 14px;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.ant-pro-global-header-logo {
a img {
// 移动端logo被拉伸
@@ -490,7 +568,7 @@ textarea.ant-input {
.ant-pro-sider-collapsed,
body[data-mode='phone'] header {
.title {
.brand-title {
display: none;
}
}
@@ -510,6 +588,10 @@ body[data-mode='phone'] header {
}
body[data-dark='true'] {
.brand-version {
color: #a6adb4;
}
.upgrade-notice {
background: #3a3214;
border-color: #6b5415;
+19 -31
View File
@@ -278,12 +278,6 @@ export default function () {
}
}
const isFirefox = navigator.userAgent.includes('Firefox');
const isSafari =
navigator.userAgent.includes('Safari') &&
!navigator.userAgent.includes('Chrome');
const isQQBrowser = navigator.userAgent.includes('QQBrowser');
const menu: MenuProps = {
items: [
{
@@ -304,36 +298,30 @@ export default function () {
logo={
<>
<Image preview={false} src="https://qn.whyour.cn/logo.png" />
<div className="title">
<span className="title">{intl.get('青龙')}</span>
<span
onClick={(e) => {
e.stopPropagation();
window.open(systemInfo?.changeLogLink, '_blank');
}}
>
<div className="brand-title">
<span className="brand-name">{intl.get('青龙')}</span>
{systemInfo?.version && (
<Tooltip
title={
systemInfo?.branch === 'develop'
title={`v${systemInfo.version} · ${
systemInfo.branch === 'develop'
? intl.get('开发版')
: intl.get('正式版')
}
}`}
>
<Badge size="small" dot={systemInfo?.branch === 'develop'}>
<span
style={{
fontSize: isFirefox ? 9 : 12,
color: '#666',
marginLeft: 2,
zoom: isSafari ? 0.66 : 0.8,
letterSpacing: isQQBrowser ? -2 : 0,
}}
>
v{systemInfo?.version}
</span>
</Badge>
<span
className="brand-version-link"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
window.open(systemInfo.changeLogLink, '_blank');
}}
>
<Badge size="small" dot={systemInfo.branch === 'develop'}>
<span className="brand-version">v{systemInfo.version}</span>
</Badge>
</span>
</Tooltip>
</span>
)}
</div>
</>
}
+2 -2
View File
@@ -110,8 +110,8 @@ const Config = () => {
defaultValue="config.sh"
onSelect={onSelect}
/>,
<Space key="word-wrap" size={8}>
<span>{intl.get('自动换行')}</span>
<Space key="word-wrap" size={8} className="editor-wrap-setting">
<span className="editor-wrap-label">{intl.get('自动换行')}</span>
<Switch
aria-label={intl.get('自动换行')}
checked={wordWrap}
+2 -2
View File
@@ -483,8 +483,8 @@ const Script = () => {
</>
}
extra={[
<Space key="word-wrap" size={8}>
<span>{intl.get('自动换行')}</span>
<Space key="word-wrap" size={8} className="editor-wrap-setting">
<span className="editor-wrap-label">{intl.get('自动换行')}</span>
<Switch
aria-label={intl.get('自动换行')}
checked={wordWrap}
+93
View File
@@ -0,0 +1,93 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { once } = require('node:events');
const { spawnCronCommand, releaseCronCommand } = require('../../back/shared/cronCommandProcess');
const { observeChildProcess } = require('../../back/shared/childProcess');
const { shellQuote } = require('../../back/shared/shellQuote');
async function fixture(t) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-supervisor-log-'));
const previous = process.env.QL_DATA_DIR;
process.env.QL_DATA_DIR = root;
t.after(async () => {
if (previous === undefined) delete process.env.QL_DATA_DIR;
else process.env.QL_DATA_DIR = previous;
await fs.rm(root, { recursive: true, force: true });
});
return root;
}
function nodeCommand(code) {
return `${shellQuote(process.execPath)} -e ${shellQuote(code)}`;
}
test('supervisor appends complete merged output once and preserves start telemetry and exit status', { timeout: 10000 }, async t => {
const root = await fixture(t);
const log = path.join(root, "log's $name.log");
const output = '尾行 '.repeat(100000);
await fs.writeFile(log, 'previous\n');
let started;
let forwarded = '';
const child = spawnCronCommand(nodeCommand(`const fs=require('node:fs');const b=Buffer.from('尾行 '.repeat(100000));let i=0;while(i<b.length)i+=fs.writeSync(1,b,i,b.length-i);fs.writeSync(2,'STDERR\\n');process.exitCode=17;`),
'log-append', value => { started = value; }, log);
const result = await observeChildProcess(child, {
onStart: () => releaseCronCommand(child),
onStdout: async text => { forwarded += text; },
onStderr: async text => { forwarded += text; },
}).completed;
assert.equal(result.code, 17);
assert.equal(result.error, undefined);
assert.equal(forwarded, '');
assert.ok(Number.isInteger(started) && Math.abs(Date.now() - started) < 10000);
assert.equal(await fs.readFile(log, 'utf8'), 'previous\n' + output + 'STDERR\n');
});
for (const fault of ['open', 'full']) {
for (const disconnected of [false, true]) {
test(`log ${fault} failure drains output without interrupting command (reader disconnected=${disconnected})`,
{ timeout: 10000, skip: fault === 'full' && process.platform !== 'linux' }, async t => {
const root = await fixture(t);
const marker = path.join(root, 'completed');
// A directory fails at open; /dev/full opens but every write fails ENOSPC.
const log = fault === 'open' ? root : '/dev/full';
const code = `const fs=require('node:fs');const b=Buffer.alloc(65536,120);for(let n=0;n<64;n++){let i=0;while(i<b.length)i+=fs.writeSync(n%2?2:1,b,i,b.length-i);}fs.writeFileSync(${JSON.stringify(marker)},'completed');`;
const child = spawnCronCommand(nodeCommand(code), 'log-fault', undefined, log);
let result, errors = '';
if (disconnected) {
const closed = once(child, 'close');
child.stdout.destroy();
child.stderr.destroy();
await releaseCronCommand(child);
const [code, signal] = await closed;
result = { code, signal };
} else {
result = await observeChildProcess(child, {
onStart: () => releaseCronCommand(child),
onStderr: async text => { errors += text; },
}).completed;
assert.equal(result.error, undefined);
assert.equal((errors.match(/Could not write command log/g) || []).length, 1);
assert.match(errors, fault === 'full' ? /No space left/ : /Is a directory/);
}
assert.equal(result.code, 0);
assert.equal(result.signal, null);
assert.equal(await fs.readFile(marker, 'utf8'), 'completed');
});
}
}
test('cancelled launch neither creates a log nor executes the command', { timeout: 10000 }, async t => {
const root = await fixture(t);
const marker = path.join(root, 'executed');
const log = path.join(root, 'cancelled.log');
const child = spawnCronCommand(nodeCommand(`require('node:fs').writeFileSync(${JSON.stringify(marker)},'bad')`),
'log-cancel', undefined, log);
const closed = once(child, 'close');
child.stdin.end();
assert.equal((await closed)[0], 125);
await assert.rejects(fs.access(log), { code: 'ENOENT' });
await assert.rejects(fs.access(marker), { code: 'ENOENT' });
});
+61
View File
@@ -0,0 +1,61 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { fork } = require('node:child_process');
const { once } = require('node:events');
async function waitFor(read, predicate) {
const deadline = Date.now() + 10000;
while (Date.now() < deadline) {
const value = await read().catch(error => {
if (error.code !== 'ENOENT') throw error;
});
if (predicate(value)) return value;
await new Promise(resolve => setTimeout(resolve, 20));
}
throw Error('Timed out waiting for command evidence');
}
for (const crash of [false, true]) {
test(`manual compound command keeps complete, nonduplicated logs (worker crash=${crash})`, { timeout: 20000 }, async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-survival-'));
const gate = path.join(root, 'continue');
const script = path.join(root, 'command.sh');
await fs.writeFile(script, `#!/bin/bash\necho BEFORE\nwhile [ ! -f '${gate}' ]; do sleep 0.02; done\necho '尾行 AFTER'\necho STDERR >&2\n`);
const command = `bash '${script}'; echo COMPOUND; exit 17`;
const worker = fork(path.resolve('test/helpers/manual-log-worker.cjs'), [root, command], {
execArgv: ['-r', require.resolve('ts-node/register/transpile-only')],
env: { ...process.env, TS_NODE_PROJECT: 'back/tsconfig.json' },
stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
});
let supervisor;
const messages = [];
worker.on('message', value => messages.push(value));
const exited = once(worker, 'exit');
t.after(async () => {
await fs.writeFile(gate, 'continue');
worker.kill('SIGKILL');
if (supervisor) { try { process.kill(supervisor, 'SIGKILL'); } catch {} }
await fs.rm(root, { recursive: true, force: true });
});
const launched = await waitFor(async () => messages.find(x => x.pid), Boolean);
supervisor = launched.pid;
const log = path.join(root, launched.log);
await waitFor(() => fs.readFile(log, 'utf8'), text => text?.includes('BEFORE'));
if (crash) {
worker.kill('SIGKILL');
await exited;
}
await fs.writeFile(gate, 'continue');
if (crash) {
const receipt = await waitFor(() => fs.readFile(path.join(root, 'receipt.json'), 'utf8'), Boolean);
assert.equal(JSON.parse(receipt).code, 17);
} else {
await exited;
assert.equal(messages.find(x => x.result)?.result.code, 17);
}
assert.equal(await fs.readFile(log, 'utf8'), 'BEFORE\n尾行 AFTER\nSTDERR\nCOMPOUND\n');
});
}
+38
View File
@@ -0,0 +1,38 @@
// Real service launch and Python supervisor; isolate database bookkeeping only.
const path = require('node:path');
const fs = require('node:fs');
const load = require('./load-security-module.cjs');
const { spawn } = require('cross-spawn');
const { LogStreamManager } = require('../../back/shared/logStreamManager');
const [root, command] = process.argv.slice(2);
process.env.QL_DATA_DIR = root;
const reporter = path.join(root, 'reporter.cjs');
fs.writeFileSync(reporter, `require('node:fs').writeFileSync(${JSON.stringify(path.join(root, 'receipt.json'))}, process.argv[2]);`);
const Service = load('back/services/cron.ts', {
'../config': { logPath: root },
'../data/cron': {
CrontabStatus: { queued: 3, running: 0, idle: 1 },
CrontabModel: { update: async () => [1] },
},
'../data/runningInstance': {},
'../config/util': { getUniqPath: async () => "log's $directory" },
'../schedule/client': {},
'../shared/pLimit': { manualRunWithCronLimit: fn => fn() },
'../shared/triggerHistory': { TriggerHistory: class {
async bindCommand(_, pid, log) { process.send({ pid, log }); return true; }
async shouldStop() { return false; }
async complete() {}
} },
'../shared/logStreamManager': { logStreamManager: new LogStreamManager(root) },
'cross-spawn': { spawn: (file, args, options) => {
// Record the real supervisor's receipt without starting a panel database.
if (file === 'python3') args[7] = reporter;
return spawn(file, args, options);
} },
}).default;
const service = new Service({ info() {}, error(...args) { console.error(...args); } });
service.getDb = async () => ({ id: 1, status: 3, command, queued_token: 'test', log_path: '' });
service.makeCommand = () => command;
service.runSingle(1, 'test', 'manual-log-test').then(result => {
process.send({ result }, () => process.disconnect());
});