-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ResourceReaper.java
559 lines (498 loc) · 21.8 KB
/
ResourceReaper.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
package org.testcontainers.utility;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Network;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.api.model.PruneType;
import com.github.dockerjava.api.model.Volume;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.collect.Sets;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.rnorth.ducttape.ratelimits.RateLimiter;
import org.rnorth.ducttape.ratelimits.RateLimiterBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.ContainerState;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.awaitility.Awaitility.await;
/**
* Component that responsible for container removal and automatic cleanup of dead containers at JVM shutdown.
*/
@Slf4j
public final class ResourceReaper {
private static final Logger LOGGER = LoggerFactory.getLogger(ResourceReaper.class);
private static final List<List<Map.Entry<String, String>>> DEATH_NOTE = new ArrayList<>(
Arrays.asList(
DockerClientFactory.DEFAULT_LABELS.entrySet().stream()
.<Map.Entry<String, String>>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue()))
.collect(Collectors.toList())
)
);
private static final RateLimiter RYUK_ACK_RATE_LIMITER = RateLimiterBuilder
.newBuilder()
.withRate(4, TimeUnit.SECONDS)
.withConstantThroughput()
.build();
private static ResourceReaper instance;
private static AtomicBoolean ryukStarted = new AtomicBoolean(false);
private final DockerClient dockerClient = DockerClientFactory.lazyClient();
private Map<String, String> registeredContainers = new ConcurrentHashMap<>();
private Set<String> registeredNetworks = Sets.newConcurrentHashSet();
private Set<String> registeredImages = Sets.newConcurrentHashSet();
private AtomicBoolean hookIsSet = new AtomicBoolean(false);
/**
*
* @deprecated internal API
*/
@Deprecated
public static String start(String hostIpAddress, DockerClient client) {
return start(client);
}
/**
*
* @deprecated internal API
*/
@Deprecated
@SneakyThrows(InterruptedException.class)
public static String start(DockerClient client) {
String ryukImage = ImageNameSubstitutor.instance()
.apply(DockerImageName.parse("testcontainers/ryuk:0.3.3"))
.asCanonicalNameString();
DockerClientFactory.instance().checkAndPullImage(client, ryukImage);
List<Bind> binds = new ArrayList<>();
binds.add(new Bind(DockerClientFactory.instance().getRemoteDockerUnixSocketPath(), new Volume("/var/run/docker.sock")));
ExposedPort ryukExposedPort = ExposedPort.tcp(8080);
String ryukContainerId = client.createContainerCmd(ryukImage)
.withHostConfig(
new HostConfig()
.withAutoRemove(true)
.withPortBindings(new PortBinding(Ports.Binding.empty(), ryukExposedPort))
)
.withExposedPorts(ryukExposedPort)
.withName("testcontainers-ryuk-" + DockerClientFactory.SESSION_ID)
.withLabels(Collections.singletonMap(DockerClientFactory.TESTCONTAINERS_LABEL, "true"))
.withBinds(binds)
.withPrivileged(TestcontainersConfiguration.getInstance().isRyukPrivileged())
.exec()
.getId();
client.startContainerCmd(ryukContainerId).exec();
StringBuilder ryukLog = new StringBuilder();
ResultCallback.Adapter<Frame> logCallback = client.logContainerCmd(ryukContainerId)
.withSince(0)
.withFollowStream(true)
.withStdOut(true)
.withStdErr(true)
.exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
ryukLog.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
}
});
InspectContainerResponse inspectedContainer;
try {
// inspect container response might initially not contain the mapped port
inspectedContainer = await()
.atMost(5, TimeUnit.SECONDS)
.pollInterval(DynamicPollInterval.ofMillis(50))
.pollInSameThread()
.until(
() -> client.inspectContainerCmd(ryukContainerId).exec(),
inspectContainerResponse -> {
return inspectContainerResponse
.getNetworkSettings()
.getPorts()
.getBindings()
.values()
.stream()
.anyMatch(Objects::nonNull);
}
);
} catch (Exception e) {
log.warn("Ryuk container cannot be inspected and probably had a problem starting. Ryuk's logs:\n{}", ryukLog);
throw new IllegalStateException("Ryuk failed to start", e);
}
ContainerState containerState = new ContainerState() {
@Override
public List<Integer> getExposedPorts() {
return Stream.of(getContainerInfo().getConfig().getExposedPorts())
.map(ExposedPort::getPort)
.collect(Collectors.toList());
}
@Override
public InspectContainerResponse getContainerInfo() {
return inspectedContainer;
}
};
CountDownLatch ryukScheduledLatch = new CountDownLatch(1);
String host = containerState.getHost();
Integer ryukPort = containerState.getFirstMappedPort();
Thread kiraThread = new Thread(
DockerClientFactory.TESTCONTAINERS_THREAD_GROUP,
() -> {
while (true) {
RYUK_ACK_RATE_LIMITER.doWhenReady(() -> {
int index = 0;
// not set the read timeout, as Ryuk would not send anything unless a new filter is submitted, meaning that we would get a timeout exception pretty quick
try (Socket clientSocket = new Socket()) {
clientSocket.connect(new InetSocketAddress(host, ryukPort), 5 * 1000);
FilterRegistry registry = new FilterRegistry(clientSocket.getInputStream(), clientSocket.getOutputStream());
synchronized (DEATH_NOTE) {
while (true) {
if (DEATH_NOTE.size() <= index) {
try {
DEATH_NOTE.wait(1_000);
continue;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
List<Map.Entry<String, String>> filters = DEATH_NOTE.get(index);
boolean isAcknowledged = registry.register(filters);
if (isAcknowledged) {
log.debug("Received 'ACK' from Ryuk");
ryukScheduledLatch.countDown();
index++;
} else {
log.debug("Didn't receive 'ACK' from Ryuk. Will retry to send filters.");
}
}
}
} catch (IOException e) {
log.warn("Can not connect to Ryuk at {}:{}", host, ryukPort, e);
}
});
}
},
"testcontainers-ryuk"
);
kiraThread.setDaemon(true);
kiraThread.start();
try {
// We need to wait before we can start any containers to make sure that we delete them
if (!ryukScheduledLatch.await(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS)) {
log.error("Timed out waiting for Ryuk container to start. Ryuk's logs:\n{}", ryukLog);
throw new IllegalStateException(String.format("Could not connect to Ryuk at %s:%s", host, ryukPort));
}
} finally {
try {
logCallback.close();
} catch (IOException ignored) {
}
}
ryukStarted.set(true);
return ryukContainerId;
}
public synchronized static ResourceReaper instance() {
if (instance == null) {
instance = new ResourceReaper();
}
return instance;
}
/**
* Perform a cleanup.
*/
public synchronized void performCleanup() {
registeredContainers.forEach(this::removeContainer);
registeredNetworks.forEach(this::removeNetwork);
registeredImages.forEach(this::removeImage);
}
/**
* Register a filter to be cleaned up.
*
* @param filter the filter
* @deprecated only label filter is supported by the prune API, use {@link #registerLabelsFilterForCleanup(Map)}
*/
@Deprecated
public void registerFilterForCleanup(List<Map.Entry<String, String>> filter) {
synchronized (DEATH_NOTE) {
DEATH_NOTE.add(filter);
DEATH_NOTE.notifyAll();
}
}
/**
* Register a label to be cleaned up.
*
* @param labels the filter
*/
public void registerLabelsFilterForCleanup(Map<String, String> labels) {
registerFilterForCleanup(
labels.entrySet().stream()
.map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue()))
.collect(Collectors.toList())
);
}
/**
* Register a container to be cleaned up, either on explicit call to stopAndRemoveContainer, or at JVM shutdown.
*
* @param containerId the ID of the container
* @param imageName the image name of the container (used for logging)
*/
public void registerContainerForCleanup(String containerId, String imageName) {
setHook();
registeredContainers.put(containerId, imageName);
}
/**
* Stop a potentially running container and remove it, including associated volumes.
*
* @param containerId the ID of the container
*/
public void stopAndRemoveContainer(String containerId) {
removeContainer(containerId, registeredContainers.get(containerId));
registeredContainers.remove(containerId);
}
/**
* Stop a potentially running container and remove it, including associated volumes.
*
* @param containerId the ID of the container
* @param imageName the image name of the container (used for logging)
*/
public void stopAndRemoveContainer(String containerId, String imageName) {
removeContainer(containerId, imageName);
registeredContainers.remove(containerId);
}
private void removeContainer(String containerId, String imageName) {
boolean running;
try {
InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(containerId).exec();
running = containerInfo.getState() != null && Boolean.TRUE.equals(containerInfo.getState().getRunning());
} catch (NotFoundException e) {
LOGGER.trace("Was going to stop container but it apparently no longer exists: {}", containerId);
return;
} catch (Exception e) {
LOGGER.trace("Error encountered when checking container for shutdown (ID: {}) - it may not have been stopped, or may already be stopped. Root cause: {}",
containerId,
Throwables.getRootCause(e).getMessage());
return;
}
if (running) {
try {
LOGGER.trace("Stopping container: {}", containerId);
dockerClient.killContainerCmd(containerId).exec();
LOGGER.trace("Stopped container: {}", imageName);
} catch (Exception e) {
LOGGER.trace("Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped. Root cause: {}",
containerId,
Throwables.getRootCause(e).getMessage());
}
}
try {
dockerClient.inspectContainerCmd(containerId).exec();
} catch (Exception e) {
LOGGER.trace("Was going to remove container but it apparently no longer exists: {}", containerId);
return;
}
try {
LOGGER.trace("Removing container: {}", containerId);
dockerClient.removeContainerCmd(containerId).withRemoveVolumes(true).withForce(true).exec();
LOGGER.debug("Removed container and associated volume(s): {}", imageName);
} catch (Exception e) {
LOGGER.trace("Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped. Root cause: {}",
containerId,
Throwables.getRootCause(e).getMessage());
}
}
/**
* Register a network to be cleaned up at JVM shutdown.
*
* @param id the ID of the network
*/
public void registerNetworkIdForCleanup(String id) {
setHook();
registeredNetworks.add(id);
}
/**
* @param networkName the name of the network
* @deprecated see {@link ResourceReaper#registerNetworkIdForCleanup(String)}
*/
@Deprecated
public void registerNetworkForCleanup(String networkName) {
try {
// Try to find the network by name, so that we can register its ID for later deletion
dockerClient.listNetworksCmd()
.withNameFilter(networkName)
.exec()
.forEach(network -> registerNetworkIdForCleanup(network.getId()));
} catch (Exception e) {
LOGGER.trace("Error encountered when looking up network (name: {})", networkName);
}
}
/**
* Removes a network by ID.
* @param id
*/
public void removeNetworkById(String id) {
removeNetwork(id);
}
/**
* Removes a network by ID.
* @param identifier
* @deprecated see {@link ResourceReaper#removeNetworkById(String)}
*/
@Deprecated
public void removeNetworks(String identifier) {
removeNetworkById(identifier);
}
private void removeNetwork(String id) {
try {
List<Network> networks;
try {
// Try to find the network if it still exists
// Listing by ID first prevents docker-java logging an error if we just go blindly into removeNetworkCmd
networks = dockerClient.listNetworksCmd().withIdFilter(id).exec();
} catch (Exception e) {
LOGGER.trace("Error encountered when looking up network for removal (name: {}) - it may not have been removed", id);
return;
}
// at this point networks should contain either 0 or 1 entries, depending on whether the network exists
// using a for loop we essentially treat the network like an optional, only applying the removal if it exists
for (Network network : networks) {
try {
dockerClient.removeNetworkCmd(network.getId()).exec();
registeredNetworks.remove(network.getId());
LOGGER.debug("Removed network: {}", id);
} catch (Exception e) {
LOGGER.trace("Error encountered removing network (name: {}) - it may not have been removed", network.getName());
}
}
} finally {
registeredNetworks.remove(id);
}
}
public void unregisterNetwork(String identifier) {
registeredNetworks.remove(identifier);
}
public void unregisterContainer(String identifier) {
registeredContainers.remove(identifier);
}
public void registerImageForCleanup(String dockerImageName) {
setHook();
registeredImages.add(dockerImageName);
}
private void removeImage(String dockerImageName) {
LOGGER.trace("Removing image tagged {}", dockerImageName);
try {
dockerClient.removeImageCmd(dockerImageName).withForce(true).exec();
} catch (Throwable e) {
LOGGER.warn("Unable to delete image " + dockerImageName, e);
}
}
private void prune(PruneType pruneType, List<Map.Entry<String, String>> filters) {
String[] labels = filters.stream()
.filter(it -> "label".equals(it.getKey()))
.map(Map.Entry::getValue)
.toArray(String[]::new);
switch (pruneType) {
// Docker only prunes stopped containers, so we have to do it manually
case CONTAINERS:
List<Container> containers = dockerClient.listContainersCmd()
.withFilter("label", Arrays.asList(labels))
.withShowAll(true)
.exec();
containers.parallelStream().forEach(container -> {
removeContainer(container.getId(), container.getImage());
});
break;
default:
dockerClient.pruneCmd(pruneType).withLabelFilter(labels).exec();
break;
}
}
/**
* @deprecated internal API, not intended for public usage
*/
@Deprecated
public void setHook() {
if (hookIsSet.compareAndSet(false, true)) {
// If the JVM stops without containers being stopped, try and stop the container.
Runtime.getRuntime().addShutdownHook(
new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP,
() -> {
performCleanup();
if (!ryukStarted.get()) {
synchronized (DEATH_NOTE) {
DEATH_NOTE.forEach(filters -> prune(PruneType.CONTAINERS, filters));
DEATH_NOTE.forEach(filters -> prune(PruneType.NETWORKS, filters));
DEATH_NOTE.forEach(filters -> prune(PruneType.VOLUMES, filters));
DEATH_NOTE.forEach(filters -> prune(PruneType.IMAGES, filters));
}
}
}
)
);
}
}
static class FilterRegistry {
@VisibleForTesting
static final String ACKNOWLEDGMENT = "ACK";
private final BufferedReader in;
private final OutputStream out;
FilterRegistry(InputStream ryukInputStream, OutputStream ryukOutputStream) {
this.in = new BufferedReader(new InputStreamReader(ryukInputStream));
this.out = ryukOutputStream;
}
/**
* Registers the given filters with Ryuk
*
* @param filters the filter to register
* @return true if the filters have been registered successfuly, false otherwise
* @throws IOException if communication with Ryuk fails
*/
protected boolean register(List<Map.Entry<String, String>> filters) throws IOException {
String query = filters.stream()
.map(it -> {
try {
return URLEncoder.encode(it.getKey(), "UTF-8") + "=" + URLEncoder.encode(it.getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.joining("&"));
log.debug("Sending '{}' to Ryuk", query);
out.write(query.getBytes());
out.write('\n');
out.flush();
return waitForAcknowledgment(in);
}
private static boolean waitForAcknowledgment(BufferedReader in) throws IOException {
String line = in.readLine();
while (line != null && !ACKNOWLEDGMENT.equalsIgnoreCase(line)) {
line = in.readLine();
}
return ACKNOWLEDGMENT.equalsIgnoreCase(line);
}
}
}