dockerBackendDockerCommand.test.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import { EventEmitter } from "node:events";
  2. import { mkdtemp, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { PassThrough } from "node:stream";
  6. import { fileURLToPath } from "node:url";
  7. import { beforeEach, describe, expect, it, vi } from "vitest";
  8. const mocks = vi.hoisted(() => ({
  9. execFile: vi.fn(),
  10. isDockerAvailable: vi.fn(),
  11. listDockerContainers: vi.fn(),
  12. resolveDockerCommand: vi.fn(),
  13. spawn: vi.fn(),
  14. }));
  15. vi.mock("node:child_process", () => ({
  16. execFile: mocks.execFile,
  17. spawn: mocks.spawn,
  18. }));
  19. vi.mock("@zcode/server/remote/docker-detect.js", () => ({
  20. isDockerAvailable: mocks.isDockerAvailable,
  21. listDockerContainers: mocks.listDockerContainers,
  22. resolveDockerCommand: mocks.resolveDockerCommand,
  23. }));
  24. import { DockerBackend } from "@zcode/server/remote/docker-backend.js";
  25. const RESOLVED_DOCKER_COMMAND = "/resolved/bin/docker";
  26. function createBackend(): DockerBackend {
  27. return new DockerBackend({
  28. kind: "docker",
  29. container: "zcode-dev",
  30. });
  31. }
  32. function createSpawnChild() {
  33. const child = new EventEmitter() as EventEmitter & {
  34. stderr: PassThrough;
  35. stdin: PassThrough;
  36. stdout: PassThrough;
  37. };
  38. child.stdin = new PassThrough();
  39. child.stdout = new PassThrough();
  40. child.stderr = new PassThrough();
  41. queueMicrotask(() => child.emit("spawn"));
  42. return child;
  43. }
  44. function resolveDockerExecStdout(args: string[]): string {
  45. const shellCommand = args.at(-1) ?? "";
  46. if (shellCommand === "printf %s ~") {
  47. return "/root";
  48. }
  49. if (shellCommand === "uname -s") {
  50. return "Linux\n";
  51. }
  52. if (shellCommand === "uname -m") {
  53. return "arm64\n";
  54. }
  55. if (shellCommand.includes("/proc/sys/kernel/ostype")) {
  56. return "Linux\n";
  57. }
  58. return "";
  59. }
  60. describe("DockerBackend docker command resolution", () => {
  61. beforeEach(() => {
  62. mocks.execFile.mockReset();
  63. mocks.spawn.mockReset();
  64. mocks.isDockerAvailable.mockReset();
  65. mocks.listDockerContainers.mockReset();
  66. mocks.resolveDockerCommand.mockReset();
  67. mocks.resolveDockerCommand.mockReturnValue(RESOLVED_DOCKER_COMMAND);
  68. mocks.isDockerAvailable.mockResolvedValue(true);
  69. mocks.listDockerContainers.mockResolvedValue([
  70. {
  71. id: "abc123",
  72. image: "ubuntu:24.04",
  73. name: "zcode-dev",
  74. state: "running",
  75. status: "Up 2 minutes",
  76. },
  77. ]);
  78. mocks.execFile.mockImplementation(
  79. (
  80. _command: string,
  81. args: string[],
  82. _options: unknown,
  83. callback: (error: Error | null, stdout: string, stderr: string) => void,
  84. ) => {
  85. queueMicrotask(() => callback(null, resolveDockerExecStdout(args), ""));
  86. return {} as never;
  87. },
  88. );
  89. mocks.spawn.mockImplementation(() => createSpawnChild());
  90. });
  91. it("exec 链路中的 docker exec 使用解析后的 Docker CLI", async () => {
  92. const backend = createBackend();
  93. await backend.exec("printf ok");
  94. expect(mocks.execFile).toHaveBeenCalledWith(
  95. RESOLVED_DOCKER_COMMAND,
  96. ["exec", "-i", "zcode-dev", "sh", "-lc", "printf %s ~"],
  97. expect.any(Object),
  98. expect.any(Function),
  99. );
  100. expect(mocks.spawn).toHaveBeenCalledWith(
  101. RESOLVED_DOCKER_COMMAND,
  102. ["exec", "-i", "zcode-dev", "sh", "-lc", "printf ok"],
  103. expect.any(Object),
  104. );
  105. });
  106. it("无进度上传也应由容器用户流式写入,避免 docker cp 文件所有权错配", async () => {
  107. mocks.spawn.mockImplementation(() => {
  108. const child = createSpawnChild();
  109. child.stdin.resume();
  110. child.stdin.on("finish", () => queueMicrotask(() => child.emit("close", 0)));
  111. return child;
  112. });
  113. const backend = createBackend();
  114. await backend.upload(fileURLToPath(import.meta.url), "~/.zcode/server/server.tgz");
  115. expect(mocks.spawn).toHaveBeenCalledWith(
  116. RESOLVED_DOCKER_COMMAND,
  117. ["exec", "-i", "zcode-dev", "sh", "-lc", "cat > '/root/.zcode/server/server.tgz'"],
  118. expect.any(Object),
  119. );
  120. expect(mocks.execFile.mock.calls.some((call) => (call[1] as string[])[0] === "cp")).toBe(false);
  121. expect(
  122. [...mocks.execFile.mock.calls, ...mocks.spawn.mock.calls].every(
  123. (call) => call[0] === RESOLVED_DOCKER_COMMAND,
  124. ),
  125. ).toBe(true);
  126. });
  127. it("流式上传失败时应保留容器 stderr 诊断", async () => {
  128. mocks.spawn.mockImplementation(() => {
  129. const child = createSpawnChild();
  130. child.stdin.resume();
  131. child.stdin.on("finish", () =>
  132. queueMicrotask(() => {
  133. child.stderr.write("cat: /root/file: Permission denied\n");
  134. child.stderr.end();
  135. child.emit("close", 1);
  136. }),
  137. );
  138. return child;
  139. });
  140. const backend = createBackend();
  141. await expect(backend.upload(fileURLToPath(import.meta.url), "/root/file")).rejects.toThrow(
  142. "Permission denied",
  143. );
  144. });
  145. it("带 progress 选项时改走 exec 流式上传并上报字节", async () => {
  146. const tempDir = await mkdtemp(join(tmpdir(), "docker-upload-progress-"));
  147. const localPath = join(tempDir, "attachment.bin");
  148. await writeFile(localPath, Buffer.alloc(96 * 1024, "a"));
  149. mocks.spawn.mockImplementation(() => {
  150. const child = createSpawnChild();
  151. child.stdin.resume();
  152. child.stdin.on("finish", () => queueMicrotask(() => child.emit("close", 0)));
  153. return child;
  154. });
  155. const backend = createBackend();
  156. const progress: Array<{ uploadedBytes: number; totalBytes: number }> = [];
  157. await backend.upload(localPath, "~/.zcode/tmp/attachment.bin", {
  158. onProgress: (event) => progress.push(event),
  159. });
  160. expect(mocks.spawn).toHaveBeenCalledWith(
  161. RESOLVED_DOCKER_COMMAND,
  162. ["exec", "-i", "zcode-dev", "sh", "-lc", "cat > '/root/.zcode/tmp/attachment.bin'"],
  163. expect.any(Object),
  164. );
  165. expect(progress.at(-1)).toEqual({
  166. uploadedBytes: 96 * 1024,
  167. totalBytes: 96 * 1024,
  168. });
  169. });
  170. });