mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 01:39:52 +08:00
feat: harden cron execution recovery and expose scheduling diagnostics
Reconcile scheduled and system cron triggers, isolate concurrent executions and retain verifiable exit statistics across restarts. Add paged task history, log and script browsing, dashboard timing details and regression coverage.
This commit is contained in:
1 parent
3b6a873520
commit
8a9e70e90b
166 files changed
+18942
-1800
No files matched your search
+122
-11
@@ -1,4 +1,10 @@
|
||||
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
|
||||
import { readDailyResults } from '../shared/legacyDailyStatistics';
|
||||
import { PendingCronInstall } from '../shared/errors';
|
||||
import { triggerHistory } from '../shared/triggerHistory';
|
||||
import { previewSchedule, withNextRun } from '../shared/cronPreview';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { literal, Op } from 'sequelize';
|
||||
import { Container } from 'typedi';
|
||||
import { Logger } from 'winston';
|
||||
import CronService from '../services/cron';
|
||||
@@ -164,14 +170,25 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.crontabs(req.query as any);
|
||||
return res.send({ code: 200, data });
|
||||
const result = await cronService.crontabs(req.query as any, true);
|
||||
return res.send({ code: 200, data: { ...result, data: result.data.map(withNextRun) } });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
});
|
||||
|
||||
route.get('/preview', celebrate({ query: Joi.object({
|
||||
schedule: Joi.string().required(),
|
||||
}).unknown(true) }), (req, res) => {
|
||||
try {
|
||||
const times = previewSchedule(String(req.query.schedule), 3, Date.now());
|
||||
return res.send({ code: 200, data: { times, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone } });
|
||||
} catch {
|
||||
return res.status(400).send({ code: 400, message: t('Cron表达式格式有误') });
|
||||
}
|
||||
});
|
||||
|
||||
route.get(
|
||||
'/detail',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -199,6 +216,11 @@ export default (app: Router) => {
|
||||
const data = await cronService.create(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
if (e instanceof PendingCronInstall) {
|
||||
return res.status(e.status).send({
|
||||
code: e.status, message: e.message, data: { id: e.cronId, saved: false },
|
||||
});
|
||||
}
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -224,13 +246,14 @@ export default (app: Router) => {
|
||||
route.put(
|
||||
'/stop',
|
||||
celebrate({
|
||||
headers: Joi.object({ 'idempotency-key': Joi.string().guid().optional() }).unknown(true),
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.stop(req.body);
|
||||
const data = await cronService.stop(req.body, req.get('Idempotency-Key'));
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
@@ -322,6 +345,11 @@ export default (app: Router) => {
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
query: Joi.object({
|
||||
triggerId: Joi.string().max(256).optional(),
|
||||
instanceId: Joi.number().integer().positive().optional(),
|
||||
previousPath: Joi.string().optional(),
|
||||
follow: Joi.boolean().optional(),
|
||||
cursor: Joi.string().pattern(/^\d{1,16}\.[a-f0-9]{64}$/).optional(),
|
||||
offset: Joi.number().integer().min(0).optional(),
|
||||
limit: Joi.number()
|
||||
.integer()
|
||||
@@ -337,6 +365,11 @@ export default (app: Router) => {
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const result = await cronService.log(req.params.id, {
|
||||
triggerId: req.query.triggerId as string | undefined,
|
||||
instanceId: req.query.instanceId === undefined ? undefined : Number(req.query.instanceId),
|
||||
previousPath: req.query.previousPath as string | undefined,
|
||||
follow: req.query.follow as unknown as boolean,
|
||||
cursor: req.query.cursor as string | undefined,
|
||||
offset: req.query.offset as unknown as number,
|
||||
limit: req.query.limit as unknown as number,
|
||||
tail: req.query.tail as unknown as boolean,
|
||||
@@ -345,6 +378,10 @@ export default (app: Router) => {
|
||||
code: 200,
|
||||
data: result.content,
|
||||
logStatus: result.status,
|
||||
logPath: result.logPath,
|
||||
triggerId: result.triggerId,
|
||||
cursor: result.cursor,
|
||||
reset: result.reset,
|
||||
offset: result.offset,
|
||||
nextOffset: result.nextOffset,
|
||||
total: result.total,
|
||||
@@ -379,7 +416,10 @@ export default (app: Router) => {
|
||||
route.delete(
|
||||
'/',
|
||||
celebrate({
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
body: Joi.array().min(1).items(Joi.number().integer().positive(), Joi.object({
|
||||
id: Joi.number().integer().positive().required(), script: Joi.string().required(),
|
||||
revision: Joi.number().integer(), command: Joi.string(), sub_id: Joi.number().integer().allow(null),
|
||||
})),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
@@ -452,8 +492,8 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.getDb({ id: req.params.id });
|
||||
return res.send({ code: 200, data });
|
||||
const data = await cronService.getDb({ id: req.params.id }, true);
|
||||
return res.send({ code: 200, data: withNextRun(data) });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
@@ -471,13 +511,19 @@ export default (app: Router) => {
|
||||
last_running_time: Joi.number().optional().allow(null),
|
||||
last_execution_time: Joi.number().optional().allow(null),
|
||||
exit_code: Joi.number().optional().allow(null),
|
||||
}),
|
||||
trigger_stopped: Joi.boolean().optional(),
|
||||
execution_id: Joi.string().pattern(executionIdPattern).optional(),
|
||||
trigger_id: Joi.string().pattern(/^[a-z0-9-]{1,120}$/).optional(),
|
||||
}).oxor('execution_id', 'trigger_id'),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const { execution_id, ...body } = req.body;
|
||||
const data = await cronService.status({
|
||||
...req.body,
|
||||
...body,
|
||||
finished_at: receiptFinishTime(req.get('X-QL-Finished-At')),
|
||||
...(execution_id && { trigger_id: executionTriggerId(execution_id) }),
|
||||
status: req.body.status ? parseInt(req.body.status) : undefined,
|
||||
pid: req.body.pid ? parseInt(req.body.pid) : undefined,
|
||||
});
|
||||
@@ -488,22 +534,87 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
|
||||
route.get('/:id/daily-results', celebrate({
|
||||
params: Joi.object({ id: Joi.number().integer().positive().required() }),
|
||||
}), async (req, res, next) => {
|
||||
try {
|
||||
const data = await readDailyResults(RunningInstanceModel.sequelize!, Number(req.params.id));
|
||||
return res.send({ code: 200, data });
|
||||
} catch (error) {
|
||||
return next(error);
|
||||
}
|
||||
});
|
||||
|
||||
route.get('/:id/triggers', celebrate({
|
||||
params: Joi.object({ id: Joi.number().integer().positive().required() }),
|
||||
query: Joi.object({
|
||||
offset: Joi.number().integer().min(0),
|
||||
limit: Joi.number().integer().min(1).max(26).default(25),
|
||||
ids: Joi.array().items(Joi.string().max(256)).min(1).max(25).single(),
|
||||
beforeTime: Joi.number().integer().min(0),
|
||||
beforeId: Joi.string().max(256),
|
||||
}).and('beforeTime', 'beforeId').oxor('offset', 'beforeTime', 'ids').unknown(true),
|
||||
}), async (req, res, next) => {
|
||||
try {
|
||||
const { offset, limit, beforeTime, beforeId, ids } = req.query;
|
||||
const history = triggerHistory();
|
||||
const before = beforeId ? { time: Number(beforeTime), id: String(beforeId) } : undefined;
|
||||
const data = ids
|
||||
? await history.visibleTriggers(Number(req.params.id), ids as string[])
|
||||
: await history.recent(Number(req.params.id), Number(offset || 0), Number(limit), before);
|
||||
if (req.query.withQueueWait === 'true') {
|
||||
const now = Date.now();
|
||||
return res.send({ code: 200, data: data.map(row => row.state === 'queued' && row.queued_at != null
|
||||
? { ...row, queue_wait_ms: Math.max(0, (row.dequeued_at ?? now) - row.queued_at) } : row) });
|
||||
}
|
||||
return res.send({ code: 200, data });
|
||||
} catch (err) { next(err); }
|
||||
});
|
||||
|
||||
route.get(
|
||||
'/:id/instances',
|
||||
celebrate({
|
||||
// This route historically ignored query parameters. Only validate and
|
||||
// apply cursor options when the caller explicitly requests pagination.
|
||||
query: Joi.alternatives().conditional(Joi.object({ paged: Joi.valid('true').required() }).unknown(), {
|
||||
then: Joi.object({
|
||||
limit: Joi.number().integer().min(1).max(100),
|
||||
before: Joi.number().integer().positive(),
|
||||
ids: Joi.string().pattern(/^\d+(,\d+){0,99}$/),
|
||||
}).unknown(true).oxor('ids', 'limit').oxor('ids', 'before'),
|
||||
otherwise: Joi.object().unknown(true),
|
||||
}),
|
||||
params: Joi.object({
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
// The instance row may retain a provisional end for cleanup after a restart.
|
||||
const pending = `EXISTS (SELECT 1 FROM CronTriggers t WHERE t.instance_id=RunningInstance.id
|
||||
AND (t.exit_pending=1 OR (t.state='unknown' AND t.reason='restart')))`;
|
||||
const paged = req.query.paged === 'true';
|
||||
const ids = paged && req.query.ids ? String(req.query.ids).split(',').map(Number) : undefined;
|
||||
const limit = paged && !ids ? Number(req.query.limit ?? 25) : undefined;
|
||||
const instances = await RunningInstanceModel.findAll({
|
||||
attributes: {
|
||||
exclude: ['finished_at', 'exit_code'],
|
||||
include: [
|
||||
[literal(`CASE WHEN ${pending} THEN NULL ELSE finished_at END`), 'finished_at'],
|
||||
[literal(`CASE WHEN ${pending} THEN NULL ELSE exit_code END`), 'exit_code'],
|
||||
],
|
||||
},
|
||||
where: {
|
||||
cron_id: req.params.id,
|
||||
...(ids && { id: { [Op.in]: ids } }),
|
||||
...(paged && req.query.before && { id: { [Op.lt]: Number(req.query.before) } }),
|
||||
},
|
||||
order: [['started_at', 'DESC']],
|
||||
order: paged ? [['id', 'DESC']] : [['started_at', 'DESC'], ['id', 'DESC']],
|
||||
...(limit && { limit: limit + 1 }),
|
||||
raw: true,
|
||||
});
|
||||
if (limit) return res.send({ code: 200, data: instances.slice(0, limit),
|
||||
next: instances.length > limit ? instances[limit - 1].id : null });
|
||||
return res.send({ code: 200, data: instances });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
@@ -522,8 +633,8 @@ export default (app: Router) => {
|
||||
async (req: Request<{ id: number; instanceId: number }>, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.stopInstance(req.params.instanceId);
|
||||
return res.send(data);
|
||||
const data = await cronService.stopInstance(Number(req.params.id), Number(req.params.instanceId));
|
||||
return res.status(data.code).send(data);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user