-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathDockerHelper.java
333 lines (295 loc) · 12.5 KB
/
DockerHelper.java
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.kernel;
import com.palantir.docker.compose.configuration.DockerComposeFiles;
import com.palantir.docker.compose.configuration.ProjectName;
import com.palantir.docker.compose.connection.Cluster;
import com.palantir.docker.compose.connection.Container;
import com.palantir.docker.compose.connection.ContainerCache;
import com.palantir.docker.compose.connection.DockerMachine;
import com.palantir.docker.compose.connection.ImmutableCluster;
import com.palantir.docker.compose.execution.DefaultDockerCompose;
import com.palantir.docker.compose.execution.Docker;
import com.palantir.docker.compose.execution.DockerCompose;
import com.palantir.docker.compose.execution.DockerComposeExecutable;
import com.palantir.docker.compose.execution.DockerExecutable;
import com.palantir.docker.compose.execution.RetryingDockerCompose;
import sirius.kernel.commons.Explain;
import sirius.kernel.commons.Strings;
import sirius.kernel.commons.Tuple;
import sirius.kernel.commons.Wait;
import sirius.kernel.di.Initializable;
import sirius.kernel.di.std.ConfigValue;
import sirius.kernel.di.std.Register;
import sirius.kernel.health.Exceptions;
import sirius.kernel.health.Log;
import sirius.kernel.settings.PortMapper;
import java.io.File;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Initializes <b>Docker Composer</b> if requested by the framework.
* <p>
* This basically uses <tt>docker.file</tt> from the system config to determine which
* composer file to use and start / stops docker for each test run or staging environment.
* <p>
* Also it provides a {@link PortMapper} to map the desired production ports to the
* ones provided by the docker containers.
*/
@Register
public class DockerHelper extends PortMapper implements Initializable, Killable {
private static final int MAX_WAIT_SECONDS = 10;
@ConfigValue("docker.project")
private String project;
@ConfigValue("docker.hostIp")
private String hostIp;
@ConfigValue("docker.hostPort")
private String hostPort;
@SuppressWarnings("FieldMayBeFinal")
@Explain("This is only the default, the field is filled with a config later")
@ConfigValue("docker.file")
private List<String> dockerfiles = Collections.emptyList();
@ConfigValue("docker.retryAttempts")
private int retryAttempts;
@ConfigValue("docker.pull")
private boolean pull;
@ConfigValue("docker.keepRunning")
private boolean keepRunning;
private static final Log LOG = Log.get("docker");
private DockerCompose dockerCompose;
private Cluster cluster;
private DockerMachine machine;
private DockerExecutable executable;
@Override
public int getPriority() {
return 10;
}
@Override
protected Tuple<String, Integer> map(String service, String host, int port) {
if (dockerCompose == null) {
return Tuple.create(host, port);
}
return Tuple.create(machine.getIp(), containers().container(service).port(port).getExternalPort());
}
private DockerMachine machine() {
if (machine == null) {
if (Strings.isEmpty(hostIp)) {
machine = DockerMachine.localMachine().build();
} else {
LOG.INFO("Using hostIp: %s", hostIp);
String dockerHost = Strings.apply("tcp://%s:%s", hostIp, hostPort);
machine = DockerMachine.remoteMachine().withEnvironment(System.getenv()).host(dockerHost).build();
}
}
return machine;
}
private DockerExecutable dockerExecutable() {
if (executable == null) {
executable = DockerExecutable.builder().dockerConfiguration(this.machine()).build();
}
return executable;
}
private Cluster containers() {
if (cluster == null) {
cluster = ImmutableCluster.builder()
.ip(this.machine().getIp())
.containerCache(new ContainerCache(this.docker(), this.dockerCompose))
.build();
}
return cluster;
}
private Docker docker() {
return new Docker(this.dockerExecutable());
}
private DockerComposeExecutable dockerComposeExecutable() {
return DockerComposeExecutable.builder()
.dockerComposeFiles(getDockerComposeFiles())
.dockerConfiguration(this.machine())
.projectName(projectName())
.build();
}
private ProjectName projectName() {
return Strings.isFilled(project) && !Sirius.isStartedAsTest() ?
ProjectName.fromString(project) :
ProjectName.random();
}
@Override
public void initialize() throws Exception {
if (!dockerfiles.isEmpty()) {
LOG.INFO("Starting docker compose using: %s", dockerfiles);
this.dockerCompose = new RetryingDockerCompose(retryAttempts,
new DefaultDockerCompose(dockerComposeExecutable(),
machine()));
if (pull) {
try {
LOG.INFO("Executing docker-compose pull...");
dockerCompose.pull();
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
LOG.WARN("docker-compose pull failed: %s (%s)",
exception.getMessage(),
exception.getClass().getName());
} catch (Exception exception) {
LOG.WARN("docker-compose pull failed: %s (%s)",
exception.getMessage(),
exception.getClass().getName());
}
}
try {
LOG.INFO("Executing docker-compose up...");
dockerCompose.up();
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
LOG.WARN("docker-compose up failed: %s (%s)", exception.getMessage(), exception.getClass().getName());
} catch (Exception exception) {
LOG.WARN("docker-compose up failed: %s (%s)", exception.getMessage(), exception.getClass().getName());
}
awaitClusterHealth();
PortMapper.setMapper(this);
} else {
LOG.INFO("No docker file is present - skipping....");
}
}
private DockerComposeFiles getDockerComposeFiles() {
final String[] dockerfilesArray = dockerfiles.stream()
.map(this::resolveDockerComposeFile)
.filter(Objects::nonNull)
.toArray(i -> new String[i]);
return DockerComposeFiles.from(dockerfilesArray);
}
private String resolveDockerComposeFile(String dockerfile) {
if (Strings.isEmpty(dockerfile)) {
return null;
}
if (new File(dockerfile).exists()) {
return dockerfile;
}
return Optional.of(dockerfile)
.map(file -> file.startsWith("/") ? file : "/" + file)
.map(file -> getClass().getResource(file))
.map(resource -> {
try {
return resource.toURI();
} catch (URISyntaxException exception) {
throw Exceptions.handle(exception);
}
})
.map(File::new)
.filter(File::exists)
.map(File::getAbsolutePath)
.orElse(null);
}
private void awaitClusterHealth() {
try {
containers().allContainers().forEach(this::awaitContainerStart);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
LOG.SEVERE(exception);
} catch (Exception exception) {
LOG.SEVERE(exception);
}
}
private void awaitContainerStart(Container container) {
LOG.INFO("Waiting for '%s' to become ready...", container.getContainerName());
try {
int retries = MAX_WAIT_SECONDS;
while (container.areAllPortsOpen().failed()) {
Wait.seconds(1);
if (retries-- <= 0) {
LOG.WARN("Failed to start '%s' - Ports: %s",
container.getContainerName(),
container.ports().stream().map(Object::toString).collect(Collectors.joining(", ")));
return;
}
}
LOG.INFO("Container '%s' is ONLINE - Ports: %s",
container.getContainerName(),
container.ports().stream().map(Object::toString).collect(Collectors.joining(", ")));
} catch (Exception exception) {
LOG.SEVERE(exception);
}
}
@Override
public void awaitTermination() {
if (dockerfiles.isEmpty()) {
return;
}
if (keepRunning) {
return;
}
if (Sirius.isStartedAsTest()) {
kill();
down();
rm();
} else {
try {
LOG.INFO("Executing docker-compose stop...");
containers().allContainers().forEach(this::stop);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
LOG.WARN("docker-compose stop failed: %s (%s)", exception.getMessage(), exception.getClass().getName());
} catch (Exception exception) {
LOG.WARN("docker-compose stop failed: %s (%s)", exception.getMessage(), exception.getClass().getName());
}
}
}
private void stop(Container container) {
try {
LOG.INFO("Executing docker-compose stop for '%s'...", container.getContainerName());
dockerCompose.stop(container);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
LOG.WARN("docker-compose stop for '%s' failed: %s (%s)",
container.getContainerName(),
exception.getMessage(),
exception.getClass().getName());
} catch (Exception exception) {
LOG.WARN("docker-compose stop for '%s' failed: %s (%s)",
container.getContainerName(),
exception.getMessage(),
exception.getClass().getName());
}
}
private void rm() {
try {
LOG.INFO("Executing docker-compose rm...");
dockerCompose.rm();
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
LOG.WARN("docker-compose rm failed: %s (%s)", exception.getMessage(), exception.getClass().getName());
} catch (Exception exception) {
LOG.WARN("docker-compose rm failed: %s (%s)", exception.getMessage(), exception.getClass().getName());
}
}
private void down() {
try {
LOG.INFO("Executing docker-compose down...");
dockerCompose.down();
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
LOG.WARN("docker-compose down failed: %s (%s)", exception.getMessage(), exception.getClass().getName());
} catch (Exception exception) {
LOG.WARN("docker-compose down failed: %s (%s)", exception.getMessage(), exception.getClass().getName());
}
}
private void kill() {
try {
LOG.INFO("Executing docker-compose kill...");
dockerCompose.kill();
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
LOG.WARN("docker-compose kill failed: %s (%s)", exception.getMessage(), exception.getClass().getName());
} catch (Exception exception) {
LOG.WARN("docker-compose kill failed: %s (%s)", exception.getMessage(), exception.getClass().getName());
}
}
}