@andy.ian/dsh-homing 2.0.1 → 2.0.3

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/watchdog.mjs CHANGED
@@ -1,163 +1,144 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * 看门狗 / 重启脚本的安装器。
3
+ * 守护进程的安装 / 状态 / 卸载命令(纯 Node,无 PowerShell、无计划任务)。
4
4
  *
5
- * 为什么需要它:
6
- * 重启脚本必须跑在 DSH 之外(它要杀掉承载插件的进程),所以不能由插件自己在运行时执行。
7
- * 换电脑后,插件包装好了,但 ~/.dsh/watchdog 下的脚本和计划任务都不会自动跟过来。
8
- * 这个命令把这件事变成一条:
9
- *
10
- * dsh-homing-watchdog install # 装脚本 + 注册看门狗计划任务
11
- * dsh-homing-watchdog status # 看状态(等价 restart-now.ps1 -Check)
12
- * dsh-homing-watchdog remove # 卸载计划任务(保留脚本)
13
- * dsh-homing-watchdog restart # 立刻重启 DSH(默认等空闲)
14
- * dsh-homing-watchdog restart --immediate # 一空闲就重启
15
- *
16
- * 只支持 Windows(脚本是 PowerShell + 计划任务)。
5
+ * 守护逻辑在 bin/supervisor.mjs:常驻、监视 DSH、崩溃自动拉起、升级期间等待。
6
+ * 本命令只负责入口管理:
7
+ * install 写入「登录时启动守护进程」(Win 启动文件夹 / macOS LaunchAgent / Linux systemd user unit)
8
+ * status 向守护进程控制接口取状态
9
+ * remove 删除启动项
10
+ * restart 请求重启(默认等空闲,--immediate 立即)
11
+ * stop 让守护进程退出(不再拉起 DSH)
17
12
  */
18
13
  import fs from 'node:fs'
19
14
  import path from 'node:path'
20
- import { spawnSync } from 'node:child_process'
15
+ import os from 'node:os'
16
+ import http from 'node:http'
21
17
  import { fileURLToPath } from 'node:url'
22
18
 
23
19
  const here = path.dirname(fileURLToPath(import.meta.url))
24
20
  const pkgRoot = path.resolve(here, '..')
25
- const sourceDir = path.join(pkgRoot, 'ops', 'watchdog')
26
- const dshHome = process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? '', '.dsh')
27
- const targetDir = path.join(dshHome, 'watchdog')
21
+ const supervisor = path.join(pkgRoot, 'bin', 'supervisor.mjs')
22
+ const controlPort = Number(process.env.DSH_HOMING_CONTROL ?? 8790)
28
23
 
29
- const TASK_WATCHDOG = 'DSH-Watchdog'
30
- const TASK_RESTART = 'DSH-Restart-Now'
31
- const EXE = 'powershell.exe'
32
- const NODE = process.execPath
24
+ const has = (name) => process.argv.includes('--' + name)
25
+ const [command] = process.argv.slice(2)
33
26
 
34
- const run = (args, opts = {}) => spawnSync(EXE, args, { encoding: 'utf8', windowsHide: true, ...opts })
35
- const ps = (script) => run(['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', script])
36
- const psFile = (file, extra = []) => {
37
- // 中文 Windows 的 PowerShell 默认按 GBK 输出,Node 按 utf8 读会乱码;
38
- // 这里先设 [Console]::OutputEncoding 再执行脚本,保证能读懂结果。
39
- const quoted = "'" + file.replaceAll("'", "''") + "'"
40
- // 开关参数必须原样传(加引号会变成位置参数,被 ValidateSet 拒绝)
41
- const args = extra.join(' ')
42
- return run(['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
43
- `[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; & ${quoted} ${args}`])
27
+ function call(pathname, method = 'POST') {
28
+ return new Promise((resolve, reject) => {
29
+ const req = http.request({ host: '127.0.0.1', port: controlPort, path: pathname, method, timeout: 8000 }, (res) => {
30
+ const chunks = []
31
+ res.on('data', (chunk) => chunks.push(chunk))
32
+ res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks).toString('utf8') }))
33
+ })
34
+ req.on('timeout', () => { req.destroy(); reject(new Error('timeout')) })
35
+ req.on('error', reject)
36
+ req.end()
37
+ })
44
38
  }
45
39
 
46
- function requireWindows() {
47
- if (process.platform !== 'win32') {
48
- console.error('这个命令只支持 Windows(用 PowerShell + 计划任务实现)。')
49
- process.exit(1)
40
+ function startupPath() {
41
+ if (process.platform === 'win32') {
42
+ return path.join(process.env.APPDATA ?? '', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', 'dsh-homing-supervisor.vbs')
43
+ }
44
+ if (process.platform === 'darwin') {
45
+ return path.join(os.homedir(), 'Library', 'LaunchAgents', 'online.gitsrc.dsh-homing.plist')
50
46
  }
47
+ return path.join(os.homedir(), '.config', 'systemd', 'user', 'dsh-homing-supervisor.service')
51
48
  }
52
49
 
53
50
  function install() {
54
- requireWindows()
55
- if (!fs.existsSync(sourceDir)) {
56
- console.error(`找不到脚本目录:${sourceDir}`)
57
- process.exit(1)
58
- }
59
- fs.mkdirSync(targetDir, { recursive: true })
60
- for (const name of fs.readdirSync(sourceDir)) {
61
- if (!name.endsWith('.ps1')) continue
62
- fs.copyFileSync(path.join(sourceDir, name), path.join(targetDir, name))
63
- console.log(` ✓ 已复制 ${name}`)
64
- }
51
+ const file = startupPath()
52
+ fs.mkdirSync(path.dirname(file), { recursive: true })
53
+ if (process.platform === 'win32') {
54
+ // 用 wscript 启动,登录时才不会闪控制台窗口
55
+ const vbs = `' 由 dsh-homing 生成:登录时以隐藏窗口启动守护进程\r\nSet sh = CreateObject("WScript.Shell")\r\nsh.Run """${process.execPath}"" ""${supervisor}"" --detach", 0, False\r\n`
56
+ fs.writeFileSync(file, vbs, 'ascii')
57
+ } else if (process.platform === 'darwin') {
58
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
59
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
60
+ <plist version="1.0"><dict>
61
+ <key>Label</key><string>online.gitsrc.dsh-homing</string>
62
+ <key>ProgramArguments</key><array><string>${process.execPath}</string><string>${supervisor}</string><string>--detach</string></array>
63
+ <key>RunAtLoad</key><true/>
64
+ </dict></plist>
65
+ `
66
+ fs.writeFileSync(file, xml, 'utf8')
67
+ } else {
68
+ const text = `[Unit]
69
+ Description=DSH Homing supervisor
65
70
 
66
- const watchdog = path.join(targetDir, 'dsh-watchdog.ps1')
67
- const register = `
68
- $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "${watchdog}"'
69
- $trigger1 = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(2) -RepetitionInterval (New-TimeSpan -Minutes 5)
70
- $trigger2 = New-ScheduledTaskTrigger -AtLogOn
71
- $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
72
- $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\\$env:USERNAME" -LogonType Interactive -RunLevel Limited
73
- Register-ScheduledTask -TaskName '${TASK_WATCHDOG}' -Action $action -Trigger $trigger1,$trigger2 -Settings $settings -Principal $principal -Force | Out-Null
74
- Write-Output 'registered'
75
- `
76
- const registered = ps(register)
77
- if (!String(registered.stdout).includes('registered')) {
78
- console.error('注册看门狗计划任务失败:' + (registered.stderr || registered.stdout || '').slice(0, 400))
79
- process.exit(1)
71
+ [Service]
72
+ ExecStart=${process.execPath} ${supervisor} --detach
73
+
74
+ [Install]
75
+ WantedBy=default.target
76
+ `
77
+ fs.writeFileSync(file, text, 'utf8')
80
78
  }
81
- console.log(` ✓ 已注册计划任务 ${TASK_WATCHDOG}(每 5 分钟体检)`)
82
- console.log('\n装好了。常用命令:')
83
- console.log(' dsh-homing-watchdog status 查看状态与能否重启')
84
- console.log(' dsh-homing-watchdog restart 重启 DSH(等空闲)')
85
- console.log(' dsh-homing-watchdog restart --immediate 一空闲就重启')
79
+ console.log(` ✓ 已写入启动项:${file}`)
80
+ if (process.platform === 'linux') console.log(' 启用:systemctl --user enable --now dsh-homing-supervisor')
81
+ console.log('\n常用命令:')
82
+ console.log(' dsh-homing-watchdog status')
83
+ console.log(' dsh-homing-watchdog restart [--immediate]')
84
+ console.log(' dsh-homing-watchdog stop')
86
85
  }
87
86
 
88
- function status() {
89
- requireWindows()
90
- const restart = path.join(targetDir, 'restart-now.ps1')
91
- if (!fs.existsSync(restart)) {
92
- console.error('还没安装:先跑 dsh-homing-watchdog install')
93
- process.exit(1)
94
- }
95
- const result = psFile(restart, ['-Check'])
96
- const text = String(result.stdout || '').replace(/^\uFEFF/u, '')
97
- if (text.trim() === '') {
98
- console.error('读取状态失败:' + (result.stderr || '').slice(0, 300))
87
+ async function status() {
88
+ try {
89
+ const res = await call('/status', 'GET')
90
+ console.log(res.body.trim())
91
+ } catch {
92
+ console.error('守护进程没在运行(控制端口连不上)。先 dsh-homing-watchdog install,或手动运行 supervisor.mjs --detach。')
99
93
  process.exit(1)
100
94
  }
101
- console.log(text.trim())
102
95
  }
103
96
 
104
97
  function remove() {
105
- requireWindows()
106
- const result = ps(`Unregister-ScheduledTask -TaskName '${TASK_WATCHDOG}' -Confirm:$false -ErrorAction SilentlyContinue; Unregister-ScheduledTask -TaskName '${TASK_RESTART}' -Confirm:$false -ErrorAction SilentlyContinue; Write-Output 'removed'`)
107
- if (String(result.stdout).includes('removed')) {
108
- console.log(` ✓ 已卸载计划任务(脚本仍保留在 ${targetDir})`)
98
+ const file = startupPath()
99
+ if (fs.existsSync(file)) {
100
+ fs.rmSync(file, { force: true })
101
+ console.log(` ✓ 已删除启动项:${file}`)
109
102
  } else {
110
- console.error('卸载失败:' + (result.stderr || '').slice(0, 300))
111
- process.exit(1)
103
+ console.log(' 启动项不存在')
112
104
  }
113
105
  }
114
106
 
115
- function restart({ immediate }) {
116
- requireWindows()
107
+ async function restart(immediate) {
117
108
  const mode = immediate ? 'immediate' : 'default'
118
- // 优先走常驻守护进程(无闪窗、事件驱动);它不在时退回旧计划任务
119
- const request = spawnSync(NODE, [path.join(pkgRoot, 'bin', 'supervisor.mjs'), '--restart', ...(immediate ? ['--immediate'] : [])], {
120
- encoding: 'utf8', windowsHide: true,
121
- })
122
- if (request.status === 0) {
123
- console.log(String(request.stdout).trim() || `已请求守护进程重启(模式 ${mode})`)
124
- return
125
- }
126
- // 守护进程不在:退回计划任务(仍然可用,但会有闪窗)
127
- const script = path.join(targetDir, 'restart-now.ps1')
128
- if (!fs.existsSync(script)) {
129
- console.error('守护进程没有运行,且找不到 restart-now.ps1。先启动守护进程:dsh-homing-supervisor --detach')
109
+ try {
110
+ const res = await call(`/restart?mode=${mode}`)
111
+ console.log(res.status === 202 ? ` 已请求重启(模式 ${mode})` : ` 请求被拒绝(HTTP ${res.status})`)
112
+ } catch {
113
+ console.error('守护进程没在运行。先 install 或手动启动 supervisor.mjs --detach。')
130
114
  process.exit(1)
131
115
  }
132
- console.warn('守护进程未运行,退回计划任务方式(可能闪窗)')
133
- const cmd = `
134
- $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "${script}" -Mode ${mode} -Reason "命令行请求"'
135
- $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(5)
136
- $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 30)
137
- $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\\$env:USERNAME" -LogonType Interactive -RunLevel Limited
138
- Register-ScheduledTask -TaskName 'DSH-Restart-Now' -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null
139
- Write-Output 'queued'
140
- `
141
- const result = ps(cmd)
142
- if (String(result.stdout).includes('queued')) console.log(`已排队(模式 ${mode})`)
143
- else { console.error('排队失败:' + (result.stderr || '').slice(0, 300)); process.exit(1) }
144
116
  }
145
117
 
146
- const [command, ...rest] = process.argv.slice(2)
147
- const has = (flag) => rest.includes(flag)
118
+ async function stop() {
119
+ try {
120
+ await call('/stop')
121
+ console.log(' 守护进程已退出(不会自动拉起 DSH)')
122
+ } catch {
123
+ console.error('守护进程没在运行')
124
+ process.exit(1)
125
+ }
126
+ }
148
127
 
149
128
  switch (command) {
150
129
  case 'install': install(); break
151
- case 'status': status(); break
130
+ case 'status': await status(); break
152
131
  case 'remove': remove(); break
153
- case 'restart': restart({ immediate: has('--immediate') || has('-i') }); break
132
+ case 'restart': await restart(has('--immediate') || has('-i')); break
133
+ case 'stop': await stop(); break
154
134
  default:
155
- console.log(`用法: dsh-homing-watchdog <install|status|remove|restart> [--immediate]
135
+ console.log(`用法: dsh-homing-watchdog <install|status|remove|restart|stop> [--immediate]
156
136
 
157
- install 安装/更新重启脚本与看门狗计划任务(换电脑后跑这个)
158
- status 查看进程、端口、会话活动与能否重启
159
- remove 卸载计划任务(保留脚本文件)
160
- restart 重启 DSH;默认等会话空闲,加 --immediate 则一空闲就重启
137
+ install 写入登录自启(Windows 启动项 / macOS LaunchAgent / Linux systemd user unit)
138
+ status 向守护进程查询状态
139
+ remove 删除登录自启
140
+ restart 请求重启 DSH(默认等空闲,--immediate 立即)
141
+ stop 让守护进程退出(不再拉起 DSH)
161
142
  `)
162
143
  process.exit(command === undefined ? 0 : 1)
163
144
  }