-
-
Notifications
You must be signed in to change notification settings - Fork 210
/
Copy pathdocker-container-client.ts
293 lines (270 loc) · 10.3 KB
/
docker-container-client.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
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
import Dockerode, {
Container,
ContainerCreateOptions,
ContainerInfo,
ContainerInspectInfo,
ContainerLogsOptions,
ExecCreateOptions,
Network,
} from "dockerode";
import { PassThrough, Readable } from "stream";
import { IncomingMessage } from "http";
import { ExecOptions, ExecResult } from "./types";
import byline from "byline";
import { ContainerClient } from "./container-client";
import { execLog, log, streamToString } from "../../../common";
export class DockerContainerClient implements ContainerClient {
constructor(public readonly dockerode: Dockerode) {}
getById(id: string): Container {
try {
log.debug(`Getting container by ID...`, { containerId: id });
const container = this.dockerode.getContainer(id);
log.debug(`Got container by ID`, { containerId: id });
return container;
} catch (err) {
log.error(`Failed to get container by ID: ${err}`, { containerId: id });
throw err;
}
}
async fetchByLabel(labelName: string, labelValue: string): Promise<Container | undefined> {
try {
log.debug(`Fetching container by label "${labelName}=${labelValue}"...`);
const containers = await this.dockerode.listContainers({
limit: 1,
filters: {
status: ["running"],
label: [`${labelName}=${labelValue}`],
},
});
if (containers.length === 0) {
log.debug(`No container found with label "${labelName}=${labelValue}"`);
return undefined;
} else {
log.debug(`Fetched container by label "${labelName}=${labelValue}"`);
return this.getById(containers[0].Id);
}
} catch (err) {
log.error(`Failed to fetch container by label "${labelName}=${labelValue}": ${err}`);
throw err;
}
}
async fetchArchive(container: Container, path: string): Promise<NodeJS.ReadableStream> {
try {
log.debug(`Fetching archive from container...`, { containerId: container.id });
const archive = await container.getArchive({ path });
log.debug(`Fetched archive from container`, { containerId: container.id });
return archive;
} catch (err) {
log.error(`Failed to fetch archive from container: ${err}`, { containerId: container.id });
throw err;
}
}
async putArchive(container: Dockerode.Container, stream: Readable, path: string): Promise<void> {
try {
log.debug(`Putting archive to container...`, { containerId: container.id });
await streamToString(Readable.from(await container.putArchive(stream, { path })));
log.debug(`Put archive to container`, { containerId: container.id });
} catch (err) {
log.error(`Failed to put archive to container: ${err}`, { containerId: container.id });
throw err;
}
}
async list(): Promise<ContainerInfo[]> {
try {
log.debug(`Listing containers...`);
const containers = await this.dockerode.listContainers();
log.debug(`Listed containers`);
return containers;
} catch (err) {
log.error(`Failed to list containers: ${err}`);
throw err;
}
}
async create(opts: ContainerCreateOptions): Promise<Container> {
try {
log.debug(`Creating container for image "${opts.Image}"...`);
const container = await this.dockerode.createContainer(opts);
log.debug(`Created container for image "${opts.Image}"`, { containerId: container.id });
return container;
} catch (err) {
log.error(`Failed to create container for image "${opts.Image}": ${err}`);
throw err;
}
}
async start(container: Container): Promise<void> {
try {
log.debug(`Starting container...`, { containerId: container.id });
await container.start();
log.debug(`Started container`, { containerId: container.id });
} catch (err) {
log.error(`Failed to start container: ${err}`, { containerId: container.id });
throw err;
}
}
async inspect(container: Dockerode.Container): Promise<ContainerInspectInfo> {
try {
log.debug(`Inspecting container...`, { containerId: container.id });
const inspectInfo = await container.inspect();
log.debug(`Inspected container`, { containerId: container.id });
return inspectInfo;
} catch (err) {
log.error(`Failed to inspect container: ${err}`, { containerId: container.id });
throw err;
}
}
async stop(container: Container, opts?: { timeout: number }): Promise<void> {
try {
log.debug(`Stopping container...`, { containerId: container.id });
await container.stop({ t: opts?.timeout });
log.debug(`Stopped container`, { containerId: container.id });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
if (err.statusCode === 304) {
log.debug(`Container already stopped`, { containerId: container.id });
} else {
log.error(`Failed to stop container: ${err}`, { containerId: container.id });
throw err;
}
}
}
async attach(container: Container): Promise<Readable> {
try {
log.debug(`Attaching to container...`, { containerId: container.id });
const stream = (await container.attach({
stream: true,
stdout: true,
stderr: true,
})) as NodeJS.ReadableStream as Readable;
const demuxedStream = this.demuxStream(container.id, stream);
log.debug(`Attached to container`, { containerId: container.id });
return demuxedStream;
} catch (err) {
log.error(`Failed to attach to container: ${err}`, { containerId: container.id });
throw err;
}
}
async logs(container: Container, opts?: ContainerLogsOptions): Promise<Readable> {
try {
log.debug(`Fetching container logs...`, { containerId: container.id });
const stream = (await container.logs({
follow: true,
stdout: true,
stderr: true,
tail: opts?.tail ?? -1,
since: opts?.since ?? 0,
})) as IncomingMessage;
stream.socket.unref();
const demuxedStream = this.demuxStream(container.id, stream);
log.debug(`Fetched container logs`, { containerId: container.id });
return demuxedStream;
} catch (err) {
log.error(`Failed to fetch container logs: ${err}`, { containerId: container.id });
throw err;
}
}
async exec(container: Container, command: string[], opts?: Partial<ExecOptions>): Promise<ExecResult> {
const execOptions: ExecCreateOptions = {
Cmd: command,
AttachStdout: true,
AttachStderr: true,
};
if (opts?.env !== undefined) {
execOptions.Env = Object.entries(opts.env).map(([key, value]) => `${key}=${value}`);
}
if (opts?.workingDir !== undefined) {
execOptions.WorkingDir = opts.workingDir;
}
if (opts?.user !== undefined) {
execOptions.User = opts.user;
}
const chunks: string[] = [];
try {
if (opts?.log) {
log.debug(`Execing container with command "${command.join(" ")}"...`, { containerId: container.id });
}
const exec = await container.exec(execOptions);
const stream = await exec.start({ stdin: true, Detach: false, Tty: true });
if (opts?.log && execLog.enabled()) {
byline(stream).on("data", (line) => execLog.trace(line, { containerId: container.id }));
}
await new Promise((res, rej) => {
stream.on("data", (chunk) => chunks.push(chunk));
stream.on("end", res);
stream.on("error", rej);
});
stream.destroy();
const inspectResult = await exec.inspect();
const exitCode = inspectResult.ExitCode ?? -1;
const output = chunks.join("");
if (opts?.log) {
log.debug(`Execed container with command "${command.join(" ")}"...`, { containerId: container.id });
}
return { output, exitCode };
} catch (err) {
log.error(`Failed to exec container with command "${command.join(" ")}": ${err}: ${chunks.join("")}`, {
containerId: container.id,
});
throw err;
}
}
async restart(container: Container, opts?: { timeout: number }): Promise<void> {
try {
log.debug(`Restarting container...`, { containerId: container.id });
await container.restart({ t: opts?.timeout });
log.debug(`Restarted container`, { containerId: container.id });
} catch (err) {
log.error(`Failed to restart container: ${err}`, { containerId: container.id });
throw err;
}
}
async remove(container: Container, opts?: { removeVolumes: boolean }): Promise<void> {
try {
log.debug(`Removing container...`, { containerId: container.id });
await container.remove({ v: opts?.removeVolumes });
log.debug(`Removed container`, { containerId: container.id });
} catch (err) {
log.error(`Failed to remove container: ${err}`, { containerId: container.id });
throw err;
}
}
async events(container: Container, eventNames: string[]): Promise<Readable> {
log.debug(`Fetching event stream...`, { containerId: container.id });
const stream = (await this.dockerode.getEvents({
filters: {
type: ["container"],
container: [container.id],
event: eventNames,
},
})) as Readable;
log.debug(`Fetched event stream...`, { containerId: container.id });
return stream;
}
protected async demuxStream(containerId: string, stream: Readable): Promise<Readable> {
try {
log.debug(`Demuxing stream...`, { containerId });
const demuxedStream = new PassThrough({ autoDestroy: true, encoding: "utf-8" });
this.dockerode.modem.demuxStream(stream, demuxedStream, demuxedStream);
stream.on("end", () => demuxedStream.end());
demuxedStream.on("close", () => {
if (!stream.destroyed) {
stream.destroy();
}
});
log.debug(`Demuxed stream`, { containerId });
return demuxedStream;
} catch (err) {
log.error(`Failed to demux stream: ${err}`);
throw err;
}
}
async connectToNetwork(container: Container, network: Network, networkAliases: string[]): Promise<void> {
try {
log.debug(`Connecting to network "${network.id}"...`, { containerId: container.id });
await network.connect({ Container: container.id, EndpointConfig: { Aliases: networkAliases } });
log.debug(`Connected to network "${network.id}"...`, { containerId: container.id });
} catch (err) {
log.error(`Failed to connect to network "${network.id}": ${err}`, { containerId: container.id });
throw err;
}
}
}