-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
DockerClientConfigUtils.java
67 lines (61 loc) · 2.37 KB
/
DockerClientConfigUtils.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
package org.testcontainers.dockerclient;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.testcontainers.DockerClientFactory;
import java.io.File;
import java.net.URI;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@Slf4j
public class DockerClientConfigUtils {
// See https://github.com/docker/docker/blob/a9fa38b1edf30b23cae3eade0be48b3d4b1de14b/daemon/initlayer/setup_unix.go#L25
public static final boolean IN_A_CONTAINER = new File("/.dockerenv").exists();
@Getter(lazy = true)
private static final Optional<String> defaultGateway = Optional
.ofNullable(
DockerClientFactory
.instance()
.runInsideDocker(
cmd -> cmd.withCmd("sh", "-c", "ip route|awk '/default/ { print $3 }'"),
(client, id) -> {
try {
LogToStringContainerCallback loggingCallback = new LogToStringContainerCallback();
client
.logContainerCmd(id)
.withStdOut(true)
.withFollowStream(true)
.exec(loggingCallback)
.awaitStarted();
loggingCallback.awaitCompletion(3, TimeUnit.SECONDS);
return loggingCallback.toString();
} catch (Exception e) {
log.warn("Can't parse the default gateway IP", e);
return null;
}
}
)
)
.map(StringUtils::trimToEmpty)
.filter(StringUtils::isNotBlank);
/**
* @deprecated use {@link DockerClientProviderStrategy#getDockerHostIpAddress()}
*/
@Deprecated
public static String getDockerHostIpAddress(URI dockerHost) {
switch (dockerHost.getScheme()) {
case "http":
case "https":
case "tcp":
return dockerHost.getHost();
case "unix":
case "npipe":
if (IN_A_CONTAINER) {
return getDefaultGateway().orElse("localhost");
}
return "localhost";
default:
return null;
}
}
}