remote-restart-stale-daemon.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. */
  145. export async function pointStaleDaemonFilesAt(
  146. container: string,
  147. account: RemoteAccount,
  148. pids: { lockPid: number; statusPid: number },
  149. ): Promise<void> {
  150. const replacePid = (file: string, pid: number) =>
  151. `sed -i -E '0,/"pid"[[:space:]]*:[[:space:]]*[0-9]+/s//"pid":${pid}/' "$HOME/.zcode/server/run/${file}"`;
  152. await shAs(
  153. container,
  154. account,
  155. [
  156. "set -eu",
  157. replacePid("server.lock", pids.lockPid),
  158. replacePid("status.json", pids.statusPid),
  159. ].join("; "),
  160. );
  161. }
  162. export async function isRemotePidAlive(
  163. container: string,
  164. account: RemoteAccount,
  165. pid: number,
  166. ): Promise<boolean> {
  167. return (await shAs(container, account, `kill -0 ${pid} 2>/dev/null && echo alive || echo dead`))
  168. .trim()
  169. .startsWith("alive");
  170. }