mirror of
https://github.com/whyour/qinglong.git
synced 2026-08-08 18:04:32 +08:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fcf0ee619b | |||
| f3ec352066 | |||
| 023d0f1cc4 | |||
| f526d3f972 | |||
| e28f746294 |
@@ -3,7 +3,6 @@ import { Container } from 'typedi';
|
|||||||
import { Logger } from 'winston';
|
import { Logger } from 'winston';
|
||||||
import CronService from '../services/cron';
|
import CronService from '../services/cron';
|
||||||
import CronViewService from '../services/cronView';
|
import CronViewService from '../services/cronView';
|
||||||
import CronStatsService from '../services/cronStats';
|
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
import { commonCronSchema } from '../validation/schedule';
|
import { commonCronSchema } from '../validation/schedule';
|
||||||
|
|
||||||
@@ -142,58 +141,6 @@ export default (app: Router) => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
route.get(
|
|
||||||
'/stats',
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const cronStatsService = Container.get(CronStatsService);
|
|
||||||
const data = await cronStatsService.stats();
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.get(
|
|
||||||
'/stats/trend',
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const cronStatsService = Container.get(CronStatsService);
|
|
||||||
const data = await cronStatsService.trend();
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.get(
|
|
||||||
'/stats/top-duration',
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const cronStatsService = Container.get(CronStatsService);
|
|
||||||
const data = await cronStatsService.topDuration();
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.get(
|
|
||||||
'/stats/top-count',
|
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
const cronStatsService = Container.get(CronStatsService);
|
|
||||||
const data = await cronStatsService.topCount();
|
|
||||||
return res.send({ code: 200, data });
|
|
||||||
} catch (e) {
|
|
||||||
return next(e);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
|
|||||||
+61
-4
@@ -535,12 +535,43 @@ export async function setSystemTimezone(timezone: string): Promise<boolean> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Helper function to check if a name is a GitHub URL
|
||||||
|
function isGitHubUrl(name: string): boolean {
|
||||||
|
// Support git+https://, git+http://, https://, and http:// URLs
|
||||||
|
// This covers GitHub URLs and other git-compatible repositories
|
||||||
|
return !!name.match(/^(git\+https?:\/\/|https?:\/\/)/i);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to check if a name is a requirements file
|
||||||
|
function isRequirementsFile(name: string): boolean {
|
||||||
|
return !!name.match(/requirements.*\.(txt|in)$/i);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to check if a name is a pyproject.toml file
|
||||||
|
function isPyprojectToml(name: string): boolean {
|
||||||
|
return name.endsWith('pyproject.toml');
|
||||||
|
}
|
||||||
|
|
||||||
export function getGetCommand(type: DependenceTypes, name: string): string {
|
export function getGetCommand(type: DependenceTypes, name: string): string {
|
||||||
|
const trimmedName = name.trim();
|
||||||
|
|
||||||
|
// For Python dependencies installed from GitHub or requirements files,
|
||||||
|
// we can't reliably check if they're installed, so skip the check
|
||||||
|
if (type === DependenceTypes.python3) {
|
||||||
|
if (isGitHubUrl(trimmedName) ||
|
||||||
|
isRequirementsFile(trimmedName) ||
|
||||||
|
isPyprojectToml(trimmedName)) {
|
||||||
|
// Return a command that will always indicate not installed
|
||||||
|
// This ensures GitHub URLs and requirements files are always installed
|
||||||
|
return 'echo ""';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const baseCommands = {
|
const baseCommands = {
|
||||||
[DependenceTypes.nodejs]: `pnpm ls -g | grep "${name}" | head -1`,
|
[DependenceTypes.nodejs]: `pnpm ls -g | grep "${trimmedName}" | head -1`,
|
||||||
[DependenceTypes.python3]: `
|
[DependenceTypes.python3]: `
|
||||||
python3 -c "exec('''
|
python3 -c "exec('''
|
||||||
name='${name}'
|
name='${trimmedName}'
|
||||||
try:
|
try:
|
||||||
from importlib.metadata import version
|
from importlib.metadata import version
|
||||||
print(version(name))
|
print(version(name))
|
||||||
@@ -550,7 +581,7 @@ except:
|
|||||||
spec=u.find_spec(name)
|
spec=u.find_spec(name)
|
||||||
print(name if spec else '')
|
print(name if spec else '')
|
||||||
''')"`,
|
''')"`,
|
||||||
[DependenceTypes.linux]: `apk info -es ${name}`,
|
[DependenceTypes.linux]: `apk info -es ${trimmedName}`,
|
||||||
};
|
};
|
||||||
|
|
||||||
return baseCommands[type];
|
return baseCommands[type];
|
||||||
@@ -570,7 +601,33 @@ export function getInstallCommand(type: DependenceTypes, name: string): string {
|
|||||||
command = `${command} --prefix=${PYTHON_INSTALL_DIR}`;
|
command = `${command} --prefix=${PYTHON_INSTALL_DIR}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${command} ${name.trim()}`;
|
const trimmedName = name.trim();
|
||||||
|
|
||||||
|
// Handle different installation methods for Python
|
||||||
|
if (type === DependenceTypes.python3) {
|
||||||
|
// Check if it's a GitHub URL (support both git+ and direct URLs)
|
||||||
|
if (isGitHubUrl(trimmedName)) {
|
||||||
|
return `${command} ${trimmedName}`;
|
||||||
|
}
|
||||||
|
// Check if it's a requirements file path
|
||||||
|
if (isRequirementsFile(trimmedName)) {
|
||||||
|
return `${command} -r ${trimmedName}`;
|
||||||
|
}
|
||||||
|
// Check if it's a pyproject.toml file
|
||||||
|
if (isPyprojectToml(trimmedName)) {
|
||||||
|
// For pyproject.toml, install from the directory containing it
|
||||||
|
const pathMatch = trimmedName.match(/^(.+)\/pyproject\.toml$/);
|
||||||
|
if (pathMatch) {
|
||||||
|
// Has a path prefix, use the directory
|
||||||
|
return `${command} ${pathMatch[1]}`;
|
||||||
|
} else {
|
||||||
|
// Just "pyproject.toml", install current directory
|
||||||
|
return `${command} .`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${command} ${trimmedName}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getUninstallCommand(
|
export function getUninstallCommand(
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
import { sequelize } from '.';
|
|
||||||
import { DataTypes, Model } from 'sequelize';
|
|
||||||
|
|
||||||
export class CronLog {
|
|
||||||
id?: number;
|
|
||||||
cron_id: number;
|
|
||||||
cron_name: string;
|
|
||||||
start_time: number;
|
|
||||||
duration: number;
|
|
||||||
|
|
||||||
constructor(options: CronLog) {
|
|
||||||
this.cron_id = options.cron_id;
|
|
||||||
this.cron_name = options.cron_name;
|
|
||||||
this.start_time = options.start_time;
|
|
||||||
this.duration = options.duration;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CronLogInstance extends Model<CronLog, CronLog>, CronLog {}
|
|
||||||
export const CronLogModel = sequelize.define<CronLogInstance>(
|
|
||||||
'CronLog',
|
|
||||||
{
|
|
||||||
cron_id: DataTypes.NUMBER,
|
|
||||||
cron_name: DataTypes.STRING,
|
|
||||||
start_time: DataTypes.NUMBER,
|
|
||||||
duration: DataTypes.NUMBER,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
indexes: [{ fields: ['cron_id'] }, { fields: ['start_time'] }],
|
|
||||||
},
|
|
||||||
);
|
|
||||||
@@ -6,7 +6,6 @@ import { AppModel } from '../data/open';
|
|||||||
import { SystemModel } from '../data/system';
|
import { SystemModel } from '../data/system';
|
||||||
import { SubscriptionModel } from '../data/subscription';
|
import { SubscriptionModel } from '../data/subscription';
|
||||||
import { CrontabViewModel } from '../data/cronView';
|
import { CrontabViewModel } from '../data/cronView';
|
||||||
import { CronLogModel } from '../data/cronLog';
|
|
||||||
import { sequelize } from '../data';
|
import { sequelize } from '../data';
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
@@ -18,7 +17,6 @@ export default async () => {
|
|||||||
await EnvModel.sync();
|
await EnvModel.sync();
|
||||||
await SubscriptionModel.sync();
|
await SubscriptionModel.sync();
|
||||||
await CrontabViewModel.sync();
|
await CrontabViewModel.sync();
|
||||||
await CronLogModel.sync();
|
|
||||||
|
|
||||||
// 初始化新增字段
|
// 初始化新增字段
|
||||||
const migrations = [
|
const migrations = [
|
||||||
|
|||||||
+5
-34
@@ -13,29 +13,9 @@ import { isValidToken } from '../shared/auth';
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
export default ({ app }: { app: Application }) => {
|
export default ({ app }: { app: Application }) => {
|
||||||
// Security: Enable strict routing to prevent case-insensitive path bypass
|
|
||||||
app.set('case sensitive routing', true);
|
|
||||||
app.set('strict routing', true);
|
|
||||||
app.set('trust proxy', 'loopback');
|
app.set('trust proxy', 'loopback');
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
|
|
||||||
// Security: Path normalization middleware to prevent case variation attacks
|
|
||||||
app.use((req, res, next) => {
|
|
||||||
const originalPath = req.path;
|
|
||||||
const normalizedPath = originalPath.toLowerCase();
|
|
||||||
|
|
||||||
// Block requests with case variations on protected paths
|
|
||||||
if (originalPath !== normalizedPath &&
|
|
||||||
(normalizedPath.startsWith('/api/') || normalizedPath.startsWith('/open/'))) {
|
|
||||||
return res.status(400).json({
|
|
||||||
code: 400,
|
|
||||||
message: 'Invalid path format'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
next();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Rewrite URLs to strip baseUrl prefix if configured
|
// Rewrite URLs to strip baseUrl prefix if configured
|
||||||
// This allows the rest of the app to work without baseUrl awareness
|
// This allows the rest of the app to work without baseUrl awareness
|
||||||
if (config.baseUrl) {
|
if (config.baseUrl) {
|
||||||
@@ -56,7 +36,7 @@ export default ({ app }: { app: Application }) => {
|
|||||||
secret: config.jwt.secret,
|
secret: config.jwt.secret,
|
||||||
algorithms: ['HS384'],
|
algorithms: ['HS384'],
|
||||||
}).unless({
|
}).unless({
|
||||||
path: [...config.apiWhiteList, /^(\/(?!api\/).*)$/i],
|
path: [...config.apiWhiteList, /^\/(?!api\/).*/],
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -71,20 +51,19 @@ export default ({ app }: { app: Application }) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.use(async (req: Request, res, next) => {
|
app.use(async (req: Request, res, next) => {
|
||||||
const pathLower = req.path.toLowerCase();
|
if (!['/open/', '/api/'].some((x) => req.path.startsWith(x))) {
|
||||||
if (!['/open/', '/api/'].some((x) => pathLower.startsWith(x))) {
|
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
const headerToken = getToken(req);
|
const headerToken = getToken(req);
|
||||||
if (pathLower.startsWith('/open/')) {
|
if (req.path.startsWith('/open/')) {
|
||||||
const apps = await shareStore.getApps();
|
const apps = await shareStore.getApps();
|
||||||
const doc = apps?.filter((x) =>
|
const doc = apps?.filter((x) =>
|
||||||
x.tokens?.find((y) => y.value === headerToken),
|
x.tokens?.find((y) => y.value === headerToken),
|
||||||
)?.[0];
|
)?.[0];
|
||||||
if (doc && doc.tokens && doc.tokens.length > 0) {
|
if (doc && doc.tokens && doc.tokens.length > 0) {
|
||||||
const currentToken = doc.tokens.find((x) => x.value === headerToken);
|
const currentToken = doc.tokens.find((x) => x.value === headerToken);
|
||||||
const keyMatch = pathLower.match(/\/open\/([a-z]+)\/*/);
|
const keyMatch = req.path.match(/\/open\/([a-z]+)\/*/);
|
||||||
const key = keyMatch && keyMatch[1];
|
const key = keyMatch && keyMatch[1];
|
||||||
if (
|
if (
|
||||||
doc.scopes.includes(key as any) &&
|
doc.scopes.includes(key as any) &&
|
||||||
@@ -119,15 +98,7 @@ export default ({ app }: { app: Application }) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.use(async (req, res, next) => {
|
app.use(async (req, res, next) => {
|
||||||
const pathLower = req.path.toLowerCase();
|
if (!['/api/user/init', '/api/user/notification/init'].includes(req.path)) {
|
||||||
if (
|
|
||||||
![
|
|
||||||
'/api/user/init',
|
|
||||||
'/api/user/notification/init',
|
|
||||||
'/open/user/init',
|
|
||||||
'/open/user/notification/init',
|
|
||||||
].includes(req.path)
|
|
||||||
) {
|
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
const authInfo =
|
const authInfo =
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { AuthDataType, SystemModel } from '../data/system';
|
|||||||
import SystemService from '../services/system';
|
import SystemService from '../services/system';
|
||||||
import UserService from '../services/user';
|
import UserService from '../services/user';
|
||||||
import { writeFile, readFile } from 'fs/promises';
|
import { writeFile, readFile } from 'fs/promises';
|
||||||
import { createRandomString, fileExist, isDemoEnv, safeJSONParse } from '../config/util';
|
import { createRandomString, fileExist, safeJSONParse } from '../config/util';
|
||||||
import OpenService from '../services/open';
|
import OpenService from '../services/open';
|
||||||
import { shareStore } from '../shared/store';
|
import { shareStore } from '../shared/store';
|
||||||
import Logger from './logger';
|
import Logger from './logger';
|
||||||
@@ -50,7 +50,7 @@ export default async () => {
|
|||||||
const [authConfig] = await SystemModel.findOrCreate({
|
const [authConfig] = await SystemModel.findOrCreate({
|
||||||
where: { type: AuthDataType.authConfig },
|
where: { type: AuthDataType.authConfig },
|
||||||
});
|
});
|
||||||
if (!authConfig?.info || isDemoEnv()) {
|
if (!authConfig?.info) {
|
||||||
let authInfo = {
|
let authInfo = {
|
||||||
username: 'admin',
|
username: 'admin',
|
||||||
password: 'admin',
|
password: 'admin',
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { Service, Inject } from 'typedi';
|
|||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
||||||
import { CronLog, CronLogModel } from '../data/cronLog';
|
|
||||||
import { exec, execSync } from 'child_process';
|
import { exec, execSync } from 'child_process';
|
||||||
import fs from 'fs/promises';
|
import fs from 'fs/promises';
|
||||||
import CronExpressionParser from 'cron-parser';
|
import CronExpressionParser from 'cron-parser';
|
||||||
@@ -177,18 +176,6 @@ export default class CronService {
|
|||||||
{ ...pickBy(options, (v) => v === 0 || !!v) },
|
{ ...pickBy(options, (v) => v === 0 || !!v) },
|
||||||
{ where: { id } },
|
{ where: { id } },
|
||||||
);
|
);
|
||||||
|
|
||||||
if (status === CrontabStatus.idle && last_running_time > 0) {
|
|
||||||
const cronName = (cron.name || cron.command || '').substring(0, 255);
|
|
||||||
await CronLogModel.create(
|
|
||||||
new CronLog({
|
|
||||||
cron_id: id,
|
|
||||||
cron_name: cronName,
|
|
||||||
start_time: last_execution_time,
|
|
||||||
duration: last_running_time,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,137 +0,0 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
|
||||||
import winston from 'winston';
|
|
||||||
import { CrontabModel } from '../data/cron';
|
|
||||||
import { CronLog, CronLogModel } from '../data/cronLog';
|
|
||||||
import { Op } from 'sequelize';
|
|
||||||
import dayjs from 'dayjs';
|
|
||||||
|
|
||||||
type GroupedLog = {
|
|
||||||
cron_id: number;
|
|
||||||
cron_name: string;
|
|
||||||
durations: number[];
|
|
||||||
};
|
|
||||||
|
|
||||||
@Service()
|
|
||||||
export default class CronStatsService {
|
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
|
||||||
|
|
||||||
private groupLogsByCronId(logs: CronLog[]): Record<number, GroupedLog> {
|
|
||||||
const grouped: Record<number, GroupedLog> = {};
|
|
||||||
for (const log of logs) {
|
|
||||||
if (!grouped[log.cron_id]) {
|
|
||||||
grouped[log.cron_id] = {
|
|
||||||
cron_id: log.cron_id,
|
|
||||||
cron_name: log.cron_name,
|
|
||||||
durations: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
grouped[log.cron_id].durations.push(log.duration);
|
|
||||||
}
|
|
||||||
return grouped;
|
|
||||||
}
|
|
||||||
|
|
||||||
private avgOf(nums: number[]): number {
|
|
||||||
if (nums.length === 0) return 0;
|
|
||||||
return Math.round(nums.reduce((a, b) => a + b, 0) / nums.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
private getTodayRange() {
|
|
||||||
return {
|
|
||||||
start: dayjs().startOf('day').unix(),
|
|
||||||
end: dayjs().endOf('day').unix(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public async stats() {
|
|
||||||
const { start, end } = this.getTodayRange();
|
|
||||||
|
|
||||||
const [allCrons, todayLogs] = await Promise.all([
|
|
||||||
CrontabModel.findAll({ where: {} }),
|
|
||||||
CronLogModel.findAll({
|
|
||||||
where: { start_time: { [Op.between]: [start, end] } },
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const total = allCrons.length;
|
|
||||||
const enabled = allCrons.filter((c: any) => c.isDisabled !== 1).length;
|
|
||||||
const disabled = allCrons.filter((c: any) => c.isDisabled === 1).length;
|
|
||||||
|
|
||||||
const todayCount = todayLogs.length;
|
|
||||||
const todayTotalDuration = todayLogs.reduce(
|
|
||||||
(sum: number, l: any) => sum + (l.duration || 0),
|
|
||||||
0,
|
|
||||||
);
|
|
||||||
const todayAvgDuration =
|
|
||||||
todayCount > 0 ? Math.round(todayTotalDuration / todayCount) : 0;
|
|
||||||
|
|
||||||
return {
|
|
||||||
total,
|
|
||||||
enabled,
|
|
||||||
disabled,
|
|
||||||
today: {
|
|
||||||
count: todayCount,
|
|
||||||
avgDuration: todayAvgDuration,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public async trend() {
|
|
||||||
const days = 7;
|
|
||||||
const result: Array<{ date: string; count: number }> = [];
|
|
||||||
|
|
||||||
for (let i = days - 1; i >= 0; i--) {
|
|
||||||
const dayStart = dayjs().subtract(i, 'day').startOf('day').unix();
|
|
||||||
const dayEnd = dayjs().subtract(i, 'day').endOf('day').unix();
|
|
||||||
const date = dayjs().subtract(i, 'day').format('MM-DD');
|
|
||||||
|
|
||||||
const logs = await CronLogModel.findAll({
|
|
||||||
where: { start_time: { [Op.between]: [dayStart, dayEnd] } },
|
|
||||||
});
|
|
||||||
|
|
||||||
result.push({ date, count: logs.length });
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async topDuration(limit = 5) {
|
|
||||||
const { start, end } = this.getTodayRange();
|
|
||||||
|
|
||||||
const logs = await CronLogModel.findAll({
|
|
||||||
where: { start_time: { [Op.between]: [start, end] } },
|
|
||||||
});
|
|
||||||
|
|
||||||
const grouped = this.groupLogsByCronId(logs as any);
|
|
||||||
|
|
||||||
return Object.values(grouped)
|
|
||||||
.map((g) => ({
|
|
||||||
cron_id: g.cron_id,
|
|
||||||
cron_name: g.cron_name,
|
|
||||||
count: g.durations.length,
|
|
||||||
avgDuration: this.avgOf(g.durations),
|
|
||||||
maxDuration: Math.max(...g.durations),
|
|
||||||
}))
|
|
||||||
.sort((a, b) => b.avgDuration - a.avgDuration)
|
|
||||||
.slice(0, limit);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async topCount(limit = 5) {
|
|
||||||
const { start, end } = this.getTodayRange();
|
|
||||||
|
|
||||||
const logs = await CronLogModel.findAll({
|
|
||||||
where: { start_time: { [Op.between]: [start, end] } },
|
|
||||||
});
|
|
||||||
|
|
||||||
const grouped = this.groupLogsByCronId(logs as any);
|
|
||||||
|
|
||||||
return Object.values(grouped)
|
|
||||||
.map((g) => ({
|
|
||||||
cron_id: g.cron_id,
|
|
||||||
cron_name: g.cron_name,
|
|
||||||
count: g.durations.length,
|
|
||||||
avgDuration: this.avgOf(g.durations),
|
|
||||||
}))
|
|
||||||
.sort((a, b) => b.count - a.count)
|
|
||||||
.slice(0, limit);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -69,10 +69,9 @@ RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
|||||||
|
|
||||||
ENV PNPM_HOME=${QL_DIR}/data/dep_cache/node \
|
ENV PNPM_HOME=${QL_DIR}/data/dep_cache/node \
|
||||||
PYTHON_HOME=${QL_DIR}/data/dep_cache/python3 \
|
PYTHON_HOME=${QL_DIR}/data/dep_cache/python3 \
|
||||||
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3 \
|
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3
|
||||||
HOME=/root
|
|
||||||
|
|
||||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin:${HOME}/bin \
|
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin \
|
||||||
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules:${PNPM_HOME}/global/5/node_modules \
|
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules:${PNPM_HOME}/global/5/node_modules \
|
||||||
PIP_CACHE_DIR=${PYTHON_HOME}/pip \
|
PIP_CACHE_DIR=${PYTHON_HOME}/pip \
|
||||||
PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
|
PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
|
||||||
@@ -84,6 +83,6 @@ COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
|||||||
WORKDIR ${QL_DIR}
|
WORKDIR ${QL_DIR}
|
||||||
|
|
||||||
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
||||||
CMD curl -sf --noproxy '*' http://127.0.0.1:${QlPort:-5700}/api/health || exit 1
|
CMD curl -sf --noproxy '*' http://127.0.0.1:5700/api/health || exit 1
|
||||||
|
|
||||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||||
|
|||||||
+3
-4
@@ -69,10 +69,9 @@ RUN git clone --depth=1 -b ${QL_BRANCH} ${QL_URL} ${QL_DIR} \
|
|||||||
|
|
||||||
ENV PNPM_HOME=${QL_DIR}/data/dep_cache/node \
|
ENV PNPM_HOME=${QL_DIR}/data/dep_cache/node \
|
||||||
PYTHON_HOME=${QL_DIR}/data/dep_cache/python3 \
|
PYTHON_HOME=${QL_DIR}/data/dep_cache/python3 \
|
||||||
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3 \
|
PYTHONUSERBASE=${QL_DIR}/data/dep_cache/python3
|
||||||
HOME=/root
|
|
||||||
|
|
||||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin:${HOME}/bin \
|
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PNPM_HOME}:${PYTHON_HOME}/bin \
|
||||||
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules:${PNPM_HOME}/global/5/node_modules \
|
NODE_PATH=/usr/local/bin:/usr/local/lib/node_modules:${PNPM_HOME}/global/5/node_modules \
|
||||||
PIP_CACHE_DIR=${PYTHON_HOME}/pip \
|
PIP_CACHE_DIR=${PYTHON_HOME}/pip \
|
||||||
PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
|
PYTHONPATH=${PYTHON_HOME}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}:${PYTHON_HOME}/lib/python${PYTHON_SHORT_VERSION}/site-packages
|
||||||
@@ -84,6 +83,6 @@ COPY --from=builder /tmp/build/node_modules/. /ql/node_modules/
|
|||||||
WORKDIR ${QL_DIR}
|
WORKDIR ${QL_DIR}
|
||||||
|
|
||||||
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
HEALTHCHECK --interval=5s --timeout=2s --retries=20 \
|
||||||
CMD curl -sf --noproxy '*' http://127.0.0.1:${QlPort:-5700}/api/health || exit 1
|
CMD curl -sf --noproxy '*' http://127.0.0.1:5700/api/health || exit 1
|
||||||
|
|
||||||
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
ENTRYPOINT ["./docker/docker-entrypoint.sh"]
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
|
export PATH="$HOME/bin:$PATH"
|
||||||
|
|
||||||
dir_shell=/ql/shell
|
dir_shell=/ql/shell
|
||||||
. $dir_shell/share.sh
|
. $dir_shell/share.sh
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -77,9 +77,9 @@
|
|||||||
"js-yaml": "^4.1.0",
|
"js-yaml": "^4.1.0",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"multer": "2.1.1",
|
"multer": "1.4.5-lts.1",
|
||||||
"node-schedule": "^2.1.0",
|
"node-schedule": "^2.1.0",
|
||||||
"nodemailer": "^8.0.1",
|
"nodemailer": "^6.9.16",
|
||||||
"p-queue-cjs": "7.3.4",
|
"p-queue-cjs": "7.3.4",
|
||||||
"@bufbuild/protobuf": "^2.10.0",
|
"@bufbuild/protobuf": "^2.10.0",
|
||||||
"ps-tree": "^1.2.0",
|
"ps-tree": "^1.2.0",
|
||||||
|
|||||||
Generated
+259
-568
File diff suppressed because it is too large
Load Diff
@@ -111,6 +111,76 @@ add_cron() {
|
|||||||
notify_api "$path 新增任务" "$detail"
|
notify_api "$path 新增任务" "$detail"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
## 自动安装订阅仓库中的Python依赖
|
||||||
|
auto_install_python_deps() {
|
||||||
|
local repo_path="$1"
|
||||||
|
local uniq_path="$2"
|
||||||
|
|
||||||
|
echo -e "\n检测订阅仓库中的Python依赖文件...\n"
|
||||||
|
|
||||||
|
get_token
|
||||||
|
|
||||||
|
# 检查 requirements.txt
|
||||||
|
if [[ -f "${repo_path}/requirements.txt" ]]; then
|
||||||
|
echo -e "发现 requirements.txt,开始自动安装依赖...\n"
|
||||||
|
local req_file="${dir_scripts}/${uniq_path}/requirements.txt"
|
||||||
|
|
||||||
|
# 确保目标目录存在
|
||||||
|
make_dir "${dir_scripts}/${uniq_path}"
|
||||||
|
|
||||||
|
# 复制文件并检查结果
|
||||||
|
if cp -f "${repo_path}/requirements.txt" "${req_file}" 2>/dev/null; then
|
||||||
|
# 调用API添加依赖安装任务
|
||||||
|
local dep_name="${uniq_path}/requirements.txt"
|
||||||
|
local currentTimeStamp=$(date +%s)
|
||||||
|
local result=$(curl -s --noproxy "*" "http://127.0.0.1:${ql_port}/open/dependencies?t=$currentTimeStamp" \
|
||||||
|
-X POST \
|
||||||
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
|
--data-raw "[{\"name\":\"${dep_name}\",\"type\":1,\"remark\":\"自动检测:${uniq_path} 订阅依赖\"}]" 2>/dev/null)
|
||||||
|
|
||||||
|
local code=$(echo "$result" | jq -r '.code' 2>/dev/null)
|
||||||
|
if [[ "$code" == "200" ]]; then
|
||||||
|
echo -e "已添加 requirements.txt 依赖安装任务\n"
|
||||||
|
else
|
||||||
|
echo -e "添加 requirements.txt 依赖失败,请手动添加\n"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo -e "复制 requirements.txt 失败,跳过自动安装\n"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 检查 pyproject.toml
|
||||||
|
if [[ -f "${repo_path}/pyproject.toml" ]]; then
|
||||||
|
echo -e "发现 pyproject.toml,开始自动安装依赖...\n"
|
||||||
|
local pyproject_file="${dir_scripts}/${uniq_path}/pyproject.toml"
|
||||||
|
|
||||||
|
# 确保目标目录存在
|
||||||
|
make_dir "${dir_scripts}/${uniq_path}"
|
||||||
|
|
||||||
|
# 复制文件并检查结果
|
||||||
|
if cp -f "${repo_path}/pyproject.toml" "${pyproject_file}" 2>/dev/null; then
|
||||||
|
# 调用API添加依赖安装任务
|
||||||
|
local dep_name="${uniq_path}/pyproject.toml"
|
||||||
|
local currentTimeStamp=$(date +%s)
|
||||||
|
local result=$(curl -s --noproxy "*" "http://127.0.0.1:${ql_port}/open/dependencies?t=$currentTimeStamp" \
|
||||||
|
-X POST \
|
||||||
|
-H "Content-Type: application/json;charset=UTF-8" \
|
||||||
|
-H "Authorization: Bearer ${__ql_token__}" \
|
||||||
|
--data-raw "[{\"name\":\"${dep_name}\",\"type\":1,\"remark\":\"自动检测:${uniq_path} 订阅依赖\"}]" 2>/dev/null)
|
||||||
|
|
||||||
|
local code=$(echo "$result" | jq -r '.code' 2>/dev/null)
|
||||||
|
if [[ "$code" == "200" ]]; then
|
||||||
|
echo -e "已添加 pyproject.toml 依赖安装任务\n"
|
||||||
|
else
|
||||||
|
echo -e "添加 pyproject.toml 依赖失败,请手动添加\n"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo -e "复制 pyproject.toml 失败,跳过自动安装\n"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
## 更新仓库
|
## 更新仓库
|
||||||
update_repo() {
|
update_repo() {
|
||||||
local url="$1"
|
local url="$1"
|
||||||
@@ -137,6 +207,10 @@ update_repo() {
|
|||||||
|
|
||||||
if [[ $exit_status -eq 0 ]]; then
|
if [[ $exit_status -eq 0 ]]; then
|
||||||
echo -e "拉取 ${uniq_path} 成功...\n"
|
echo -e "拉取 ${uniq_path} 成功...\n"
|
||||||
|
|
||||||
|
# 自动检测并安装Python依赖
|
||||||
|
auto_install_python_deps "${repo_path}" "${uniq_path}"
|
||||||
|
|
||||||
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions" "$autoAddCron" "$autoDelCron"
|
diff_scripts "$repo_path" "$author" "$path" "$blackword" "$dependence" "$extensions" "$autoAddCron" "$autoDelCron"
|
||||||
else
|
else
|
||||||
echo -e "拉取 ${uniq_path} 失败,请检查日志...\n"
|
echo -e "拉取 ${uniq_path} 失败,请检查日志...\n"
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import intl from 'react-intl-universal';
|
import intl from 'react-intl-universal';
|
||||||
import { BarChartOutlined, SettingOutlined } from '@ant-design/icons';
|
import { SettingOutlined } from '@ant-design/icons';
|
||||||
import IconFont from '@/components/iconfont';
|
import IconFont from '@/components/iconfont';
|
||||||
import { BasicLayoutProps } from '@ant-design/pro-layout';
|
import { BasicLayoutProps } from '@ant-design/pro-layout';
|
||||||
|
|
||||||
@@ -30,12 +30,6 @@ export default {
|
|||||||
icon: <IconFont type="ql-icon-crontab" />,
|
icon: <IconFont type="ql-icon-crontab" />,
|
||||||
component: '@/pages/crontab/index',
|
component: '@/pages/crontab/index',
|
||||||
},
|
},
|
||||||
{
|
|
||||||
path: '/statistics',
|
|
||||||
name: intl.get('统计面板'),
|
|
||||||
icon: <BarChartOutlined />,
|
|
||||||
component: '@/pages/statistics/index',
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
path: '/subscription',
|
path: '/subscription',
|
||||||
name: intl.get('订阅管理'),
|
name: intl.get('订阅管理'),
|
||||||
|
|||||||
@@ -18,25 +18,6 @@
|
|||||||
"青龙": "Qinglong",
|
"青龙": "Qinglong",
|
||||||
"返回首页": "Return to Home",
|
"返回首页": "Return to Home",
|
||||||
"保存": "Save",
|
"保存": "Save",
|
||||||
"统计面板": "Statistics",
|
|
||||||
"总体概览": "Overview",
|
|
||||||
"总任务数量": "Total Tasks",
|
|
||||||
"启用任务数": "Enabled Tasks",
|
|
||||||
"禁用任务数": "Disabled Tasks",
|
|
||||||
"今日总执行次数": "Today's Executions",
|
|
||||||
"今日平均耗时(秒)": "Today's Avg Duration (s)",
|
|
||||||
"近7日执行趋势": "7-Day Execution Trend",
|
|
||||||
"今日平均耗时 Top 5": "Top 5 Slowest Today",
|
|
||||||
"今日执行次数 Top 5": "Top 5 Most Frequent Today",
|
|
||||||
"排名": "Rank",
|
|
||||||
"任务名称": "Task Name",
|
|
||||||
"平均耗时(秒)": "Avg Duration (s)",
|
|
||||||
"最长单次(秒)": "Max Duration (s)",
|
|
||||||
"今日执行次数": "Today's Count",
|
|
||||||
"今日暂无执行记录": "No execution records today",
|
|
||||||
"暂无数据": "No data",
|
|
||||||
"次": "times",
|
|
||||||
"刷新": "Refresh",
|
|
||||||
"日志": "Log",
|
"日志": "Log",
|
||||||
"脚本": "Script",
|
"脚本": "Script",
|
||||||
"确认保存文件": "Confirm to Save File",
|
"确认保存文件": "Confirm to Save File",
|
||||||
|
|||||||
@@ -18,25 +18,6 @@
|
|||||||
"青龙": "青龙",
|
"青龙": "青龙",
|
||||||
"返回首页": "返回首页",
|
"返回首页": "返回首页",
|
||||||
"保存": "保存",
|
"保存": "保存",
|
||||||
"统计面板": "统计面板",
|
|
||||||
"总体概览": "总体概览",
|
|
||||||
"总任务数量": "总任务数量",
|
|
||||||
"启用任务数": "启用任务数",
|
|
||||||
"禁用任务数": "禁用任务数",
|
|
||||||
"今日总执行次数": "今日总执行次数",
|
|
||||||
"今日平均耗时(秒)": "今日平均耗时(秒)",
|
|
||||||
"近7日执行趋势": "近7日执行趋势",
|
|
||||||
"今日平均耗时 Top 5": "今日平均耗时 Top 5",
|
|
||||||
"今日执行次数 Top 5": "今日执行次数 Top 5",
|
|
||||||
"排名": "排名",
|
|
||||||
"任务名称": "任务名称",
|
|
||||||
"平均耗时(秒)": "平均耗时(秒)",
|
|
||||||
"最长单次(秒)": "最长单次(秒)",
|
|
||||||
"今日执行次数": "今日执行次数",
|
|
||||||
"今日暂无执行记录": "今日暂无执行记录",
|
|
||||||
"暂无数据": "暂无数据",
|
|
||||||
"次": "次",
|
|
||||||
"刷新": "刷新",
|
|
||||||
"日志": "日志",
|
"日志": "日志",
|
||||||
"脚本": "脚本",
|
"脚本": "脚本",
|
||||||
"确认保存文件": "确认保存文件",
|
"确认保存文件": "确认保存文件",
|
||||||
|
|||||||
@@ -22,6 +22,9 @@ const DependenceModal = ({
|
|||||||
}) => {
|
}) => {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [selectedType, setSelectedType] = useState(
|
||||||
|
DependenceTypes[defaultType as any],
|
||||||
|
);
|
||||||
|
|
||||||
const handleOk = async (values: any) => {
|
const handleOk = async (values: any) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -90,7 +93,7 @@ const DependenceModal = ({
|
|||||||
label={intl.get('依赖类型')}
|
label={intl.get('依赖类型')}
|
||||||
initialValue={DependenceTypes[defaultType as any]}
|
initialValue={DependenceTypes[defaultType as any]}
|
||||||
>
|
>
|
||||||
<Select>
|
<Select onChange={(value) => setSelectedType(value)}>
|
||||||
{config.dependenceTypes.map((x, i) => (
|
{config.dependenceTypes.map((x, i) => (
|
||||||
<Option key={i} value={i}>
|
<Option key={i} value={i}>
|
||||||
{x}
|
{x}
|
||||||
@@ -121,11 +124,24 @@ const DependenceModal = ({
|
|||||||
whitespace: true,
|
whitespace: true,
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
|
tooltip={
|
||||||
|
selectedType === DependenceTypes.python3
|
||||||
|
? intl.get(
|
||||||
|
'Python支持多种安装方式:\n1. 包名(如:requests)\n2. GitHub链接(如:git+https://github.com/user/repo.git)\n3. requirements文件路径(如:path/to/requirements.txt)\n4. pyproject.toml文件路径',
|
||||||
|
)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<Input.TextArea
|
<Input.TextArea
|
||||||
rows={4}
|
rows={4}
|
||||||
autoSize={{ minRows: 1, maxRows: 5 }}
|
autoSize={{ minRows: 1, maxRows: 5 }}
|
||||||
placeholder={intl.get('请输入依赖名称')}
|
placeholder={
|
||||||
|
selectedType === DependenceTypes.python3
|
||||||
|
? intl.get(
|
||||||
|
'支持包名、GitHub链接、requirements.txt或pyproject.toml路径',
|
||||||
|
)
|
||||||
|
: intl.get('请输入依赖名称')
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="remark" label={intl.get('备注')}>
|
<Form.Item name="remark" label={intl.get('备注')}>
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
.stats-section {
|
|
||||||
margin-bottom: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.trend-chart-wrapper {
|
|
||||||
width: 100%;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.trend-chart-empty {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
height: 200px;
|
|
||||||
color: #999;
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
|
||||||
@@ -1,402 +0,0 @@
|
|||||||
import { SharedContext } from '@/layouts';
|
|
||||||
import config from '@/utils/config';
|
|
||||||
import { request } from '@/utils/http';
|
|
||||||
import { BarChartOutlined, ReloadOutlined } from '@ant-design/icons';
|
|
||||||
import { PageContainer } from '@ant-design/pro-layout';
|
|
||||||
import { useOutletContext } from '@umijs/max';
|
|
||||||
import {
|
|
||||||
Button,
|
|
||||||
Card,
|
|
||||||
Col,
|
|
||||||
Row,
|
|
||||||
Statistic,
|
|
||||||
Table,
|
|
||||||
Tooltip,
|
|
||||||
Typography,
|
|
||||||
} from 'antd';
|
|
||||||
import { ColumnProps } from 'antd/lib/table';
|
|
||||||
import React, { useEffect, useState } from 'react';
|
|
||||||
import intl from 'react-intl-universal';
|
|
||||||
import './index.less';
|
|
||||||
|
|
||||||
const { Title } = Typography;
|
|
||||||
|
|
||||||
interface StatsData {
|
|
||||||
total: number;
|
|
||||||
enabled: number;
|
|
||||||
disabled: number;
|
|
||||||
today: {
|
|
||||||
count: number;
|
|
||||||
avgDuration: number;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TrendItem {
|
|
||||||
date: string;
|
|
||||||
count: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TopDurationItem {
|
|
||||||
cron_id: number;
|
|
||||||
cron_name: string;
|
|
||||||
count: number;
|
|
||||||
avgDuration: number;
|
|
||||||
maxDuration: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TopCountItem {
|
|
||||||
cron_id: number;
|
|
||||||
cron_name: string;
|
|
||||||
count: number;
|
|
||||||
avgDuration: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const TrendChart = ({ data }: { data: TrendItem[] }) => {
|
|
||||||
if (!data || data.length === 0) {
|
|
||||||
return (
|
|
||||||
<div className="trend-chart-empty">
|
|
||||||
{intl.get('暂无数据')}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const width = 600;
|
|
||||||
const height = 200;
|
|
||||||
const paddingLeft = 40;
|
|
||||||
const paddingRight = 20;
|
|
||||||
const paddingTop = 20;
|
|
||||||
const paddingBottom = 40;
|
|
||||||
|
|
||||||
const chartWidth = width - paddingLeft - paddingRight;
|
|
||||||
const chartHeight = height - paddingTop - paddingBottom;
|
|
||||||
|
|
||||||
const maxCount = Math.max(...data.map((d) => d.count), 1);
|
|
||||||
|
|
||||||
const points = data.map((d, i) => ({
|
|
||||||
x: paddingLeft + (i / Math.max(data.length - 1, 1)) * chartWidth,
|
|
||||||
y: paddingTop + chartHeight - (d.count / maxCount) * chartHeight,
|
|
||||||
...d,
|
|
||||||
}));
|
|
||||||
|
|
||||||
const pathD = points
|
|
||||||
.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x.toFixed(1)} ${p.y.toFixed(1)}`)
|
|
||||||
.join(' ');
|
|
||||||
|
|
||||||
const areaD =
|
|
||||||
pathD +
|
|
||||||
` L ${points[points.length - 1].x.toFixed(1)} ${(paddingTop + chartHeight).toFixed(1)}` +
|
|
||||||
` L ${points[0].x.toFixed(1)} ${(paddingTop + chartHeight).toFixed(1)} Z`;
|
|
||||||
|
|
||||||
const yTicks = [0, Math.ceil(maxCount / 2), maxCount];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="trend-chart-wrapper">
|
|
||||||
<svg
|
|
||||||
viewBox={`0 0 ${width} ${height}`}
|
|
||||||
preserveAspectRatio="xMidYMid meet"
|
|
||||||
style={{ width: '100%', height: 200 }}
|
|
||||||
>
|
|
||||||
{/* Grid lines */}
|
|
||||||
{yTicks.map((tick) => {
|
|
||||||
const y =
|
|
||||||
paddingTop + chartHeight - (tick / maxCount) * chartHeight;
|
|
||||||
return (
|
|
||||||
<g key={tick}>
|
|
||||||
<line
|
|
||||||
x1={paddingLeft}
|
|
||||||
y1={y}
|
|
||||||
x2={paddingLeft + chartWidth}
|
|
||||||
y2={y}
|
|
||||||
stroke="#f0f0f0"
|
|
||||||
strokeWidth={1}
|
|
||||||
/>
|
|
||||||
<text
|
|
||||||
x={paddingLeft - 6}
|
|
||||||
y={y + 4}
|
|
||||||
textAnchor="end"
|
|
||||||
fontSize={10}
|
|
||||||
fill="#999"
|
|
||||||
>
|
|
||||||
{tick}
|
|
||||||
</text>
|
|
||||||
</g>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
|
|
||||||
{/* Area fill */}
|
|
||||||
<path d={areaD} fill="rgba(24, 144, 255, 0.1)" />
|
|
||||||
|
|
||||||
{/* Line */}
|
|
||||||
<path
|
|
||||||
d={pathD}
|
|
||||||
fill="none"
|
|
||||||
stroke="#1890ff"
|
|
||||||
strokeWidth={2}
|
|
||||||
strokeLinejoin="round"
|
|
||||||
strokeLinecap="round"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Points */}
|
|
||||||
{points.map((p, i) => (
|
|
||||||
<Tooltip
|
|
||||||
key={i}
|
|
||||||
title={`${p.date}: ${p.count} ${intl.get('次')}`}
|
|
||||||
>
|
|
||||||
<circle
|
|
||||||
cx={p.x}
|
|
||||||
cy={p.y}
|
|
||||||
r={4}
|
|
||||||
fill="#1890ff"
|
|
||||||
stroke="#fff"
|
|
||||||
strokeWidth={2}
|
|
||||||
style={{ cursor: 'pointer' }}
|
|
||||||
/>
|
|
||||||
</Tooltip>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{/* X axis labels */}
|
|
||||||
{points.map((p, i) => (
|
|
||||||
<text
|
|
||||||
key={i}
|
|
||||||
x={p.x}
|
|
||||||
y={height - 8}
|
|
||||||
textAnchor="middle"
|
|
||||||
fontSize={10}
|
|
||||||
fill="#999"
|
|
||||||
>
|
|
||||||
{p.date}
|
|
||||||
</text>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{/* Axes */}
|
|
||||||
<line
|
|
||||||
x1={paddingLeft}
|
|
||||||
y1={paddingTop}
|
|
||||||
x2={paddingLeft}
|
|
||||||
y2={paddingTop + chartHeight}
|
|
||||||
stroke="#e8e8e8"
|
|
||||||
strokeWidth={1}
|
|
||||||
/>
|
|
||||||
<line
|
|
||||||
x1={paddingLeft}
|
|
||||||
y1={paddingTop + chartHeight}
|
|
||||||
x2={paddingLeft + chartWidth}
|
|
||||||
y2={paddingTop + chartHeight}
|
|
||||||
stroke="#e8e8e8"
|
|
||||||
strokeWidth={1}
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const Statistics = () => {
|
|
||||||
const { headerStyle, isPhone } = useOutletContext<SharedContext>();
|
|
||||||
const [stats, setStats] = useState<StatsData | null>(null);
|
|
||||||
const [trend, setTrend] = useState<TrendItem[]>([]);
|
|
||||||
const [topDuration, setTopDuration] = useState<TopDurationItem[]>([]);
|
|
||||||
const [topCount, setTopCount] = useState<TopCountItem[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
|
|
||||||
const loadAll = async () => {
|
|
||||||
setLoading(true);
|
|
||||||
try {
|
|
||||||
const [
|
|
||||||
statsRes,
|
|
||||||
trendRes,
|
|
||||||
topDurationRes,
|
|
||||||
topCountRes,
|
|
||||||
] = await Promise.all([
|
|
||||||
request.get(`${config.apiPrefix}crons/stats`),
|
|
||||||
request.get(`${config.apiPrefix}crons/stats/trend`),
|
|
||||||
request.get(`${config.apiPrefix}crons/stats/top-duration`),
|
|
||||||
request.get(`${config.apiPrefix}crons/stats/top-count`),
|
|
||||||
]);
|
|
||||||
if (statsRes.code === 200) setStats(statsRes.data);
|
|
||||||
if (trendRes.code === 200) setTrend(trendRes.data);
|
|
||||||
if (topDurationRes.code === 200) setTopDuration(topDurationRes.data);
|
|
||||||
if (topCountRes.code === 200) setTopCount(topCountRes.data);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
loadAll();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const topDurationColumns: ColumnProps<TopDurationItem>[] = [
|
|
||||||
{
|
|
||||||
title: intl.get('排名'),
|
|
||||||
key: 'rank',
|
|
||||||
width: 60,
|
|
||||||
render: (_: any, __: any, index: number) => index + 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: intl.get('任务名称'),
|
|
||||||
dataIndex: 'cron_name',
|
|
||||||
key: 'cron_name',
|
|
||||||
ellipsis: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: intl.get('平均耗时(秒)'),
|
|
||||||
dataIndex: 'avgDuration',
|
|
||||||
key: 'avgDuration',
|
|
||||||
width: 120,
|
|
||||||
render: (v: number) => `${v}s`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: intl.get('最长单次(秒)'),
|
|
||||||
dataIndex: 'maxDuration',
|
|
||||||
key: 'maxDuration',
|
|
||||||
width: 120,
|
|
||||||
render: (v: number) => `${v}s`,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
const topCountColumns: ColumnProps<TopCountItem>[] = [
|
|
||||||
{
|
|
||||||
title: intl.get('排名'),
|
|
||||||
key: 'rank',
|
|
||||||
width: 60,
|
|
||||||
render: (_: any, __: any, index: number) => index + 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: intl.get('任务名称'),
|
|
||||||
dataIndex: 'cron_name',
|
|
||||||
key: 'cron_name',
|
|
||||||
ellipsis: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: intl.get('今日执行次数'),
|
|
||||||
dataIndex: 'count',
|
|
||||||
key: 'count',
|
|
||||||
width: 120,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: intl.get('平均耗时(秒)'),
|
|
||||||
dataIndex: 'avgDuration',
|
|
||||||
key: 'avgDuration',
|
|
||||||
width: 120,
|
|
||||||
render: (v: number) => `${v}s`,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<PageContainer
|
|
||||||
header={{
|
|
||||||
style: headerStyle,
|
|
||||||
}}
|
|
||||||
title={
|
|
||||||
<span>
|
|
||||||
<BarChartOutlined style={{ marginRight: 8 }} />
|
|
||||||
{intl.get('统计面板')}
|
|
||||||
</span>
|
|
||||||
}
|
|
||||||
extra={[
|
|
||||||
<Button
|
|
||||||
key="refresh"
|
|
||||||
icon={<ReloadOutlined />}
|
|
||||||
loading={loading}
|
|
||||||
onClick={loadAll}
|
|
||||||
>
|
|
||||||
{intl.get('刷新')}
|
|
||||||
</Button>,
|
|
||||||
]}
|
|
||||||
>
|
|
||||||
{/* Section 1: Overview Cards */}
|
|
||||||
<Card
|
|
||||||
className="stats-section"
|
|
||||||
title={intl.get('总体概览')}
|
|
||||||
loading={loading}
|
|
||||||
>
|
|
||||||
<Row gutter={[16, 16]}>
|
|
||||||
<Col xs={12} sm={8} md={6} lg={4}>
|
|
||||||
<Statistic
|
|
||||||
title={intl.get('总任务数量')}
|
|
||||||
value={stats?.total ?? '-'}
|
|
||||||
/>
|
|
||||||
</Col>
|
|
||||||
<Col xs={12} sm={8} md={6} lg={4}>
|
|
||||||
<Statistic
|
|
||||||
title={intl.get('启用任务数')}
|
|
||||||
value={stats?.enabled ?? '-'}
|
|
||||||
valueStyle={{ color: '#52c41a' }}
|
|
||||||
/>
|
|
||||||
</Col>
|
|
||||||
<Col xs={12} sm={8} md={6} lg={4}>
|
|
||||||
<Statistic
|
|
||||||
title={intl.get('禁用任务数')}
|
|
||||||
value={stats?.disabled ?? '-'}
|
|
||||||
valueStyle={{ color: '#d9d9d9' }}
|
|
||||||
/>
|
|
||||||
</Col>
|
|
||||||
<Col xs={12} sm={8} md={6} lg={4}>
|
|
||||||
<Statistic
|
|
||||||
title={intl.get('今日总执行次数')}
|
|
||||||
value={stats?.today?.count ?? '-'}
|
|
||||||
valueStyle={{ color: '#1890ff' }}
|
|
||||||
/>
|
|
||||||
</Col>
|
|
||||||
<Col xs={12} sm={8} md={6} lg={4}>
|
|
||||||
<Statistic
|
|
||||||
title={intl.get('今日平均耗时(秒)')}
|
|
||||||
value={stats?.today?.avgDuration ?? '-'}
|
|
||||||
suffix="s"
|
|
||||||
valueStyle={{ color: '#faad14' }}
|
|
||||||
/>
|
|
||||||
</Col>
|
|
||||||
</Row>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Section 2: 7-day Trend */}
|
|
||||||
<Card
|
|
||||||
className="stats-section"
|
|
||||||
title={intl.get('近7日执行趋势')}
|
|
||||||
loading={loading}
|
|
||||||
>
|
|
||||||
<TrendChart data={trend} />
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Section 3 & 4: Top Tables */}
|
|
||||||
<Row gutter={[16, 16]}>
|
|
||||||
<Col xs={24} lg={12}>
|
|
||||||
<Card
|
|
||||||
className="stats-section"
|
|
||||||
title={intl.get('今日平均耗时 Top 5')}
|
|
||||||
loading={loading}
|
|
||||||
>
|
|
||||||
<Table
|
|
||||||
dataSource={topDuration}
|
|
||||||
columns={topDurationColumns}
|
|
||||||
rowKey="cron_id"
|
|
||||||
pagination={false}
|
|
||||||
size="small"
|
|
||||||
locale={{ emptyText: intl.get('今日暂无执行记录') }}
|
|
||||||
/>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
<Col xs={24} lg={12}>
|
|
||||||
<Card
|
|
||||||
className="stats-section"
|
|
||||||
title={intl.get('今日执行次数 Top 5')}
|
|
||||||
loading={loading}
|
|
||||||
>
|
|
||||||
<Table
|
|
||||||
dataSource={topCount}
|
|
||||||
columns={topCountColumns}
|
|
||||||
rowKey="cron_id"
|
|
||||||
pagination={false}
|
|
||||||
size="small"
|
|
||||||
locale={{ emptyText: intl.get('今日暂无执行记录') }}
|
|
||||||
/>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
</Row>
|
|
||||||
</PageContainer>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Statistics;
|
|
||||||
@@ -504,7 +504,6 @@ export default {
|
|||||||
'/login': intl.get('登录'),
|
'/login': intl.get('登录'),
|
||||||
'/initialization': intl.get('初始化'),
|
'/initialization': intl.get('初始化'),
|
||||||
'/crontab': intl.get('定时任务'),
|
'/crontab': intl.get('定时任务'),
|
||||||
'/statistics': intl.get('统计面板'),
|
|
||||||
'/env': intl.get('环境变量'),
|
'/env': intl.get('环境变量'),
|
||||||
'/subscription': intl.get('订阅管理'),
|
'/subscription': intl.get('订阅管理'),
|
||||||
'/config': intl.get('配置文件'),
|
'/config': intl.get('配置文件'),
|
||||||
|
|||||||
+10
-5
@@ -1,6 +1,11 @@
|
|||||||
version: 2.20.2
|
version: 2.20.1
|
||||||
changeLogLink: https://t.me/jiao_long/434
|
changeLogLink: https://t.me/jiao_long/433
|
||||||
publishTime: 2026-03-01 1800
|
publishTime: 2025-12-26 22:00
|
||||||
changeLog: |
|
changeLog: |
|
||||||
1. 修复 path 安全漏洞(重要)
|
1. 修复获取依赖管理列表
|
||||||
|
2. notify.js 修复 TG_PROXY_AUTH 参数拼接
|
||||||
|
3. QLAPI.notify larkSecret 参数
|
||||||
|
4. 修复 cron parser 定时规则校验
|
||||||
|
5. 修复设置 baseUrl 后无法访问
|
||||||
|
6. 修复环境变量排序
|
||||||
|
7. 修复定时任务无法停止
|
||||||
Reference in New Issue
Block a user