-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
run-in-container.ts
57 lines (49 loc) · 1.89 KB
/
run-in-container.ts
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
import { log } from "../../logger";
import { DockerImageName } from "../../docker-image-name";
import { Command } from "../types";
import { pullImage } from "./image/pull-image";
import { startContainer } from "./container/start-container";
import { attachContainer } from "./container/attach-container";
import { inspectContainer } from "./container/inspect-container";
import Dockerode from "dockerode";
export const runInContainer = async (
dockerode: Dockerode,
image: string,
command: Command[]
): Promise<string | undefined> => {
try {
const imageName = DockerImageName.fromString(image);
await pullImage(dockerode, { imageName, force: false });
log.debug(`Creating container: ${image} with command: ${command.join(" ")}`);
const container = await dockerode.createContainer({ Image: image, Cmd: command, HostConfig: { AutoRemove: true } });
log.debug(`Attaching to container: ${container.id}`);
const stream = await attachContainer(dockerode, container);
const promise = new Promise<string>((resolve) => {
const interval = setInterval(async () => {
const inspect = await inspectContainer(container);
if (inspect.state.status === "exited") {
clearInterval(interval);
stream.destroy();
}
}, 100);
const chunks: string[] = [];
stream.on("data", (chunk) => chunks.push(chunk));
stream.on("end", () => {
clearInterval(interval);
resolve(chunks.join("").trim());
});
});
log.debug(`Starting container: ${container.id}`);
await startContainer(container);
log.debug(`Waiting for container output: ${container.id}`);
const output = await promise;
if (output.length === 0) {
return undefined;
} else {
return output;
}
} catch (err) {
log.error(`Failed to run command in container: "${command.join(" ")}", error: "${err}"`);
return undefined;
}
};