@andy.ian/dsh-homing 2.0.2 → 2.1.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/bin/restart-daemon.mjs +3 -0
- package/bin/restart.mjs +3 -0
- package/index.js +785 -29
- package/lib/devices.mjs +0 -1
- package/lib/files-page.mjs +10 -18
- package/lib/files.mjs +39 -27
- package/package.json +8 -9
- package/restart/client.mjs +184 -0
- package/restart/config.mjs +187 -0
- package/restart/engine.mjs +93 -0
- package/restart/face.mjs +62 -0
- package/restart/runner.mjs +184 -0
- package/restart/service.mjs +91 -0
- package/restart-daemon/README.md +66 -0
- package/restart-daemon/cli.mjs +321 -0
- package/restart-daemon/lib/detach.mjs +126 -0
- package/restart-daemon/lib/process-tree.mjs +69 -0
- package/restart-daemon/lib/restart-flow.mjs +111 -0
- package/restart-daemon/lib/update-state.mjs +72 -0
- package/restart-daemon/main.mjs +691 -0
- package/bin/supervisor.mjs +0 -488
- package/bin/watchdog.mjs +0 -144
- package/lib/vendor/node_modules/ssh2/examples/server-chat.js +0 -238
- package/lib/vendor/node_modules/ssh2/examples/sftp-server-download-only.js +0 -134
- package/lib/vendor/node_modules/ssh2/test/common.js +0 -316
- package/lib/vendor/node_modules/ssh2/test/fixtures/bad_rsa_private_key +0 -26
- package/lib/vendor/node_modules/ssh2/test/fixtures/https_cert.pem +0 -33
- package/lib/vendor/node_modules/ssh2/test/fixtures/https_key.pem +0 -52
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_dsa +0 -12
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_ecdsa +0 -5
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa +0 -15
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa.ppk +0 -26
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa_enc +0 -30
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +0 -21
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +0 -22
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +0 -23
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +0 -9
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +0 -10
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +0 -10
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +0 -27
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +0 -28
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +0 -29
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +0 -12
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +0 -15
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +0 -5
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa +0 -27
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +0 -30
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +0 -54
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +0 -1
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +0 -6
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +0 -6
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +0 -17
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +0 -26
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +0 -18
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +0 -9
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +0 -10
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +0 -11
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +0 -11
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +0 -8
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +0 -13
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +0 -7
- package/lib/vendor/node_modules/ssh2/test/fixtures/openssh_new_rsa +0 -27
- package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +0 -12
- package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +0 -5
- package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +0 -15
- package/lib/vendor/node_modules/ssh2/test/test-exec.js +0 -578
- package/lib/vendor/node_modules/ssh2/test/test-integration-openssh.js +0 -486
- package/lib/vendor/node_modules/ssh2/test/test-keygen.js +0 -60
- package/lib/vendor/node_modules/ssh2/test/test-misc-client-server.js +0 -1460
- package/lib/vendor/node_modules/ssh2/test/test-openssh.js +0 -261
- package/lib/vendor/node_modules/ssh2/test/test-protocol-crypto.js +0 -631
- package/lib/vendor/node_modules/ssh2/test/test-protocol-keyparser.js +0 -177
- package/lib/vendor/node_modules/ssh2/test/test-server-hostkeys.js +0 -138
- package/lib/vendor/node_modules/ssh2/test/test-sftp.js +0 -842
- package/lib/vendor/node_modules/ssh2/test/test-shell.js +0 -109
- package/lib/vendor/node_modules/ssh2/test/test-userauth-agent-openssh.js +0 -110
- package/lib/vendor/node_modules/ssh2/test/test-userauth-agent.js +0 -171
- package/lib/vendor/node_modules/ssh2/test/test-userauth.js +0 -611
- package/lib/vendor/node_modules/ssh2/test/test-worker-imports.js +0 -25
- package/lib/vendor/node_modules/ssh2/test/test.js +0 -20
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 守护进程的安装 / 状态 / 卸载命令(纯 Node,无 PowerShell、无计划任务)。
|
|
4
|
+
*
|
|
5
|
+
* 守护逻辑在 bin/restart-daemon.mjs:常驻、监视 DSH、崩溃自动拉起、升级期间等待。
|
|
6
|
+
* 本命令只负责入口管理:
|
|
7
|
+
* install 写入「登录时启动守护进程」(Win 启动文件夹 / macOS LaunchAgent / Linux systemd user unit)
|
|
8
|
+
* status 向守护进程控制接口取状态
|
|
9
|
+
* remove 删除启动项
|
|
10
|
+
* restart 请求重启(默认等空闲,--immediate 立即)
|
|
11
|
+
* stop 让守护进程退出(不再拉起 DSH)
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import os from 'node:os'
|
|
16
|
+
import http from 'node:http'
|
|
17
|
+
import { spawnSync } from 'node:child_process'
|
|
18
|
+
import { fileURLToPath } from 'node:url'
|
|
19
|
+
import { startHidden, startViaCim } from './lib/detach.mjs'
|
|
20
|
+
|
|
21
|
+
const here = path.dirname(fileURLToPath(import.meta.url))
|
|
22
|
+
const pkgRoot = path.resolve(here, '..')
|
|
23
|
+
const daemonEntry = path.join(pkgRoot, 'bin', 'restart-daemon.mjs')
|
|
24
|
+
const controlPort = Number(process.env.DSH_HOMING_CONTROL ?? 8790)
|
|
25
|
+
|
|
26
|
+
const has = (name) => process.argv.includes('--' + name)
|
|
27
|
+
const argValue = (name, fallback) => {
|
|
28
|
+
const idx = process.argv.indexOf(name)
|
|
29
|
+
return idx >= 0 && process.argv[idx + 1] ? process.argv[idx + 1] : fallback
|
|
30
|
+
}
|
|
31
|
+
const [command] = process.argv.slice(2)
|
|
32
|
+
|
|
33
|
+
function call(pathname, method = 'POST', headers = {}) {
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
// agent:false —— Node 19+ 的 globalAgent 默认 keepAlive,会把进程挂住不退
|
|
36
|
+
const req = http.request({ host: '127.0.0.1', port: controlPort, path: pathname, method, headers, timeout: 8000, agent: false }, (res) => {
|
|
37
|
+
const chunks = []
|
|
38
|
+
res.on('data', (chunk) => chunks.push(chunk))
|
|
39
|
+
res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks).toString('utf8') }))
|
|
40
|
+
})
|
|
41
|
+
req.on('timeout', () => { req.destroy(); reject(new Error('timeout')) })
|
|
42
|
+
req.on('error', reject)
|
|
43
|
+
req.end()
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const TASK_NAME = 'dsh-homing-restart-daemon'
|
|
48
|
+
|
|
49
|
+
function startupPath() {
|
|
50
|
+
if (process.platform === 'win32') {
|
|
51
|
+
return path.join(process.env.APPDATA ?? '', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', 'dsh-homing-restart-daemon.vbs')
|
|
52
|
+
}
|
|
53
|
+
if (process.platform === 'darwin') {
|
|
54
|
+
return path.join(os.homedir(), 'Library', 'LaunchAgents', 'online.gitsrc.dsh-homing.plist')
|
|
55
|
+
}
|
|
56
|
+
return path.join(os.homedir(), '.config', 'systemd', 'user', 'dsh-homing-restart-daemon.service')
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 找当前可用的 node 运行时:先自己,再扫 dsh-runtimes 下的候选 */
|
|
60
|
+
function findNodeRuntime() {
|
|
61
|
+
const candidates = [process.execPath]
|
|
62
|
+
try {
|
|
63
|
+
const base = path.join(dshHome, 'dsh-runtimes')
|
|
64
|
+
for (const dir of fs.readdirSync(base)) {
|
|
65
|
+
const candidate = path.join(base, dir, 'dependencies', 'node', 'bin', process.platform === 'win32' ? 'node.exe' : 'node')
|
|
66
|
+
if (fs.existsSync(candidate)) candidates.push(candidate)
|
|
67
|
+
}
|
|
68
|
+
} catch { /* 没有 dsh-runtimes 目录 */ }
|
|
69
|
+
for (const candidate of candidates) {
|
|
70
|
+
if (candidate && fs.existsSync(candidate)) return candidate
|
|
71
|
+
}
|
|
72
|
+
return process.execPath
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 检查启动项里引用的路径是否还有效 */
|
|
76
|
+
function checkStartup() {
|
|
77
|
+
if (process.platform === 'win32') {
|
|
78
|
+
try {
|
|
79
|
+
const q = spawnSync('schtasks', ['/query', '/tn', TASK_NAME, '/fo', 'LIST'], { encoding: 'utf8', windowsHide: true, timeout: 10000 })
|
|
80
|
+
if (q.status === 0) {
|
|
81
|
+
const action = /任务要运行的任务|Task To Run/i.exec(q.stdout ?? '')
|
|
82
|
+
const last = /上次运行结果|Last Result/i.exec(q.stdout ?? '')
|
|
83
|
+
return {
|
|
84
|
+
exists: true,
|
|
85
|
+
ok: true,
|
|
86
|
+
mode: 'task',
|
|
87
|
+
reason: '任务计划(' + (last ?? '无上次结果') + ')',
|
|
88
|
+
file: TASK_NAME,
|
|
89
|
+
paths: [],
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
} catch { /* 回退到启动文件夹检查 */ }
|
|
93
|
+
}
|
|
94
|
+
if (process.platform === 'win32') {
|
|
95
|
+
try {
|
|
96
|
+
const q = spawnSync('reg', ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', 'dsh-homing-restart-daemon'], { encoding: 'utf8', windowsHide: true, timeout: 8000 })
|
|
97
|
+
if (q.status === 0) return { exists: true, ok: true, mode: 'registry', reason: '注册表 Run(HKCU)', file: 'HKCU\\...\\Run' }
|
|
98
|
+
} catch { /* 忽略 */ }
|
|
99
|
+
}
|
|
100
|
+
const file = startupPath()
|
|
101
|
+
if (!fs.existsSync(file)) return { exists: false, ok: false, reason: '启动项不存在', file }
|
|
102
|
+
const text = fs.readFileSync(file, 'utf8')
|
|
103
|
+
const paths = [...text.matchAll(/(?:[A-Za-z]:\\[^"\r\n]+?\.exe|[A-Za-z]:\\[^"\r\n]+?\.mjs)/gu)].map((m) => m[0])
|
|
104
|
+
const missing = paths.filter((item) => !fs.existsSync(item))
|
|
105
|
+
if (missing.length > 0) return { exists: true, ok: false, mode: 'vbs', reason: '启动文件夹(路径已失效:' + missing.join(', ') + ')', file, missing }
|
|
106
|
+
if (paths.length === 0) return { exists: true, ok: false, mode: 'vbs', reason: '启动文件夹(无可识别路径)', file }
|
|
107
|
+
return { exists: true, ok: true, mode: 'vbs', reason: '启动文件夹(路径有效)', file, paths }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 生成一个可"右键 → 以管理员身份运行"的批处理,用来安装任务计划 */
|
|
111
|
+
function writeElevatedLauncher(nodePath, daemonPath) {
|
|
112
|
+
const dir = path.join(process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'), 'restart-daemon')
|
|
113
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
114
|
+
const file = path.join(dir, 'install-task.cmd')
|
|
115
|
+
const lines = [
|
|
116
|
+
'@echo off',
|
|
117
|
+
'rem Right-click -> Run as administrator: create the dsh-homing restart-daemon logon task',
|
|
118
|
+
'chcp 65001 >nul',
|
|
119
|
+
'"' + nodePath + '" "' + path.join(path.dirname(daemonPath), 'restart.mjs') + '" install --task',
|
|
120
|
+
'echo.',
|
|
121
|
+
'pause',
|
|
122
|
+
]
|
|
123
|
+
fs.writeFileSync(file, lines.join('\r\n') + '\r\n', 'utf8')
|
|
124
|
+
return file
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function writeAutostartMarker(mode) {
|
|
128
|
+
try {
|
|
129
|
+
const dir = path.join(process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'), 'restart-daemon')
|
|
130
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
131
|
+
fs.writeFileSync(path.join(dir, 'autostart.json'), JSON.stringify({ mode, at: new Date().toISOString() }, null, 2), 'utf8')
|
|
132
|
+
} catch { /* 写不了就算了 */ }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function install() {
|
|
136
|
+
const wantTask = process.argv.includes('--task')
|
|
137
|
+
const file = startupPath()
|
|
138
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
139
|
+
// 启动项必须指向"已安装"的副本;开发仓库路径可能被移动/清理
|
|
140
|
+
const dshRoot = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
|
|
141
|
+
const installedDaemon = path.join(dshRoot, 'plugins', 'dsh-homing', 'bin', 'restart-daemon.mjs')
|
|
142
|
+
const preferredDaemon = fs.existsSync(installedDaemon) ? installedDaemon : daemonEntry
|
|
143
|
+
const nodePath = findNodeRuntime()
|
|
144
|
+
if (!fs.existsSync(nodePath)) {
|
|
145
|
+
console.error(' 找不到可用的 node 运行时,无法写入启动项')
|
|
146
|
+
process.exit(1)
|
|
147
|
+
}
|
|
148
|
+
if (process.platform === 'win32') {
|
|
149
|
+
// 微软推荐:登录触发的任务计划(不需要脚本文件,也没有窗口)
|
|
150
|
+
const action = '"' + nodePath + '" "' + preferredDaemon + '" --detach'
|
|
151
|
+
const created = spawnSync('schtasks', ['/create', '/f', '/tn', TASK_NAME, '/sc', 'onlogon', '/tr', action, '/rl', 'LIMITED'], {
|
|
152
|
+
encoding: 'utf8', windowsHide: true, timeout: 15000,
|
|
153
|
+
})
|
|
154
|
+
let mode = 'task'
|
|
155
|
+
if (created.status !== 0) {
|
|
156
|
+
if (wantTask) {
|
|
157
|
+
const launcher = writeElevatedLauncher(nodePath, preferredDaemon)
|
|
158
|
+
console.error(' 任务计划创建失败:当前会话不是管理员。')
|
|
159
|
+
console.error(' 请右键以管理员身份运行这个文件,然后重试:')
|
|
160
|
+
console.error(' ' + launcher)
|
|
161
|
+
process.exit(1)
|
|
162
|
+
}
|
|
163
|
+
// 兜底:注册表 Run(PowerShell 隐藏启动,不依赖 VBS)
|
|
164
|
+
const ps = 'Start-Process -FilePath "' + nodePath + '" -ArgumentList @("' + preferredDaemon + '","--detach") -WindowStyle Hidden'
|
|
165
|
+
const encoded = Buffer.from(ps, 'utf16le').toString('base64')
|
|
166
|
+
const runValue = 'powershell -NoProfile -WindowStyle Hidden -EncodedCommand ' + encoded
|
|
167
|
+
const reg = spawnSync('reg', ['add', 'HKCU\\' + 'Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', 'dsh-homing-restart-daemon', '/t', 'REG_SZ', '/d', runValue, '/f'], {
|
|
168
|
+
encoding: 'utf8', windowsHide: true, timeout: 10000,
|
|
169
|
+
})
|
|
170
|
+
if (reg.status !== 0) {
|
|
171
|
+
console.error(' 注册表 Run 写入失败:' + String(reg.stderr ?? '').trim().slice(0, 160))
|
|
172
|
+
process.exit(1)
|
|
173
|
+
}
|
|
174
|
+
mode = 'registry'
|
|
175
|
+
console.log(' 已写入注册表启动项(任务计划需要管理员权限,已改用 HKCU Run)')
|
|
176
|
+
}
|
|
177
|
+
// 清理旧的启动文件夹 VBS(不再使用 VBScript)
|
|
178
|
+
try { fs.rmSync(file, { force: true }) } catch { /* 忽略 */ }
|
|
179
|
+
writeAutostartMarker(mode)
|
|
180
|
+
if (mode === 'task') console.log(' ✓ 已创建登录任务:' + TASK_NAME)
|
|
181
|
+
} else if (process.platform === 'darwin') {
|
|
182
|
+
const xml = `<?xml version="1.0" encoding="UTF-8"?>
|
|
183
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
184
|
+
<plist version="1.0"><dict>
|
|
185
|
+
<key>Label</key><string>online.gitsrc.dsh-homing</string>
|
|
186
|
+
<key>ProgramArguments</key><array><string>${nodePath}</string><string>${preferredDaemon}</string><string>--detach</string></array>
|
|
187
|
+
<key>RunAtLoad</key><true/>
|
|
188
|
+
</dict></plist>
|
|
189
|
+
`
|
|
190
|
+
fs.writeFileSync(file, xml, 'utf8')
|
|
191
|
+
writeAutostartMarker('launchd')
|
|
192
|
+
} else {
|
|
193
|
+
const text = `[Unit]
|
|
194
|
+
Description=DSH Homing restart daemon
|
|
195
|
+
|
|
196
|
+
[Service]
|
|
197
|
+
ExecStart=${nodePath} ${preferredDaemon} --detach
|
|
198
|
+
|
|
199
|
+
[Install]
|
|
200
|
+
WantedBy=default.target
|
|
201
|
+
`
|
|
202
|
+
fs.writeFileSync(file, text, 'utf8')
|
|
203
|
+
writeAutostartMarker('systemd')
|
|
204
|
+
}
|
|
205
|
+
const check = checkStartup()
|
|
206
|
+
if (!check.ok) {
|
|
207
|
+
console.error(' ✗ 写入后校验失败:' + check.reason)
|
|
208
|
+
process.exit(1)
|
|
209
|
+
}
|
|
210
|
+
console.log(' ✓ 已写入启动项:' + file)
|
|
211
|
+
console.log(' node:' + nodePath)
|
|
212
|
+
if (process.platform === 'linux') console.log(' 启用:systemctl --user enable --now dsh-homing-restart-daemon')
|
|
213
|
+
console.log('\n常用命令:')
|
|
214
|
+
console.log(' dsh-homing-restart status')
|
|
215
|
+
console.log(' dsh-homing-restart restart [--immediate]')
|
|
216
|
+
console.log(' dsh-homing-restart stop')
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function status() {
|
|
220
|
+
const startup = checkStartup()
|
|
221
|
+
console.log(' 启动项:' + (startup.exists ? (startup.ok ? '有效 · ' + startup.reason : '失效 · ' + startup.reason) : '未安装'))
|
|
222
|
+
try {
|
|
223
|
+
const res = await call('/status', 'GET')
|
|
224
|
+
console.log(res.body.trim())
|
|
225
|
+
} catch {
|
|
226
|
+
console.error('守护进程没在运行(控制端口连不上)。先 dsh-homing-restart install,或手动运行 bin/restart-daemon.mjs --detach。')
|
|
227
|
+
process.exit(1)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function remove() {
|
|
232
|
+
if (process.platform === 'win32') {
|
|
233
|
+
const del = spawnSync('schtasks', ['/delete', '/f', '/tn', TASK_NAME], { encoding: 'utf8', windowsHide: true, timeout: 10000 })
|
|
234
|
+
if (del.status === 0) console.log(' 已删除任务计划:' + TASK_NAME)
|
|
235
|
+
}
|
|
236
|
+
const file = startupPath()
|
|
237
|
+
if (fs.existsSync(file)) {
|
|
238
|
+
fs.rmSync(file, { force: true })
|
|
239
|
+
console.log(` ✓ 已删除启动项:${file}`)
|
|
240
|
+
} else {
|
|
241
|
+
console.log(' 启动项不存在')
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function start() {
|
|
246
|
+
// 已在运行就不重复启动
|
|
247
|
+
try {
|
|
248
|
+
const alive = await call('/status', 'GET')
|
|
249
|
+
if (alive.status === 200) {
|
|
250
|
+
console.log(' 守护进程已在运行')
|
|
251
|
+
return
|
|
252
|
+
}
|
|
253
|
+
} catch { /* 没在跑,继续启动 */ }
|
|
254
|
+
|
|
255
|
+
const here = path.dirname(fileURLToPath(import.meta.url))
|
|
256
|
+
const script = path.join(here, 'main.mjs')
|
|
257
|
+
// 守护进程是控制台程序:必须无窗口启动,否则会弹黑框
|
|
258
|
+
let result = startViaCim({ command: process.execPath, args: [script] })
|
|
259
|
+
if (!result.ok) {
|
|
260
|
+
console.log(' CIM 启动失败(' + (result.error ?? '未知') + '),回退到 spawn-hidden')
|
|
261
|
+
result = startHidden({ command: process.execPath, args: [script], stateDir: path.join(process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'), 'restart-daemon') })
|
|
262
|
+
}
|
|
263
|
+
if (!result.ok) {
|
|
264
|
+
console.error(' 启动失败:' + (result.error ?? '未知原因'))
|
|
265
|
+
process.exit(1)
|
|
266
|
+
}
|
|
267
|
+
console.log(' 已用 ' + result.how + ' 方式启动' + (result.pid ? '(PID ' + result.pid + ')' : ''))
|
|
268
|
+
|
|
269
|
+
// 等端口就绪(最多 8 秒)
|
|
270
|
+
for (let i = 0; i < 16; i += 1) {
|
|
271
|
+
await new Promise((resolve) => setTimeout(resolve, 500))
|
|
272
|
+
try {
|
|
273
|
+
const ready = await call('/status', 'GET')
|
|
274
|
+
if (ready.status === 200) {
|
|
275
|
+
console.log(' 控制口已就绪:http://127.0.0.1:' + controlPort + '/status')
|
|
276
|
+
return
|
|
277
|
+
}
|
|
278
|
+
} catch { /* 继续等 */ }
|
|
279
|
+
}
|
|
280
|
+
console.error(' 启动后 8 秒内控制口仍不可用,请查看日志:' + path.join(process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'), 'restart-daemon', 'restart-daemon.log'))
|
|
281
|
+
process.exit(1)
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function restart() {
|
|
285
|
+
try {
|
|
286
|
+
const res = await call('/restart-now', 'POST', {})
|
|
287
|
+
console.log(res.status === 202 ? ' 已请求立即重启(策略层不参与,慎用)' : ` 请求被拒绝(HTTP ${res.status})`)
|
|
288
|
+
} catch {
|
|
289
|
+
console.error('守护进程没在运行。先 install 或手动启动 bin/restart-daemon.mjs --detach。')
|
|
290
|
+
process.exit(1)
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function stop() {
|
|
295
|
+
try {
|
|
296
|
+
await call('/stop')
|
|
297
|
+
console.log(' 守护进程已退出(不会自动拉起 DSH)')
|
|
298
|
+
} catch {
|
|
299
|
+
console.error('守护进程没在运行')
|
|
300
|
+
process.exit(1)
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
switch (command) {
|
|
305
|
+
case 'install': install(); break
|
|
306
|
+
case 'start': await start(); break
|
|
307
|
+
case 'status': await status(); break
|
|
308
|
+
case 'remove': remove(); break
|
|
309
|
+
case 'restart': await restart(); break
|
|
310
|
+
case 'stop': await stop(); break
|
|
311
|
+
default:
|
|
312
|
+
console.log(`用法: dsh-homing-restart <install|start|status|remove|restart|stop> [--immediate]
|
|
313
|
+
|
|
314
|
+
install 写入登录自启(Windows 启动项 / macOS LaunchAgent / Linux systemd user unit)
|
|
315
|
+
status 向守护进程查询状态
|
|
316
|
+
remove 删除登录自启
|
|
317
|
+
restart 请求重启 DSH(等所有会话结束且无人输入;可加 --after N 表示最早 N 秒后)
|
|
318
|
+
stop 让守护进程退出(不再拉起 DSH)
|
|
319
|
+
`)
|
|
320
|
+
process.exit(command === undefined ? 0 : 1)
|
|
321
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 进程脱离与无窗口启动
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要:
|
|
5
|
+
* Windows 的 `taskkill /T` 按"父子链"杀整棵树。若守护进程由 DSH 直接 spawn,
|
|
6
|
+
* 它的父 PID 就是 DSH,会被连带杀掉——那时 DSH 死了也没人拉起。
|
|
7
|
+
*
|
|
8
|
+
* 启动策略(按优先级):
|
|
9
|
+
* ① startViaCim —— WMI 创建,父进程 = WmiPrvSE.exe,进程树与 DSH 无关
|
|
10
|
+
* ② startHidden —— Node spawn + windowsHide(CREATE_NO_WINDOW),无控制台
|
|
11
|
+
* Unix 平台统一用 detached spawn(setsid)。
|
|
12
|
+
*
|
|
13
|
+
* 两个踩过的坑(勿重犯):
|
|
14
|
+
* 1. `New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly` 建出的对象
|
|
15
|
+
* 存不住属性(读回为空),于是 StartupInfo 形同虚设、控制台照建。
|
|
16
|
+
* 必须用 `([wmiclass]'Win32_ProcessStartup').CreateInstance()`。
|
|
17
|
+
* 2. 经 WMI 传 `CREATE_NO_WINDOW(0x08000000)` 会被拒绝(ReturnValue=21);
|
|
18
|
+
* `CREATE_NEW_CONSOLE` 会带出控制台;只有 `DETACHED_PROCESS(0x8)` 能得到
|
|
19
|
+
* "没有控制台"的进程(判据:目标进程没有 conhost.exe 子进程)。
|
|
20
|
+
*
|
|
21
|
+
* 纯逻辑(ancestorMatches / chainNames / buildCimStartScript)与副作用分离,便于单测。
|
|
22
|
+
*/
|
|
23
|
+
import fs from 'node:fs';
|
|
24
|
+
import os from 'node:os';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 沿父链查找是否命中谓词。
|
|
30
|
+
* @param {number|null} startPid
|
|
31
|
+
* @param {(pid: number) => number|null} parentOf
|
|
32
|
+
* @param {(pid: number) => string|null} nameOf
|
|
33
|
+
* @param {(name: string) => boolean} predicate
|
|
34
|
+
* @returns {boolean}
|
|
35
|
+
*/
|
|
36
|
+
export function ancestorMatches(startPid, parentOf, nameOf, predicate) {
|
|
37
|
+
const seen = new Set();
|
|
38
|
+
let current = startPid;
|
|
39
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
40
|
+
if (current === null || current === undefined) return false;
|
|
41
|
+
if (seen.has(current)) return false;
|
|
42
|
+
seen.add(current);
|
|
43
|
+
const name = nameOf(current);
|
|
44
|
+
if (name && predicate(String(name))) return true;
|
|
45
|
+
current = parentOf(current);
|
|
46
|
+
}
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 收集父链上的进程名(排障用) */
|
|
51
|
+
export function chainNames(startPid, parentOf, nameOf, limit = 8) {
|
|
52
|
+
const out = [];
|
|
53
|
+
const seen = new Set();
|
|
54
|
+
let current = startPid;
|
|
55
|
+
for (let depth = 0; depth < limit; depth += 1) {
|
|
56
|
+
if (current === null || current === undefined) break;
|
|
57
|
+
if (seen.has(current)) break;
|
|
58
|
+
seen.add(current);
|
|
59
|
+
const name = nameOf(current);
|
|
60
|
+
if (!name) break;
|
|
61
|
+
out.push(name);
|
|
62
|
+
current = parentOf(current);
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 生成用 WMI 创建进程的 PowerShell 脚本(纯函数,便于测试)
|
|
69
|
+
*
|
|
70
|
+
* 关键点见文件头注释:wmiclass 实例 + DETACHED_PROCESS(8)。
|
|
71
|
+
*/
|
|
72
|
+
export function buildCimStartScript({ command, args = [], cwd }) {
|
|
73
|
+
const cmdline = [command, ...args].map((item) => '"' + String(item) + '"').join(' ');
|
|
74
|
+
const workDir = cwd ?? path.dirname(command);
|
|
75
|
+
return [
|
|
76
|
+
"$si = ([wmiclass]'Win32_ProcessStartup').CreateInstance()",
|
|
77
|
+
'$si.CreateFlags = [uint32]8',
|
|
78
|
+
'$si.ShowWindow = [uint16]0',
|
|
79
|
+
"$r = ([wmiclass]'Win32_Process').Create('" + cmdline.replaceAll("'", "''") + "', '" + workDir.replaceAll("'", "''") + "', $si)",
|
|
80
|
+
'Write-Output ($r.ReturnValue.ToString() + "|" + $r.ProcessId)',
|
|
81
|
+
].join('; ');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 用 CIM/WMI 创建进程(父进程 = WmiPrvSE.exe,与 DSH 进程树无关)
|
|
86
|
+
* @returns {{ ok: boolean, how: string, pid?: number, error?: string }}
|
|
87
|
+
*/
|
|
88
|
+
export function startViaCim({ command, args = [], cwd }) {
|
|
89
|
+
if (process.platform !== 'win32') return { ok: false, how: 'cim', error: 'not-windows' };
|
|
90
|
+
try {
|
|
91
|
+
const ps = buildCimStartScript({ command, args, cwd });
|
|
92
|
+
const encoded = Buffer.from(ps, 'utf16le').toString('base64');
|
|
93
|
+
const out = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], {
|
|
94
|
+
encoding: 'utf8',
|
|
95
|
+
windowsHide: true,
|
|
96
|
+
timeout: 25_000,
|
|
97
|
+
});
|
|
98
|
+
const text = String(out.stdout ?? '').trim();
|
|
99
|
+
const [retText, pidText] = text.split('|');
|
|
100
|
+
const ret = Number(retText);
|
|
101
|
+
const pid = Number(pidText);
|
|
102
|
+
if (ret === 0 && Number.isFinite(pid) && pid > 0) return { ok: true, how: 'cim', pid };
|
|
103
|
+
return { ok: false, how: 'cim', error: 'ReturnValue=' + (Number.isFinite(ret) ? ret : text.slice(0, 80)) };
|
|
104
|
+
} catch (error) {
|
|
105
|
+
return { ok: false, how: 'cim', error: error.message };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 直接 spawn(Windows 上 windowsHide 会设置 CREATE_NO_WINDOW,无控制台)
|
|
111
|
+
* 兜底路径:父进程是调用者,调用者退出后父 PID 消失。
|
|
112
|
+
*/
|
|
113
|
+
export function startHidden({ command, args = [], cwd }) {
|
|
114
|
+
try {
|
|
115
|
+
const child = spawn(command, args, {
|
|
116
|
+
cwd: cwd ?? path.dirname(command),
|
|
117
|
+
detached: true,
|
|
118
|
+
stdio: 'ignore',
|
|
119
|
+
windowsHide: true,
|
|
120
|
+
});
|
|
121
|
+
child.unref();
|
|
122
|
+
return { ok: true, how: 'spawn-hidden', pid: child.pid };
|
|
123
|
+
} catch (error) {
|
|
124
|
+
return { ok: false, how: 'spawn-hidden', error: error.message };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 进程树与重启授权的纯逻辑(可单测,不依赖真实进程表)
|
|
3
|
+
*
|
|
4
|
+
* 背景:授权对象与操作对象不是同一个东西——
|
|
5
|
+
* - 授权:调用者必须是"插件宿主进程"(严格相等)
|
|
6
|
+
* - 操作:杀掉 DSH 主进程及其整棵子树
|
|
7
|
+
* 因此必须显式断言"待重启的树包含插件宿主自己",
|
|
8
|
+
* 避免出现"授权通过、却杀掉一棵与授权方无关的树"。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 找出进程树的根:父进程不在集合内的那个。
|
|
13
|
+
* @param {number[]} pids 进程集合
|
|
14
|
+
* @param {(pid: number) => number|null} parentOf 父进程查询
|
|
15
|
+
*/
|
|
16
|
+
export function rootOf(pids, parentOf) {
|
|
17
|
+
const set = new Set(pids);
|
|
18
|
+
for (const pid of pids) {
|
|
19
|
+
const parent = parentOf(pid);
|
|
20
|
+
if (parent === null || parent === undefined) return pid;
|
|
21
|
+
if (!set.has(parent)) return pid;
|
|
22
|
+
}
|
|
23
|
+
return pids[0] ?? null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* ancestor 是否是 pid 本身或它的祖先。
|
|
28
|
+
* @param {number} ancestor
|
|
29
|
+
* @param {number} pid
|
|
30
|
+
* @param {(pid: number) => number|null} parentOf
|
|
31
|
+
*/
|
|
32
|
+
export function isAncestorOrSelf(ancestor, pid, parentOf) {
|
|
33
|
+
let current = pid;
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
36
|
+
if (current === ancestor) return true;
|
|
37
|
+
if (current === null || current === undefined) return false;
|
|
38
|
+
if (seen.has(current)) return false;
|
|
39
|
+
seen.add(current);
|
|
40
|
+
current = parentOf(current);
|
|
41
|
+
}
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 判断一次重启请求是否应当被接受。
|
|
47
|
+
* @param {object} options
|
|
48
|
+
* @param {number|null} options.srcPid 发起请求的进程
|
|
49
|
+
* @param {number|null} options.hostPid 插件宿主进程(监听桥接端口者)
|
|
50
|
+
* @param {number[]} options.pids 当前 DSH 进程集合
|
|
51
|
+
* @param {(pid: number) => number|null} options.parentOf
|
|
52
|
+
* @returns {{ ok: boolean, reason?: string, rootPid?: number|null, treeSize?: number }}
|
|
53
|
+
*/
|
|
54
|
+
/**
|
|
55
|
+
* 授权(不依赖父子关系,适配 Windows 已移除 wmic 的现实):
|
|
56
|
+
* - 来源必须是插件宿主
|
|
57
|
+
* - 插件宿主必须属于 DSH 进程集合
|
|
58
|
+
*/
|
|
59
|
+
export function authorizeRestart({ srcPid, hostPid, pids }) {
|
|
60
|
+
if (!hostPid) return { ok: false, reason: 'plugin-host-unknown' };
|
|
61
|
+
if (!srcPid) return { ok: false, reason: 'source-unknown' };
|
|
62
|
+
if (srcPid !== hostPid) return { ok: false, reason: 'source-not-plugin-host' };
|
|
63
|
+
if (!Array.isArray(pids) || pids.length === 0) return { ok: false, reason: 'no-dsh-processes' };
|
|
64
|
+
if (!pids.includes(hostPid)) return { ok: false, reason: 'host-not-in-dsh-processes' };
|
|
65
|
+
return { ok: true, rootPid: null, treeSize: pids.length };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 重启流程(可单测的编排层)
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独拆出来:
|
|
5
|
+
* restart() 里的顺序(杀 → 等升级 → 启动 → 等恢复)和边界(并发、超时、异常复位)
|
|
6
|
+
* 是守护进程最核心的逻辑,但原来埋在 main.mjs 里,只能靠真跑一遍验证。
|
|
7
|
+
* 这里把副作用全部注入(probe/killDsh/launch/waitForUpgrade/sleep/now),
|
|
8
|
+
* 就能用假进程、假时钟覆盖所有分支。
|
|
9
|
+
*
|
|
10
|
+
* main.mjs 只负责提供真实实现并把状态读写回调接上。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** 崩溃拉起退避:1s × 次数,最多 30s(至少 1s) */
|
|
14
|
+
export function computeBackoff(restarts, { baseMs = 1000, maxMs = 30_000 } = {}) {
|
|
15
|
+
const times = Number.isFinite(restarts) && restarts > 0 ? restarts : 1;
|
|
16
|
+
return Math.min(maxMs, baseMs * times);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 子进程退出后该怎么办(纯函数)
|
|
21
|
+
* @returns {{ action: 'skip'|'relaunch', delayMs?: number, reason?: string }}
|
|
22
|
+
*/
|
|
23
|
+
export function planAfterExit({ stopping, pausedUntil = 0, restarts = 1, now = Date.now() }) {
|
|
24
|
+
if (stopping) return { action: 'skip', reason: 'stopping-for-restart' };
|
|
25
|
+
const delayMs = computeBackoff(restarts);
|
|
26
|
+
if (pausedUntil > now) return { action: 'skip', reason: 'paused' };
|
|
27
|
+
return { action: 'relaunch', delayMs };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 创建重启流程执行器
|
|
32
|
+
*
|
|
33
|
+
* @param {object} deps
|
|
34
|
+
* @param {() => Promise<{running:boolean,pids:number[]}>} deps.probe
|
|
35
|
+
* @param {() => Promise<void>} deps.killDsh
|
|
36
|
+
* @param {() => any} deps.launch
|
|
37
|
+
* @param {() => Promise<{upgrading?:boolean,reason?:string}>} deps.waitForUpgrade
|
|
38
|
+
* @param {(v:boolean) => void} deps.setRestarting
|
|
39
|
+
* @param {(v:boolean) => void} deps.setStopping
|
|
40
|
+
* @param {(child:any) => void} deps.setChild
|
|
41
|
+
* @param {() => void} [deps.persist]
|
|
42
|
+
* @param {(msg:string) => void} [deps.log]
|
|
43
|
+
* @param {(ms:number) => Promise<void>} [deps.sleep]
|
|
44
|
+
* @param {() => number} [deps.now]
|
|
45
|
+
* @param {number} [deps.deadlineMs]
|
|
46
|
+
* @param {number} [deps.pollMs]
|
|
47
|
+
*/
|
|
48
|
+
export function createRestartFlow({
|
|
49
|
+
probe,
|
|
50
|
+
killDsh,
|
|
51
|
+
launch,
|
|
52
|
+
waitForUpgrade,
|
|
53
|
+
setRestarting,
|
|
54
|
+
setStopping,
|
|
55
|
+
setChild,
|
|
56
|
+
persist = () => {},
|
|
57
|
+
log = () => {},
|
|
58
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
59
|
+
now = () => Date.now(),
|
|
60
|
+
deadlineMs = 60_000,
|
|
61
|
+
pollMs = 1000,
|
|
62
|
+
}) {
|
|
63
|
+
let inFlight = false;
|
|
64
|
+
|
|
65
|
+
async function restart() {
|
|
66
|
+
if (inFlight) {
|
|
67
|
+
log('已有重启在进行中,忽略本次请求');
|
|
68
|
+
return { ok: false, busy: true };
|
|
69
|
+
}
|
|
70
|
+
inFlight = true;
|
|
71
|
+
setRestarting(true);
|
|
72
|
+
setStopping(true);
|
|
73
|
+
persist();
|
|
74
|
+
try {
|
|
75
|
+
log('开始重启:终止 DSH 进程');
|
|
76
|
+
await killDsh();
|
|
77
|
+
log('DSH 已退出');
|
|
78
|
+
|
|
79
|
+
const upgrade = await waitForUpgrade();
|
|
80
|
+
if (upgrade && upgrade.upgrading) log('检测到升级进行中,等待安装完成');
|
|
81
|
+
|
|
82
|
+
log('启动 DSH');
|
|
83
|
+
setChild(launch());
|
|
84
|
+
|
|
85
|
+
const deadline = now() + deadlineMs;
|
|
86
|
+
while (now() < deadline) {
|
|
87
|
+
await sleep(pollMs);
|
|
88
|
+
const info = await probe();
|
|
89
|
+
if (info && info.running) {
|
|
90
|
+
log('重启完成:DSH 已恢复(PID ' + (info.pids ?? []).join(',') + ')');
|
|
91
|
+
return { ok: true, pids: info.pids ?? [] };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
log('重启后 ' + Math.round(deadlineMs / 1000) + ' 秒内 DSH 未恢复');
|
|
95
|
+
return { ok: false, error: 'dsh-not-back' };
|
|
96
|
+
} catch (error) {
|
|
97
|
+
log('重启失败:' + (error?.message ?? String(error)));
|
|
98
|
+
return { ok: false, error: error?.message ?? String(error) };
|
|
99
|
+
} finally {
|
|
100
|
+
inFlight = false;
|
|
101
|
+
setRestarting(false);
|
|
102
|
+
setStopping(false);
|
|
103
|
+
persist();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
restart,
|
|
109
|
+
get inFlight() { return inFlight; },
|
|
110
|
+
};
|
|
111
|
+
}
|