forked from testcontainers/testcontainers-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InternalCommandPortListeningCheck.java
49 lines (41 loc) · 1.72 KB
/
InternalCommandPortListeningCheck.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
package org.testcontainers.containers.wait.internal;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.testcontainers.containers.Container.ExecResult;
import org.testcontainers.containers.ExecInContainerPattern;
import org.testcontainers.containers.wait.strategy.WaitStrategyTarget;
import java.time.Duration;
import java.time.Instant;
import java.util.Set;
import static java.lang.String.format;
/**
* Mechanism for testing that a socket is listening when run from the container being checked.
*/
@RequiredArgsConstructor
@Slf4j
public class InternalCommandPortListeningCheck implements java.util.concurrent.Callable<Boolean> {
private final WaitStrategyTarget waitStrategyTarget;
private final Set<Integer> internalPorts;
@Override
public Boolean call() {
String command = "true";
for (int internalPort : internalPorts) {
command += " && ";
command += " (";
command += format("cat /proc/net/tcp* | awk '{print $2}' | grep -i :%x", internalPort);
command += " || ";
command += format("nc -vz -w 1 localhost %d", internalPort);
command += " || ";
command += format("/bin/bash -c '</dev/tcp/localhost/%d'", internalPort);
command += ")";
}
Instant before = Instant.now();
try {
ExecResult result = ExecInContainerPattern.execInContainer(waitStrategyTarget.getContainerInfo(), "/bin/sh", "-c", command);
log.trace("Check for {} took {}", internalPorts, Duration.between(before, Instant.now()));
return result.getExitCode() == 0;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}