-
-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathdocker-compose-environment.ts
More file actions
236 lines (205 loc) · 8.08 KB
/
docker-compose-environment.ts
File metadata and controls
236 lines (205 loc) · 8.08 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
import { ContainerInfo } from "dockerode";
import { containerLog, log, RandomUuid, Uuid } from "../common";
import { ComposeOptions, 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 autoCleanup = true;
private recreate = true;
private environmentFile = "";
private profiles: string[] = [];
private environment: Environment = {};
private pullPolicy: ImagePullPolicy = PullPolicy.defaultPolicy();
private defaultWaitStrategy: WaitStrategy = Wait.forListeningPorts();
private waitStrategy: { [containerName: string]: WaitStrategy } = {};
private startupTimeoutMs?: number;
private clientOptions: Partial<ComposeOptions> = {};
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 withAutoCleanup(autoCleanup: boolean): this {
this.autoCleanup = autoCleanup;
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 withDefaultWaitStrategy(waitStrategy: WaitStrategy): this {
this.defaultWaitStrategy = waitStrategy;
return this;
}
public withWaitStrategy(containerName: string, waitStrategy: WaitStrategy): this {
this.waitStrategy[containerName] = waitStrategy;
return this;
}
public withStartupTimeout(startupTimeoutMs: number): this {
this.startupTimeoutMs = startupTimeoutMs;
return this;
}
public withProjectName(projectName: string): this {
this.projectName = projectName;
return this;
}
public withClientOptions(
options: Partial<Omit<ComposeOptions, "filePath" | "files" | "projectName" | "environment">>
): this {
this.clientOptions = { ...this.clientOptions, ...options };
return this;
}
public async up(services?: Array<string>): Promise<StartedDockerComposeEnvironment> {
log.info(`Starting DockerCompose environment "${this.projectName}"...`);
const client = await getContainerRuntimeClient();
if (this.autoCleanup) {
const reaper = await getReaper(client);
reaper.addComposeProject(this.projectName);
}
const {
composeOptions: clientComposeOptions = [],
commandOptions: clientCommandOptions = [],
...remainingClientOptions
} = this.clientOptions;
const options = {
...remainingClientOptions,
filePath: this.composeFilePath,
files: this.composeFiles,
projectName: this.projectName,
};
const commandOptions = [...clientCommandOptions];
if (this.build) {
commandOptions.push("--build");
}
if (!this.recreate) {
commandOptions.push("--no-recreate");
}
const composeOptions = [...clientComposeOptions];
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 startedContainerNameSet = new Set(
startedContainers.map((startedContainer) =>
parseComposeContainerName(this.projectName, startedContainer.Names[0])
)
);
this.warnForUnusedWaitStrategies(startedContainerNameSet);
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]
: this.defaultWaitStrategy;
if (this.startupTimeoutMs !== undefined) {
waitStrategy.withStartupTimeout(this.startupTimeoutMs);
}
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,
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,
});
}
private warnForUnusedWaitStrategies(startedContainerNames: Set<string>): void {
const unusedWaitStrategyContainerNames = Object.keys(this.waitStrategy).filter(
(configuredContainerName) => !startedContainerNames.has(configuredContainerName)
);
if (unusedWaitStrategyContainerNames.length > 0) {
log.warn(
`No containers were started for the configured wait strategy names: "${unusedWaitStrategyContainerNames.join('", "')}". Wait strategies are matched against container names (for example "redis-1"), not service names.`
);
}
}
}