use of org.testcontainers.containers.output.ToStringConsumer in project testcontainers-java by testcontainers.
the class ExecInContainerPattern method execInContainer.
/**
* Run a command inside a running container, as though using "docker exec".
* <p>
* This functionality is not available on a docker daemon running the older "lxc" execution driver. At
* the time of writing, CircleCI was using this driver.
* @param containerInfo the container info
* @param outputCharset the character set used to interpret the output.
* @param command the parts of the command to run
* @return the result of execution
* @throws IOException if there's an issue communicating with Docker
* @throws InterruptedException if the thread waiting for the response is interrupted
* @throws UnsupportedOperationException if the docker daemon you're connecting to doesn't support "exec".
*/
public Container.ExecResult execInContainer(InspectContainerResponse containerInfo, Charset outputCharset, String... command) throws UnsupportedOperationException, IOException, InterruptedException {
if (!TestEnvironment.dockerExecutionDriverSupportsExec()) {
// at time of writing, this is the expected result in CircleCI.
throw new UnsupportedOperationException("Your docker daemon is running the \"lxc\" driver, which doesn't support \"docker exec\".");
}
if (!isRunning(containerInfo)) {
throw new IllegalStateException("execInContainer can only be used while the Container is running");
}
String containerId = containerInfo.getId();
String containerName = containerInfo.getName();
DockerClient dockerClient = DockerClientFactory.instance().client();
dockerClient.execCreateCmd(containerId).withCmd(command);
log.debug("{}: Running \"exec\" command: {}", containerName, String.join(" ", command));
final ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId).withAttachStdout(true).withAttachStderr(true).withCmd(command).exec();
final ToStringConsumer stdoutConsumer = new ToStringConsumer();
final ToStringConsumer stderrConsumer = new ToStringConsumer();
FrameConsumerResultCallback callback = new FrameConsumerResultCallback();
callback.addConsumer(OutputFrame.OutputType.STDOUT, stdoutConsumer);
callback.addConsumer(OutputFrame.OutputType.STDERR, stderrConsumer);
dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(callback).awaitCompletion();
final Container.ExecResult result = new Container.ExecResult(stdoutConsumer.toString(outputCharset), stderrConsumer.toString(outputCharset));
log.trace("{}: stdout: {}", containerName, result.getStdout());
log.trace("{}: stderr: {}", containerName, result.getStderr());
return result;
}
Aggregations