use of com.github.dockerjava.api.command.ExecCreateCmdResponse in project elastest-torm by elastest.
the class DockerService method execCommand.
public String execCommand(String containerName, boolean awaitCompletion, String... command) throws IOException, InterruptedException {
assert (command.length > 0);
String output = null;
String commandStr = Arrays.toString(command);
log.trace("Executing command {} in container {} (await completion {})", commandStr, containerName, awaitCompletion);
if (existsContainer(containerName)) {
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerName).withCmd(command).withTty(true).withAttachStdin(true).withAttachStdout(true).withAttachStderr(true).exec();
log.trace("Command executed. Exec id: {}", exec.getId());
OutputStream outputStream = new ByteArrayOutputStream();
try (ExecStartResultCallback startResultCallback = dockerClient.execStartCmd(exec.getId()).withDetach(false).withTty(true).exec(new ExecStartResultCallback(outputStream, outputStream))) {
if (awaitCompletion) {
startResultCallback.awaitCompletion();
}
output = outputStream.toString();
} finally {
log.trace("Callback terminated. Result: {}", output);
}
}
return output;
}
use of com.github.dockerjava.api.command.ExecCreateCmdResponse in project vespa by vespa-engine.
the class DockerImpl method executeInContainerAsUser.
/**
* Execute command in container as user, "user" can be "username", "username:group", "uid" or "uid:gid"
*/
private ProcessResult executeInContainerAsUser(ContainerName containerName, String user, Optional<Long> timeoutSeconds, String... command) {
try {
final ExecCreateCmdResponse response = dockerClient.execCreateCmd(containerName.asString()).withCmd(command).withAttachStdout(true).withAttachStderr(true).withUser(user).exec();
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errors = new ByteArrayOutputStream();
ExecStartCmd execStartCmd = dockerClient.execStartCmd(response.getId());
ExecStartResultCallback callback = execStartCmd.exec(new ExecStartResultCallback(output, errors));
if (timeoutSeconds.isPresent()) {
if (!callback.awaitCompletion(timeoutSeconds.get(), TimeUnit.SECONDS)) {
throw new DockerExecTimeoutException(String.format("Command '%s' did not finish within %s seconds.", command[0], timeoutSeconds));
}
} else {
// Wait for completion no timeout
callback.awaitCompletion();
}
final InspectExecResponse state = dockerClient.inspectExecCmd(execStartCmd.getExecId()).exec();
assert !state.isRunning();
Integer exitCode = state.getExitCode();
assert exitCode != null;
return new ProcessResult(exitCode, new String(output.toByteArray()), new String(errors.toByteArray()));
} catch (RuntimeException | InterruptedException e) {
numberOfDockerDaemonFails.add();
throw new DockerException("Container '" + containerName.asString() + "' failed to execute " + Arrays.toString(command), e);
}
}
use of com.github.dockerjava.api.command.ExecCreateCmdResponse 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;
}
use of com.github.dockerjava.api.command.ExecCreateCmdResponse in project vespa by vespa-engine.
the class DockerImplTest method testExecuteCompletes.
@Test
public void testExecuteCompletes() throws Exception {
final String containerId = "container-id";
final String[] command = new String[] { "/bin/ls", "-l" };
final String execId = "exec-id";
final int exitCode = 3;
final DockerClient dockerClient = mock(DockerClient.class);
final ExecCreateCmdResponse response = mock(ExecCreateCmdResponse.class);
when(response.getId()).thenReturn(execId);
final ExecCreateCmd execCreateCmd = mock(ExecCreateCmd.class);
when(dockerClient.execCreateCmd(any(String.class))).thenReturn(execCreateCmd);
when(execCreateCmd.withCmd(Matchers.<String>anyVararg())).thenReturn(execCreateCmd);
when(execCreateCmd.withAttachStdout(any(Boolean.class))).thenReturn(execCreateCmd);
when(execCreateCmd.withAttachStderr(any(Boolean.class))).thenReturn(execCreateCmd);
when(execCreateCmd.withUser(any(String.class))).thenReturn(execCreateCmd);
when(execCreateCmd.exec()).thenReturn(response);
final ExecStartCmd execStartCmd = mock(ExecStartCmd.class);
when(dockerClient.execStartCmd(any(String.class))).thenReturn(execStartCmd);
when(execStartCmd.exec(any(ExecStartResultCallback.class))).thenReturn(mock(ExecStartResultCallback.class));
final InspectExecCmd inspectExecCmd = mock(InspectExecCmd.class);
final InspectExecResponse state = mock(InspectExecResponse.class);
when(dockerClient.inspectExecCmd(any(String.class))).thenReturn(inspectExecCmd);
when(inspectExecCmd.exec()).thenReturn(state);
when(state.isRunning()).thenReturn(false);
when(state.getExitCode()).thenReturn(exitCode);
final Docker docker = new DockerImpl(dockerClient);
final ProcessResult result = docker.executeInContainer(new ContainerName(containerId), command);
assertThat(result.getExitStatus(), is(exitCode));
}
use of com.github.dockerjava.api.command.ExecCreateCmdResponse in project hub-docker-inspector by blackducksoftware.
the class DockerClientManager method execCommandInContainer.
private void execCommandInContainer(final DockerClient dockerClient, final String imageId, final String containerId, final List<String> cmd) throws InterruptedException {
logger.info(String.format("Running %s in container %s from image %s", cmd.get(0), containerId, imageId));
final ExecCreateCmd execCreateCmd = dockerClient.execCreateCmd(containerId).withAttachStdout(true).withAttachStderr(true);
// final String[] cmdArr = (String[]) cmd.toArray();
final String[] cmdArr = new String[cmd.size()];
for (int i = 0; i < cmd.size(); i++) {
logger.debug(String.format("cmdArr[%d]=%s", i, cmd.get(i)));
cmdArr[i] = cmd.get(i);
}
execCreateCmd.withCmd(cmdArr);
final ExecCreateCmdResponse execCreateCmdResponse = execCreateCmd.exec();
logger.info("Invoking container appropriate for this target image");
dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(new ExecStartResultCallback(System.out, System.err)).awaitCompletion();
logger.info("The container execution has completed");
}
Aggregations