forked from testcontainers/testcontainers-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstarted-generic-container.ts
More file actions
280 lines (233 loc) · 10.8 KB
/
started-generic-container.ts
File metadata and controls
280 lines (233 loc) · 10.8 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
import AsyncLock from "async-lock";
import Dockerode, { ContainerInspectInfo } from "dockerode";
import { Readable } from "stream";
import { buffer } from "stream/consumers";
import { containerLog, log } from "../common";
import { ContainerRuntimeClient, getContainerRuntimeClient } from "../container-runtime";
import { getReaper } from "../reaper/reaper";
import { RestartOptions, StartedTestContainer, StopOptions, StoppedTestContainer } from "../test-container";
import { CommitOptions, ContentToCopy, DirectoryToCopy, ExecOptions, ExecResult, FileToCopy, Labels } from "../types";
import { BoundPorts } from "../utils/bound-ports";
import { LABEL_TESTCONTAINERS_SESSION_ID } from "../utils/labels";
import { mapInspectResult } from "../utils/map-inspect-result";
import { PortWithOptionalBinding } from "../utils/port";
import { waitForContainer } from "../wait-strategies/wait-for-container";
import { WaitStrategy } from "../wait-strategies/wait-strategy";
import { inspectContainerUntilPortsExposed } from "./inspect-container-util-ports-exposed";
import { StoppedGenericContainer } from "./stopped-generic-container";
export class StartedGenericContainer implements StartedTestContainer {
private stoppedContainer?: StoppedTestContainer;
private readonly stopContainerLock = new AsyncLock();
constructor(
private readonly container: Dockerode.Container,
private readonly host: string,
private inspectResult: ContainerInspectInfo,
private boundPorts: BoundPorts,
private readonly name: string,
private readonly waitStrategy: WaitStrategy,
private readonly autoRemove: boolean
) {}
protected containerIsStopping?(): Promise<void>;
public async stop(options: Partial<StopOptions> = {}): Promise<StoppedTestContainer> {
return this.stopContainerLock.acquire("stop", async () => {
if (this.stoppedContainer) {
return this.stoppedContainer;
}
this.stoppedContainer = await this.stopContainer(options);
return this.stoppedContainer;
});
}
/**
* Construct the command(s) to apply changes to the container before committing it to an image.
*/
private async getContainerCommitChangeCommands(options: {
deleteOnExit: boolean;
changes?: string[];
client: ContainerRuntimeClient;
}): Promise<string> {
const { deleteOnExit, client } = options;
const changes = options.changes || [];
if (deleteOnExit) {
let sessionId = this.getLabels()[LABEL_TESTCONTAINERS_SESSION_ID];
if (!sessionId) {
sessionId = await getReaper(client).then((reaper) => reaper.sessionId);
}
changes.push(`LABEL ${LABEL_TESTCONTAINERS_SESSION_ID}=${sessionId}`);
} else if (!deleteOnExit && this.getLabels()[LABEL_TESTCONTAINERS_SESSION_ID]) {
// By default, commit will save the existing labels (including the session ID) to the new image. If
// deleteOnExit is false, we need to remove the session ID label.
changes.push(`LABEL ${LABEL_TESTCONTAINERS_SESSION_ID}=`);
}
return changes.join("\n");
}
public async commit(options: CommitOptions): Promise<string> {
const client = await getContainerRuntimeClient();
const { deleteOnExit = true, changes, ...commitOpts } = options;
const changeCommands = await this.getContainerCommitChangeCommands({ deleteOnExit, changes, client });
const imageId = await client.container.commit(this.container, { ...commitOpts, changes: changeCommands });
return imageId;
}
protected containerIsStopped?(): Promise<void>;
public async restart(options: Partial<RestartOptions> = {}): Promise<void> {
log.info(`Restarting container...`, { containerId: this.container.id });
const client = await getContainerRuntimeClient();
const resolvedOptions: RestartOptions = { timeout: 0, ...options };
await client.container.restart(this.container, resolvedOptions);
this.inspectResult = await inspectContainerUntilPortsExposed(
() => client.container.inspect(this.container),
this.container.id
);
const mappedInspectResult = mapInspectResult(this.inspectResult);
const startTime = new Date(this.inspectResult.State.StartedAt);
if (containerLog.enabled()) {
(await client.container.logs(this.container, { since: startTime.getTime() / 1000 }))
.on("data", (data) => containerLog.trace(data.trim(), { containerId: this.container.id }))
.on("err", (data) => containerLog.error(data.trim(), { containerId: this.container.id }));
}
this.boundPorts = BoundPorts.fromInspectResult(client.info.containerRuntime.hostIps, mappedInspectResult).filter(
Array.from(this.boundPorts.iterator()).map((port) => {
const [portNumber, protocol] = port[0].split("/");
return `${portNumber}/${protocol}` as PortWithOptionalBinding;
})
);
await waitForContainer(client, this.container, this.waitStrategy, this.boundPorts, startTime);
log.info(`Restarted container`, { containerId: this.container.id });
}
private async stopContainer(options: Partial<StopOptions> = {}): Promise<StoppedGenericContainer> {
log.info(`Stopping container...`, { containerId: this.container.id });
const client = await getContainerRuntimeClient();
if (this.containerIsStopping) {
await this.containerIsStopping();
}
const resolvedOptions: StopOptions = { remove: this.autoRemove, timeout: 0, removeVolumes: true, ...options };
await client.container.stop(this.container, { timeout: resolvedOptions.timeout });
if (resolvedOptions.remove) {
await client.container.remove(this.container, { removeVolumes: resolvedOptions.removeVolumes });
}
log.info(`Stopped container`, { containerId: this.container.id });
if (this.containerIsStopped) {
await this.containerIsStopped();
}
return new StoppedGenericContainer(this.container);
}
public getHost(): string {
return this.host;
}
public getHostname(): string {
return this.inspectResult.Config.Hostname;
}
public getFirstMappedPort(): number {
return this.boundPorts.getFirstBinding();
}
public getMappedPort(port: string | number, protocol: string = "tcp"): number {
return this.boundPorts.getBinding(port, protocol);
}
public getId(): string {
return this.container.id;
}
public getName(): string {
return this.name;
}
public getLabels(): Labels {
return this.inspectResult.Config.Labels;
}
public getNetworkNames(): string[] {
return Object.keys(this.getNetworkSettings());
}
public getNetworkId(networkName: string): string {
return this.getNetworkSettings()[networkName].networkId;
}
public getIpAddress(networkName: string): string {
return this.getNetworkSettings()[networkName].ipAddress;
}
private getNetworkSettings() {
return Object.entries(this.inspectResult.NetworkSettings.Networks)
.map(([networkName, network]) => ({
[networkName]: {
networkId: network.NetworkID,
ipAddress: network.IPAddress,
},
}))
.reduce((prev, next) => ({ ...prev, ...next }), {});
}
public async copyFilesToContainer(filesToCopy: FileToCopy[]): Promise<void> {
log.debug(`Copying files to container...`, { containerId: this.container.id });
if (filesToCopy.length === 0) {
return;
}
const client = await getContainerRuntimeClient();
const { packTar } = await import("modern-tar/fs");
const sources = filesToCopy.map((file) => ({
type: "file" as const,
source: file.source,
target: file.target,
mode: file.mode,
}));
const archive = packTar(sources);
await client.container.putArchive(this.container, archive, "/");
log.debug(`Copied files to container`, { containerId: this.container.id });
}
public async copyDirectoriesToContainer(directoriesToCopy: DirectoryToCopy[]): Promise<void> {
log.debug(`Copying directories to container...`, { containerId: this.container.id });
if (directoriesToCopy.length === 0) {
return;
}
const client = await getContainerRuntimeClient();
const { packTar } = await import("modern-tar/fs");
const sources = directoriesToCopy.map((dir) => ({
type: "directory" as const,
source: dir.source,
target: dir.target,
mode: dir.mode,
}));
const archive = packTar(sources);
await client.container.putArchive(this.container, archive, "/");
log.debug(`Copied directories to container`, { containerId: this.container.id });
}
public async copyContentToContainer(contentsToCopy: ContentToCopy[]): Promise<void> {
log.debug(`Copying content to container...`, { containerId: this.container.id });
if (contentsToCopy.length === 0) {
return;
}
const sources = await Promise.all(
contentsToCopy.map(async ({ content, target, mode }) => {
const processedContent = content instanceof Readable ? await buffer(content) : content;
return { type: "content" as const, content: processedContent, target, mode };
})
);
const client = await getContainerRuntimeClient();
const { packTar } = await import("modern-tar/fs");
const archive = packTar(sources);
await client.container.putArchive(this.container, archive, "/");
log.debug(`Copied content to container`, { containerId: this.container.id });
}
public async copyArchiveToContainer(tar: Readable, target = "/"): Promise<void> {
log.debug(`Copying archive to container...`, { containerId: this.container.id });
const client = await getContainerRuntimeClient();
await client.container.putArchive(this.container, tar, target);
log.debug(`Copied archive to container`, { containerId: this.container.id });
}
public async copyArchiveFromContainer(path: string): Promise<NodeJS.ReadableStream> {
log.debug(`Copying archive "${path}" from container...`, { containerId: this.container.id });
const client = await getContainerRuntimeClient();
const stream = await client.container.fetchArchive(this.container, path);
log.debug(`Copied archive "${path}" from container`, { containerId: this.container.id });
return stream;
}
public async exec(command: string | string[], opts?: Partial<ExecOptions>): Promise<ExecResult> {
const commandArr = Array.isArray(command) ? command : command.split(" ");
const commandStr = commandArr.join(" ");
const client = await getContainerRuntimeClient();
log.debug(`Executing command "${commandStr}"...`, { containerId: this.container.id });
const output = await client.container.exec(this.container, commandArr, opts);
log.debug(`Executed command "${commandStr}"...`, { containerId: this.container.id });
return output;
}
public async logs(opts?: { since?: number; tail?: number }): Promise<Readable> {
const client = await getContainerRuntimeClient();
return client.container.logs(this.container, opts);
}
async [Symbol.asyncDispose]() {
await this.stop();
}
}