-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ResourceReaper.java
422 lines (369 loc) · 16.5 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
package org.testcontainers.utility;
import com.github.dockerjava.api.DockerClient;
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.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Network;
import com.github.dockerjava.api.model.Ports;
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 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.Socket;
import java.net.URLEncoder;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
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;
/**
* 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<>();
private static final RateLimiter RYUK_ACK_RATE_LIMITER = RateLimiterBuilder
.newBuilder()
.withRate(4, TimeUnit.SECONDS)
.withConstantThroughput()
.build();
private static ResourceReaper instance;
private final DockerClient dockerClient;
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);
private ResourceReaper() {
dockerClient = DockerClientFactory.instance().client();
}
@Deprecated
public static String start(String hostIpAddress, DockerClient client, boolean withDummyMount) {
return start(hostIpAddress, client);
}
@SneakyThrows(InterruptedException.class)
public static String start(String hostIpAddress, DockerClient client) {
String ryukImage = TestcontainersConfiguration.getInstance().getRyukImage();
DockerClientFactory.instance().checkAndPullImage(client, ryukImage);
List<Bind> binds = new ArrayList<>();
binds.add(new Bind("//var/run/docker.sock", new Volume("/var/run/docker.sock")));
String ryukContainerId = client.createContainerCmd(ryukImage)
.withHostConfig(new HostConfig().withAutoRemove(true))
.withExposedPorts(new ExposedPort(8080))
.withPublishAllPorts(true)
.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();
InspectContainerResponse inspectedContainer = client.inspectContainerCmd(ryukContainerId).exec();
Integer ryukPort = inspectedContainer.getNetworkSettings().getPorts().getBindings().values().stream()
.flatMap(Stream::of)
.findFirst()
.map(Ports.Binding::getHostPortSpec)
.map(Integer::parseInt)
.get();
CountDownLatch ryukScheduledLatch = new CountDownLatch(1);
synchronized (DEATH_NOTE) {
DEATH_NOTE.add(
DockerClientFactory.DEFAULT_LABELS.entrySet().stream()
.<Map.Entry<String, String>>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue()))
.collect(Collectors.toList())
);
}
Thread kiraThread = new Thread(
DockerClientFactory.TESTCONTAINERS_THREAD_GROUP,
() -> {
while (true) {
RYUK_ACK_RATE_LIMITER.doWhenReady(() -> {
int index = 0;
try(Socket clientSocket = new Socket(hostIpAddress, ryukPort)) {
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 {}:{}", hostIpAddress, ryukPort, e);
}
});
}
},
"testcontainers-ryuk"
);
kiraThread.setDaemon(true);
kiraThread.start();
// 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)) {
throw new IllegalStateException("Can not connect to Ryuk");
}
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::stopContainer);
registeredNetworks.forEach(this::removeNetwork);
registeredImages.forEach(this::removeImage);
}
/**
* Register a filter to be cleaned up.
*
* @param filter the filter
*/
public void registerFilterForCleanup(List<Map.Entry<String, String>> filter) {
synchronized (DEATH_NOTE) {
DEATH_NOTE.add(filter);
DEATH_NOTE.notifyAll();
}
}
/**
* 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) {
stopContainer(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) {
stopContainer(containerId, imageName);
registeredContainers.remove(containerId);
}
private void stopContainer(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 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, this::performCleanup));
}
}
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);
}
}
}