remote-restart-stale-daemon.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import { execFile } from "node:child_process";
  2. import { resolve } from "node:path";
  3. import { promisify } from "node:util";
  4. import { execInRemoteContainer } from "#e2e/helpers/remote-docker-target";
  5. // R7 远端环境重启的真实验证(本机 Docker runner):容器重启后进程全没了,run/ 下的
  6. // server.lock 与 status.json 留在磁盘上,PID 从小号重新分配。用例把残留文件里的 PID 指向
  7. // 一个同用户的存活进程,复现“旧 PID 被复用”,再从 Desktop 连接。
  8. const execFileAsync = promisify(execFile);
  9. /** 远端账号:SSH 用例登录 dev,Docker transport 以容器默认用户 root 执行。 */
  10. export interface RemoteAccount {
  11. user: string;
  12. home: string;
  13. }
  14. export interface RemoteDaemonFiles {
  15. lock: Record<string, unknown> | null;
  16. status: Record<string, unknown> | null;
  17. }
  18. async function shAs(container: string, account: RemoteAccount, script: string): Promise<string> {
  19. return (
  20. await execInRemoteContainer(container, ["env", `HOME=${account.home}`, "sh", "-c", script], {
  21. user: account.user,
  22. })
  23. ).stdout;
  24. }
  25. /** 用 Desktop 将要安装的同一份 archive 预装远端并启动 daemon,使连接直接进入 ensureDaemon。 */
  26. export async function installAndStartRemoteDaemon(
  27. container: string,
  28. account: RemoteAccount,
  29. options: {
  30. desktopRoot: string;
  31. appVersion: string;
  32. /** 注入远端 Supervisor/Core 的 NODE_OPTIONS,用于测试接缝;update 拉起的 daemon 会先停掉。 */
  33. nodeOptions?: string;
  34. },
  35. ): Promise<void> {
  36. await installRemoteServerArchive(container, account, options);
  37. await shAs(
  38. container,
  39. account,
  40. [
  41. "set -eu",
  42. ...(options.nodeOptions
  43. ? [
  44. `"$HOME/.zcode/server/bin/zcode" stop --wait --server-root "$HOME/.zcode/server" --json >/dev/null`,
  45. ]
  46. : []),
  47. `${options.nodeOptions ? `NODE_OPTIONS='${options.nodeOptions}' ` : ""}ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1 "$HOME/.zcode/server/bin/zcode" serve --daemon --server-root "$HOME/.zcode/server" --json >/dev/null`,
  48. ].join("; "),
  49. );
  50. }
  51. /** 用 Desktop 将要安装的同一份 archive 安装到远端 `~/.zcode/server`,不启动 daemon。 */
  52. export async function installRemoteServerArchive(
  53. container: string,
  54. account: RemoteAccount,
  55. options: { desktopRoot: string; appVersion: string },
  56. ): Promise<void> {
  57. const machine = (await shAs(container, account, "uname -m")).trim();
  58. const target = machine === "aarch64" ? "linux-arm64" : "linux-x64";
  59. const archive = resolve(
  60. options.desktopRoot,
  61. "mock-cdn/releases",
  62. options.appVersion,
  63. `zcode-server-${target}.tar.gz`,
  64. );
  65. const remoteArchive = `/tmp/e2e-zcode-server-${account.user}.tar.gz`;
  66. await execFileAsync("docker", ["cp", archive, `${container}:${remoteArchive}`], {
  67. maxBuffer: 16 * 1024 * 1024,
  68. });
  69. await execInRemoteContainer(container, ["chown", `${account.user}:`, remoteArchive], {
  70. user: "0",
  71. });
  72. await shAs(
  73. container,
  74. account,
  75. [
  76. "set -eu",
  77. 'b="$HOME/.zcode/server/.e2e-bootstrap"',
  78. 'rm -rf "$b"',
  79. 'mkdir -p "$b"',
  80. `tar -xzf ${remoteArchive} -C "$b" --strip-components=1`,
  81. // WSL/Docker 的 daemon 不注册 OS service,与 Desktop 的 Docker transport 一致。
  82. `ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1 "$b/bin/zcode" update --from-archive ${remoteArchive} --server-root "$HOME/.zcode/server" --json >/dev/null`,
  83. `rm -rf "$b" ${remoteArchive}`,
  84. ].join("; "),
  85. );
  86. }
  87. export async function readRemoteDaemonFiles(
  88. container: string,
  89. account: RemoteAccount,
  90. ): Promise<RemoteDaemonFiles> {
  91. const read = async (name: string): Promise<Record<string, unknown> | null> => {
  92. try {
  93. return JSON.parse(
  94. await shAs(container, account, `cat "$HOME/.zcode/server/run/${name}"`),
  95. ) as Record<string, unknown>;
  96. } catch {
  97. return null;
  98. }
  99. };
  100. return { lock: await read("server.lock"), status: await read("status.json") };
  101. }
  102. /** docker restart:远端进程全部结束,文件系统保留;等 sshd 重新起来。 */
  103. export async function restartRemoteContainer(container: string): Promise<void> {
  104. await execFileAsync("docker", ["restart", "--time", "1", container]);
  105. const deadline = Date.now() + 30_000;
  106. while (Date.now() < deadline) {
  107. const sshd = await execInRemoteContainer(container, ["pgrep", "-x", "sshd"], { user: "0" })
  108. .then(() => true)
  109. .catch(() => false);
  110. if (sshd) return;
  111. await new Promise<void>((done) => setTimeout(done, 200));
  112. }
  113. throw new Error(`容器 ${container} 重启后 30 秒内没有 sshd`);
  114. }
  115. /** 起一个同用户的空闲进程,代表“旧 PID 被同用户的其他进程复用”。返回它的 PID。 */
  116. export async function spawnPidReuseHolder(
  117. container: string,
  118. account: RemoteAccount,
  119. ): Promise<number> {
  120. // 每个账号用不同的时长,pgrep 才能唯一定位。
  121. const seconds = account.user === "dev" ? 3601 : 3602;
  122. await execFileAsync("docker", [
  123. "exec",
  124. "--detach",
  125. "--user",
  126. account.user,
  127. container,
  128. "sleep",
  129. String(seconds),
  130. ]);
  131. const deadline = Date.now() + 10_000;
  132. while (Date.now() < deadline) {
  133. const pid = Number(
  134. (await shAs(container, account, `pgrep -n -f '^sleep ${seconds}$' || true`)).trim(),
  135. );
  136. if (Number.isInteger(pid) && pid > 0) return pid;
  137. await new Promise<void>((done) => setTimeout(done, 100));
  138. }
  139. throw new Error(`容器 ${container} 内没有找到 sleep ${seconds}`);
  140. }
  141. /**
  142. * 把残留锁里的 PID 改成 holderPid。statusPid 为 holderPid 时,status.json 快照仍是 ready 且
  143. * PID 存活,probe 会复用旧端口(#14–#16);为已死的 PID 时,probe 判定未就绪,直接 serve --daemon(#13)。
  144. * lockIdentity 给出时同时改写锁的 processIdentity,使持锁者按进程身份判定为同一进程。
  145. */
  146. export async function pointStaleDaemonFilesAt(
  147. container: string,
  148. account: RemoteAccount,
  149. pids: { lockPid: number; statusPid: number; lockIdentity?: string },
  150. ): Promise<void> {
  151. const replacePid = (file: string, pid: number) =>
  152. `sed -i -E '0,/"pid"[[:space:]]*:[[:space:]]*[0-9]+/s//"pid":${pid}/' "$HOME/.zcode/server/run/${file}"`;
  153. await shAs(
  154. container,
  155. account,
  156. [
  157. "set -eu",
  158. replacePid("server.lock", pids.lockPid),
  159. replacePid("status.json", pids.statusPid),
  160. ...(pids.lockIdentity
  161. ? [
  162. `sed -i -E 's/"processIdentity":"[^"]*"/"processIdentity":"${pids.lockIdentity}"/' "$HOME/.zcode/server/run/server.lock"`,
  163. ]
  164. : []),
  165. ].join("; "),
  166. );
  167. }
  168. /** kill -9 锁里的 Supervisor 与快照里的 Core,模拟非正常死亡;等两者都不存在后返回。 */
  169. export async function killRemoteDaemon(container: string, account: RemoteAccount): Promise<void> {
  170. const files = await readRemoteDaemonFiles(container, account);
  171. const pids = [files.lock?.pid, files.status?.pid].filter(
  172. (pid): pid is number => typeof pid === "number" && pid > 0,
  173. );
  174. if (pids.length === 0) throw new Error(`容器 ${container} 内没有可结束的 daemon 进程`);
  175. await shAs(container, account, `kill -9 ${pids.join(" ")} 2>/dev/null || true`);
  176. const deadline = Date.now() + 10_000;
  177. while (Date.now() < deadline) {
  178. const alive = await Promise.all(pids.map((pid) => isRemotePidAlive(container, account, pid)));
  179. if (alive.every((value) => !value)) return;
  180. await new Promise<void>((done) => setTimeout(done, 100));
  181. }
  182. throw new Error(`容器 ${container} 内 daemon 进程 ${pids.join(",")} 10 秒内未退出`);
  183. }
  184. /**
  185. * 造一个已退出但未被回收的进程(僵尸)并返回其 PID。父进程 exec 成不回收子进程的 sleep,
  186. * 与 PID 1 不回收子进程的容器里 Supervisor/Core 死亡后的状态相同(ZCT-2117275161536565248)。
  187. */
  188. export async function spawnZombieProcess(
  189. container: string,
  190. account: RemoteAccount,
  191. ): Promise<number> {
  192. const seconds = account.user === "dev" ? 3603 : 3604;
  193. await execFileAsync("docker", [
  194. "exec",
  195. "--detach",
  196. "--user",
  197. account.user,
  198. container,
  199. "sh",
  200. "-c",
  201. `sleep 0.5 & exec sleep ${seconds}`,
  202. ]);
  203. const deadline = Date.now() + 10_000;
  204. while (Date.now() < deadline) {
  205. const zombie = Number(
  206. (
  207. await shAs(
  208. container,
  209. account,
  210. // 子进程还没退出时循环里最后一次判断为假;显式 exit 0,交给外层轮询重试。
  211. `p=$(pgrep -n -f '^sleep ${seconds}$' || true); [ -n "$p" ] || exit 0; for c in $(pgrep -P "$p" || true); do [ "$(awk '{print $3}' /proc/$c/stat 2>/dev/null)" = Z ] && echo "$c"; done; exit 0`,
  212. )
  213. ).trim(),
  214. );
  215. if (Number.isInteger(zombie) && zombie > 0) return zombie;
  216. await new Promise<void>((done) => setTimeout(done, 100));
  217. }
  218. throw new Error(`容器 ${container} 内 10 秒内没有出现僵尸进程`);
  219. }
  220. /** 按 lock.ts 的 Linux 规则读取进程身份:boot_id 加 /proc/<pid>/stat 的 starttime。 */
  221. export async function readRemoteProcessIdentity(
  222. container: string,
  223. account: RemoteAccount,
  224. pid: number,
  225. ): Promise<string> {
  226. // comm 可能含空格;与 lock.ts 一样从最后一个 ")" 之后数,starttime 是其后第 20 个字段。
  227. return (
  228. await shAs(
  229. container,
  230. account,
  231. `printf '%s:%s' "$(cat /proc/sys/kernel/random/boot_id)" "$(awk '{ s = $0; sub(/.*\\) /, "", s); split(s, f, " "); print f[20] }' /proc/${pid}/stat)"`,
  232. )
  233. ).trim();
  234. }
  235. /** 远端以 systemd 为 PID 1(`run-local-docker.mjs --systemd`)时,SSH 连接走 OS service 启动方式。 */
  236. export async function isRemoteSystemdTarget(container: string): Promise<boolean> {
  237. return await execInRemoteContainer(container, ["test", "-d", "/run/systemd/system"], {
  238. user: "0",
  239. })
  240. .then(() => true)
  241. .catch(() => false);
  242. }
  243. /**
  244. * ready 之后连续 kill -9 Core,直到 Supervisor 耗尽崩溃预算进入 crash-loop-stopped(R3-ISSUE-031)。
  245. * 每次等新的 Core 起来再结束它,使每次结束都计入崩溃预算。返回最终的 status.json。
  246. */
  247. export async function driveRemoteCrashLoop(
  248. container: string,
  249. account: RemoteAccount,
  250. ): Promise<Record<string, unknown> | null> {
  251. const deadline = Date.now() + 120_000;
  252. let lastKilled: number | undefined;
  253. while (Date.now() < deadline) {
  254. const { status } = await readRemoteDaemonFiles(container, account);
  255. if (status?.state === "crash-loop-stopped") return status;
  256. const pid = status?.pid;
  257. if (status?.state === "ready" && typeof pid === "number" && pid !== lastKilled) {
  258. await shAs(container, account, `kill -9 ${pid} 2>/dev/null || true`);
  259. lastKilled = pid;
  260. }
  261. await new Promise<void>((done) => setTimeout(done, 200));
  262. }
  263. throw new Error(`容器 ${container} 内 120 秒内未进入 crash-loop-stopped`);
  264. }
  265. export async function isRemotePidAlive(
  266. container: string,
  267. account: RemoteAccount,
  268. pid: number,
  269. ): Promise<boolean> {
  270. return (await shAs(container, account, `kill -0 ${pid} 2>/dev/null && echo alive || echo dead`))
  271. .trim()
  272. .startsWith("alive");
  273. }