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
193 lines (159 loc) · 7.64 KB
/
started-generic-container.ts
File metadata and controls
193 lines (159 loc) · 7.64 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
import { RestartOptions, StartedTestContainer, StopOptions, StoppedTestContainer } from "../test-container";
import Dockerode, { ContainerInspectInfo } from "dockerode";
import { ContentToCopy, DirectoryToCopy, ExecOptions, ExecResult, FileToCopy, Labels } from "../types";
import { Readable } from "stream";
import { StoppedGenericContainer } from "./stopped-generic-container";
import { WaitStrategy } from "../wait-strategies/wait-strategy";
import AsyncLock from "async-lock";
import archiver from "archiver";
import { waitForContainer } from "../wait-strategies/wait-for-container";
import { BoundPorts } from "../utils/bound-ports";
import { containerLog, log } from "../common";
import { getContainerRuntimeClient } from "../container-runtime";
import { mapInspectResult } from "../utils/map-inspect-result";
export class StartedGenericContainer implements StartedTestContainer {
private stoppedContainer?: StoppedTestContainer;
private 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
) {}
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;
});
}
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 client.container.inspect(this.container);
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) => port[0])
);
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: true, 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: number): number {
return this.boundPorts.getBinding(port);
}
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 });
const client = await getContainerRuntimeClient();
const tar = archiver("tar");
filesToCopy.forEach(({ source, target }) => tar.file(source, { name: target }));
tar.finalize();
await client.container.putArchive(this.container, tar, "/");
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 });
const client = await getContainerRuntimeClient();
const tar = archiver("tar");
directoriesToCopy.forEach(({ source, target }) => tar.directory(source, target));
tar.finalize();
await client.container.putArchive(this.container, tar, "/");
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 });
const client = await getContainerRuntimeClient();
const tar = archiver("tar");
contentsToCopy.forEach(({ content, target, mode }) => tar.append(content, { name: target, mode: mode }));
tar.finalize();
await client.container.putArchive(this.container, tar, "/");
log.debug(`Copied content 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);
}
}