@feng-vip/xxl 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/xxl.js +8 -0
- package/package.json +25 -4
- package/skills/xxl/SKILL.md +68 -0
- package/src/api.js +288 -0
- package/src/cli.js +111 -0
- package/src/commands.js +154 -0
- package/README.md +0 -3
package/bin/xxl.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@feng-vip/xxl",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "XXL-JOB 分布式调度平台命令行:任务查询/触发、执行日志追踪、启停控制(无官方 CLI 故自研)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"xxl": "bin/xxl.js"
|
|
8
|
+
},
|
|
9
|
+
"dependencies": {
|
|
10
|
+
"commander": "^14.0.3",
|
|
11
|
+
"smol-toml": "^1.3.0",
|
|
12
|
+
"undici": "^7.30.1",
|
|
13
|
+
"@feng-vip/core": "^0.1.0"
|
|
14
|
+
},
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"author": {
|
|
17
|
+
"name": "maofeng"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"bin",
|
|
21
|
+
"src",
|
|
22
|
+
"skills"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=22"
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: xxl
|
|
3
|
+
description: XXL-JOB 调度平台命令行 skill:任务清单/详情、手动触发、执行记录查询(失败排查)、执行日志滚动读取、启停/终止。当用户说"查一下定时任务"、"昨晚哪个任务失败了"、"触发一次 xxl 任务"、"看看调度日志"、"停掉/启用那个任务"等时触发。
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# xxl:XXL-JOB 调度平台命令行
|
|
7
|
+
|
|
8
|
+
无官方 CLI 故自研(控制台同源表单接口封装)。本机 shim:`xxl`。会话 Cookie 自动续期(过期自动重登)。
|
|
9
|
+
|
|
10
|
+
## 前置:登录(一次即可)
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
xxl login --url http://job.example.com/xxl-job-admin -u <用户> -p <密码> --save
|
|
14
|
+
xxl login # 已配置后单测连通(自动续期)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
- 存于 `~/.config/xxl/config.toml`(多环境 `--profile dev|test|prod` 分节);环境变量 `XXL_URL` / `XXL_USER` / `XXL_PASSWORD` 亦可
|
|
18
|
+
- 通用 flag:`--profile <名>`、`-j/--json`
|
|
19
|
+
|
|
20
|
+
## 执行器组与任务查询(安全)
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
xxl groups # 执行器组清单(appname/id 映射)
|
|
24
|
+
xxl groups --appname my-job # 按 appname 过滤
|
|
25
|
+
xxl jobs list -g <appname|组id> # 任务清单(先 groups 拿 appname)
|
|
26
|
+
xxl jobs list -g my-job --handler handleXxx # 按执行器方法名过滤
|
|
27
|
+
xxl jobs list -g my-job --desc 订单 --status running # 按描述关键词 + 调度状态过滤
|
|
28
|
+
xxl jobs list --limit 200 # 加大批次(默认 100)
|
|
29
|
+
xxl jobs info <jobId> --json # 单任务详情(cron/参数/路由策略/负责人)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`jobs list` flag:`-g/--group <appname|id>`、`--handler <名>`、`--desc <关键词>`、`--status running|stop`、`--limit <n>`(默认 100)、`-j`。
|
|
33
|
+
|
|
34
|
+
## 执行记录与日志(失败排查入口)
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
xxl jobs logs <jobId> --status fail --today --json # 今天的失败记录(排查第一步)
|
|
38
|
+
xxl jobs logs <jobId> --date 2026-01-02 --limit 100 # 指定日期、加大条数(默认 50)
|
|
39
|
+
xxl jobs logs <jobId> --status running # 正在跑的实例
|
|
40
|
+
xxl jobs log-detail <LOGID> # 日志正文(LOGID 从 logs 拿)
|
|
41
|
+
xxl jobs log-detail <LOGID> --from-line 500 # 超长日志续读(isEnd=false 时按 stderr 提示)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`jobs logs` flag:`--status success|fail|running`、`--date <YYYY-MM-DD>`、`--today`、`--limit <n>`(默认 50)、`-j`。
|
|
45
|
+
|
|
46
|
+
## 调度操作(写操作,必须 -y,且先和用户确认影响)
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
xxl jobs trigger <jobId> -y # 手动触发一次
|
|
50
|
+
xxl jobs trigger <jobId> -y --param '{"date":"2026-01-02"}' # 带执行参数
|
|
51
|
+
xxl jobs trigger <jobId> -y --address 10.0.0.1:9999 # 指定执行器地址(缺省自动路由)
|
|
52
|
+
xxl jobs enable <jobId> -y # 启用(恢复调度)
|
|
53
|
+
xxl jobs disable <jobId> -y # 停用(暂停调度)
|
|
54
|
+
xxl jobs kill <LOGID> -y # 终止运行中的执行实例(注意是 LOGID 不是 jobId)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## 排查套路(失败任务定位)
|
|
58
|
+
|
|
59
|
+
1. `xxl jobs logs <jobId> --status fail --today --json` 拿失败记录的 `LOGID`
|
|
60
|
+
2. `xxl jobs log-detail <LOGID>` 看异常堆栈;`isEnd=false` 时按 stderr 提示 `--from-line` 续读
|
|
61
|
+
3. `xxl jobs info <jobId> --json` 看 handler/参数/路由策略
|
|
62
|
+
4. 修复后 `xxl jobs trigger <jobId> -y` 验证,再回看 logs 确认成功
|
|
63
|
+
|
|
64
|
+
## Agent 使用建议
|
|
65
|
+
|
|
66
|
+
- 查询类全程 `--json` 便于解析;jobId 从 `jobs list` 拿,LOGID 从 `jobs logs` 拿,两者别混
|
|
67
|
+
- `trigger`/`enable`/`disable`/`kill` 真实影响调度:必须带 `-y`,执行前向用户确认
|
|
68
|
+
- 报错自带下一步:会话失效自动重登失败→提示重新 `xxl login`;任务/执行器不存在→先 `groups` / `jobs list`
|
package/src/api.js
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// XXL-JOB admin REST 客户端 —— 无官方 API 鉴权 token,走控制台同源表单接口。
|
|
2
|
+
// 认证:POST <base>/login 换 Cookie(XXL_JOB_LOGIN_IDENTITY),会话过期 302 → 自动重登一次。
|
|
3
|
+
// profile 解析统一走 @feng-vip/core 的 createProfileConfig。
|
|
4
|
+
import fs from 'node:fs'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import { request, Agent } from 'undici'
|
|
7
|
+
import { fail, createProfileConfig, homeDirSafe } from '@feng-vip/core'
|
|
8
|
+
|
|
9
|
+
// 自签证书调度台(公司内网 https)TLS 校验可关:XXL_INSECURE=true 或 --insecure
|
|
10
|
+
const insecure = process.env.XXL_INSECURE === 'true' || process.env.XXL_INSECURE === '1'
|
|
11
|
+
const tlsDispatcher = insecure
|
|
12
|
+
? new Agent({ connect: { rejectUnauthorized: false }, connectTimeout: 10000 })
|
|
13
|
+
: undefined
|
|
14
|
+
|
|
15
|
+
const profileConfig = createProfileConfig({
|
|
16
|
+
dir: path.join(homeDirSafe(), '.config', 'xxl'),
|
|
17
|
+
envProfile: 'XXL_PROFILE',
|
|
18
|
+
fields: {
|
|
19
|
+
url: { env: 'XXL_URL' },
|
|
20
|
+
user: { env: 'XXL_USER' },
|
|
21
|
+
password: { env: 'XXL_PASSWORD' },
|
|
22
|
+
},
|
|
23
|
+
onMissing(missing, profile) {
|
|
24
|
+
fail(
|
|
25
|
+
`配置不完整(profile=${profile}),缺少: ${missing.join(', ')}\n` +
|
|
26
|
+
`To fix, run: xxl login --url <http://host/xxl-job-admin> -u <用户> -p <密码> --save` +
|
|
27
|
+
`(或设置环境变量 XXL_URL / XXL_USER / XXL_PASSWORD)`,
|
|
28
|
+
)
|
|
29
|
+
},
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
export const CONFIG_DIR = profileConfig.CONFIG_DIR
|
|
33
|
+
export const CONFIG_FILE = profileConfig.CONFIG_FILE
|
|
34
|
+
export const sanitizeProfile = profileConfig.sanitizeProfile
|
|
35
|
+
export const resolveProfile = profileConfig.resolveProfile
|
|
36
|
+
export const saveProfile = (profile, { url, user, password }) =>
|
|
37
|
+
profileConfig.saveProfile(profile, { url, user, password })
|
|
38
|
+
|
|
39
|
+
/** flag > 环境变量 > config.toml[profile],url 统一去尾斜杠 */
|
|
40
|
+
export function resolveEnv(opts = {}) {
|
|
41
|
+
const merged = profileConfig.resolveConfig(opts)
|
|
42
|
+
merged.url = String(merged.url).replace(/\/+$/, '')
|
|
43
|
+
return merged
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function cookieFile(profile) {
|
|
47
|
+
return path.join(CONFIG_DIR, `${profile}.cookie`)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readCookie(profile) {
|
|
51
|
+
try {
|
|
52
|
+
const c = fs.readFileSync(cookieFile(profile), 'utf8').trim()
|
|
53
|
+
return c || null
|
|
54
|
+
} catch { /* 未登录过 */ }
|
|
55
|
+
return null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function saveCookie(profile, cookie) {
|
|
59
|
+
fs.mkdirSync(CONFIG_DIR, { recursive: true })
|
|
60
|
+
fs.writeFileSync(cookieFile(profile), cookie)
|
|
61
|
+
if (process.platform !== 'win32') fs.chmodSync(cookieFile(profile), 0o600)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 从 Set-Cookie 头提取 cookie 键值对(丢弃 Path/Expires 等属性);头可能是数组/单字符串 */
|
|
65
|
+
function setCookiePairs(res) {
|
|
66
|
+
const h = res.headers
|
|
67
|
+
let raw = []
|
|
68
|
+
if (typeof h?.getSetCookie === 'function') raw = h.getSetCookie()
|
|
69
|
+
else if (typeof h?.get === 'function') {
|
|
70
|
+
const v = h.get('set-cookie')
|
|
71
|
+
if (v) raw = [v]
|
|
72
|
+
} else if (h?.['set-cookie'] != null) {
|
|
73
|
+
raw = Array.isArray(h['set-cookie']) ? h['set-cookie'] : [h['set-cookie']]
|
|
74
|
+
}
|
|
75
|
+
const pairs = []
|
|
76
|
+
for (const line of raw) {
|
|
77
|
+
const kv = String(line).split(';')[0]
|
|
78
|
+
if (kv.includes('=')) pairs.push(kv.trim())
|
|
79
|
+
}
|
|
80
|
+
return pairs
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function login(opts) {
|
|
84
|
+
const env = resolveEnv(opts)
|
|
85
|
+
const body = new URLSearchParams({ userName: env.user, password: env.password }).toString()
|
|
86
|
+
let res
|
|
87
|
+
try {
|
|
88
|
+
res = await request(env.url + '/login', {
|
|
89
|
+
method: 'POST',
|
|
90
|
+
headers: {
|
|
91
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
92
|
+
'X-Requested-With': 'XMLHttpRequest',
|
|
93
|
+
'User-Agent': 'agentkit-xxl/0.1',
|
|
94
|
+
},
|
|
95
|
+
body,
|
|
96
|
+
headersTimeout: 20000,
|
|
97
|
+
bodyTimeout: 60000,
|
|
98
|
+
// DNS/connect 阶段单独限时:隔离网络下 NXDOMAIN 可能永不返回(容器实测踩坑)
|
|
99
|
+
connectTimeout: 10000,
|
|
100
|
+
...(tlsDispatcher ? { dispatcher: tlsDispatcher } : {}),
|
|
101
|
+
})
|
|
102
|
+
} catch (err) {
|
|
103
|
+
fail('网络错误: ' + ((err?.code || err?.cause?.code || err?.message) ?? String(err)))
|
|
104
|
+
}
|
|
105
|
+
const text = await res.body.text()
|
|
106
|
+
let data
|
|
107
|
+
try {
|
|
108
|
+
data = JSON.parse(text)
|
|
109
|
+
} catch {
|
|
110
|
+
fail(`登录响应不是 JSON(确认 URL 是否为调度中心根地址,如 http://host/xxl-job-admin): ${text.slice(0, 120)}`)
|
|
111
|
+
}
|
|
112
|
+
if (data.code !== 200) fail(`登录失败: ${data.msg ?? 'code=' + data.code}(检查账号密码与调度中心地址)`)
|
|
113
|
+
const cookie = setCookiePairs(res).join('; ')
|
|
114
|
+
if (!cookie) fail('登录成功但响应未返回会话 Cookie,无法维持会话(检查部署是否为标准 xxl-job-admin)')
|
|
115
|
+
saveCookie(env.profile, cookie)
|
|
116
|
+
return env
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function ensureCookie(env) {
|
|
120
|
+
const cookie = readCookie(env.profile)
|
|
121
|
+
if (cookie) return cookie
|
|
122
|
+
await login({ profile: env.profile })
|
|
123
|
+
const c = readCookie(env.profile)
|
|
124
|
+
if (!c) fail('自动登录后仍无会话 Cookie')
|
|
125
|
+
return c
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 表单 POST 管理接口。页面列表类返回 {recordsTotal, data:[...]},
|
|
130
|
+
* 动作类返回 ReturnT {code, msg, content};统一校验 code!==200 报错。
|
|
131
|
+
* 会话过期(302/401/403)自动重登一次后重试。
|
|
132
|
+
*/
|
|
133
|
+
async function post(pathAbs, fields, env, retried = false) {
|
|
134
|
+
const cookie = await ensureCookie(env)
|
|
135
|
+
let res
|
|
136
|
+
try {
|
|
137
|
+
res = await request(env.url + pathAbs, {
|
|
138
|
+
method: 'POST',
|
|
139
|
+
headers: {
|
|
140
|
+
Cookie: cookie,
|
|
141
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
142
|
+
'X-Requested-With': 'XMLHttpRequest',
|
|
143
|
+
'User-Agent': 'agentkit-xxl/0.1',
|
|
144
|
+
},
|
|
145
|
+
body: new URLSearchParams(Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, v == null ? '' : String(v)]))).toString(),
|
|
146
|
+
headersTimeout: 20000,
|
|
147
|
+
bodyTimeout: 60000,
|
|
148
|
+
connectTimeout: 10000,
|
|
149
|
+
...(tlsDispatcher ? { dispatcher: tlsDispatcher } : {}),
|
|
150
|
+
})
|
|
151
|
+
} catch (err) {
|
|
152
|
+
fail('网络错误: ' + ((err?.code || err?.cause?.code || err?.message) ?? String(err)))
|
|
153
|
+
}
|
|
154
|
+
if ([301, 302, 303, 307, 401, 403].includes(res.statusCode)) {
|
|
155
|
+
if (retried) fail('会话失效且自动重登未恢复。\nTo fix, run: xxl login(重新验证并刷新会话)')
|
|
156
|
+
await login({ profile: env.profile })
|
|
157
|
+
return post(pathAbs, fields, env, true)
|
|
158
|
+
}
|
|
159
|
+
const text = await res.body.text()
|
|
160
|
+
if (res.statusCode >= 400) fail(`调度中心请求失败 HTTP ${res.statusCode}: ${text.slice(0, 200)}`)
|
|
161
|
+
let data
|
|
162
|
+
try {
|
|
163
|
+
data = JSON.parse(text)
|
|
164
|
+
} catch {
|
|
165
|
+
fail('响应不是合法 JSON(检查 URL 是否指向调度中心): ' + text.slice(0, 120))
|
|
166
|
+
}
|
|
167
|
+
if (typeof data.code === 'number' && data.code !== 200) {
|
|
168
|
+
fail(`调度中心返回失败 code=${data.code}: ${data.msg ?? ''}`)
|
|
169
|
+
}
|
|
170
|
+
return data
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export async function apiPost(pathAbs, fields, opts) {
|
|
174
|
+
return post(pathAbs, fields, resolveEnv(opts))
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** 查执行器组列表,并建立 appname/id 双向映射缓存 */
|
|
178
|
+
export async function listGroups(opts) {
|
|
179
|
+
// 新版(≥2.4):POST /jobgroup/pageList 返回 JSON。
|
|
180
|
+
// 老版(如公司 test 站 2.1.2):无该接口(404),执行器表内嵌在 /jobgroup 页面 HTML
|
|
181
|
+
// (编辑按钮属性 appName/id/addressList 携带数据)——页面解析兜底。
|
|
182
|
+
try {
|
|
183
|
+
const r = await apiPost('/jobgroup/pageList', { start: 0, length: 1000, appname: opts?.appname ?? '' }, opts)
|
|
184
|
+
return r.data ?? []
|
|
185
|
+
} catch (err) {
|
|
186
|
+
if (!/HTTP 404/.test(err?.message ?? '')) throw err
|
|
187
|
+
return listGroupsFromPage(opts)
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** 老版 xxl(2.1.x):解析 /jobgroup 页面内嵌的执行器表格 */
|
|
192
|
+
async function listGroupsFromPage(opts) {
|
|
193
|
+
const env = resolveEnv(opts)
|
|
194
|
+
const cookie = await ensureCookie(env)
|
|
195
|
+
let res
|
|
196
|
+
try {
|
|
197
|
+
res = await request(env.url + '/jobgroup', {
|
|
198
|
+
headers: { Cookie: cookie, 'User-Agent': 'agentkit-xxl/0.1' },
|
|
199
|
+
headersTimeout: 20000,
|
|
200
|
+
bodyTimeout: 60000,
|
|
201
|
+
connectTimeout: 10000,
|
|
202
|
+
...(tlsDispatcher ? { dispatcher: tlsDispatcher } : {}),
|
|
203
|
+
})
|
|
204
|
+
} catch (err) {
|
|
205
|
+
fail('网络错误: ' + ((err?.code || err?.cause?.code || err?.message) ?? String(err)))
|
|
206
|
+
}
|
|
207
|
+
const html = await res.body.text()
|
|
208
|
+
const rows = []
|
|
209
|
+
// 每个"编辑"按钮携带一行完整数据:id / appName / title / order / addressType / addressList
|
|
210
|
+
const re = /<button[^>]*class="btn btn-warning btn-xs update"[^>]*>/g
|
|
211
|
+
for (const m of html.matchAll(re)) {
|
|
212
|
+
const tag = m[0]
|
|
213
|
+
const attr = (name) => {
|
|
214
|
+
const a = new RegExp(`${name}="([^"]*)"`).exec(tag)
|
|
215
|
+
return a ? a[1] : ''
|
|
216
|
+
}
|
|
217
|
+
rows.push({
|
|
218
|
+
id: attr('id'),
|
|
219
|
+
appname: attr('appName'),
|
|
220
|
+
title: attr('title'),
|
|
221
|
+
order: attr('order'),
|
|
222
|
+
addressType: attr('addressType'),
|
|
223
|
+
addressList: attr('addressList'),
|
|
224
|
+
registryList: attr('addressType') === '0' && attr('addressList') ? attr('addressList').split(',').filter(Boolean) : [],
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
if (opts?.appname) return rows.filter((g) => g.appname === opts.appname)
|
|
228
|
+
return rows
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** 解析 --group:数字即组 id,否则按 appname 匹配 */
|
|
232
|
+
export async function resolveGroupId(group, opts) {
|
|
233
|
+
if (group == null || group === '') return ''
|
|
234
|
+
if (/^\d+$/.test(String(group))) return String(group)
|
|
235
|
+
const hit = (await listGroups(opts)).find((g) => g.appname === group)
|
|
236
|
+
if (!hit) fail(`执行器 "${group}" 不存在\nTo fix, run: xxl groups 查看可用执行器 appname`)
|
|
237
|
+
return String(hit.id)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export async function listJobs({ group = '', status, handler = '', desc = '', limit = 100 }, opts) {
|
|
241
|
+
// 2.4.1 jobinfo/pageList 为平铺 int 参数:空串会 400,jobGroup=0 表示不过滤(mapper 仅 >0 时拼条件)
|
|
242
|
+
const jobGroup = (await resolveGroupId(group, opts)) || 0
|
|
243
|
+
const triggerStatus = status === 'running' ? 1 : status === 'stop' ? 0 : -1
|
|
244
|
+
const r = await apiPost('/jobinfo/pageList', {
|
|
245
|
+
jobGroup, triggerStatus, executorHandler: handler, jobDesc: desc, start: 0, length: limit,
|
|
246
|
+
}, opts)
|
|
247
|
+
return r.data ?? []
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export async function findJob(jobId, opts) {
|
|
251
|
+
const rows = await listJobs({ limit: 2000 }, opts)
|
|
252
|
+
const hit = rows.find((j) => String(j.id) === String(jobId))
|
|
253
|
+
if (!hit) fail(`任务 id=${jobId} 不存在\nTo fix, run: xxl jobs list 查看任务清单`)
|
|
254
|
+
return hit
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** 触发时间/处理时间格式化:真实环境返回 epoch 毫秒,字符串原样截取 */
|
|
258
|
+
export function fmtTime(v) {
|
|
259
|
+
if (typeof v === 'number') {
|
|
260
|
+
const d = new Date(v)
|
|
261
|
+
const p = (n) => String(n).padStart(2, '0')
|
|
262
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
|
|
263
|
+
}
|
|
264
|
+
return String(v ?? '').replace('T', ' ').slice(0, 19)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** 执行状态推导:2.x 语义 triggerCode!=200 触发失败;handleCode 0=未回调(运行中)/200=成功/500=失败
|
|
268
|
+
* (不依赖 handleTime 类型——admin 版本间有 epoch 数字与格式化字符串两种返回) */
|
|
269
|
+
export function deriveStatus(row) {
|
|
270
|
+
if (Number(row.triggerCode) !== 200) return '触发失败'
|
|
271
|
+
if (Number(row.handleCode) === 0) return '运行中'
|
|
272
|
+
return Number(row.handleCode) === 200 ? '成功' : '失败'
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export function stripHtml(s) {
|
|
276
|
+
return String(s ?? '').replace(/<[^>]*>/g, '').trim()
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** filterTime 参数:'yyyy-MM-dd 00:00:00 - yyyy-MM-dd 23:59:59'(默认今天,按本地时区) */
|
|
280
|
+
export function dayFilter(dateStr) {
|
|
281
|
+
let d = dateStr
|
|
282
|
+
if (!d) {
|
|
283
|
+
const now = new Date()
|
|
284
|
+
const p = (n) => String(n).padStart(2, '0')
|
|
285
|
+
d = `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}`
|
|
286
|
+
}
|
|
287
|
+
return `${d} 00:00:00 - ${d} 23:59:59`
|
|
288
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// commander 装配 —— XXL-JOB CLI 命令树。
|
|
2
|
+
import { Command } from 'commander'
|
|
3
|
+
import * as c from './commands.js'
|
|
4
|
+
|
|
5
|
+
export async function run(argv) {
|
|
6
|
+
const program = new Command()
|
|
7
|
+
program.name('xxl').description('XXL-JOB 调度平台命令行:任务查询/触发、执行日志追踪、启停控制').version('0.1.0')
|
|
8
|
+
|
|
9
|
+
program.option('--profile <name>', '环境 profile(默认 config.toml 的 default 键,或环境变量 XXL_PROFILE)')
|
|
10
|
+
program.option('--url <url>', '调度中心地址(如 http://host/xxl-job-admin;或环境变量 XXL_URL)')
|
|
11
|
+
program.option('--user <user>', '登录用户(或环境变量 XXL_USER)')
|
|
12
|
+
program.option('--password <pwd>', '登录密码(或环境变量 XXL_PASSWORD)')
|
|
13
|
+
|
|
14
|
+
program
|
|
15
|
+
.command('login')
|
|
16
|
+
.description('校验凭据并刷新会话(--save 把 url/user/password 存入 ~/.config/xxl/config.toml)')
|
|
17
|
+
.option('--profile <name>', '环境 profile(默认 config.toml 的 default 键,或环境变量 XXL_PROFILE)')
|
|
18
|
+
.option('--url <url>', '调度中心地址(如 http://host/xxl-job-admin;或环境变量 XXL_URL)')
|
|
19
|
+
.option('-u, --user <user>', '登录用户(或环境变量 XXL_USER)')
|
|
20
|
+
.option('-p, --password <pwd>', '登录密码(或环境变量 XXL_PASSWORD)')
|
|
21
|
+
.option('--save', '保存凭据到配置文件', false)
|
|
22
|
+
.option('-j, --json', 'JSON 输出', false)
|
|
23
|
+
.action((o, cmd) => c.login(withGlobals(o, cmd)))
|
|
24
|
+
|
|
25
|
+
program
|
|
26
|
+
.command('groups')
|
|
27
|
+
.description('列出执行器组')
|
|
28
|
+
.option('--appname <name>', '按 appname 过滤')
|
|
29
|
+
.option('-j, --json', 'JSON 输出', false)
|
|
30
|
+
.action((o, cmd) => c.groups(withGlobals(o, cmd)))
|
|
31
|
+
|
|
32
|
+
const jobs = program.command('jobs').description('任务管理:list / info / trigger / logs / log-detail / enable / disable / kill')
|
|
33
|
+
|
|
34
|
+
jobs
|
|
35
|
+
.command('list')
|
|
36
|
+
.description('任务清单')
|
|
37
|
+
.option('-g, --group <appname|id>', '按执行器过滤(appname 或组 id)')
|
|
38
|
+
.option('--handler <name>', '按执行器方法名过滤')
|
|
39
|
+
.option('--desc <kw>', '按任务描述关键词过滤')
|
|
40
|
+
.option('--status <running|stop>', '按调度状态过滤')
|
|
41
|
+
.option('--limit <n>', '返回条数上限', '100')
|
|
42
|
+
.option('-j, --json', 'JSON 输出', false)
|
|
43
|
+
.action((o, cmd) => c.jobsList(withGlobals(o, cmd)))
|
|
44
|
+
|
|
45
|
+
jobs
|
|
46
|
+
.command('info')
|
|
47
|
+
.description('查看单个任务详情')
|
|
48
|
+
.argument('<jobId>', '任务 id')
|
|
49
|
+
.option('-j, --json', 'JSON 输出', false)
|
|
50
|
+
.action((jobId, o, cmd) => c.jobsInfo(withGlobals({ ...o, jobId }, cmd)))
|
|
51
|
+
|
|
52
|
+
jobs
|
|
53
|
+
.command('trigger')
|
|
54
|
+
.description('手动触发一次执行(写操作,需 -y)')
|
|
55
|
+
.argument('<jobId>', '任务 id')
|
|
56
|
+
.option('--param <params>', '任务参数(executorParam)')
|
|
57
|
+
.option('--address <list>', '指定执行器地址(逗号分隔,缺省走自动路由)')
|
|
58
|
+
.option('-y, --yes', '确认执行(agent 必加)', false)
|
|
59
|
+
.option('-j, --json', 'JSON 输出', false)
|
|
60
|
+
.action((jobId, o, cmd) => c.jobsTrigger(withGlobals({ ...o, jobId }, cmd)))
|
|
61
|
+
|
|
62
|
+
jobs
|
|
63
|
+
.command('logs')
|
|
64
|
+
.description('执行记录列表(排查入口:--status fail --today)')
|
|
65
|
+
.argument('<jobId>', '任务 id')
|
|
66
|
+
.option('--status <success|fail|running>', '按执行状态过滤')
|
|
67
|
+
.option('--date <YYYY-MM-DD>', '按日期过滤')
|
|
68
|
+
.option('--today', '只看今天', false)
|
|
69
|
+
.option('--limit <n>', '返回条数上限', '50')
|
|
70
|
+
.option('-j, --json', 'JSON 输出', false)
|
|
71
|
+
.action((jobId, o, cmd) => c.jobsLogs(withGlobals({ ...o, jobId }, cmd)))
|
|
72
|
+
|
|
73
|
+
jobs
|
|
74
|
+
.command('log-detail')
|
|
75
|
+
.description('查看某次执行日志正文(从 jobs logs 拿 LOGID)')
|
|
76
|
+
.argument('<logId>', '执行记录 id')
|
|
77
|
+
.option('--from-line <n>', '起始行号(日志超长时按提示续读)', '1')
|
|
78
|
+
.option('-j, --json', 'JSON 输出', false)
|
|
79
|
+
.action((logId, o, cmd) => c.jobsLogDetail(withGlobals({ ...o, logId }, cmd)))
|
|
80
|
+
|
|
81
|
+
jobs
|
|
82
|
+
.command('enable')
|
|
83
|
+
.description('启用任务(恢复调度,写操作需 -y)')
|
|
84
|
+
.argument('<jobId>', '任务 id')
|
|
85
|
+
.option('-y, --yes', '确认执行(agent 必加)', false)
|
|
86
|
+
.option('-j, --json', 'JSON 输出', false)
|
|
87
|
+
.action((jobId, o, cmd) => c.jobsToggle(withGlobals({ ...o, jobId, action: 'enable' }, cmd)))
|
|
88
|
+
|
|
89
|
+
jobs
|
|
90
|
+
.command('disable')
|
|
91
|
+
.description('停用任务(暂停调度,写操作需 -y)')
|
|
92
|
+
.argument('<jobId>', '任务 id')
|
|
93
|
+
.option('-y, --yes', '确认执行(agent 必加)', false)
|
|
94
|
+
.option('-j, --json', 'JSON 输出', false)
|
|
95
|
+
.action((jobId, o, cmd) => c.jobsToggle(withGlobals({ ...o, jobId, action: 'disable' }, cmd)))
|
|
96
|
+
|
|
97
|
+
jobs
|
|
98
|
+
.command('kill')
|
|
99
|
+
.description('终止运行中的执行实例(按执行记录 id,写操作需 -y)')
|
|
100
|
+
.argument('<logId>', '执行记录 id')
|
|
101
|
+
.option('-y, --yes', '确认执行(agent 必加)', false)
|
|
102
|
+
.option('-j, --json', 'JSON 输出', false)
|
|
103
|
+
.action((logId, o, cmd) => c.jobsKill(withGlobals({ ...o, logId }, cmd)))
|
|
104
|
+
|
|
105
|
+
await program.parseAsync(argv)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function withGlobals(o, cmd) {
|
|
109
|
+
const g = cmd?.parent?.parent?.opts?.() ?? cmd?.parent?.opts?.() ?? {}
|
|
110
|
+
return { ...g, ...o }
|
|
111
|
+
}
|
package/src/commands.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// 命令实现 —— XXL-JOB 查询与调度操作(trigger/启停/终止按家族铁律需 -y)。
|
|
2
|
+
import { printJson, printTable, fail } from '@feng-vip/core'
|
|
3
|
+
import {
|
|
4
|
+
apiPost, listGroups, listJobs, findJob, resolveGroupId,
|
|
5
|
+
login as doLogin, saveProfile, resolveProfile,
|
|
6
|
+
fmtTime, deriveStatus, stripHtml, dayFilter,
|
|
7
|
+
} from './api.js'
|
|
8
|
+
|
|
9
|
+
function requireYes(yes, action) {
|
|
10
|
+
if (yes) return
|
|
11
|
+
fail(`该操作会真实影响调度(执行/启停/终止),需显式确认\nTo fix, run: 加上 -y/--yes 执行:${action}`)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const S = (v) => String(v ?? '')
|
|
15
|
+
|
|
16
|
+
// ── login ────────────────────────────────────────────────────────────────────
|
|
17
|
+
export async function login(opts) {
|
|
18
|
+
const env = await doLogin(opts)
|
|
19
|
+
if (opts.save) saveProfile(env.profile, env)
|
|
20
|
+
if (opts.json) return printJson({ ok: true, url: env.url, user: env.user, profile: env.profile, saved: !!opts.save })
|
|
21
|
+
console.log(`✓ 登录成功: ${env.url}(用户 ${env.user},profile=${env.profile}${opts.save ? ',已保存配置' : ''})`)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// ── groups ───────────────────────────────────────────────────────────────────
|
|
25
|
+
export async function groups(opts) {
|
|
26
|
+
const rows = await listGroups(opts)
|
|
27
|
+
if (opts.json) return printJson(rows)
|
|
28
|
+
printTable(['ID', 'APPNAME', '标题', '地址方式', '机器'], rows.map((g) => [
|
|
29
|
+
S(g.id), S(g.appname), S(g.title),
|
|
30
|
+
Number(g.addressType) === 1 ? '手动录入' : '自动注册',
|
|
31
|
+
Number(g.addressType) === 1
|
|
32
|
+
? S(g.addressList)
|
|
33
|
+
: `${(Array.isArray(g.registryList) ? g.registryList : []).length} 台在线`,
|
|
34
|
+
]))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ── jobs ─────────────────────────────────────────────────────────────────────
|
|
38
|
+
const GROUP_NAME_CACHE = {}
|
|
39
|
+
|
|
40
|
+
async function groupLabel(id, opts) {
|
|
41
|
+
if (!(id in GROUP_NAME_CACHE)) {
|
|
42
|
+
const g = (await listGroups(opts)).find((x) => S(x.id) === S(id))
|
|
43
|
+
GROUP_NAME_CACHE[id] = g?.appname ?? S(id)
|
|
44
|
+
}
|
|
45
|
+
return GROUP_NAME_CACHE[id]
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function jobRow(j) {
|
|
49
|
+
return {
|
|
50
|
+
id: j.id,
|
|
51
|
+
group: j.jobGroup,
|
|
52
|
+
appname: undefined,
|
|
53
|
+
desc: j.jobDesc,
|
|
54
|
+
handler: j.executorHandler,
|
|
55
|
+
schedule: `${S(j.scheduleType)}${j.scheduleConf ? '(' + S(j.scheduleConf) + ')' : ''}`,
|
|
56
|
+
status: Number(j.triggerStatus) === 1 ? '运行' : '停止',
|
|
57
|
+
author: j.author,
|
|
58
|
+
updateTime: fmtTime(j.updateTime),
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function jobsList(opts) {
|
|
63
|
+
const rows = await listJobs({
|
|
64
|
+
group: opts.group ?? '', status: opts.status, handler: opts.handler ?? '',
|
|
65
|
+
desc: opts.desc ?? '', limit: opts.limit ?? 100,
|
|
66
|
+
}, opts)
|
|
67
|
+
if (opts.json) {
|
|
68
|
+
return printJson(await Promise.all(rows.map(async (j) => {
|
|
69
|
+
const r = jobRow(j)
|
|
70
|
+
r.appname = await groupLabel(r.group, opts)
|
|
71
|
+
return { ...j, ...r }
|
|
72
|
+
})))
|
|
73
|
+
}
|
|
74
|
+
const view = []
|
|
75
|
+
for (const j of rows) {
|
|
76
|
+
const r = jobRow(j)
|
|
77
|
+
r.appname = await groupLabel(r.group, opts)
|
|
78
|
+
view.push([S(r.id), r.appname, r.desc, r.handler, r.schedule, r.status, S(r.author)])
|
|
79
|
+
}
|
|
80
|
+
printTable(['ID', '执行器', '任务描述', 'HANDLER', '调度', '状态', '作者'], view)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function jobsInfo(opts) {
|
|
84
|
+
const j = await findJob(opts.jobId, opts)
|
|
85
|
+
if (opts.json) return printJson(j)
|
|
86
|
+
const r = jobRow(j)
|
|
87
|
+
r.appname = await groupLabel(r.group, opts)
|
|
88
|
+
printTable(['字段', '值'], Object.entries(r).map(([k, v]) => [k, S(v)]))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function jobsTrigger(opts) {
|
|
92
|
+
requireYes(opts.yes, `xxl jobs trigger ${opts.jobId}`)
|
|
93
|
+
const j = await findJob(opts.jobId, opts)
|
|
94
|
+
const r = await apiPost('/jobinfo/trigger', {
|
|
95
|
+
id: j.id, executorParam: opts.param ?? '', addressList: opts.address ?? '',
|
|
96
|
+
}, opts)
|
|
97
|
+
if (opts.json) return printJson({ ok: true, jobId: opts.jobId, ...r })
|
|
98
|
+
console.log(`✓ 已触发: ${S(j.jobDesc)} (id=${j.id})`)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function jobsToggle(opts) {
|
|
102
|
+
const enable = opts.action === 'enable'
|
|
103
|
+
requireYes(opts.yes, `xxl jobs ${enable ? 'enable' : 'disable'} ${opts.jobId}`)
|
|
104
|
+
const j = await findJob(opts.jobId, opts)
|
|
105
|
+
await apiPost(enable ? '/jobinfo/start' : '/jobinfo/stop', { id: j.id }, opts)
|
|
106
|
+
if (opts.json) return printJson({ ok: true, jobId: opts.jobId, action: opts.action })
|
|
107
|
+
console.log(`✓ 已${enable ? '启用(恢复调度)' : '停用(暂停调度)'}: ${S(j.jobDesc)} (id=${j.id})`)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ── logs ─────────────────────────────────────────────────────────────────────
|
|
111
|
+
const LOG_STATUS = { success: 1, fail: 2, running: 3 }
|
|
112
|
+
|
|
113
|
+
export async function jobsLogs(opts) {
|
|
114
|
+
const j = await findJob(opts.jobId, opts)
|
|
115
|
+
const filterTime = opts.date || opts.today ? dayFilter(opts.date) : ''
|
|
116
|
+
const r = await apiPost('/joblog/pageList', {
|
|
117
|
+
jobGroup: j.jobGroup,
|
|
118
|
+
jobId: j.id,
|
|
119
|
+
logStatus: LOG_STATUS[opts.status] ?? -1,
|
|
120
|
+
filterTime,
|
|
121
|
+
start: 0,
|
|
122
|
+
length: opts.limit ?? 50,
|
|
123
|
+
}, opts)
|
|
124
|
+
const rows = r.data ?? []
|
|
125
|
+
if (opts.json) return printJson(rows.map((x) => ({ ...x, status: deriveStatus(x) })))
|
|
126
|
+
printTable(
|
|
127
|
+
['LOGID', '触发时间', '状态', '耗时', '说明'],
|
|
128
|
+
rows.map((x) => {
|
|
129
|
+
const dur = Number(x.handleTime) > 0 && Number(x.triggerTime) > 0
|
|
130
|
+
? `${Number(x.handleTime) - Number(x.triggerTime)}ms` : ''
|
|
131
|
+
return [S(x.id), fmtTime(x.triggerTime), deriveStatus(x), dur, stripHtml(x.handleMsg || x.triggerMsg).slice(0, 40)]
|
|
132
|
+
}),
|
|
133
|
+
)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function jobsLogDetail(opts) {
|
|
137
|
+
const r = await apiPost('/joblog/logDetailCat', { logId: opts.logId, fromLineNum: opts.fromLine ?? 1 }, opts)
|
|
138
|
+
const c = r.content ?? {}
|
|
139
|
+
if (opts.json) return printJson({ logId: opts.logId, ...c })
|
|
140
|
+
process.stdout.write(S(c.logContent))
|
|
141
|
+
if (!c.isEnd && c.toLineNum != null) {
|
|
142
|
+
process.stderr.write(
|
|
143
|
+
`\n日志未到末尾(isEnd=false,已读至第 ${c.toLineNum} 行)\n` +
|
|
144
|
+
`To fix, run: xxl jobs log-detail ${opts.logId} --from-line ${Number(c.toLineNum) + 1}\n`,
|
|
145
|
+
)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export async function jobsKill(opts) {
|
|
150
|
+
requireYes(opts.yes, `xxl jobs kill ${opts.logId}`)
|
|
151
|
+
await apiPost('/joblog/logKill', { id: opts.logId }, opts)
|
|
152
|
+
if (opts.json) return printJson({ ok: true, logId: opts.logId })
|
|
153
|
+
console.log(`✓ 已发送终止请求: 执行记录 id=${opts.logId}`)
|
|
154
|
+
}
|
package/README.md
DELETED