-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathdevcontainerCli.ts
More file actions
637 lines (550 loc) · 18.1 KB
/
Copy pathdevcontainerCli.ts
File metadata and controls
637 lines (550 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
/**
* Devcontainer CLI helper - wraps `devcontainer` CLI commands.
*
* This module provides async functions for devcontainer operations:
* - checkVersion: verify CLI is installed and get version
* - up: build/start container with streaming logs
* - exec: execute commands inside the container
* - down: stop and remove the container
*/
import { spawn } from "child_process";
import type { BindMount } from "./credentialForwarding";
import type { InitLogger } from "./Runtime";
import { LineBuffer } from "./initHook";
import { redactDevcontainerArgsForLog } from "./devcontainerLogRedaction";
import { getErrorMessage } from "@/common/utils/errors";
import { log } from "@/node/services/log";
type DevcontainerUpOutcome = "success" | "error";
export interface DevcontainerUpResultLine {
outcome: DevcontainerUpOutcome;
containerId?: string;
remoteUser?: string;
remoteWorkspaceFolder?: string;
message?: string;
description?: string;
}
export type DevcontainerStdoutParse =
| { kind: "result"; result: DevcontainerUpResultLine }
| { kind: "log"; text: string }
| { kind: "raw"; text: string };
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isDevcontainerUpOutcome(value: unknown): value is DevcontainerUpOutcome {
return value === "success" || value === "error";
}
function isDevcontainerUpResult(value: unknown): value is DevcontainerUpResultLine {
if (!isRecord(value)) return false;
return isDevcontainerUpOutcome(value.outcome);
}
function extractDevcontainerLogText(value: Record<string, unknown>): string | null {
const text = typeof value.text === "string" ? value.text : undefined;
if (text) {
const level = typeof value.level === "number" ? value.level : 0;
const channel = typeof value.channel === "string" ? value.channel : "";
const type = typeof value.type === "string" ? value.type : "";
const isError = channel === "error" || type === "error";
if (level >= 2 || isError) {
return text;
}
return null;
}
const name = typeof value.name === "string" ? value.name : undefined;
if (name) {
return name;
}
return null;
}
function parseJsonLine(line: string): unknown {
try {
return JSON.parse(line) as unknown;
} catch {
return null;
}
}
export function parseDevcontainerStdoutLine(line: string): DevcontainerStdoutParse | null {
const trimmed = line.trim();
if (!trimmed) return null;
if (!trimmed.startsWith("{")) {
return { kind: "raw", text: line };
}
const parsed = parseJsonLine(trimmed);
if (!parsed) {
return { kind: "raw", text: line };
}
if (isDevcontainerUpResult(parsed)) {
return { kind: "result", result: parsed };
}
if (isRecord(parsed)) {
const text = extractDevcontainerLogText(parsed);
if (text) {
return { kind: "log", text };
}
}
return null;
}
export function formatDevcontainerUpError(
result: DevcontainerUpResultLine,
stderrSummary?: string
): string {
const messageParts = [result.message, result.description].filter(
(value): value is string => typeof value === "string" && value.trim().length > 0
);
if (messageParts.length > 0) {
return `devcontainer up failed: ${messageParts.join(" - ")}`;
}
if (stderrSummary && stderrSummary.trim().length > 0) {
return `devcontainer up failed: ${stderrSummary.trim()}`;
}
return "devcontainer up failed";
}
export function shouldCleanupDevcontainer(result: DevcontainerUpResultLine): boolean {
return (
result.outcome === "error" &&
typeof result.containerId === "string" &&
result.containerId.trim().length > 0
);
}
/** Output from `devcontainer up` command */
export interface DevcontainerUpResult {
containerId: string;
remoteUser: string;
remoteWorkspaceFolder: string;
}
/** Devcontainer CLI availability info */
export interface DevcontainerCliInfo {
available: true;
version: string;
}
/** devcontainer up options */
export interface DevcontainerUpOptions {
workspaceFolder: string;
configPath?: string;
initLogger: InitLogger;
abortSignal?: AbortSignal;
/** Additional bind mounts (formatted to CLI wire format when emitting --mount args) */
additionalMounts?: BindMount[];
/** Additional remote env vars */
remoteEnv?: Record<string, string>;
/** Timeout in milliseconds (default: 30 minutes) */
timeoutMs?: number;
}
const DEFAULT_UP_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
const MAX_STDERR_BUFFER_LENGTH = 8_000; // 8KB cap for error summaries
const DEFAULT_CLEANUP_TIMEOUT_MS = 60_000; // 1 minute
async function removeDevcontainerContainer(containerId: string): Promise<void> {
await new Promise<void>((resolve) => {
const proc = spawn("docker", ["rm", "-f", containerId], {
stdio: ["ignore", "pipe", "pipe"],
timeout: DEFAULT_CLEANUP_TIMEOUT_MS,
});
proc.on("error", () => {
resolve();
});
proc.on("close", () => {
resolve();
});
});
}
const VERSION_CHECK_TIMEOUT_MS = 10_000; // 10 seconds
/**
* Check if devcontainer CLI is installed and get version.
*/
export async function checkDevcontainerCliVersion(): Promise<DevcontainerCliInfo | null> {
return new Promise((resolve) => {
const proc = spawn("devcontainer", ["--version"], {
stdio: ["ignore", "pipe", "pipe"],
timeout: VERSION_CHECK_TIMEOUT_MS,
});
let stdout = "";
proc.stdout?.on("data", (data: Buffer) => {
stdout += data.toString();
});
proc.on("error", () => {
resolve(null);
});
proc.on("close", (code) => {
if (code === 0 && stdout.trim()) {
resolve({ available: true, version: stdout.trim() });
} else {
resolve(null);
}
});
});
}
/**
* Run `devcontainer up` with streaming logs.
* Parses the JSON output to extract container info.
*/
export async function devcontainerUp(
options: DevcontainerUpOptions
): Promise<DevcontainerUpResult> {
const {
workspaceFolder,
configPath,
initLogger,
abortSignal,
additionalMounts,
remoteEnv,
timeoutMs = DEFAULT_UP_TIMEOUT_MS,
} = options;
const baseArgs = ["up", "--log-format", "json", "--workspace-folder", workspaceFolder];
if (configPath) {
baseArgs.push("--config", configPath);
}
// Add mounts for credential sharing
if (additionalMounts) {
for (const mount of additionalMounts) {
// Single formatting point — the devcontainer CLI only accepts type/source/target/external.
baseArgs.push("--mount", `type=bind,source=${mount.source},target=${mount.target}`);
}
}
// Add remote env vars
if (remoteEnv) {
for (const [key, value] of Object.entries(remoteEnv)) {
baseArgs.push("--remote-env", `${key}=${value}`);
}
}
const runUp = (args: string[]): Promise<DevcontainerUpResult> => {
const logArgs = redactDevcontainerArgsForLog(args);
initLogger.logStep(`Running: devcontainer ${logArgs.join(" ")}`);
return new Promise((resolve, reject) => {
if (abortSignal?.aborted) {
reject(new Error("devcontainer up aborted"));
return;
}
const proc = spawn("devcontainer", args, {
stdio: ["ignore", "pipe", "pipe"],
timeout: timeoutMs,
cwd: workspaceFolder,
});
let settled = false;
let lastResultLine: DevcontainerUpResultLine | null = null;
let stderrBuffer = "";
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const settleSuccess = (result: DevcontainerUpResult) => {
if (settled) return;
settled = true;
if (timeoutId) clearTimeout(timeoutId);
resolve(result);
};
const appendStderrSummary = (text: string) => {
if (stderrBuffer.length >= MAX_STDERR_BUFFER_LENGTH) return;
const next = `${text}\n`;
stderrBuffer = (stderrBuffer + next).slice(0, MAX_STDERR_BUFFER_LENGTH);
};
const settleError = (error: Error) => {
if (settled) return;
settled = true;
if (timeoutId) clearTimeout(timeoutId);
reject(error);
};
const stdoutLineBuffer = new LineBuffer((line) => {
const parsed = parseDevcontainerStdoutLine(line);
if (!parsed) return;
if (parsed.kind === "result") {
lastResultLine = parsed.result;
return;
}
if (parsed.kind === "log") {
initLogger.logStdout(parsed.text);
return;
}
initLogger.logStdout(parsed.text);
});
const stderrLineBuffer = new LineBuffer((line) => {
const parsed = parseDevcontainerStdoutLine(line);
if (parsed?.kind === "result") {
lastResultLine ??= parsed.result;
return;
}
const summaryText = parsed ? parsed.text : line;
appendStderrSummary(summaryText);
if (!parsed) return;
initLogger.logStdout(parsed.text);
});
proc.stdout?.on("data", (data: Buffer) => {
stdoutLineBuffer.append(data.toString());
});
proc.stderr?.on("data", (data: Buffer) => {
stderrLineBuffer.append(data.toString());
});
const abortHandler = () => {
proc.kill("SIGTERM");
settleError(new Error("devcontainer up aborted"));
};
if (timeoutMs && timeoutMs > 0) {
timeoutId = setTimeout(() => {
proc.kill("SIGTERM");
settleError(new Error(`devcontainer up timed out after ${timeoutMs}ms`));
}, timeoutMs);
}
abortSignal?.addEventListener("abort", abortHandler, { once: true });
if (abortSignal?.aborted) {
abortHandler();
}
const finalizeError = async (message: string, result?: DevcontainerUpResultLine | null) => {
if (result && shouldCleanupDevcontainer(result)) {
try {
await removeDevcontainerContainer(result.containerId ?? "");
} catch (cleanupError) {
log.debug("Failed to remove devcontainer container", {
cleanupError,
containerId: result.containerId,
});
}
}
settleError(new Error(message));
};
proc.on("error", (err) => {
abortSignal?.removeEventListener("abort", abortHandler);
stdoutLineBuffer.flush();
stderrLineBuffer.flush();
settleError(new Error(`devcontainer up failed: ${getErrorMessage(err)}`));
});
proc.on("close", (code) => {
const handleClose = async () => {
abortSignal?.removeEventListener("abort", abortHandler);
stdoutLineBuffer.flush();
stderrLineBuffer.flush();
if (settled) return;
const stderrSummary = stderrBuffer.trim();
if (lastResultLine) {
if (lastResultLine.outcome === "success") {
if (
!lastResultLine.containerId ||
!lastResultLine.remoteUser ||
!lastResultLine.remoteWorkspaceFolder
) {
await finalizeError(
"devcontainer up output missing required fields",
lastResultLine
);
return;
}
settleSuccess({
containerId: lastResultLine.containerId,
remoteUser: lastResultLine.remoteUser,
remoteWorkspaceFolder: lastResultLine.remoteWorkspaceFolder,
});
return;
}
await finalizeError(
formatDevcontainerUpError(lastResultLine, stderrSummary),
lastResultLine
);
return;
}
if (code !== 0) {
const suffix = stderrSummary.length > 0 ? `: ${stderrSummary}` : "";
settleError(new Error(`devcontainer up exited with code ${String(code)}${suffix}`));
return;
}
const suffix = stderrSummary.length > 0 ? `: ${stderrSummary}` : "";
settleError(new Error(`devcontainer up did not produce result output${suffix}`));
};
void handleClose();
});
});
};
return runUp(baseArgs);
}
export type DevcontainerProbeResult =
| { kind: "found"; containerId: string }
| { kind: "absent" }
| { kind: "error"; message: string };
export type DevcontainerStopResult =
| { kind: "stopped" }
| { kind: "absent" }
| { kind: "error"; message: string };
export async function probeDevcontainerStatuses(
workspacePaths: string[],
timeoutMs = 10_000
): Promise<Record<string, DevcontainerProbeResult>> {
const results: Record<string, DevcontainerProbeResult> = {};
for (const workspacePath of workspacePaths) {
results[workspacePath] = { kind: "absent" };
}
if (workspacePaths.length === 0) {
return results;
}
const requestedPaths = new Set(workspacePaths);
return await new Promise((resolve) => {
const proc = spawn(
"docker",
[
"ps",
"--filter",
"label=devcontainer.local_folder",
"--format",
'{{.ID}}\t{{.Label "devcontainer.local_folder"}}',
],
{
stdio: ["ignore", "pipe", "pipe"],
timeout: timeoutMs,
}
);
let stdout = "";
let stderr = "";
proc.stdout?.on("data", (data: Buffer) => {
stdout += data.toString();
});
proc.stderr?.on("data", (data: Buffer) => {
stderr += data.toString();
});
const resolveAllError = (message: string) => {
for (const workspacePath of workspacePaths) {
results[workspacePath] = { kind: "error", message };
}
resolve(results);
};
proc.on("error", (error) => {
resolveAllError(getErrorMessage(error));
});
proc.on("close", (code, signal) => {
if (code !== 0) {
const stderrMessage = stderr.trim();
const exitMessage = signal
? `docker ps exited with signal ${signal}`
: `docker ps exited with code ${code ?? "null"}`;
resolveAllError(stderrMessage ? `${exitMessage}: ${stderrMessage}` : exitMessage);
return;
}
for (const line of stdout.split("\n")) {
const [containerId, workspacePath] = line.split("\t");
if (!containerId || !workspacePath || !requestedPaths.has(workspacePath)) {
continue;
}
results[workspacePath] = { kind: "found", containerId };
}
resolve(results);
});
});
}
export async function probeDevcontainerStatus(
workspacePath: string,
timeoutMs = 10_000
): Promise<DevcontainerProbeResult> {
const results = await probeDevcontainerStatuses([workspacePath], timeoutMs);
return results[workspacePath] ?? { kind: "absent" };
}
/**
* Get the container name for a devcontainer workspace.
* Returns null if no container exists.
*
* Note: VS Code devcontainer deep links require the container NAME (not ID).
* The devcontainer CLI only returns container ID, so we query Docker directly.
*/
export async function getDevcontainerContainerName(
workspaceFolder: string,
timeoutMs = 10_000
): Promise<string | null> {
// The devcontainer CLI labels containers with the workspace folder path
const labelValue = workspaceFolder;
return new Promise((resolve) => {
const proc = spawn(
"docker",
["ps", "--format", "{{.Names}}", "--filter", `label=devcontainer.local_folder=${labelValue}`],
{
stdio: ["ignore", "pipe", "pipe"],
timeout: timeoutMs,
}
);
let stdout = "";
proc.stdout?.on("data", (data: Buffer) => {
stdout += data.toString();
});
proc.on("error", () => {
resolve(null);
});
proc.on("close", (code) => {
if (code === 0 && stdout.trim()) {
// Return first container name (there should only be one)
resolve(stdout.trim().split("\n")[0]);
} else {
resolve(null);
}
});
});
}
export async function stopDevcontainer(workspacePath: string): Promise<DevcontainerStopResult> {
const labelValue = workspacePath;
return new Promise((resolve) => {
const proc = spawn(
"docker",
["ps", "-q", "--filter", `label=devcontainer.local_folder=${labelValue}`],
{
stdio: ["ignore", "pipe", "pipe"],
timeout: 10_000,
}
);
let stdout = "";
let stderr = "";
proc.stdout?.on("data", (data: Buffer) => {
stdout += data.toString();
});
proc.stderr?.on("data", (data: Buffer) => {
stderr += data.toString();
});
proc.on("error", (error) => {
resolve({
kind: "error",
message: `Docker is not available: ${getErrorMessage(error)}`,
});
});
proc.on("close", (code) => {
if (code !== 0) {
const stderrMessage = stderr.trim();
resolve({
kind: "error",
message: `Failed to query containers: ${stderrMessage || `docker ps exited with code ${code ?? "null"}`}`,
});
return;
}
const containerId = stdout.trim().split("\n")[0];
if (!containerId) {
resolve({ kind: "absent" });
return;
}
const removeProc = spawn("docker", ["rm", "-f", containerId], {
stdio: ["ignore", "pipe", "pipe"],
timeout: DEFAULT_CLEANUP_TIMEOUT_MS,
});
let removeStderr = "";
removeProc.stderr?.on("data", (data: Buffer) => {
removeStderr += data.toString();
});
removeProc.on("error", (error) => {
resolve({
kind: "error",
message: `Docker is not available: ${getErrorMessage(error)}`,
});
});
removeProc.on("close", (removeCode) => {
if (removeCode === 0) {
resolve({ kind: "stopped" });
return;
}
const stderrMessage = removeStderr.trim();
resolve({
kind: "error",
message: `Failed to remove container: ${stderrMessage || `docker rm -f exited with code ${removeCode ?? "null"}`}`,
});
});
});
});
}
/**
* Stop and remove the devcontainer (best-effort cleanup).
* Does not throw on failure - container may not exist.
*
* Note: `devcontainer down` is not yet implemented in the CLI (as of v0.81.1),
* so we use docker commands directly with the container label.
*/
export async function devcontainerDown(
workspaceFolder: string,
_configPath?: string,
_timeoutMs = 60_000
): Promise<void> {
await stopDevcontainer(workspaceFolder);
}