forked from testcontainers/testcontainers-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker-compose-environment.ts
More file actions
189 lines (164 loc) · 6.46 KB
/
docker-compose-environment.ts
File metadata and controls
189 lines (164 loc) · 6.46 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
import { ContainerInfo } from "dockerode";
import { containerLog, log, RandomUuid, Uuid } from "../common";
import { getContainerRuntimeClient, parseComposeContainerName } from "../container-runtime";
import { StartedGenericContainer } from "../generic-container/started-generic-container";
import { getReaper } from "../reaper/reaper";
import { Environment } from "../types";
import { BoundPorts } from "../utils/bound-ports";
import { mapInspectResult } from "../utils/map-inspect-result";
import { ImagePullPolicy, PullPolicy } from "../utils/pull-policy";
import { Wait } from "../wait-strategies/wait";
import { waitForContainer } from "../wait-strategies/wait-for-container";
import { WaitStrategy } from "../wait-strategies/wait-strategy";
import { StartedDockerComposeEnvironment } from "./started-docker-compose-environment";
export class DockerComposeEnvironment {
private readonly composeFilePath: string;
private readonly composeFiles: string | string[];
private projectName: string;
private build = false;
private recreate = true;
private environmentFile = "";
private profiles: string[] = [];
private environment: Environment = {};
private pullPolicy: ImagePullPolicy = PullPolicy.defaultPolicy();
private waitStrategy: { [containerName: string]: WaitStrategy } = {};
private startupTimeout?: number;
constructor(composeFilePath: string, composeFiles: string | string[], uuid: Uuid = new RandomUuid()) {
this.composeFilePath = composeFilePath;
this.composeFiles = composeFiles;
this.projectName = `testcontainers-${uuid.nextUuid()}`;
}
public withBuild(): this {
this.build = true;
return this;
}
public withEnvironment(environment: Environment): this {
this.environment = { ...this.environment, ...environment };
return this;
}
public withEnvironmentFile(environmentFile: string): this {
this.environmentFile = environmentFile;
return this;
}
public withProfiles(...profiles: string[]): this {
this.profiles = [...this.profiles, ...profiles];
return this;
}
public withNoRecreate(): this {
this.recreate = false;
this.projectName = "testcontainers-node";
return this;
}
public withPullPolicy(pullPolicy: ImagePullPolicy): this {
this.pullPolicy = pullPolicy;
return this;
}
public withWaitStrategy(containerName: string, waitStrategy: WaitStrategy): this {
this.waitStrategy[containerName] = waitStrategy;
return this;
}
public withStartupTimeout(startupTimeout: number): this {
this.startupTimeout = startupTimeout;
return this;
}
public withProjectName(projectName: string): this {
this.projectName = projectName;
return this;
}
public async up(services?: Array<string>): Promise<StartedDockerComposeEnvironment> {
log.info(`Starting DockerCompose environment "${this.projectName}"...`);
const client = await getContainerRuntimeClient();
const reaper = await getReaper(client);
reaper.addComposeProject(this.projectName);
const options = {
filePath: this.composeFilePath,
files: this.composeFiles,
projectName: this.projectName,
};
const commandOptions = [];
if (this.build) {
commandOptions.push("--build");
}
if (!this.recreate) {
commandOptions.push("--no-recreate");
}
const composeOptions: string[] = [];
if (this.environmentFile) {
composeOptions.push("--env-file", this.environmentFile);
}
this.profiles.forEach((profile) => composeOptions.push("--profile", profile));
if (this.pullPolicy.shouldPull()) {
await client.compose.pull(options, services);
}
await client.compose.up(
{
...options,
commandOptions,
composeOptions,
environment: { ...this.environment },
},
services
);
const startedContainers = (await client.container.list()).filter(
(container) => container.Labels["com.docker.compose.project"] === this.projectName
);
const startedContainerNames = startedContainers.reduce(
(containerNames: string[], startedContainer: ContainerInfo) => [
...containerNames,
startedContainer.Names.join(", "),
],
[]
);
log.info(`Started containers "${startedContainerNames.join('", "')}"`);
const startedGenericContainers = (
await Promise.all(
startedContainers.map(async (startedContainer) => {
const container = client.container.getById(startedContainer.Id);
const containerName = parseComposeContainerName(this.projectName, startedContainer.Names[0]);
const inspectResult = await client.container.inspect(container);
const mappedInspectResult = mapInspectResult(inspectResult);
const boundPorts = BoundPorts.fromInspectResult(client.info.containerRuntime.hostIps, mappedInspectResult);
const waitStrategy = this.waitStrategy[containerName]
? this.waitStrategy[containerName]
: Wait.forListeningPorts();
if (this.startupTimeout !== undefined) {
waitStrategy.withStartupTimeout(this.startupTimeout);
}
if (containerLog.enabled()) {
(await client.container.logs(container))
.on("data", (data) => containerLog.trace(`${containerName}: ${data.trim()}`))
.on("err", (data) => containerLog.error(`${containerName}: ${data.trim()}`));
}
try {
await waitForContainer(client, container, waitStrategy, boundPorts);
} catch (err) {
try {
await client.compose.down(options, { removeVolumes: true, timeout: 0 });
} catch {
log.warn(`Failed to stop DockerCompose environment after failed up`);
}
throw err;
}
return new StartedGenericContainer(
container,
client.info.containerRuntime.host,
inspectResult,
boundPorts,
containerName,
waitStrategy
// not sure how to control 'remove' option for the whole compose stack, will use default value here (true)
);
})
)
).reduce((map, startedGenericContainer) => {
const containerName = startedGenericContainer.getName();
return { ...map, [containerName]: startedGenericContainer };
}, {});
log.info(`DockerCompose environment started`);
return new StartedDockerComposeEnvironment(startedGenericContainers, {
...options,
composeOptions,
environment: this.environment,
});
}
}