mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 09:45:36 +08:00
feat(cron): expose run receipts and modularize execution
Return committed trigger IDs and add CLI wait and trigger-specific logs while preserving API, CLI, transaction, deduplication and unknown-result semantics. Move scheduling, lifecycle, settlement, queries and legacy adapters into back/cron; remove obsolete internal import paths and circular dependencies. Apply project formatting across the repository, cover CJS/MJS in formatting hooks, add prettier:check and require formatting checks in AGENTS.md. Validation: backend build; 1398 backend/frontend tests passed (17 platform skips); 327 CLI tests passed (6 platform skips); 670 files pass format checks.
This commit is contained in:
1 parent
77ece406ac
commit
c5458596c8
346 files changed
+32133
-11556
No files matched your search
@@ -0,0 +1,11 @@
|
||||
// Match command text literally: looking up a task must never execute its input.
|
||||
export function findCronId(crontab: string, command: string): string {
|
||||
if (!command) return '';
|
||||
for (const line of crontab.split('\n')) {
|
||||
const id = /\bID=(\d+)\s/.exec(line);
|
||||
if (id && line.includes(command, id.index + id[0].length)) {
|
||||
return id[1];
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { join } from 'path';
|
||||
import { existsSync } from 'fs';
|
||||
import { receiptPath } from '../settlement/exitReceipt.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,
|
||||
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');
|
||||
const args = [
|
||||
'-I',
|
||||
'-S',
|
||||
supervisor,
|
||||
command,
|
||||
String(process.pid),
|
||||
receiptPath(triggerId) || '',
|
||||
process.execPath,
|
||||
join(__dirname, '../../shared/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]) {
|
||||
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,930 @@
|
||||
import type { Logger } from 'winston';
|
||||
import { randomUUID } from 'crypto';
|
||||
import {
|
||||
Op,
|
||||
where,
|
||||
col as colFn,
|
||||
FindOptions,
|
||||
QueryTypes,
|
||||
Transaction,
|
||||
} from 'sequelize';
|
||||
import config from '../../config/index';
|
||||
import { Crontab, CrontabModel, CrontabStatus } from '../../data/cron';
|
||||
import {
|
||||
RunningInstanceModel,
|
||||
InstanceStatus,
|
||||
} from '../../data/runningInstance';
|
||||
import { TriggerHistory, TriggerState } from '../history';
|
||||
import {
|
||||
finishStoppedTree,
|
||||
hasLiveCronProcess,
|
||||
pidNamespaceOwner,
|
||||
systemOwner,
|
||||
verifyCronProcess,
|
||||
} from './cronProcess';
|
||||
import { killTask, getUniqPath } from '../../config/util';
|
||||
import { resolveLogPath } from '../../shared/logPath';
|
||||
import { resolveFileAccess } from '../../shared/fileAccess';
|
||||
import { shellValue } from '../scheduling/cronScheduling';
|
||||
import taskLimit from './cronLimit';
|
||||
import { logStreamManager } from '../../shared/logStreamManager';
|
||||
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
|
||||
import { observeChildProcess, asError } from '../../shared/childProcess';
|
||||
import { t } from '../../shared/i18n';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
type BatchStopSnapshot = {
|
||||
docs: Array<
|
||||
Pick<
|
||||
Crontab,
|
||||
| 'id'
|
||||
| 'status'
|
||||
| 'pid'
|
||||
| 'log_path'
|
||||
| 'queued_token'
|
||||
| 'last_execution_time'
|
||||
>
|
||||
>;
|
||||
instances: Array<{ id?: number; cron_id: number; pid?: number }>;
|
||||
cancelled: string[];
|
||||
missingPids?: number[];
|
||||
missingTargets?: string[];
|
||||
identityConflict: boolean;
|
||||
};
|
||||
|
||||
type StopResult = { code: number; message: string; data?: { outcome: string } };
|
||||
|
||||
// Boundary to the existing service facade; no dependency on CronService itself.
|
||||
export interface CronExecutionHost {
|
||||
getDb(query: FindOptions<Crontab>['where']): Promise<Crontab>;
|
||||
makeCommand(tab: Crontab, realTime?: boolean): string;
|
||||
runSingle(
|
||||
cronId: number,
|
||||
expectedToken?: string,
|
||||
triggerId?: string,
|
||||
submitted?: Crontab,
|
||||
): Promise<number | void>;
|
||||
stopInstance(cronId: number, instanceId: number): Promise<StopResult>;
|
||||
stop(ids: number[], requestId?: string): Promise<void>;
|
||||
}
|
||||
|
||||
export class CronExecution {
|
||||
constructor(private logger: Logger, private host: CronExecutionHost) {}
|
||||
|
||||
public async run(ids: number[], source: 'manual' | 'boot' = 'manual') {
|
||||
const token = randomUUID();
|
||||
const database = CrontabModel.sequelize!;
|
||||
const history = new TriggerHistory(database);
|
||||
const submission = await database.transaction(async (transaction) => {
|
||||
const rows = await CrontabModel.findAll({
|
||||
where: { id: ids },
|
||||
transaction,
|
||||
});
|
||||
const accepted: Crontab[] = [];
|
||||
const triggers: Array<{
|
||||
taskId: number;
|
||||
triggerId: string;
|
||||
state: 'queued' | 'skipped';
|
||||
reason: 'overlap' | null;
|
||||
}> = [];
|
||||
for (const row of rows) {
|
||||
const id = row.id!;
|
||||
const trigger = token + '-' + id;
|
||||
await history.enqueue(
|
||||
trigger,
|
||||
id,
|
||||
source,
|
||||
null,
|
||||
Date.now(),
|
||||
transaction,
|
||||
);
|
||||
if (
|
||||
!row.allow_multiple_instances &&
|
||||
(hasLiveCronProcess(row.status, row.pid) ||
|
||||
(await history.isRunning(id, transaction)))
|
||||
) {
|
||||
await history.finish(
|
||||
trigger,
|
||||
'skipped',
|
||||
'overlap',
|
||||
null,
|
||||
transaction,
|
||||
);
|
||||
triggers.push({
|
||||
taskId: id,
|
||||
triggerId: trigger,
|
||||
state: 'skipped',
|
||||
reason: 'overlap',
|
||||
});
|
||||
} else {
|
||||
accepted.push(row.get({ plain: true }));
|
||||
triggers.push({
|
||||
taskId: id,
|
||||
triggerId: trigger,
|
||||
state: 'queued',
|
||||
reason: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.queued, queued_token: token },
|
||||
{
|
||||
where: { id: accepted.map((row) => row.id!) },
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
return { queued: accepted, triggers };
|
||||
});
|
||||
for (const row of submission.queued) {
|
||||
const id = row.id!;
|
||||
void this.host
|
||||
.runSingle(id, token, token + '-' + id, row)
|
||||
.catch((err) => this.logger.error(String(err)));
|
||||
}
|
||||
return submission.triggers;
|
||||
}
|
||||
|
||||
private readonly stoppingBatches = new Map<string, Promise<void>>();
|
||||
|
||||
public async stop(ids: number[], requestId?: string) {
|
||||
if (!ids.length && !requestId) return;
|
||||
const targets = [...new Set(ids)].sort((a, b) => a - b);
|
||||
const cronIds = JSON.stringify(targets);
|
||||
if (!requestId) return this.stopBatch(targets, cronIds);
|
||||
const key = requestId + '/' + cronIds;
|
||||
const pending = this.stoppingBatches.get(key);
|
||||
if (pending) return pending;
|
||||
// The database arbitrates different payloads and competing workers.
|
||||
const done = this.stopBatch(targets, cronIds, requestId).finally(() =>
|
||||
this.stoppingBatches.delete(key),
|
||||
);
|
||||
this.stoppingBatches.set(key, done);
|
||||
return done;
|
||||
}
|
||||
|
||||
private async stopBatch(ids: number[], cronIds: string, requestId?: string) {
|
||||
const database = CrontabModel.sequelize!;
|
||||
const history = new TriggerHistory(database);
|
||||
const snapshot = await database.transaction(
|
||||
{ type: Transaction.TYPES.IMMEDIATE },
|
||||
async (transaction): Promise<BatchStopSnapshot | null> => {
|
||||
if (requestId) {
|
||||
const [existing] = await database.query<{
|
||||
cron_ids: string;
|
||||
snapshot: string | null;
|
||||
status_code: number;
|
||||
}>(
|
||||
'SELECT cron_ids,snapshot,status_code FROM CronStopBatches WHERE request_id=$requestId',
|
||||
{ transaction, bind: { requestId }, type: QueryTypes.SELECT },
|
||||
);
|
||||
if (existing) {
|
||||
if (existing.cron_ids !== cronIds)
|
||||
throw Object.assign(
|
||||
new Error('Idempotency-Key already used for different tasks'),
|
||||
{ status: 409 },
|
||||
);
|
||||
if (existing.status_code === 409)
|
||||
throw Object.assign(new Error(t('实例不存在或已停止')), {
|
||||
status: 409,
|
||||
});
|
||||
return existing.snapshot ? JSON.parse(existing.snapshot) : null;
|
||||
}
|
||||
}
|
||||
const docs = await CrontabModel.findAll({
|
||||
attributes: [
|
||||
'id',
|
||||
'status',
|
||||
'pid',
|
||||
'log_path',
|
||||
'queued_token',
|
||||
'last_execution_time',
|
||||
],
|
||||
where: { id: ids },
|
||||
transaction,
|
||||
raw: true,
|
||||
});
|
||||
const cancelled = await history.cancelQueuedInTransaction(
|
||||
ids,
|
||||
transaction,
|
||||
);
|
||||
const instances = await RunningInstanceModel.findAll({
|
||||
attributes: ['id', 'cron_id', 'pid'],
|
||||
where: { cron_id: ids, status: InstanceStatus.running },
|
||||
transaction,
|
||||
raw: true,
|
||||
});
|
||||
const { missingTargets, identityConflict } =
|
||||
await this.attachLegacyStopTargets(
|
||||
docs,
|
||||
instances,
|
||||
history,
|
||||
transaction,
|
||||
);
|
||||
for (const instance of instances) {
|
||||
if (instance.pid)
|
||||
await history.queueInstanceStop(
|
||||
instance.id!,
|
||||
instance.cron_id,
|
||||
instance.pid,
|
||||
transaction,
|
||||
);
|
||||
}
|
||||
for (const doc of docs) {
|
||||
if (doc.status === CrontabStatus.queued) {
|
||||
await CrontabModel.update(
|
||||
{
|
||||
status: CrontabStatus.idle,
|
||||
pid: null,
|
||||
queued_token: null,
|
||||
} as any,
|
||||
{
|
||||
where: { id: doc.id, status: CrontabStatus.queued },
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
const batch = {
|
||||
docs,
|
||||
cancelled,
|
||||
instances,
|
||||
missingTargets,
|
||||
identityConflict,
|
||||
};
|
||||
if (requestId) {
|
||||
await database.query(
|
||||
'INSERT INTO CronStopBatches(request_id,cron_ids,snapshot) VALUES ($requestId,$cronIds,$snapshot)',
|
||||
{
|
||||
transaction,
|
||||
bind: { requestId, cronIds, snapshot: JSON.stringify(batch) },
|
||||
},
|
||||
);
|
||||
}
|
||||
return batch;
|
||||
},
|
||||
);
|
||||
if (!snapshot) return;
|
||||
const {
|
||||
docs,
|
||||
cancelled,
|
||||
instances,
|
||||
missingPids,
|
||||
missingTargets,
|
||||
identityConflict,
|
||||
} = snapshot;
|
||||
if (cancelled.length)
|
||||
process.send?.({ type: 'cancel-queued-triggers', ids: cancelled });
|
||||
const stopped = new Set(missingTargets);
|
||||
let failure: Error | undefined;
|
||||
for (const instance of instances) {
|
||||
try {
|
||||
const result = await this.host.stopInstance(
|
||||
instance.cron_id,
|
||||
instance.id!,
|
||||
);
|
||||
if (result.code === 409)
|
||||
failure ??= Object.assign(new Error(result.message), { status: 409 });
|
||||
if (
|
||||
instance.pid &&
|
||||
'data' in result &&
|
||||
result.data?.outcome === 'stopped'
|
||||
)
|
||||
stopped.add(instance.cron_id + '/' + instance.pid);
|
||||
} catch (error) {
|
||||
failure ??= asError(error);
|
||||
}
|
||||
}
|
||||
for (const doc of docs) {
|
||||
if (
|
||||
doc.status !== CrontabStatus.running ||
|
||||
(doc.pid &&
|
||||
!missingPids?.includes(doc.pid) &&
|
||||
!stopped.has(doc.id + '/' + doc.pid))
|
||||
)
|
||||
continue;
|
||||
const remaining = await RunningInstanceModel.count({
|
||||
where: { cron_id: doc.id, status: InstanceStatus.running },
|
||||
});
|
||||
if (remaining) continue;
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: null, queued_token: null } as any,
|
||||
{
|
||||
where: {
|
||||
id: doc.id,
|
||||
status: CrontabStatus.running,
|
||||
[Op.and]: [
|
||||
where(colFn('queued_token'), {
|
||||
[Op.eq]: doc.queued_token ?? null,
|
||||
}),
|
||||
where(colFn('pid'), { [Op.eq]: doc.pid ?? null }),
|
||||
where(colFn('log_path'), { [Op.eq]: doc.log_path ?? null }),
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
if (failure) throw failure;
|
||||
// Retain the key after success. Even a much later retry must never take a new snapshot.
|
||||
if (requestId)
|
||||
await database.query(
|
||||
'UPDATE CronStopBatches SET snapshot=NULL,status_code=$status WHERE request_id=$requestId AND snapshot IS NOT NULL',
|
||||
{ bind: { requestId, status: identityConflict ? 409 : 200 } },
|
||||
);
|
||||
if (identityConflict)
|
||||
throw Object.assign(new Error(t('实例不存在或已停止')), { status: 409 });
|
||||
}
|
||||
|
||||
// Older databases may have a PID or command receipt without an instance.
|
||||
// Attach verified targets before releasing the stop snapshot transaction.
|
||||
private async attachLegacyStopTargets(
|
||||
docs: BatchStopSnapshot['docs'],
|
||||
instances: BatchStopSnapshot['instances'],
|
||||
history: TriggerHistory,
|
||||
transaction: Transaction,
|
||||
) {
|
||||
const commands = await history.activeCommands(
|
||||
docs.map((doc) => doc.id!),
|
||||
transaction,
|
||||
);
|
||||
const registered = new Set(
|
||||
instances.map((row) => row.cron_id + '/' + row.pid),
|
||||
);
|
||||
const registeredPids = new Set(instances.map((row) => row.pid));
|
||||
const legacy = new Map<
|
||||
string,
|
||||
{
|
||||
pid: number;
|
||||
cronId: number;
|
||||
trigger?: string;
|
||||
identity?: string;
|
||||
started?: number;
|
||||
log?: string;
|
||||
}
|
||||
>();
|
||||
for (const doc of docs) {
|
||||
const key = doc.id + '/' + doc.pid;
|
||||
if (
|
||||
doc.status === CrontabStatus.running &&
|
||||
doc.pid &&
|
||||
!registered.has(key)
|
||||
)
|
||||
legacy.set(key, {
|
||||
pid: doc.pid,
|
||||
cronId: doc.id!,
|
||||
started: doc.last_execution_time,
|
||||
log: doc.log_path,
|
||||
});
|
||||
}
|
||||
for (const command of commands) {
|
||||
const pid = Number(command.command_identity.split(':')[1]);
|
||||
const key = command.cron_id + '/' + pid;
|
||||
if (!registered.has(key))
|
||||
legacy.set(key, {
|
||||
pid,
|
||||
cronId: command.cron_id,
|
||||
trigger: command.id,
|
||||
identity: command.command_identity,
|
||||
started: Math.floor(command.started_at / 1000),
|
||||
log: command.log_path,
|
||||
});
|
||||
}
|
||||
let identityConflict = false;
|
||||
const missingTargets: string[] = [];
|
||||
for (const target of legacy.values()) {
|
||||
const { pid } = target;
|
||||
// A different task already owns this PID in the snapshot.
|
||||
if (registeredPids.has(pid)) {
|
||||
identityConflict = true;
|
||||
continue;
|
||||
}
|
||||
let identity: string;
|
||||
try {
|
||||
identity = systemOwner(pid);
|
||||
verifyCronProcess(pid, target.cronId, target.identity, target.started);
|
||||
} catch (error) {
|
||||
if (
|
||||
['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)
|
||||
)
|
||||
missingTargets.push(target.cronId + '/' + pid);
|
||||
else if ((error as { status?: number }).status === 409)
|
||||
identityConflict = true;
|
||||
else throw error;
|
||||
continue;
|
||||
}
|
||||
const row = await RunningInstanceModel.create(
|
||||
{
|
||||
cron_id: target.cronId,
|
||||
pid,
|
||||
status: InstanceStatus.running,
|
||||
started_at: target.started || dayjs().unix(),
|
||||
log_path: target.log,
|
||||
},
|
||||
{ transaction },
|
||||
);
|
||||
if (target.trigger)
|
||||
await CrontabModel.sequelize!.query(
|
||||
"UPDATE CronTriggers SET instance_id=$id,process_identity=$identity WHERE id=$trigger AND state='running'",
|
||||
{
|
||||
transaction,
|
||||
bind: { id: row.id, identity, trigger: target.trigger },
|
||||
},
|
||||
);
|
||||
await history.queueInstanceStop(
|
||||
row.id!,
|
||||
target.cronId,
|
||||
pid,
|
||||
transaction,
|
||||
identity,
|
||||
);
|
||||
instances.push({ id: row.id, cron_id: target.cronId, pid });
|
||||
}
|
||||
return { missingTargets, identityConflict };
|
||||
}
|
||||
|
||||
public async resumePendingStops(
|
||||
history: TriggerHistory,
|
||||
requests: Awaited<ReturnType<TriggerHistory['pendingStops']>>,
|
||||
batches: Awaited<ReturnType<TriggerHistory['pendingStopBatches']>> = [],
|
||||
) {
|
||||
for (const row of requests) {
|
||||
try {
|
||||
const result = await this.host.stopInstance(
|
||||
row.cron_id,
|
||||
row.instance_id,
|
||||
);
|
||||
if (result.code !== 200) this.logger.warn(result.message);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
t('[panel][停止实例失败] 实例ID: %s, PID: %s, 错误: %s'),
|
||||
row.instance_id,
|
||||
row.pid,
|
||||
asError(error).message,
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const batch of batches) {
|
||||
try {
|
||||
await this.host.stop(JSON.parse(batch.cron_ids), batch.request_id);
|
||||
} catch (error) {
|
||||
this.logger.error(asError(error).message);
|
||||
}
|
||||
}
|
||||
await history.recoverSystemOwners();
|
||||
}
|
||||
|
||||
private readonly stoppingInstances = new Map<
|
||||
string,
|
||||
Promise<{ code: number; message: string; data?: { outcome: string } }>
|
||||
>();
|
||||
|
||||
public stopInstance(cronId: number, instanceId: number) {
|
||||
const key = `${cronId}/${instanceId}`;
|
||||
const pending = this.stoppingInstances.get(key);
|
||||
if (pending) return pending;
|
||||
const stop = this.stopOneInstance(cronId, instanceId).finally(() =>
|
||||
this.stoppingInstances.delete(key),
|
||||
);
|
||||
this.stoppingInstances.set(key, stop);
|
||||
return stop;
|
||||
}
|
||||
|
||||
private async stopOneInstance(cronId: number, instanceId: number) {
|
||||
const ended = {
|
||||
code: 200,
|
||||
data: { outcome: 'ended' },
|
||||
message: t('实例已结束'),
|
||||
};
|
||||
const stopped = {
|
||||
code: 200,
|
||||
data: { outcome: 'stopped' },
|
||||
message: t('实例已停止'),
|
||||
};
|
||||
const history = new TriggerHistory(CrontabModel.sequelize!);
|
||||
const instance = await RunningInstanceModel.findOne({
|
||||
where: { id: instanceId, cron_id: cronId },
|
||||
});
|
||||
if (!instance) {
|
||||
await CrontabModel.sequelize!.query(
|
||||
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId AND cron_id=$cronId',
|
||||
{ bind: { instanceId, cronId } },
|
||||
);
|
||||
return { code: 404, message: t('实例不存在或已停止') };
|
||||
}
|
||||
const pending = await history.pendingStop(instanceId);
|
||||
const savedTargets: string[] = pending?.targets
|
||||
? JSON.parse(pending.targets)
|
||||
: [];
|
||||
const settle = () =>
|
||||
history.stopVerifiedInstance(instanceId, (transaction) =>
|
||||
this.settleLegacyStop(instanceId, cronId, instance.pid, transaction),
|
||||
);
|
||||
const finishClaim = async (claim: NonNullable<typeof pending>) => {
|
||||
await finishStoppedTree(
|
||||
claim.targets ? JSON.parse(claim.targets) : [],
|
||||
claim.signalled_at,
|
||||
);
|
||||
return (await settle()) ? stopped : ended;
|
||||
};
|
||||
const releaseUnsignalled = async (recoverEnded = false) => {
|
||||
const claimed = await history.forgetStop(
|
||||
instanceId,
|
||||
recoverEnded
|
||||
? async (tx) => {
|
||||
await history.recoverSystemOwners(cronId, tx, instanceId);
|
||||
if (
|
||||
(await history.instanceStopRequested(instanceId, tx)) ===
|
||||
undefined
|
||||
)
|
||||
await this.settleLegacyStop(
|
||||
instanceId,
|
||||
cronId,
|
||||
instance.pid,
|
||||
tx,
|
||||
InstanceStatus.unknown,
|
||||
);
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
if (claimed) return finishClaim(claimed);
|
||||
};
|
||||
if (pending?.signalled) return finishClaim(pending);
|
||||
if (instance.status !== InstanceStatus.running) {
|
||||
if (savedTargets.length) await finishStoppedTree(savedTargets);
|
||||
const claimed = pending && (await releaseUnsignalled());
|
||||
return (
|
||||
claimed ??
|
||||
(instance.status === InstanceStatus.stopped ? stopped : ended)
|
||||
);
|
||||
}
|
||||
// A cold restart destroys the old process tree. The same numeric PIDs
|
||||
// may already belong to another execution, even when script and log match.
|
||||
if (
|
||||
pending?.namespace_owner &&
|
||||
pending.namespace_owner !== pidNamespaceOwner()
|
||||
) {
|
||||
return (await releaseUnsignalled(true)) ?? ended;
|
||||
}
|
||||
if (!instance.pid || instance.pid < 1) {
|
||||
return { code: 409, message: t('实例不存在或已停止') };
|
||||
}
|
||||
let identity =
|
||||
pending?.root_identity ||
|
||||
(await history.instanceIdentity(instanceId)) ||
|
||||
savedTargets.find((birth) => birth.startsWith(`crond:${instance.pid}:`));
|
||||
const verify = () =>
|
||||
verifyCronProcess(instance.pid!, cronId, identity, instance.started_at, {
|
||||
logPath: instance.log_path,
|
||||
});
|
||||
if (
|
||||
!identity &&
|
||||
(await RunningInstanceModel.count({
|
||||
where: {
|
||||
id: { [Op.ne]: instanceId },
|
||||
status: InstanceStatus.running,
|
||||
pid: instance.pid,
|
||||
},
|
||||
}))
|
||||
) {
|
||||
const claimed = await releaseUnsignalled();
|
||||
return claimed ?? { code: 409, message: t('实例不存在或已停止') };
|
||||
}
|
||||
try {
|
||||
identity = verify() ?? identity;
|
||||
// Traversing the process tree is asynchronous. Persist the individual
|
||||
// request before traversal so a restart here also resumes this stop.
|
||||
if (!pending || (!pending.root_identity && identity))
|
||||
await history.queueInstanceStop(
|
||||
instanceId,
|
||||
cronId,
|
||||
instance.pid,
|
||||
undefined,
|
||||
identity ?? undefined,
|
||||
);
|
||||
await killTask(instance.pid, true, verify, (signal, targets) =>
|
||||
history.requestInstanceStop(instanceId, instance.pid!, signal, targets),
|
||||
);
|
||||
return (await settle()) ? stopped : ended;
|
||||
} catch (error) {
|
||||
const cause = (error as NodeJS.ErrnoException).code;
|
||||
if (cause === 'ESRCH' || cause === 'PID_REUSED') {
|
||||
if (savedTargets.length) await finishStoppedTree(savedTargets);
|
||||
const claimed = await releaseUnsignalled(true);
|
||||
if (claimed) return claimed;
|
||||
const latest = await RunningInstanceModel.findOne({
|
||||
where: { id: instanceId, cron_id: cronId },
|
||||
});
|
||||
if (latest?.status === InstanceStatus.stopped) return stopped;
|
||||
if (latest?.status === InstanceStatus.running) {
|
||||
const requested = await history.instanceStopRequested(instanceId);
|
||||
if (requested) return stopped;
|
||||
if (cause === 'PID_REUSED' || requested === undefined)
|
||||
return { code: 409, message: t('实例不存在或已停止') };
|
||||
}
|
||||
return ended;
|
||||
}
|
||||
if ((error as { status?: number }).status === 409) {
|
||||
if (savedTargets.length) await finishStoppedTree(savedTargets);
|
||||
const claimed = await releaseUnsignalled();
|
||||
return claimed ?? { code: 409, message: t('实例不存在或已停止') };
|
||||
}
|
||||
this.logger.error(
|
||||
t('[panel][停止实例失败] 实例ID: %s, PID: %s, 错误: %s'),
|
||||
instanceId,
|
||||
instance.pid,
|
||||
error,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async settleLegacyStop(
|
||||
instanceId: number,
|
||||
cronId: number,
|
||||
pid: number | undefined,
|
||||
transaction: Transaction,
|
||||
status = InstanceStatus.stopped,
|
||||
) {
|
||||
const [updated] = await RunningInstanceModel.update(
|
||||
{ status, finished_at: dayjs().unix() },
|
||||
{
|
||||
where: {
|
||||
id: instanceId,
|
||||
cron_id: cronId,
|
||||
status: InstanceStatus.running,
|
||||
},
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
|
||||
if (!updated) {
|
||||
const latest = await RunningInstanceModel.findOne({
|
||||
where: { id: instanceId, cron_id: cronId },
|
||||
transaction,
|
||||
});
|
||||
return latest?.status === InstanceStatus.stopped;
|
||||
}
|
||||
|
||||
// Check if there are still other running instances for this cron
|
||||
const otherRunning = await RunningInstanceModel.count({
|
||||
where: { cron_id: cronId, status: InstanceStatus.running },
|
||||
transaction,
|
||||
});
|
||||
if (otherRunning === 0) {
|
||||
await CrontabModel.update(
|
||||
{ status: CrontabStatus.idle, pid: null } as any,
|
||||
{
|
||||
where: { id: cronId, status: CrontabStatus.running, pid },
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
}
|
||||
return status === InstanceStatus.stopped;
|
||||
}
|
||||
|
||||
public async runSingle(
|
||||
cronId: number,
|
||||
expectedToken?: string,
|
||||
triggerId?: string,
|
||||
submitted?: Crontab,
|
||||
): Promise<number | void> {
|
||||
return taskLimit.manualRunWithCronLimit(
|
||||
async () => {
|
||||
let absolutePath: string | undefined;
|
||||
let logPath: string | undefined;
|
||||
let queuedLogPath: string | null | undefined;
|
||||
let queuedToken: string | null = null;
|
||||
let claimed = false;
|
||||
const history = new TriggerHistory(CrontabModel.sequelize!);
|
||||
let state: TriggerState = 'skipped';
|
||||
let reason: string | null = 'changed';
|
||||
let exitCode: number | null = null;
|
||||
try {
|
||||
const cron = await this.host.getDb({ id: cronId });
|
||||
const independent = Boolean(
|
||||
triggerId &&
|
||||
submitted?.allow_multiple_instances &&
|
||||
cron.allow_multiple_instances,
|
||||
);
|
||||
if (
|
||||
!independent &&
|
||||
(cron.status !== CrontabStatus.queued ||
|
||||
(expectedToken !== undefined &&
|
||||
cron.queued_token !== expectedToken))
|
||||
)
|
||||
return;
|
||||
queuedLogPath = cron.log_path ?? null;
|
||||
if (
|
||||
submitted &&
|
||||
(submitted.recovery_from !== cron.recovery_from ||
|
||||
submitted.isDisabled !== cron.isDisabled ||
|
||||
submitted.command !== cron.command)
|
||||
) {
|
||||
queuedToken = expectedToken ?? null;
|
||||
return;
|
||||
}
|
||||
queuedToken = cron.queued_token ?? null;
|
||||
const { id, command, log_name } = cron;
|
||||
if (log_name === '/dev/null') {
|
||||
logPath = '/dev/null';
|
||||
} else {
|
||||
const uniqPath = log_name
|
||||
? path.relative(
|
||||
config.logPath,
|
||||
resolveLogPath(config.logPath, log_name),
|
||||
)
|
||||
: await getUniqPath(command, `${id}`);
|
||||
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
|
||||
logPath = `${uniqPath}/${logTime}${
|
||||
independent ? '-' + expectedToken : ''
|
||||
}.log`;
|
||||
absolutePath = resolveFileAccess(config.logPath, [logPath]);
|
||||
if (!absolutePath)
|
||||
throw new Error('Log path is outside the log directory');
|
||||
await fs.mkdir(path.dirname(absolutePath), { recursive: true });
|
||||
}
|
||||
const outputPath = absolutePath;
|
||||
if (triggerId && submitted) {
|
||||
const claim = await history.claimManual(
|
||||
triggerId,
|
||||
submitted,
|
||||
expectedToken!,
|
||||
independent,
|
||||
);
|
||||
if (claim !== 'started') {
|
||||
reason = claim;
|
||||
queuedToken = expectedToken!;
|
||||
return;
|
||||
}
|
||||
}
|
||||
const launchCommand = `real_log_path=${shellValue(
|
||||
logPath,
|
||||
)} no_delay=true ${this.host.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(
|
||||
launchCommand,
|
||||
triggerId,
|
||||
undefined,
|
||||
outputPath,
|
||||
);
|
||||
// Install observers before the first await: very short children may already exit.
|
||||
const { completed } = observeChildProcess(cp, {
|
||||
onStart: async () => {
|
||||
try {
|
||||
if (
|
||||
triggerId &&
|
||||
!(await history.bindCommand(triggerId, cp.pid!, logPath))
|
||||
)
|
||||
throw new Error('Task was cancelled before startup');
|
||||
const [count] = await CrontabModel.update(
|
||||
{
|
||||
status: CrontabStatus.running,
|
||||
pid: cp.pid,
|
||||
log_path: logPath,
|
||||
...(!triggerId && {
|
||||
last_execution_time: dayjs().unix(),
|
||||
last_running_time: null,
|
||||
}),
|
||||
},
|
||||
{
|
||||
where: {
|
||||
id,
|
||||
...(independent
|
||||
? {}
|
||||
: {
|
||||
status: CrontabStatus.queued,
|
||||
[Op.and]: [
|
||||
where(colFn('queued_token'), {
|
||||
[Op.eq]: queuedToken,
|
||||
}),
|
||||
where(colFn('log_path'), {
|
||||
[Op.eq]: queuedLogPath,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
},
|
||||
);
|
||||
if (count !== 1)
|
||||
throw new Error(
|
||||
'Task was stopped or superseded before startup',
|
||||
);
|
||||
claimed = true;
|
||||
if (triggerId) {
|
||||
if (await history.shouldStop(triggerId)) cp.stdin.end();
|
||||
else await releaseCronCommand(cp);
|
||||
}
|
||||
} catch (error) {
|
||||
if (triggerId) cp.stdin.destroy();
|
||||
else if (cp.pid) await killTask(cp.pid, true);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
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';
|
||||
reason = result.error ? 'spawn' : result.signal || null;
|
||||
exitCode = result.code;
|
||||
if (result.error) {
|
||||
this.logger.error(
|
||||
t('[panel][执行任务失败] 任务ID: %s, 错误: %s'),
|
||||
id,
|
||||
result.error.message,
|
||||
);
|
||||
}
|
||||
this.logger.info(
|
||||
t('[panel][执行任务结束] 任务ID: %s, 退出码: %j'),
|
||||
id,
|
||||
result.code,
|
||||
);
|
||||
return { ...cron, pid: cp.pid, ...result } as any;
|
||||
} catch (error) {
|
||||
state = 'failed';
|
||||
reason = 'spawn';
|
||||
this.logger.error(
|
||||
t('[panel][创建任务失败] 任务ID: %s, 错误: %s'),
|
||||
cronId,
|
||||
asError(error).message,
|
||||
);
|
||||
} finally {
|
||||
try {
|
||||
if (absolutePath) await logStreamManager.closeStream(absolutePath);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
t('[panel][关闭任务日志失败] %s'),
|
||||
asError(error).message,
|
||||
);
|
||||
}
|
||||
try {
|
||||
// Do not overwrite a newer run's state or its script-reported exit code.
|
||||
await CrontabModel.update(
|
||||
{
|
||||
status: CrontabStatus.idle,
|
||||
pid: null,
|
||||
queued_token: null,
|
||||
} as any,
|
||||
{
|
||||
where: {
|
||||
id: cronId,
|
||||
[Op.and]: where(colFn('queued_token'), {
|
||||
[Op.eq]: queuedToken,
|
||||
}),
|
||||
[Op.or]: [
|
||||
...(queuedLogPath !== undefined && !claimed
|
||||
? [
|
||||
{
|
||||
status: CrontabStatus.queued,
|
||||
[Op.and]: where(colFn('log_path'), {
|
||||
[Op.eq]: queuedLogPath,
|
||||
}),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(claimed && logPath
|
||||
? [{ log_path: logPath, status: CrontabStatus.running }]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
t('[panel][清理任务状态失败] %s'),
|
||||
asError(error).message,
|
||||
);
|
||||
}
|
||||
if (triggerId)
|
||||
await history.complete(triggerId, state, reason, exitCode);
|
||||
}
|
||||
},
|
||||
undefined,
|
||||
{
|
||||
id: triggerId,
|
||||
name: submitted?.name || submitted?.command || String(cronId),
|
||||
},
|
||||
CrontabModel.sequelize,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
|
||||
import os from 'os';
|
||||
import type { Sequelize } from 'sequelize';
|
||||
import {
|
||||
QueueOccupants,
|
||||
recordQueueAdmission,
|
||||
} from '../queries/queueDiagnostics';
|
||||
import { CronWaitQueue, CronQueueOptions } from './cronWaitQueue';
|
||||
import { AuthDataType, SystemModel } from '../../data/system';
|
||||
import Logger from '../../loaders/logger';
|
||||
import { t, tf } from '../../shared/i18n';
|
||||
import type { ICronFn, TCron } from '../../shared/interface';
|
||||
import config from '../../config';
|
||||
import { credentials } from '@grpc/grpc-js';
|
||||
import { ApiClient } from '../../protos/api';
|
||||
import { getGrpcCerts } from '../../config/grpcCerts';
|
||||
|
||||
// One scheduler/manual queue owner per process; services and execution share it.
|
||||
class CronLimit {
|
||||
private queuedCrons = new Map<string, ICronFn<any>[]>();
|
||||
private repeatCronNotifyMap = new Map<string, number>();
|
||||
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({
|
||||
concurrency: Math.max(os.cpus().length, 4),
|
||||
});
|
||||
private _client: ApiClient | null = null;
|
||||
|
||||
private get client(): ApiClient {
|
||||
if (!this._client) {
|
||||
const tlsConfig = getGrpcCerts();
|
||||
const creds = tlsConfig
|
||||
? credentials.createSsl(
|
||||
Buffer.from(tlsConfig.caCert),
|
||||
Buffer.from(tlsConfig.clientKey),
|
||||
Buffer.from(tlsConfig.clientCert),
|
||||
)
|
||||
: credentials.createInsecure();
|
||||
this._client = new ApiClient(`localhost:${config.grpcPort}`, creds, {
|
||||
'grpc.enable_http_proxy': 0,
|
||||
});
|
||||
}
|
||||
return this._client;
|
||||
}
|
||||
|
||||
get cronLimitActiveCount() {
|
||||
return this.cronLimit.pending;
|
||||
}
|
||||
|
||||
get cronLimitPendingCount() {
|
||||
return this.cronLimit.size;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
this.setCustomLimit();
|
||||
this.handleEvents();
|
||||
}
|
||||
|
||||
private handleEvents() {
|
||||
this.cronLimit.on('add', () => {
|
||||
Logger.info(
|
||||
t('[schedule][任务加入队列] 运行中任务数: %s, 等待中任务数: %s'),
|
||||
this.cronLimitActiveCount,
|
||||
this.cronLimitPendingCount,
|
||||
);
|
||||
});
|
||||
this.cronLimit.on('active', () => {
|
||||
Logger.info(
|
||||
t('[schedule][开始处理任务] 运行中任务数: %s, 等待中任务数: %s'),
|
||||
this.cronLimitActiveCount + 1,
|
||||
this.cronLimitPendingCount,
|
||||
);
|
||||
});
|
||||
this.cronLimit.on('completed', (param) => {
|
||||
Logger.info(t('[schedule][任务处理成功] 参数 %s'), JSON.stringify(param));
|
||||
});
|
||||
this.cronLimit.on('error', (error) => {
|
||||
Logger.error(
|
||||
t('[schedule][任务处理错误] 参数 %s'),
|
||||
JSON.stringify(error),
|
||||
);
|
||||
});
|
||||
this.cronLimit.on('next', () => {
|
||||
Logger.info(
|
||||
t('[schedule][任务处理结束] 运行中任务数: %s, 等待中任务数: %s'),
|
||||
this.cronLimitActiveCount,
|
||||
this.cronLimitPendingCount,
|
||||
);
|
||||
});
|
||||
this.cronLimit.on('idle', () => {
|
||||
Logger.info(t(`[schedule][任务队列] 空闲中...`));
|
||||
});
|
||||
}
|
||||
|
||||
public removeQueuedCron(id: string, completed?: ICronFn<any>) {
|
||||
if (this.queuedCrons.has(id)) {
|
||||
const runs = this.queuedCrons.get(id);
|
||||
if (runs && runs.length > 0) {
|
||||
const remaining = completed
|
||||
? runs.filter((run) => run !== completed)
|
||||
: runs.slice(0, -1);
|
||||
if (remaining.length) this.queuedCrons.set(id, remaining);
|
||||
else this.queuedCrons.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
const doc = await SystemModel.findOne({
|
||||
where: { type: AuthDataType.systemConfig },
|
||||
});
|
||||
if (doc?.info?.cronConcurrency) {
|
||||
await this.setCustomLimit(doc.info.cronConcurrency);
|
||||
}
|
||||
}
|
||||
|
||||
public async runWithCronLimit<T>(
|
||||
cron: TCron,
|
||||
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;
|
||||
fn.isCurrent = isCurrent;
|
||||
// Invalidated snapshots must not consume the new revision's repeat budget.
|
||||
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) {
|
||||
if (repeatTimes < 3) {
|
||||
this.repeatCronNotifyMap.set(cron.id, repeatTimes + 1);
|
||||
this.client.systemNotify(
|
||||
{
|
||||
title: t('任务重复运行'),
|
||||
content: tf(
|
||||
'任务:%s,命令:%s,定时:%s,处于运行中的超过 %d 个,请检查定时设置',
|
||||
cron.name || '',
|
||||
cron.command || '',
|
||||
cron.schedule || '',
|
||||
5,
|
||||
),
|
||||
},
|
||||
(err, res) => {
|
||||
if (err) {
|
||||
Logger.error(
|
||||
t('[schedule][任务重复运行] 通知失败 %s'),
|
||||
JSON.stringify(err),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
Logger.warn(t('[schedule][任务重复运行] 参数 %s'), JSON.stringify(cron));
|
||||
return;
|
||||
}
|
||||
this.queuedCrons.set(cron.id, result);
|
||||
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(
|
||||
this.trackAdmission(
|
||||
this.manualOccupants,
|
||||
this.manualCronoLimit.concurrency,
|
||||
fn,
|
||||
occupant,
|
||||
db,
|
||||
),
|
||||
options,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default new CronLimit();
|
||||
@@ -0,0 +1,63 @@
|
||||
// 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,237 @@
|
||||
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,54 @@
|
||||
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,331 @@
|
||||
import { hasLiveCronProcess } from './cronProcess';
|
||||
import { EventEmitter } from 'events';
|
||||
import PQueue from 'p-queue-cjs';
|
||||
import { triggerHistory, TriggerState } from '../history';
|
||||
import { t } from '../../shared/i18n';
|
||||
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
|
||||
import taskLimit from './cronLimit';
|
||||
import Logger from '../../loaders/logger';
|
||||
import { ICron } from '../../protos/cron';
|
||||
import { CrontabModel, CrontabStatus } from '../../data/cron';
|
||||
import {
|
||||
RunningInstanceModel,
|
||||
InstanceStatus,
|
||||
} from '../../data/runningInstance';
|
||||
import dayjs from 'dayjs';
|
||||
import { observeChildProcess, asError } from '../../shared/childProcess';
|
||||
|
||||
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 (!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) },
|
||||
});
|
||||
|
||||
// A mutation may commit while this queued run is reading the database.
|
||||
if (!isCurrent() || !existingCron || existingCron.isDisabled) return;
|
||||
|
||||
// Default to single instance mode (0) for backward compatibility
|
||||
multiple = existingCron.allow_multiple_instances === 1;
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
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(
|
||||
t('[schedule][检查已运行任务失败] 任务ID: %s, 错误: %s'),
|
||||
cron.id,
|
||||
error,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Invalidation can happen during the asynchronous database check.
|
||||
if (!isCurrent()) return;
|
||||
Logger.info(
|
||||
t('[schedule][开始执行任务] 参数 %s'),
|
||||
JSON.stringify({
|
||||
...cron,
|
||||
command: cmd,
|
||||
}),
|
||||
);
|
||||
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'),
|
||||
cmd,
|
||||
message,
|
||||
);
|
||||
},
|
||||
});
|
||||
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'),
|
||||
cmd,
|
||||
result.error.message,
|
||||
);
|
||||
}
|
||||
Logger.info(
|
||||
t('[schedule][执行任务结束] 任务ID: %s, 退出码: %j'),
|
||||
cron.id,
|
||||
result.code,
|
||||
);
|
||||
return { ...cron, command: cmd, pid: cp.pid, ...result } as any;
|
||||
} catch (error) {
|
||||
state = 'failed';
|
||||
reason = 'spawn';
|
||||
Logger.error(
|
||||
t('[schedule][创建任务失败] 命令: %s, 错误: %s'),
|
||||
cmd,
|
||||
asError(error).message,
|
||||
);
|
||||
} finally {
|
||||
taskLimit.removeQueuedCron(cron.id, execute);
|
||||
}
|
||||
};
|
||||
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 },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,806 @@
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
import type { Crontab } from '../../data/cron';
|
||||
import type {
|
||||
TriggerSource,
|
||||
TriggerState,
|
||||
VerifiedSupervisorExit,
|
||||
} from '../types';
|
||||
import type { readExit } from '../settlement/exitReceipt.cjs';
|
||||
import {
|
||||
hasLiveCronProcess,
|
||||
pidNamespaceOwner,
|
||||
systemOwner,
|
||||
} from './cronProcess';
|
||||
|
||||
type ExitReceipt = Awaited<ReturnType<typeof readExit>>;
|
||||
|
||||
// Evidence inspection and settlement remain in the existing ledger. Callers must
|
||||
// use the supplied transaction so state, stop claims and statistics commit together.
|
||||
export interface TriggerLifecycleEvidence {
|
||||
exitBeforeStop(id: string): Promise<{
|
||||
canonical: ExitReceipt;
|
||||
recovered: ExitReceipt[];
|
||||
published: boolean;
|
||||
unreadable: boolean;
|
||||
}>;
|
||||
completeCommandExit(
|
||||
id: string,
|
||||
state: TriggerState,
|
||||
reason: string | null,
|
||||
code: number | null,
|
||||
transaction: Transaction,
|
||||
receipt?: ExitReceipt,
|
||||
finishedAt?: number,
|
||||
report?: VerifiedSupervisorExit | 'legacy',
|
||||
recoveredCopies?: ExitReceipt[],
|
||||
): Promise<void>;
|
||||
recoverScriptSample(id: string, transaction: Transaction): Promise<void>;
|
||||
replayPublishedExits(transaction: Transaction): Promise<void>;
|
||||
}
|
||||
|
||||
// Persisted transitions shared by manual, Node and system-crond executions.
|
||||
// In particular, recovery may reclaim an unstarted slot, never an unknown result.
|
||||
export class TriggerLifecycle {
|
||||
constructor(
|
||||
private database: Sequelize,
|
||||
private evidence: TriggerLifecycleEvidence,
|
||||
) {}
|
||||
|
||||
// Only unclaimed scheduler work can expire; its owner controls claimed runs.
|
||||
async skipQueued(id: string, reason: string, finishedAt: number) {
|
||||
await this.database.query(
|
||||
`UPDATE CronTriggers SET state='skipped', reason=$reason, finished_at=$finishedAt
|
||||
WHERE id=$id AND source IN ('node','recovery') AND state='queued' AND started_at IS NULL`,
|
||||
{ bind: { id, reason, finishedAt }, type: QueryTypes.BULKUPDATE },
|
||||
);
|
||||
}
|
||||
|
||||
async enqueue(
|
||||
id: string,
|
||||
cronId: number,
|
||||
source: TriggerSource,
|
||||
scheduledAt: number | null,
|
||||
now = Date.now(),
|
||||
transaction?: Transaction,
|
||||
) {
|
||||
// The SQLite driver returns changes on the statement that claimed this slot.
|
||||
const changed = await this.database.query(
|
||||
`INSERT INTO CronTriggers(id, cron_id, source, scheduled_at, queued_at, observed_at, owner, state)
|
||||
VALUES ($id,$cronId,$source,$scheduledAt,$now,$now,$owner,'queued')
|
||||
ON CONFLICT(id) DO UPDATE SET state='queued', reason=NULL, finished_at=NULL,
|
||||
queued_at=excluded.queued_at, dequeued_at=NULL, queue_context=NULL, queue_live_context=NULL,
|
||||
source=excluded.source, owner=excluded.owner
|
||||
WHERE excluded.source='recovery' AND state='skipped' AND reason='restart' AND started_at IS NULL`,
|
||||
{
|
||||
bind: {
|
||||
id,
|
||||
cronId,
|
||||
source,
|
||||
scheduledAt,
|
||||
now,
|
||||
owner: process.env.SERVICE_TYPE || 'http',
|
||||
},
|
||||
transaction,
|
||||
type: QueryTypes.BULKUPDATE,
|
||||
},
|
||||
);
|
||||
return changed === 1;
|
||||
}
|
||||
|
||||
// Admission and competing pending runs share one write transaction.
|
||||
async enqueueUnlessPending(
|
||||
id: string,
|
||||
cronId: number,
|
||||
source: 'node' | 'recovery',
|
||||
scheduledAt: number,
|
||||
now: number,
|
||||
revision = 0,
|
||||
) {
|
||||
return this.database.transaction(async (transaction) => {
|
||||
if (
|
||||
!(await this.enqueue(id, cronId, source, scheduledAt, now, transaction))
|
||||
)
|
||||
return false;
|
||||
await this.recoverSystemOwners(cronId, transaction);
|
||||
const pending = await this.database.query(
|
||||
`SELECT 1 FROM CronTriggers WHERE cron_id=$cronId AND id<>$id
|
||||
AND source IN ('node','recovery','system')
|
||||
AND (state='running' OR (state='queued' AND queued_at >= $revision)) LIMIT 1`,
|
||||
{
|
||||
transaction,
|
||||
bind: { cronId, id, revision },
|
||||
type: QueryTypes.SELECT,
|
||||
},
|
||||
);
|
||||
if (!pending.length) return true;
|
||||
await this.finish(id, 'skipped', 'pending', null, transaction);
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
async start(
|
||||
id: string,
|
||||
now = Date.now(),
|
||||
multiple = false,
|
||||
transaction?: Transaction,
|
||||
) {
|
||||
const claim = () =>
|
||||
this.database.query(
|
||||
`UPDATE CronTriggers SET state='running', started_at=$now WHERE id=$id AND state='queued'
|
||||
AND ($multiple OR NOT EXISTS (SELECT 1 FROM CronTriggers AS active
|
||||
WHERE active.cron_id=CronTriggers.cron_id AND active.state='running'))`,
|
||||
{
|
||||
transaction,
|
||||
bind: { id, now, multiple: Number(multiple) },
|
||||
type: QueryTypes.BULKUPDATE,
|
||||
},
|
||||
);
|
||||
let changed = await claim();
|
||||
if (!changed && !multiple && !transaction) {
|
||||
const [task] = await this.database.query<{ cron_id: number }>(
|
||||
"SELECT cron_id FROM CronTriggers WHERE id=$id AND state='queued'",
|
||||
{ bind: { id }, type: QueryTypes.SELECT },
|
||||
);
|
||||
if (task && (await this.recoverSystemOwners(task.cron_id)))
|
||||
changed = await claim();
|
||||
}
|
||||
return changed === 1;
|
||||
}
|
||||
|
||||
async claimManual(
|
||||
id: string,
|
||||
snapshot: Crontab,
|
||||
token: string,
|
||||
independent: boolean,
|
||||
) {
|
||||
return this.database.transaction(async (transaction) => {
|
||||
// The write transaction orders a configuration save and a manual claim.
|
||||
const rows = await this.database.query(
|
||||
`SELECT 1 FROM Crontabs WHERE id=$cronId AND recovery_from IS $revision
|
||||
AND command=$command AND COALESCE(isDisabled,0)=$disabled
|
||||
AND COALESCE(allow_multiple_instances,0)=$multiple
|
||||
AND ($independent OR (status=3 AND queued_token=$token))`,
|
||||
{
|
||||
transaction,
|
||||
type: QueryTypes.SELECT,
|
||||
bind: {
|
||||
cronId: snapshot.id,
|
||||
revision: snapshot.recovery_from ?? null,
|
||||
command: snapshot.command,
|
||||
disabled: snapshot.isDisabled || 0,
|
||||
multiple: snapshot.allow_multiple_instances || 0,
|
||||
independent: Number(independent),
|
||||
token,
|
||||
},
|
||||
},
|
||||
);
|
||||
if (!rows.length) return 'changed';
|
||||
if (!independent)
|
||||
await this.recoverSystemOwners(snapshot.id, transaction);
|
||||
return (await this.start(id, Date.now(), independent, transaction))
|
||||
? 'started'
|
||||
: 'overlap';
|
||||
});
|
||||
}
|
||||
|
||||
async finish(
|
||||
id: string,
|
||||
state: TriggerState,
|
||||
reason: string | null = null,
|
||||
code: number | null = null,
|
||||
transaction?: Transaction,
|
||||
finishedAt?: number,
|
||||
) {
|
||||
// A managed supervisor can observe the clock moving backwards during a run.
|
||||
// Clients supply their own timestamps; validate those against the recorded start.
|
||||
return this.database.query(
|
||||
`UPDATE CronTriggers SET state=$state, reason=$reason, exit_code=$code,
|
||||
started_at=CASE WHEN $state='skipped' THEN NULL ELSE started_at END,
|
||||
finished_at=COALESCE(CASE WHEN owner IS NOT NULL OR $finishedAt >= started_at THEN $finishedAt END,CASE WHEN state='unknown' THEN finished_at END,$now)
|
||||
WHERE id=$id AND (state IN ('running','queued') OR
|
||||
(state='unknown' AND $state IN ('finished','failed','stopped')))`,
|
||||
{
|
||||
transaction,
|
||||
type: QueryTypes.BULKUPDATE,
|
||||
bind: {
|
||||
id,
|
||||
state,
|
||||
reason,
|
||||
code,
|
||||
finishedAt: finishedAt ?? null,
|
||||
now: Date.now(),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async claimSummary(
|
||||
cronId: number,
|
||||
instance: number,
|
||||
seconds: number,
|
||||
transaction: Transaction,
|
||||
observedStart: boolean,
|
||||
duration: number | null = null,
|
||||
) {
|
||||
await this.database.query(
|
||||
`UPDATE Crontabs SET last_instance_id=$instance,
|
||||
last_execution_time=$seconds,last_running_time=$duration WHERE id=$cronId AND
|
||||
(last_execution_time IS NULL OR last_execution_time<$seconds OR
|
||||
(last_execution_time=$seconds AND (last_instance_id IS NULL OR
|
||||
($observedStart AND last_instance_id<$instance))))`,
|
||||
{
|
||||
transaction,
|
||||
bind: {
|
||||
cronId,
|
||||
instance,
|
||||
seconds,
|
||||
duration,
|
||||
observedStart: Number(observedStart),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async isRunning(cronId: number, transaction: Transaction) {
|
||||
await this.recoverSystemOwners(cronId, transaction);
|
||||
const rows = await this.database.query(
|
||||
"SELECT 1 FROM CronTriggers WHERE cron_id=$cronId AND state='running' LIMIT 1",
|
||||
{ bind: { cronId }, transaction, type: QueryTypes.SELECT },
|
||||
);
|
||||
return rows.length !== 0;
|
||||
}
|
||||
|
||||
async cancelQueued(ids: number[]) {
|
||||
if (!ids.length) return [];
|
||||
return this.database.transaction((tx) =>
|
||||
this.cancelQueuedInTransaction(ids, tx),
|
||||
);
|
||||
}
|
||||
|
||||
async cancelQueuedInTransaction(ids: number[], transaction: Transaction) {
|
||||
await this.database.query(
|
||||
"UPDATE CronTriggers SET stop_requested=1 WHERE cron_id IN (:ids) AND state='running' AND command_identity IS NULL AND instance_id IS NULL",
|
||||
{ replacements: { ids }, transaction },
|
||||
);
|
||||
const rows = await this.database.query<{ id: string }>(
|
||||
"SELECT id FROM CronTriggers WHERE cron_id IN (:ids) AND state='queued'",
|
||||
{ replacements: { ids }, transaction, type: QueryTypes.SELECT },
|
||||
);
|
||||
await this.database.query(
|
||||
`UPDATE CronTriggers SET state='stopped',reason='cancelled',finished_at=:now
|
||||
WHERE cron_id IN (:ids) AND state='queued'`,
|
||||
{ replacements: { ids, now: Date.now() }, transaction },
|
||||
);
|
||||
return rows.map((r) => r.id);
|
||||
}
|
||||
|
||||
async queueInstanceStop(
|
||||
instanceId: number,
|
||||
cronId: number,
|
||||
pid: number,
|
||||
transaction?: Transaction,
|
||||
identity?: string,
|
||||
) {
|
||||
await this.database.query(
|
||||
`INSERT INTO CronStopRequests(instance_id,cron_id,pid,root_identity,namespace_owner)
|
||||
VALUES ($instanceId,$cronId,$pid,$identity,$namespace)
|
||||
ON CONFLICT(instance_id) DO UPDATE SET root_identity=excluded.root_identity
|
||||
WHERE root_identity IS NULL AND excluded.root_identity IS NOT NULL AND pid=excluded.pid AND signalled=0`,
|
||||
{
|
||||
transaction,
|
||||
bind: {
|
||||
instanceId,
|
||||
cronId,
|
||||
pid,
|
||||
identity: identity ?? null,
|
||||
namespace: pidNamespaceOwner(),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async pendingStop(instanceId: number, transaction?: Transaction) {
|
||||
const [row] = await this.database.query<{
|
||||
targets: string | null;
|
||||
signalled: number;
|
||||
signalled_at: number | null;
|
||||
root_identity: string | null;
|
||||
namespace_owner: string | null;
|
||||
}>(
|
||||
'SELECT targets,signalled,signalled_at,root_identity,namespace_owner FROM CronStopRequests WHERE instance_id=$instanceId',
|
||||
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
|
||||
);
|
||||
return row;
|
||||
}
|
||||
|
||||
async pendingStopBatches() {
|
||||
return this.database.query<{ request_id: string; cron_ids: string }>(
|
||||
'SELECT request_id,cron_ids FROM CronStopBatches WHERE snapshot IS NOT NULL',
|
||||
{ type: QueryTypes.SELECT },
|
||||
);
|
||||
}
|
||||
|
||||
async pendingStops() {
|
||||
return this.database.query<{
|
||||
instance_id: number;
|
||||
cron_id: number;
|
||||
pid: number;
|
||||
targets: string | null;
|
||||
}>(
|
||||
'SELECT instance_id,cron_id,pid,targets FROM CronStopRequests ORDER BY instance_id',
|
||||
{ type: QueryTypes.SELECT },
|
||||
);
|
||||
}
|
||||
|
||||
async forgetStop(
|
||||
instanceId: number,
|
||||
onEnded?: (tx: Transaction) => Promise<void>,
|
||||
) {
|
||||
return this.database.transaction(async (transaction) => {
|
||||
await this.database.query(
|
||||
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId AND signalled=0',
|
||||
{ transaction, bind: { instanceId } },
|
||||
);
|
||||
const claimed = await this.pendingStop(instanceId, transaction);
|
||||
if (!claimed && onEnded) await onEnded(transaction);
|
||||
return claimed;
|
||||
});
|
||||
}
|
||||
|
||||
async shouldStop(id: string, transaction?: Transaction) {
|
||||
const rows = await this.database.query(
|
||||
'SELECT 1 FROM CronTriggers WHERE id=$id AND stop_requested=1',
|
||||
{ transaction, bind: { id }, type: QueryTypes.SELECT },
|
||||
);
|
||||
return rows.length > 0;
|
||||
}
|
||||
|
||||
// The outer command can outlive any of its task wrappers.
|
||||
async recordCommandStart(id: string, at: number) {
|
||||
await this.database.query(
|
||||
`UPDATE CronTriggers SET command_started_at=$at
|
||||
WHERE id=$id AND command_started_at IS NULL AND started_at IS NOT NULL`,
|
||||
{ bind: { id, at } },
|
||||
);
|
||||
}
|
||||
|
||||
async bindCommand(id: string, pid: number, log?: string) {
|
||||
let identity: string;
|
||||
try {
|
||||
identity = systemOwner(pid);
|
||||
} catch (error) {
|
||||
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!))
|
||||
return false;
|
||||
throw error;
|
||||
}
|
||||
return this.database.transaction(async (transaction) => {
|
||||
const [row] = await this.database.query<{
|
||||
instance_id: number | null;
|
||||
cron_id: number;
|
||||
started_at: number;
|
||||
}>(
|
||||
"SELECT instance_id,cron_id,started_at FROM CronTriggers WHERE id=$id AND state='running'",
|
||||
{ transaction, bind: { id }, type: QueryTypes.SELECT },
|
||||
);
|
||||
if (!row) return false;
|
||||
await this.database.query(
|
||||
'UPDATE CronTriggers SET command_identity=$identity WHERE id=$id',
|
||||
{ transaction, bind: { identity, id } },
|
||||
);
|
||||
if (row.instance_id) {
|
||||
await this.database.query(
|
||||
'UPDATE RunningInstances SET pid=$pid WHERE id=$instance AND status=0',
|
||||
{ transaction, bind: { pid, instance: row.instance_id } },
|
||||
);
|
||||
await this.database.query(
|
||||
'UPDATE CronTriggers SET process_identity=$identity WHERE id=$id',
|
||||
{ transaction, bind: { identity, id } },
|
||||
);
|
||||
await this.database.query(
|
||||
'UPDATE Crontabs SET pid=$pid WHERE id=$cronId AND log_path=(SELECT log_path FROM CronTriggers WHERE id=$id) AND status=0',
|
||||
{ transaction, bind: { pid, cronId: row.cron_id, id } },
|
||||
);
|
||||
} else {
|
||||
await this.registerCommandInstance(
|
||||
id,
|
||||
row.cron_id,
|
||||
pid,
|
||||
identity,
|
||||
row.started_at,
|
||||
log,
|
||||
transaction,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private async registerCommandInstance(
|
||||
id: string,
|
||||
cronId: number,
|
||||
pid: number,
|
||||
identity: string,
|
||||
started: number,
|
||||
log: string | undefined,
|
||||
transaction: Transaction,
|
||||
) {
|
||||
const seconds = Math.floor(started / 1000);
|
||||
const [instance] = await this.database.query(
|
||||
`INSERT INTO RunningInstances(cron_id,pid,log_path,started_at,status,createdAt,updatedAt)
|
||||
VALUES ($cronId,$pid,$log,$seconds,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`,
|
||||
{
|
||||
transaction,
|
||||
type: QueryTypes.INSERT,
|
||||
bind: { cronId, pid, log: log ?? null, seconds },
|
||||
},
|
||||
);
|
||||
await this.database.query(
|
||||
'UPDATE CronTriggers SET log_path=$log,instance_id=$instance,process_identity=$identity WHERE id=$id',
|
||||
{ transaction, bind: { id, log: log ?? null, instance, identity } },
|
||||
);
|
||||
await this.claimSummary(cronId, instance, seconds, transaction, true);
|
||||
if (log === undefined)
|
||||
await this.database.query(
|
||||
'UPDATE Crontabs SET status=0,pid=$pid,log_path=NULL WHERE id=$cronId AND status IS NOT 3',
|
||||
{ transaction, bind: { cronId, pid } },
|
||||
);
|
||||
}
|
||||
|
||||
async activeCommands(ids: number[], transaction?: Transaction) {
|
||||
if (!ids.length) return [];
|
||||
return this.database.query<{
|
||||
id: string;
|
||||
cron_id: number;
|
||||
command_identity: string;
|
||||
started_at: number;
|
||||
log_path: string;
|
||||
}>(
|
||||
"SELECT id,cron_id,command_identity,started_at,log_path FROM CronTriggers WHERE cron_id IN (:ids) AND state='running' AND instance_id IS NULL AND command_identity IS NOT NULL",
|
||||
{ replacements: { ids }, transaction, type: QueryTypes.SELECT },
|
||||
);
|
||||
}
|
||||
|
||||
async instanceIdentity(instanceId: number) {
|
||||
const [row] = await this.database.query<{
|
||||
process_identity: string | null;
|
||||
}>(
|
||||
'SELECT process_identity FROM CronTriggers WHERE instance_id=$instanceId',
|
||||
{ bind: { instanceId }, type: QueryTypes.SELECT },
|
||||
);
|
||||
return row?.process_identity;
|
||||
}
|
||||
|
||||
async requestInstanceStop(
|
||||
instanceId: number,
|
||||
pid: number,
|
||||
signalTree: () => void | Error,
|
||||
targets?: string[],
|
||||
) {
|
||||
// Commit the verified tree BEFORE the first signal. If this worker dies even
|
||||
// inside the following transaction, its replacement still has the original PIDs.
|
||||
if (targets)
|
||||
await this.database.query(
|
||||
`INSERT INTO CronStopRequests(instance_id,cron_id,pid,targets)
|
||||
SELECT i.id,i.cron_id,i.pid,$targets FROM RunningInstances i WHERE i.id=$instanceId AND i.pid=$pid AND i.status=0
|
||||
ON CONFLICT(instance_id) DO UPDATE SET targets=(
|
||||
SELECT json_group_array(value) FROM (SELECT value FROM json_each(CronStopRequests.targets)
|
||||
UNION SELECT value FROM json_each(excluded.targets))) WHERE CronStopRequests.signalled=0`,
|
||||
{ bind: { instanceId, pid, targets: JSON.stringify(targets) } },
|
||||
);
|
||||
const result = await this.database.transaction(
|
||||
{ type: Transaction.TYPES.IMMEDIATE },
|
||||
async (transaction) => {
|
||||
const [row] = await this.database.query<{
|
||||
id: string | null;
|
||||
pid: number;
|
||||
status: number;
|
||||
state: TriggerState | null;
|
||||
stop_requested: number | null;
|
||||
}>(
|
||||
`SELECT t.id,i.pid,i.status,t.state,t.stop_requested FROM RunningInstances i
|
||||
LEFT JOIN CronTriggers t ON t.instance_id=i.id WHERE i.id=$instanceId`,
|
||||
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
|
||||
);
|
||||
if (
|
||||
!row ||
|
||||
row.status !== 0 ||
|
||||
(row.state && row.state !== 'running')
|
||||
) {
|
||||
throw Object.assign(new Error('Instance already ended'), {
|
||||
code: 'ESRCH',
|
||||
});
|
||||
}
|
||||
if (row.pid !== pid)
|
||||
throw Object.assign(new Error('Instance process changed'), {
|
||||
status: 409,
|
||||
});
|
||||
if (row.stop_requested && !targets) return;
|
||||
const existing = await this.pendingStop(instanceId, transaction);
|
||||
const savedTargets: string[] = existing?.targets
|
||||
? JSON.parse(existing.targets)
|
||||
: [];
|
||||
if (existing?.signalled)
|
||||
return { targets: savedTargets, signalledAt: existing.signalled_at };
|
||||
// The supervisor can still be draining output after the command has exited.
|
||||
if (row.id) {
|
||||
const exit = await this.evidence.exitBeforeStop(row.id);
|
||||
// An I/O error alone cannot prove a live process has already exited.
|
||||
if (!exit.published && exit.unreadable)
|
||||
throw Object.assign(
|
||||
new Error('Cannot verify command exit. Retry the stop request.'),
|
||||
{ status: 503 },
|
||||
);
|
||||
if (exit.published) {
|
||||
await this.evidence.completeCommandExit(
|
||||
row.id,
|
||||
'unknown',
|
||||
null,
|
||||
null,
|
||||
transaction,
|
||||
exit.canonical,
|
||||
undefined,
|
||||
undefined,
|
||||
exit.recovered,
|
||||
);
|
||||
return { ended: true };
|
||||
}
|
||||
}
|
||||
if (targets && !existing?.targets) {
|
||||
// Another worker released the prepared tree. Retry from a durable
|
||||
// snapshot before issuing an irreversible signal.
|
||||
throw Object.assign(
|
||||
new Error('Stop target snapshot changed. Retry the stop request.'),
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const signalledAt = Date.now();
|
||||
await this.database.query(
|
||||
'UPDATE CronStopRequests SET signalled=1,signalled_at=$signalledAt WHERE instance_id=$instanceId',
|
||||
{ transaction, bind: { instanceId, signalledAt } },
|
||||
);
|
||||
if (row.state)
|
||||
await this.database.query(
|
||||
"UPDATE CronTriggers SET stop_requested=1 WHERE instance_id=$instanceId AND state='running'",
|
||||
{ bind: { instanceId }, transaction },
|
||||
);
|
||||
// Root delivery failure rolls back. After successful root delivery, retain
|
||||
// the stop marker even if some descendants still need recovery.
|
||||
const error = signalTree();
|
||||
return { targets: savedTargets, signalledAt, error };
|
||||
},
|
||||
);
|
||||
if (result && 'ended' in result)
|
||||
throw Object.assign(new Error('Instance already ended'), {
|
||||
code: 'ESRCH',
|
||||
});
|
||||
if (result && 'error' in result && result.error instanceof Error)
|
||||
throw result.error;
|
||||
if (targets && result)
|
||||
return { targets: result.targets, signalledAt: result.signalledAt };
|
||||
}
|
||||
|
||||
async instanceStopRequested(instanceId: number, transaction?: Transaction) {
|
||||
const [row] = await this.database.query<{ stop_requested: number | null }>(
|
||||
'SELECT stop_requested FROM CronTriggers WHERE instance_id=$instanceId',
|
||||
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
|
||||
);
|
||||
return row && Boolean(row.stop_requested);
|
||||
}
|
||||
|
||||
async stopVerifiedInstance(
|
||||
instanceId: number,
|
||||
settleLegacy?: (transaction: Transaction) => Promise<boolean>,
|
||||
) {
|
||||
return this.database.transaction(async (transaction) => {
|
||||
const [row] = await this.database.query<{
|
||||
id: string;
|
||||
owner: string | null;
|
||||
command_identity: string | null;
|
||||
reason: string | null;
|
||||
state: TriggerState;
|
||||
stop_exit_at: number | null;
|
||||
exit_code: number | null;
|
||||
exit_pending: number | null;
|
||||
}>(
|
||||
'SELECT id,owner,command_identity,reason,state,stop_exit_at,exit_code,exit_pending FROM CronTriggers WHERE instance_id=$instanceId',
|
||||
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
|
||||
);
|
||||
await this.database.query(
|
||||
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId',
|
||||
{ transaction, bind: { instanceId } },
|
||||
);
|
||||
if (!row) return settleLegacy ? settleLegacy(transaction) : false;
|
||||
if (row.state !== 'running') return row.state === 'stopped';
|
||||
const legacyCrond =
|
||||
row.owner?.startsWith('crond:') &&
|
||||
(!row.command_identity || row.owner === row.command_identity);
|
||||
// A live scheduler drains its log and reports the actual exit. If the
|
||||
// callback already arrived or its owner is gone, settle in this transaction.
|
||||
const exit = await this.evidence.exitBeforeStop(row.id);
|
||||
if (
|
||||
exit.published ||
|
||||
exit.unreadable ||
|
||||
row.exit_pending ||
|
||||
row.stop_exit_at !== null ||
|
||||
!row.owner ||
|
||||
legacyCrond ||
|
||||
row.reason === 'restart'
|
||||
) {
|
||||
await this.evidence.recoverScriptSample(row.id, transaction);
|
||||
await this.evidence.completeCommandExit(
|
||||
row.id,
|
||||
'stopped',
|
||||
'cancelled',
|
||||
row.exit_code,
|
||||
transaction,
|
||||
exit.canonical,
|
||||
row.stop_exit_at ?? undefined,
|
||||
undefined,
|
||||
exit.recovered,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
async queueCounts() {
|
||||
await this.recoverSystemOwners();
|
||||
const [row] = await this.database.query<{
|
||||
triggers: number;
|
||||
tasks: number;
|
||||
}>(
|
||||
"SELECT COUNT(*) AS triggers, COUNT(DISTINCT cron_id) AS tasks FROM CronTriggers WHERE state='queued' AND dequeued_at IS NULL",
|
||||
{ type: QueryTypes.SELECT },
|
||||
);
|
||||
return row;
|
||||
}
|
||||
|
||||
async startSystem(
|
||||
id: string,
|
||||
cronId: number,
|
||||
owner: string,
|
||||
commandIdentity = owner,
|
||||
wrapper?: { rule: string; at: number; dispatch?: number },
|
||||
) {
|
||||
// crond only tells us when the wrapper starts. It supplies no scheduled or queued time.
|
||||
return this.database.transaction(async (transaction) => {
|
||||
const [task] = await this.database.query<{
|
||||
allow_multiple_instances: number;
|
||||
status: number;
|
||||
pid: number | null;
|
||||
isDisabled: number;
|
||||
}>(
|
||||
'SELECT allow_multiple_instances, status, pid, isDisabled FROM Crontabs WHERE id=$cronId',
|
||||
{ bind: { cronId }, type: QueryTypes.SELECT, transaction },
|
||||
);
|
||||
if (!task || (task.isDisabled && !wrapper?.dispatch)) return false;
|
||||
const now = Date.now();
|
||||
const inserted = await this.database.query(
|
||||
`INSERT INTO CronTriggers(id,cron_id,source,state,owner,command_identity,observed_at,system_rule,system_dispatch_at)
|
||||
VALUES ($id,$cronId,'system','queued',$owner,$commandIdentity,$observed,$rule,$dispatch) ON CONFLICT(id) DO NOTHING`,
|
||||
{
|
||||
bind: {
|
||||
id,
|
||||
cronId,
|
||||
owner,
|
||||
commandIdentity,
|
||||
observed: wrapper?.at ?? now,
|
||||
rule: wrapper?.rule ?? null,
|
||||
dispatch: wrapper?.dispatch ?? null,
|
||||
},
|
||||
type: QueryTypes.BULKUPDATE,
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
if (!inserted) return false;
|
||||
if (task.isDisabled) {
|
||||
await this.finish(id, 'skipped', 'changed', null, transaction);
|
||||
return false;
|
||||
}
|
||||
const multiple = task.allow_multiple_instances === 1;
|
||||
const claimed =
|
||||
(multiple || !hasLiveCronProcess(task.status, task.pid)) &&
|
||||
(await this.start(id, now, multiple, transaction));
|
||||
if (claimed && wrapper)
|
||||
await this.database.query(
|
||||
'UPDATE CronTriggers SET command_started_at=$now WHERE id=$id',
|
||||
{ transaction, bind: { id, now } },
|
||||
);
|
||||
if (claimed && owner.startsWith('crond:')) {
|
||||
await this.registerCommandInstance(
|
||||
id,
|
||||
cronId,
|
||||
Number(commandIdentity.split(':')[1]),
|
||||
commandIdentity,
|
||||
now,
|
||||
undefined,
|
||||
transaction,
|
||||
);
|
||||
}
|
||||
if (!claimed)
|
||||
await this.finish(id, 'skipped', 'overlap', null, transaction);
|
||||
return claimed;
|
||||
});
|
||||
}
|
||||
|
||||
async recoverSystemOwners(
|
||||
cronId?: number,
|
||||
transaction?: Transaction,
|
||||
instanceId?: number,
|
||||
) {
|
||||
// HTTP may restart while crond children keep running. Match process birth, including across reboots.
|
||||
const active = await this.database.query<{ id: string; owner: string }>(
|
||||
`SELECT id,CASE WHEN owner LIKE 'crond:%' THEN owner ELSE COALESCE(command_identity,process_identity) END AS owner FROM CronTriggers WHERE state='running' AND (owner LIKE 'crond:%' OR reason='restart')
|
||||
AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=CronTriggers.instance_id AND s.targets IS NOT NULL)
|
||||
AND ($cronId IS NULL OR cron_id=$cronId) AND ($instanceId IS NULL OR instance_id=$instanceId)`,
|
||||
{
|
||||
transaction,
|
||||
bind: { cronId: cronId ?? null, instanceId: instanceId ?? null },
|
||||
type: QueryTypes.SELECT,
|
||||
},
|
||||
);
|
||||
let reclaimed = false;
|
||||
for (const row of active) {
|
||||
const pid = Number(row.owner.split(':')[1]);
|
||||
try {
|
||||
if (systemOwner(pid) === row.owner) continue;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code !== 'ENOENT' && code !== 'ESRCH') throw error;
|
||||
}
|
||||
const close = async (tx: Transaction) => {
|
||||
const [current] = await this.database.query<{
|
||||
stop_requested: number;
|
||||
exit_code: number | null;
|
||||
stop_exit_at: number | null;
|
||||
}>(
|
||||
`SELECT stop_requested,exit_code,stop_exit_at FROM CronTriggers WHERE id=$id AND state='running'
|
||||
AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=CronTriggers.instance_id AND s.targets IS NOT NULL)`,
|
||||
{ transaction: tx, bind: { id: row.id }, type: QueryTypes.SELECT },
|
||||
);
|
||||
if (!current) return;
|
||||
await this.evidence.recoverScriptSample(row.id, tx);
|
||||
await this.evidence.completeCommandExit(
|
||||
row.id,
|
||||
current.stop_requested ? 'stopped' : 'unknown',
|
||||
current.stop_requested ? 'cancelled' : 'restart',
|
||||
current.exit_code,
|
||||
tx,
|
||||
undefined,
|
||||
current.stop_exit_at ?? undefined,
|
||||
);
|
||||
};
|
||||
if (transaction) await close(transaction);
|
||||
else await this.database.transaction(close);
|
||||
reclaimed = true;
|
||||
}
|
||||
return reclaimed;
|
||||
}
|
||||
|
||||
async interrupt(owner: string) {
|
||||
await this.database.transaction(async (transaction) => {
|
||||
await this.evidence.replayPublishedExits(transaction);
|
||||
if (owner === 'http')
|
||||
await this.database.query(
|
||||
`INSERT OR IGNORE INTO CronStopRequests(instance_id,cron_id,pid)
|
||||
SELECT instance_id,cron_id,CAST(substr(process_identity,7) AS INTEGER) FROM CronTriggers
|
||||
WHERE state='running' AND stop_requested=1 AND instance_id IS NOT NULL AND process_identity LIKE 'crond:%'`,
|
||||
{ transaction },
|
||||
);
|
||||
// No process was bound and its launch gate closed when the worker exited.
|
||||
await this.database.query(
|
||||
`UPDATE CronTriggers SET state='stopped',reason='cancelled',started_at=NULL,finished_at=$now
|
||||
WHERE owner=$owner AND state='running' AND stop_requested=1 AND instance_id IS NULL AND command_identity IS NULL`,
|
||||
{ transaction, bind: { owner, now: Date.now() } },
|
||||
);
|
||||
await this.database.query(
|
||||
`UPDATE CronTriggers SET reason='restart',
|
||||
state=CASE WHEN state='queued' THEN 'skipped' WHEN COALESCE(command_identity,process_identity) IS NOT NULL THEN 'running' ELSE 'unknown' END,
|
||||
finished_at=CASE WHEN state='running' AND COALESCE(command_identity,process_identity) IS NOT NULL THEN NULL ELSE $now END
|
||||
WHERE (owner=$owner OR (source IN ('system','legacy','client') AND owner IS NULL AND $owner='http')) AND state IN ('queued','running')`,
|
||||
{ transaction, bind: { owner, now: Date.now() } },
|
||||
);
|
||||
await this.recoverSystemOwners(undefined, transaction);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user