dsh-mc-server-ops 0.0.0-stage → 0.4.0

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/ops/rcon.mjs ADDED
@@ -0,0 +1,471 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 跨平台运维核心:RCON、进程探测、日志、状态汇总。
4
+ *
5
+ * 只依赖 Node 内置模块,Windows / Linux / macOS 都能跑。
6
+ * 用法:
7
+ * node rcon.mjs --dir <服务器目录> --action status
8
+ * node rcon.mjs --dir <服务器目录> --action players
9
+ * node rcon.mjs --dir <服务器目录> --action logs --arg 50
10
+ * node rcon.mjs --dir <服务器目录> --action say --arg "hello"
11
+ * node rcon.mjs --dir <服务器目录> --action cmd --arg "list"
12
+ * node rcon.mjs --dir <服务器目录> --action start|stop|restart [--dry-run]
13
+ */
14
+ import { createConnection } from 'node:net'
15
+ import { execFileSync, spawn } from 'node:child_process'
16
+ import { existsSync, mkdirSync, openSync, readFileSync, readdirSync, statSync, statfsSync, writeFileSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+ import { guardCommand } from './command-guard.mjs'
19
+
20
+ function parseArgs(argv) {
21
+ const out = { dir: process.cwd(), action: 'status', arg: '', owner: false }
22
+ for (let i = 0; i < argv.length; i++) {
23
+ const a = argv[i]
24
+ if (a === '--dir') out.dir = argv[++i]
25
+ else if (a === '--action') out.action = argv[++i]
26
+ else if (a === '--arg') out.arg = argv[++i]
27
+ else if (a === '--owner') out.owner = true
28
+ }
29
+ return out
30
+ }
31
+
32
+ function readProperties(dir) {
33
+ const file = join(dir, 'server.properties')
34
+ const map = {}
35
+ if (!existsSync(file)) return map
36
+ for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) {
37
+ const m = /^([^=#][^=]*)=(.*)$/.exec(line)
38
+ if (m) map[m[1].trim()] = m[2]
39
+ }
40
+ return map
41
+ }
42
+
43
+ function rconCall(port, password, command, timeoutMs) {
44
+ return new Promise((resolve, reject) => {
45
+ const socket = createConnection({ host: '127.0.0.1', port })
46
+ let buf = Buffer.alloc(0)
47
+ let authed = false
48
+ let done = false
49
+ const finish = (err, value) => {
50
+ if (done) return
51
+ done = true
52
+ try { socket.destroy() } catch { }
53
+ if (err) reject(err)
54
+ else resolve(value)
55
+ }
56
+ const timer = setTimeout(() => finish(new Error('RCON 超时')), timeoutMs)
57
+ const send = (id, type, body) => {
58
+ const payload = Buffer.from(body, 'utf8')
59
+ const size = 4 + 4 + payload.length + 2
60
+ const pkt = Buffer.alloc(4 + size)
61
+ pkt.writeInt32LE(size, 0)
62
+ pkt.writeInt32LE(id, 4)
63
+ pkt.writeInt32LE(type, 8)
64
+ payload.copy(pkt, 12)
65
+ pkt.writeInt16LE(0, pkt.length - 2)
66
+ socket.write(pkt)
67
+ }
68
+ const body = () => {
69
+ const pkt = buf.subarray(0, 4096)
70
+ const len = pkt.readInt32LE(0)
71
+ const start = 12
72
+ const end = 4 + len - 2
73
+ return { body: buf.subarray(start, end).toString('utf8'), rest: buf.subarray(4 + len) }
74
+ }
75
+ socket.on('error', (e) => { clearTimeout(timer); finish(e) })
76
+ socket.on('connect', () => send(1, 3, password))
77
+ socket.on('data', (chunk) => {
78
+ buf = Buffer.concat([buf, chunk])
79
+ const results = []
80
+ while (buf.length >= 4) {
81
+ const len = buf.readInt32LE(0)
82
+ if (buf.length < len + 4) break
83
+ const id = buf.readInt32LE(4)
84
+ const type = buf.readInt32LE(8)
85
+ const text = buf.subarray(12, 4 + len - 2).toString('utf8')
86
+ buf = buf.subarray(4 + len)
87
+ if (type === 2 && id === -1) return clearTimeout(timer), finish(new Error('RCON 密码不对'))
88
+ if (!authed && id === 1) {
89
+ authed = true
90
+ send(2, 2, command)
91
+ continue
92
+ }
93
+ if (authed && type === 0) results.push(text)
94
+ }
95
+ if (results.length) {
96
+ clearTimeout(timer)
97
+ finish(null, results.join('\n'))
98
+ }
99
+ })
100
+ })
101
+ }
102
+
103
+ function pidAlive(pid) {
104
+ try { process.kill(pid, 0); return true } catch { return false }
105
+ }
106
+
107
+ function looksLikeJava(pid) {
108
+ try {
109
+ if (process.platform === 'win32') {
110
+ const out = execFileSync('tasklist', ['/FI', 'PID eq ' + pid, '/FO', 'CSV', '/NH'], { encoding: 'utf8' })
111
+ return /java\.exe/i.test(out)
112
+ }
113
+ return readFileSync(`/proc/${pid}/cmdline`, 'utf8').includes('java')
114
+ } catch { return false }
115
+ }
116
+
117
+ /** 端口能不能连上:比「找进程」更贴近「服务是不是活着」,且不依赖任何外部命令 */
118
+ function probePort(port, timeoutMs = 1200) {
119
+ return new Promise((resolve) => {
120
+ let done = false
121
+ const socket = createConnection({ host: '127.0.0.1', port })
122
+ const finish = (ok) => {
123
+ if (done) return
124
+ done = true
125
+ try { socket.destroy() } catch { }
126
+ resolve(ok)
127
+ }
128
+ socket.setTimeout(timeoutMs, () => finish(false))
129
+ socket.on('connect', () => finish(true))
130
+ socket.on('error', () => finish(false))
131
+ })
132
+ }
133
+
134
+ function matchByCommandLine(dir) {
135
+ const want = dir.replace(/[\\/]+$/, '').toLowerCase()
136
+ // 1) wmic(老系统,可能已被移除)
137
+ if (!process.env.MC_OPS_NO_WMIC) {
138
+ try {
139
+ const out = execFileSync('wmic', ['process', 'where', "name='java.exe'", 'get', 'ProcessId,CommandLine', '/format:csv'], { encoding: 'utf8' })
140
+ for (const line of out.split(/\r?\n/)) {
141
+ if (!line || !/java\.exe/i.test(line)) continue
142
+ if (!line.toLowerCase().includes(want)) continue
143
+ const m = /,(\d+)\s*$/.exec(line)
144
+ if (m) return { pid: Number(m[1]), via: 'wmic' }
145
+ }
146
+ return null
147
+ } catch { }
148
+ }
149
+ // 2) CIM(Windows 10/Server 2019+ 都有 PowerShell)
150
+ if (process.platform === 'win32') {
151
+ try {
152
+ const out = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command',
153
+ "Get-CimInstance Win32_Process -Filter \"Name='java.exe'\" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"], { encoding: 'utf8', timeout: 8000 })
154
+ const data = JSON.parse(out || '[]')
155
+ const list = Array.isArray(data) ? data : [data]
156
+ for (const item of list) {
157
+ const cmd = String(item.CommandLine || '').toLowerCase()
158
+ if (cmd.includes(want)) return { pid: Number(item.ProcessId), via: 'cim' }
159
+ }
160
+ } catch { }
161
+ return null
162
+ }
163
+ // 3) Linux / macOS:/proc
164
+ try {
165
+ for (const pid of readdirSync('/proc').filter((n) => /^\d+$/.test(n))) {
166
+ let cmd = ''
167
+ try { cmd = readFileSync(`/proc/${pid}/cmdline`, 'utf8') } catch { continue }
168
+ if (cmd.includes('java') && cmd.includes(want)) return { pid: Number(pid), via: 'proc' }
169
+ }
170
+ } catch { }
171
+ return null
172
+ }
173
+
174
+ /**
175
+ * 服务是否在跑:pid 文件 → 命令行匹配(wmic/CIM/proc)→ 端口探测。
176
+ * 返回 via 说明用了哪一层,方便在状态里如实报告。
177
+ */
178
+ function findJava(serverDir) {
179
+ return detectServer(serverDir).pid
180
+ }
181
+
182
+ let lastDetect = null
183
+ function detectServer(serverDir) {
184
+ try {
185
+ const f = join(serverDir, 'ops', 'data', 'server.pid')
186
+ if (existsSync(f)) {
187
+ const pid = Number(readFileSync(f, 'utf8').trim())
188
+ if (pid > 0 && pidAlive(pid) && looksLikeJava(pid)) {
189
+ lastDetect = { pid, via: 'pidfile' }
190
+ return lastDetect
191
+ }
192
+ }
193
+ } catch { }
194
+ const matched = matchByCommandLine(serverDir)
195
+ if (matched) { lastDetect = matched; return matched }
196
+ lastDetect = { pid: null, via: 'none' }
197
+ return lastDetect
198
+ }
199
+ function processInfo(pid) {
200
+ const info = { pid, rssKB: null, uptimeSec: null }
201
+ if (!pid) return info
202
+ try {
203
+ if (process.platform === 'win32') return info
204
+ const status = readFileSync(`/proc/${pid}/status`, 'utf8')
205
+ const m = /VmRSS:\s+(\d+) kB/.exec(status)
206
+ if (m) info.rssKB = Number(m[1])
207
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8').split(' ')
208
+ const startTicks = Number(stat[21])
209
+ const uptime = Number(readFileSync('/proc/uptime', 'utf8').split(' ')[0])
210
+ const hz = 100
211
+ info.uptimeSec = Math.max(0, Math.floor(uptime - startTicks / hz))
212
+ } catch { }
213
+ return info
214
+ }
215
+
216
+ function dirSizeBytes(dir) {
217
+ let total = 0
218
+ const stack = [dir]
219
+ while (stack.length) {
220
+ const cur = stack.pop()
221
+ let list
222
+ try { list = readdirSync(cur, { withFileTypes: true }) } catch { continue }
223
+ for (const e of list) {
224
+ const p = join(cur, e.name)
225
+ if (e.isDirectory()) stack.push(p)
226
+ else {
227
+ try { total += statSync(p).size } catch { }
228
+ }
229
+ }
230
+ }
231
+ return total
232
+ }
233
+
234
+ function diskFree(dir) {
235
+ try {
236
+ const st = statfsSync(dir)
237
+ return st.bsize * st.bavail
238
+ } catch { }
239
+ return null
240
+ }
241
+
242
+ function formatUptime(sec) {
243
+ if (!sec) return '-'
244
+ const d = Math.floor(sec / 86400)
245
+ const h = Math.floor((sec % 86400) / 3600)
246
+ const m = Math.floor((sec % 3600) / 60)
247
+ return (d > 0 ? d + ' 天 ' : '') + String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0')
248
+ }
249
+
250
+ async function tps(rcon) {
251
+ const probes = [
252
+ ['forge tps', /Mean TPS:\s*([\d.]+)/],
253
+ ['tps', /TPS[^\d]*([\d.]+)/],
254
+ ['spark tps', /TPS[^\d]*([\d.]+)/],
255
+ ['carpet tps', /TPS[^\d]*([\d.]+)/],
256
+ ]
257
+ for (const [cmd, re] of probes) {
258
+ try {
259
+ const out = await rcon(cmd)
260
+ const m = re.exec(out || '')
261
+ if (m) return Number(m[1])
262
+ } catch { }
263
+ }
264
+ return null
265
+ }
266
+
267
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
268
+
269
+ function dataDir(dir) { return join(dir, 'ops', 'data') }
270
+ function pidFile(dir) { return join(dataDir(dir), 'server.pid') }
271
+
272
+ function walkFind(root, name) {
273
+ const stack = [root]
274
+ while (stack.length) {
275
+ const cur = stack.pop()
276
+ let list
277
+ try { list = readdirSync(cur, { withFileTypes: true }) } catch { continue }
278
+ for (const e of list) {
279
+ const p = join(cur, e.name)
280
+ if (e.isDirectory()) stack.push(p)
281
+ else if (e.name === name) return p
282
+ }
283
+ }
284
+ return null
285
+ }
286
+
287
+ function javaExecutable(dir) {
288
+ const p = join(dir, 'java', 'bin', process.platform === 'win32' ? 'java.exe' : 'java')
289
+ return existsSync(p) ? p : 'java'
290
+ }
291
+
292
+ /** 和服务端类型无关的启动目标探测:forge 参数文件 → loader jar → 根目录 jar → 启动脚本 */
293
+ function detectLaunch(dir) {
294
+ const isWin = process.platform === 'win32'
295
+ const javaExe = javaExecutable(dir)
296
+ const jvm = existsSync(join(dir, 'user_jvm_args.txt')) ? ['@user_jvm_args.txt'] : []
297
+ const lib = join(dir, 'libraries')
298
+ if (existsSync(lib)) {
299
+ const found = walkFind(lib, isWin ? 'win_args.txt' : 'unix_args.txt')
300
+ if (found) {
301
+ const rel = '@' + found.slice(dir.length + 1).split('\\').join('/')
302
+ return { javaExe, args: [...jvm, rel, 'nogui'], desc: 'forge args: ' + rel }
303
+ }
304
+ }
305
+ for (const name of ['fabric-server-launch.jar', 'fabric-server-launcher.jar', 'quilt-server-launch.jar']) {
306
+ const p = join(dir, name)
307
+ if (existsSync(p)) return { javaExe, args: [...jvm, '-jar', p, 'nogui'], desc: 'jar: ' + name }
308
+ }
309
+ try {
310
+ const jars = readdirSync(dir)
311
+ .filter((n) => n.toLowerCase().endsWith('.jar') && !/installer|shim|sources|javadoc/i.test(n))
312
+ .map((n) => ({ n, t: statSync(join(dir, n)).mtimeMs }))
313
+ .sort((a, b) => b.t - a.t)
314
+ if (jars.length) return { javaExe, args: [...jvm, '-jar', join(dir, jars[0].n), 'nogui'], desc: 'jar: ' + jars[0].n }
315
+ } catch { }
316
+ const script = isWin ? 'run.bat' : 'run.sh'
317
+ if (existsSync(join(dir, script))) return { javaExe: script, args: [], desc: script, isScript: true }
318
+ return null
319
+ }
320
+
321
+ async function doStart(dir, dryRun) {
322
+ const detected = detectServer(dir)
323
+ const port = Number(readProperties(dir)['server-port'] || 25565)
324
+ const portOpen = await probePort(port)
325
+ if (detected.pid || portOpen) {
326
+ return `服务器已经在运行(pid ${detected.pid || '-'},检测方式 ${detected.via}${portOpen ? ' + 端口' : ''})`
327
+ }
328
+ const launch = detectLaunch(dir)
329
+ if (!launch) throw new Error('没有找到启动目标:libraries 参数文件、*.jar、run.sh 都不存在')
330
+ if (dryRun) return '[dry-run] ' + launch.javaExe + ' ' + launch.args.join(' ')
331
+ mkdirSync(join(dir, 'logs'), { recursive: true })
332
+ mkdirSync(dataDir(dir), { recursive: true })
333
+ if (launch.isScript) {
334
+ const child = spawn(launch.javaExe, [], { cwd: dir, detached: true, stdio: 'ignore', shell: true })
335
+ child.unref()
336
+ writeFileSync(pidFile(dir), String(child.pid), 'utf8')
337
+ return `已通过 ${launch.desc} 启动(pid ${child.pid})`
338
+ }
339
+ const logFd = openSync(join(dir, 'logs', 'console.log'), 'a')
340
+ const child = spawn(launch.javaExe, launch.args, { cwd: dir, detached: true, stdio: ['ignore', logFd, logFd] })
341
+ child.unref()
342
+ writeFileSync(pidFile(dir), String(child.pid), 'utf8')
343
+ return `已启动(pid ${child.pid},${launch.desc}),加载约 40 秒`
344
+ }
345
+
346
+ async function doStop(dir, call, waitSec = 90) {
347
+ const detected = detectServer(dir)
348
+ const pid = detected.pid
349
+ const port = Number(readProperties(dir)['server-port'] || 25565)
350
+ if (!pid) {
351
+ if (await probePort(port)) return '服务在跑,但找不到对应进程(可能是权限不足或检测方式不可用),没有进程可以停;请在服务器控制台手动关。'
352
+ return '服务器没在运行'
353
+ }
354
+ let asked = false
355
+ try { await call('stop', 3000); asked = true } catch { }
356
+ const deadline = Date.now() + waitSec * 1000
357
+ while (Date.now() < deadline) {
358
+ await sleep(1000)
359
+ if (!findJava(dir)) return asked ? '已停止(RCON stop)' : '已停止'
360
+ }
361
+ // 强杀之前再确认一次:这个 pid 必须仍然属于本服务器目录,防止误杀别的 Java 进程
362
+ if (findJava(dir) !== pid) return '已停止'
363
+ try { process.kill(pid) } catch { }
364
+ await sleep(1500)
365
+ return findJava(dir) ? '已强制结束进程(超时)' : '已停止'
366
+ }
367
+
368
+ async function main() {
369
+ const { dir, action, arg, owner } = parseArgs(process.argv.slice(2))
370
+ const props = readProperties(dir)
371
+ const port = Number(props['rcon.port'] || 25575)
372
+ const password = props['rcon.password'] || ''
373
+ const enabled = String(props['enable-rcon'] || '').toLowerCase() === 'true'
374
+ const call = (cmd, ms = 4000) => rconCall(port, password, cmd, ms)
375
+
376
+ if (action === 'players') {
377
+ if (!enabled) throw new Error('server.properties 里没有开启 RCON')
378
+ process.stdout.write(await call('list'))
379
+ return
380
+ }
381
+ if (action === 'say' || action === 'cmd') {
382
+ if (!enabled) throw new Error('server.properties 里没有开启 RCON')
383
+ const text = action === 'say' ? 'say ' + arg : arg
384
+ // 直调本脚本时也要过静态拦截,避免绕过插件层(--owner 由插件按 owners.json 决定)
385
+ const verdict = guardCommand(text, { id: 'cli', owner: !!owner })
386
+ if (!verdict.ok) throw new Error('命令被拦截:' + verdict.reason)
387
+ process.stdout.write(await call(text, 8000))
388
+ return
389
+ }
390
+ if (action === 'logs') {
391
+ const n = Math.max(1, Number(arg) || 40)
392
+ const file = join(dir, 'logs', 'latest.log')
393
+ if (!existsSync(file)) { process.stdout.write('(没有日志文件)'); return }
394
+ const lines = readFileSync(file, 'utf8').split(/\r?\n/).filter((l) => l && !/RCON (Client|Listener)/.test(l))
395
+ process.stdout.write(lines.slice(-n).join('\n'))
396
+ return
397
+ }
398
+ if (action === 'status') {
399
+ const detected = detectServer(dir)
400
+ const pid = detected.pid
401
+ const port = Number(props['server-port'] || 25565)
402
+ const portOpen = await probePort(port)
403
+ const running = !!pid || portOpen
404
+ const info = processInfo(pid)
405
+ let health = 'stopped'
406
+ let online = '-'
407
+ let tpsValue = null
408
+ if (running) {
409
+ if (!enabled) {
410
+ health = 'running'
411
+ } else {
412
+ let rconOk = false
413
+ try { await call('list', 3000); rconOk = true } catch { }
414
+ if (!rconOk) {
415
+ health = info.uptimeSec !== null && info.uptimeSec < 180 ? 'booting' : 'unresponsive'
416
+ } else {
417
+ tpsValue = await tps(call)
418
+ health = tpsValue !== null && tpsValue < 3 ? 'lagging' : 'healthy'
419
+ try {
420
+ const list = await call('list')
421
+ const m = /There are (\d+) of a max of (\d+) players online/.exec(list || '')
422
+ if (m) online = m[1] + '/' + m[2]
423
+ } catch { }
424
+ }
425
+ }
426
+ }
427
+ const healthText = {
428
+ stopped: '未运行',
429
+ booting: '启动中',
430
+ healthy: '正常',
431
+ running: '运行中(未启用 RCON)',
432
+ lagging: '严重卡顿',
433
+ unresponsive: '无响应(假死)',
434
+ }[health]
435
+ const viaText = pid ? detected.via : (portOpen ? '端口探测' : detected.via)
436
+ const mem = info.rssKB ? (info.rssKB / 1024).toFixed(0) + ' MB' : '-'
437
+ const free = diskFree(dir)
438
+ let world = '-'
439
+ const worldDir = join(dir, 'world')
440
+ if (existsSync(worldDir)) {
441
+ try { world = (dirSizeBytes(worldDir) / 1024 / 1024).toFixed(0) + ' MB' } catch { }
442
+ }
443
+ process.stdout.write([
444
+ `运行: ${running ? 'yes' : 'no'} 健康: ${healthText} pid: ${pid || '-'}(${viaText}) 在线: ${online}`,
445
+ `内存: ${mem} 运行时长: ${formatUptime(info.uptimeSec)}`,
446
+ `TPS: ${tpsValue === null ? '-' : tpsValue.toFixed(3)}`,
447
+ `地图: ${world} 磁盘剩余: ${free === null ? '-' : (free / 1024 / 1024 / 1024).toFixed(1) + ' GB'}`,
448
+ `难度: ${props['difficulty'] || '-'} 端口: ${props['server-port'] || '-'}`,
449
+ ].join('\n'))
450
+ return
451
+ } if (action === 'start') {
452
+ process.stdout.write(await doStart(dir, process.argv.includes('--dry-run')))
453
+ return
454
+ }
455
+ if (action === 'stop') {
456
+ process.stdout.write(await doStop(dir, call))
457
+ return
458
+ }
459
+ if (action === 'restart') {
460
+ const stopped = await doStop(dir, call)
461
+ const started = await doStart(dir, process.argv.includes('--dry-run'))
462
+ process.stdout.write(stopped + ';' + started)
463
+ return
464
+ }
465
+ throw new Error('未知 action: ' + action)
466
+ }
467
+
468
+ main().catch((err) => {
469
+ process.stdout.write(String(err && err.message ? err.message : err))
470
+ process.exitCode = 1
471
+ })
@@ -0,0 +1,92 @@
1
+ param(
2
+ [string]$ServerDir = ''
3
+ )
4
+
5
+ $ErrorActionPreference = 'Continue'
6
+ if ([string]::IsNullOrWhiteSpace($ServerDir)) {
7
+ if ($env:MC_SERVER_DIR) { $ServerDir = $env:MC_SERVER_DIR } else { $ServerDir = 'D:\server' }
8
+ }
9
+ $ServerDir = $ServerDir.TrimEnd('\', '/')
10
+ $Host.UI.RawUI.WindowTitle = 'Minecraft 服务器控制台'
11
+ Set-Location $ServerDir
12
+
13
+ $javaExe = Join-Path $ServerDir 'java\bin\java.exe'
14
+ if (-not (Test-Path $javaExe)) { $javaExe = 'java' }
15
+
16
+ # ── 启动方式自动识别 ─────────────────────────────────────────────
17
+ # 1) Forge / NeoForge / 大多数混合端:libraries/**/win_args.txt
18
+ # 2) Fabric / Quilt / Paper / Spigot / Purpur / 原版 / 其它 jar 端:根目录 jar
19
+ # 3) 脚本启动(run.bat):兜底
20
+ # 可用环境变量覆盖:MC_JAR、MC_JVM_ARGS、MC_LAUNCH_ARGS
21
+ $argList = @()
22
+ $launchDesc = ''
23
+
24
+ $jvmArgs = @()
25
+ if ($env:MC_JVM_ARGS) { $jvmArgs = @($env:MC_JVM_ARGS) }
26
+ elseif (Test-Path (Join-Path $ServerDir 'user_jvm_args.txt')) { $jvmArgs = @('@user_jvm_args.txt') }
27
+
28
+ $forgeArgs = $null
29
+ if ($env:MC_JAR) {
30
+ $jar = $env:MC_JAR
31
+ if (-not [System.IO.Path]::IsPathRooted($jar)) { $jar = Join-Path $ServerDir $jar }
32
+ $launchDesc = "jar: $(Split-Path -Leaf $jar)"
33
+ $argList = @($jvmArgs) + @('-jar', $jar) + @('nogui')
34
+ }
35
+ else {
36
+ $libDir = Join-Path $ServerDir 'libraries'
37
+ if (Test-Path $libDir) {
38
+ $forgeArgs = Get-ChildItem $libDir -Recurse -Filter 'win_args.txt' -ErrorAction SilentlyContinue | Select-Object -First 1
39
+ }
40
+ if ($forgeArgs) {
41
+ $rel = '@' + $forgeArgs.FullName.Substring($ServerDir.Length + 1)
42
+ $launchDesc = "forge args: $rel"
43
+ $argList = @($jvmArgs) + @($rel) + @('nogui')
44
+ }
45
+ else {
46
+ $preferred = @('fabric-server-launch.jar', 'fabric-server-launcher.jar', 'quilt-server-launch.jar')
47
+ $jar = $null
48
+ foreach ($name in $preferred) {
49
+ $candidate = Join-Path $ServerDir $name
50
+ if (Test-Path $candidate) { $jar = $candidate; break }
51
+ }
52
+ if (-not $jar) {
53
+ $jar = Get-ChildItem $ServerDir -Filter '*.jar' -File -ErrorAction SilentlyContinue |
54
+ Where-Object { $_.Name -notmatch '(installer|shim|base|sources|javadoc)' } |
55
+ Sort-Object LastWriteTime -Descending | Select-Object -First 1
56
+ if ($jar) { $jar = $jar.FullName }
57
+ }
58
+ if ($jar) {
59
+ $launchDesc = "jar: $(Split-Path -Leaf $jar)"
60
+ $argList = @($jvmArgs) + @('-jar', $jar) + @('nogui')
61
+ }
62
+ elseif (Test-Path (Join-Path $ServerDir 'run.bat')) {
63
+ $launchDesc = 'run.bat'
64
+ Write-Host "[启动] run.bat" -ForegroundColor Cyan
65
+ & (Join-Path $ServerDir 'run.bat')
66
+ exit $LASTEXITCODE
67
+ }
68
+ else {
69
+ Write-Host "没有找到可用的启动目标:libraries\**\win_args.txt、*.jar 或 run.bat 都不存在。" -ForegroundColor Red
70
+ Read-Host '按回车关闭'
71
+ exit 1
72
+ }
73
+ }
74
+ }
75
+
76
+ if ($env:MC_LAUNCH_ARGS) { $argList = @($jvmArgs) + $env:MC_LAUNCH_ARGS.Split(' ') }
77
+
78
+ Write-Host "[启动] $launchDesc" -ForegroundColor Cyan
79
+ Write-Host "[java] $javaExe $($argList -join ' ')" -ForegroundColor DarkGray
80
+
81
+ & $javaExe @argList 2>&1 | ForEach-Object {
82
+ $line = [string]$_
83
+ if ($line -match '(?i)\b(error|fatal|severe)\b|Exception|Caused by:|at [a-z]') {
84
+ Write-Host $line -ForegroundColor Red
85
+ }
86
+ elseif ($line -match '(?i)\bwarn(ing)?\b') {
87
+ Write-Host $line -ForegroundColor Yellow
88
+ }
89
+ else {
90
+ Write-Host $line
91
+ }
92
+ }
@@ -0,0 +1,117 @@
1
+ param(
2
+ [int]$IntervalSec = 5,
3
+ [int]$MaxRestartsPer15Min = 4,
4
+ [string]$ServerDir = ''
5
+ )
6
+
7
+ $ErrorActionPreference = 'Continue'
8
+ if ([string]::IsNullOrWhiteSpace($ServerDir)) { $ServerDir = if ($env:MC_SERVER_DIR) { $env:MC_SERVER_DIR } else { 'D:\server' } }
9
+ $ServerDir = $ServerDir.TrimEnd('\', '/')
10
+ $OpsDir = $PSScriptRoot
11
+ $DataDir = Join-Path $OpsDir 'data'
12
+ $LogDir = Join-Path $ServerDir 'logs'
13
+ $StateFile = Join-Path $DataDir 'state.json'
14
+ $PidFile = Join-Path $DataDir 'server.pid'
15
+ $WatchLog = Join-Path $LogDir 'watchdog.log'
16
+
17
+ New-Item -ItemType Directory -Force -Path $DataDir, $LogDir | Out-Null
18
+
19
+ function Log([string]$msg) {
20
+ $line = "[{0}] {1}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $msg
21
+ Add-Content -Path $WatchLog -Value $line -Encoding UTF8
22
+ }
23
+
24
+ function Read-State {
25
+ if (Test-Path $StateFile) {
26
+ try { return Get-Content $StateFile -Raw -Encoding UTF8 | ConvertFrom-Json } catch { }
27
+ }
28
+ return [pscustomobject]@{ desired = $false; restarts = @(); lastCrash = $null }
29
+ }
30
+ function Write-State($s) { $s | ConvertTo-Json -Depth 8 | Set-Content -Path $StateFile -Encoding UTF8 }
31
+
32
+ function Get-ServerProcess {
33
+ if (Test-Path $PidFile) {
34
+ $raw = (Get-Content $PidFile -Raw).Trim()
35
+ if ($raw -match '^\d+$') {
36
+ $p = Get-Process -Id ([int]$raw) -ErrorAction SilentlyContinue
37
+ if ($p -and $p.ProcessName -eq 'java') { return $p }
38
+ }
39
+ }
40
+ return (Get-Process -Name java -ErrorAction SilentlyContinue |
41
+ Where-Object { try { $_.Path -like "$ServerDir*" } catch { $false } } |
42
+ Select-Object -First 1)
43
+ }
44
+
45
+ function Start-Server {
46
+ $java = Join-Path $ServerDir 'java\bin\java.exe'
47
+ $consoleScript = Join-Path $OpsDir 'server-console.ps1'
48
+ $p = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $consoleScript, '-ServerDir', $ServerDir) -WorkingDirectory $ServerDir -WindowStyle Normal -PassThru
49
+ Start-Sleep -Seconds 3
50
+ $javaProc = Get-ServerProcess
51
+ if ($javaProc) { $javaProc.Id | Set-Content $PidFile -Encoding ASCII }
52
+ else { $p.Id | Set-Content $PidFile -Encoding ASCII }
53
+ return $p
54
+ }
55
+
56
+ Log "watchdog started (pid $PID, interval ${IntervalSec}s)"
57
+ $pid | Set-Content (Join-Path $DataDir 'watchdog.pid') -Encoding ASCII
58
+
59
+ $lastKnownRunning = $null
60
+ $crashRecorded = $false
61
+
62
+ while ($true) {
63
+ try {
64
+ $state = Read-State
65
+ $desired = [bool]$state.desired
66
+ $proc = Get-ServerProcess
67
+ $running = [bool]$proc
68
+
69
+ if ($lastKnownRunning -eq $true -and -not $running -and $desired -and -not $crashRecorded) {
70
+ $tail = ''
71
+ $logPath = Join-Path $LogDir 'latest.log'
72
+ if (-not (Test-Path $logPath) -or (Get-Item -LiteralPath $logPath).Length -eq 0) { $logPath = Join-Path $LogDir 'console.log' }
73
+ if (Test-Path $logPath) { $tail = ((Get-Content -LiteralPath $logPath -Tail 40 -Encoding UTF8) -join "`n") }
74
+ $crash = [pscustomobject]@{
75
+ at = (Get-Date).ToString('o')
76
+ tail = $tail
77
+ }
78
+ $state | Add-Member -Force -NotePropertyName lastCrash -NotePropertyValue $crash
79
+ Write-State $state
80
+ Log "CRASH detected (process gone while desired=true)"
81
+ $crashRecorded = $true
82
+ }
83
+ if ($running) { $crashRecorded = $false }
84
+
85
+ if ($desired -and -not $running) {
86
+ $recent = @($state.restarts | Where-Object { ([datetime]$_).ToUniversalTime() -gt (Get-Date).ToUniversalTime().AddMinutes(-15) })
87
+ if ($recent.Count -ge $MaxRestartsPer15Min) {
88
+ Log "RESTART LIMIT reached ($($recent.Count) in 15min) - giving up, manual intervention required"
89
+ $state | Add-Member -Force -NotePropertyName desired -NotePropertyValue $false
90
+ Write-State $state
91
+ }
92
+ else {
93
+ Log "server down (desired=true) - restarting"
94
+ try {
95
+ $p = Start-Server
96
+ $state = Read-State
97
+ $restarts = @($state.restarts) + @((Get-Date).ToString('o'))
98
+ if ($restarts.Count -gt 50) { $restarts = $restarts[-50..-1] }
99
+ $state | Add-Member -Force -NotePropertyName restarts -NotePropertyValue $restarts
100
+ $state | Add-Member -Force -NotePropertyName desired -NotePropertyValue $true
101
+ Write-State $state
102
+ Log "restarted (pid $($p.Id))"
103
+ }
104
+ catch {
105
+ Log "restart failed: $($_.Exception.Message)"
106
+ }
107
+ }
108
+ Start-Sleep -Seconds 15
109
+ }
110
+
111
+ $lastKnownRunning = $running
112
+ }
113
+ catch {
114
+ Log "watchdog loop error: $($_.Exception.Message)"
115
+ }
116
+ Start-Sleep -Seconds $IntervalSec
117
+ }