Java源码示例:com.github.dockerjava.core.command.ExecStartResultCallback
示例1
public String runCommandInContainer(String containerId, String command, int secondsOfWait)
throws InterruptedException {
ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId).withAttachStdout(true)
.withAttachStderr(true).withCmd("bash", "-c", command).exec();
CountDownLatch latch = new CountDownLatch(1);
final String[] stringResponse = new String[1];
dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(new ExecStartResultCallback() {
@Override
public void onNext(Frame item) {
stringResponse[0] = new String(item.getPayload());
latch.countDown();
}
});
latch.await(secondsOfWait, TimeUnit.SECONDS);
return stringResponse[0];
}
示例2
private void checkDiskSpace(DockerClient dockerClient, String id) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
dockerClient
.execStartCmd(dockerClient.execCreateCmd(id).withAttachStdout(true).withCmd("df", "-P").exec().getId())
.exec(new ExecStartResultCallback(outputStream, null))
.awaitCompletion();
} catch (Exception e) {
log.debug("Can't exec disk checking command", e);
}
DiskSpaceUsage df = parseAvailableDiskSpace(outputStream.toString());
check(
"Docker environment should have more than 2GB free disk space",
df.availableMB.map(it -> it >= 2048).orElse(true)
);
}
示例3
public String execCommand(String containerId, boolean awaitCompletion, String... command) {
ExecCreateCmdResponse exec = client.execCreateCmd(containerId).withCmd(command).withTty(false)
.withAttachStdin(true).withAttachStdout(true).withAttachStderr(true).exec();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String output = null;
try {
ExecStartResultCallback resultCallback = client.execStartCmd(exec.getId()).withDetach(false)
.withTty(true).exec(new ExecStartResultCallback(outputStream, System.err));
if (awaitCompletion) {
resultCallback.awaitCompletion();
}
output = new String(outputStream.toByteArray());
} catch (InterruptedException e) {
log.warn("Exception executing command {} on container {}", Arrays.toString(command),
containerId, e);
}
return output;
}
示例4
public void execCommand( String command ) throws Exception {
// Exec command inside running container with attached STDOUT and STDERR
String[] commandArray = StringUtilities.parseCommand(command);
ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)//
.withAttachStdout(true) //
.withAttachStderr(true)//
.withCmd(commandArray)//
.withUser("root")//
.exec();
dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(new ExecStartResultCallback(System.out, System.err))
.awaitCompletion();
// pm.message(execOutput);
}
示例5
@Test
public void execStartAttached() throws Exception {
String containerName = "generated_" + new SecureRandom().nextInt();
CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("sleep", "9999")
.withName(containerName).exec();
LOG.info("Created container {}", container.toString());
assertThat(container.getId(), not(is(emptyString())));
dockerRule.getClient().startContainerCmd(container.getId()).exec();
ExecCreateCmdResponse execCreateCmdResponse = dockerRule.getClient().execCreateCmd(container.getId())
.withAttachStdout(true).withCmd("touch", "/execStartTest.log").exec();
dockerRule.getClient().execStartCmd(execCreateCmdResponse.getId()).withDetach(false).withTty(true)
.exec(new ExecStartResultCallback(System.out, System.err)).awaitCompletion();
InputStream response = dockerRule.getClient().copyArchiveFromContainerCmd(container.getId(), "/execStartTest.log").exec();
// read the stream fully. Otherwise, the underlying stream will not be closed.
String responseAsString = asString(response);
assertNotNull(responseAsString);
assertTrue(responseAsString.length() > 0);
}
示例6
@Test(expected = NotFoundException.class)
public void execStartWithNonExistentUser() throws Exception {
String containerName = "generated_" + new SecureRandom().nextInt();
CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("sleep", "9999")
.withName(containerName).exec();
LOG.info("Created container {}", container.toString());
assertThat(container.getId(), not(is(emptyString())));
dockerRule.getClient().startContainerCmd(container.getId()).exec();
ExecCreateCmdResponse execCreateCmdResponse = dockerRule.getClient().execCreateCmd(container.getId())
.withAttachStdout(true).withCmd("touch", "/execStartTest.log").withUser("NonExistentUser").exec();
dockerRule.getClient().execStartCmd(execCreateCmdResponse.getId()).withDetach(false).withTty(true)
.exec(new ExecStartResultCallback(System.out, System.err)).awaitCompletion();
dockerRule.getClient().copyArchiveFromContainerCmd(container.getId(), "/execStartTest.log").exec();
}
示例7
@Override
public ProcessResult executeInContainerAsUser(ContainerName containerName, String user, OptionalLong timeoutSeconds, String... command) {
try {
ExecCreateCmdResponse response = execCreateCmd(containerName, user, command);
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errors = new ByteArrayOutputStream();
ExecStartResultCallback callback = dockerClient.execStartCmd(response.getId())
.exec(new ExecStartResultCallback(output, errors));
if (timeoutSeconds.isPresent()) {
if (!callback.awaitCompletion(timeoutSeconds.getAsLong(), TimeUnit.SECONDS))
throw new DockerExecTimeoutException(String.format(
"Command '%s' did not finish within %d seconds.", command[0], timeoutSeconds.getAsLong()));
} else {
// Wait for completion no timeout
callback.awaitCompletion();
}
InspectExecResponse state = dockerClient.inspectExecCmd(response.getId()).exec();
if (state.isRunning())
throw new DockerException("Command '%s' did not finish within %s seconds.");
return new ProcessResult(state.getExitCode(), new String(output.toByteArray()), new String(errors.toByteArray()));
} catch (RuntimeException | InterruptedException e) {
numberOfDockerApiFails.increment();
throw new DockerException("Container '" + containerName.asString()
+ "' failed to execute " + Arrays.toString(command), e);
}
}
示例8
@Test
public void testExecuteCompletes() {
final String containerId = "container-id";
final String[] command = new String[] {"/bin/ls", "-l"};
final String execId = "exec-id";
final int exitCode = 3;
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(ArgumentMatchers.<String>any())).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 ProcessResult result = docker.executeInContainerAsUser(
new ContainerName(containerId), "root", OptionalLong.empty(), command);
assertThat(result.getExitStatus(), is(exitCode));
}
示例9
/**
* @param id The container id, will be used only the first one
* @param serviceName Service name in running environment. Can be null.
* @param script Script to execute
*/
@Override
public void execScript(List<String> id, String serviceName, String script) {
log.info(String.format("Executing script: %s, in container: %s", script, id));
String[] commands = null;
try {
/**
* Due to permissions problems with mounted volume script is moved to some local directory in container
*
* 1. create new directory in container
* 2. move there script
* 3. chmod script
* 4. execute script
*/
commands = new String[] {
"bash", "-c",
scriptExecCommand(script)
};
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(id.get(0))
.withCmd(commands)
.withAttachStdout(true)
.withAttachStderr(true)
.exec();
dockerClient.execStartCmd(exec.getId())
.exec(new ExecStartResultCallback(System.out, System.err))
.awaitCompletion();
} catch (DockerException | InterruptedException ex) {
log.severe(String.format("Could not execute command: %s", Arrays.toString(commands)));
throw new EnvironmentException("Could not execute command " + Arrays.toString(commands), ex);
}
}
示例10
@Test
public void execStart() throws Exception {
assumeNotSwarm("no network in swarm", dockerRule);
String containerName = "generated_" + new SecureRandom().nextInt();
CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("top")
.withName(containerName).exec();
LOG.info("Created container {}", container.toString());
assertThat(container.getId(), not(is(emptyString())));
dockerRule.getClient().startContainerCmd(container.getId()).exec();
ExecCreateCmdResponse execCreateCmdResponse = dockerRule.getClient().execCreateCmd(container.getId())
.withAttachStdout(true)
.withCmd("touch", "/execStartTest.log")
.withUser("root")
.exec();
dockerRule.getClient().execStartCmd(execCreateCmdResponse.getId())
.exec(new ExecStartResultCallback(System.out, System.err))
.awaitCompletion();
InputStream response = dockerRule.getClient().copyArchiveFromContainerCmd(container.getId(), "/execStartTest.log").exec();
// read the stream fully. Otherwise, the underlying stream will not be closed.
String responseAsString = asString(response);
assertNotNull(responseAsString);
assertTrue(responseAsString.length() > 0);
}
示例11
@Test
public void resizeExecInstanceTtyTest() throws Exception {
String containerName = "generated_" + new SecureRandom().nextInt();
CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withUser("root")
.withCmd("sleep", "9999").withName(containerName).exec();
dockerRule.getClient().startContainerCmd(container.getId()).exec();
// wait until tty size changed to target size
ExecCreateCmdResponse execCreateCmdResponse = dockerRule.getClient().execCreateCmd(container.getId()).withTty(true)
.withAttachStdout(true).withAttachStderr(true)
.withCmd("sh", "-c", String.format("until stty size | grep '%d %d'; do : ; done", TTY_HEIGHT, TTY_WIDTH)).exec();
final ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback(System.out, System.err);
dockerRule.getClient().execStartCmd(execCreateCmdResponse.getId()).exec(execStartResultCallback).awaitStarted();
dockerRule.getClient().resizeExecCmd(execCreateCmdResponse.getId()).withSize(TTY_HEIGHT, TTY_WIDTH).exec();
// time out, exec instance resize failed
boolean waitResult = execStartResultCallback.awaitCompletion(10, TimeUnit.SECONDS);
assertThat(waitResult, equalTo(true));
}
示例12
@Test
public void inspectExec() throws Exception {
String containerName = "generated_" + new SecureRandom().nextInt();
CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("sleep", "9999")
.withName(containerName).exec();
LOG.info("Created container {}", container.toString());
assertThat(container.getId(), not(is(emptyString())));
dockerRule.getClient().startContainerCmd(container.getId()).exec();
// Check that file does not exist
ExecCreateCmdResponse checkFileExec1 = dockerRule.getClient().execCreateCmd(container.getId()).withAttachStdout(true)
.withAttachStderr(true).withCmd("test", "-e", "/marker").exec();
LOG.info("Created exec {}", checkFileExec1.toString());
assertThat(checkFileExec1.getId(), not(is(emptyString())));
dockerRule.getClient().execStartCmd(checkFileExec1.getId()).withDetach(false)
.exec(new ExecStartResultCallback(System.out, System.err)).awaitCompletion();
InspectExecResponse first = dockerRule.getClient().inspectExecCmd(checkFileExec1.getId()).exec();
assertThat(first.isRunning(), is(false));
assertThat(first.getExitCode(), is(1));
// Create the file
ExecCreateCmdResponse touchFileExec = dockerRule.getClient().execCreateCmd(container.getId()).withAttachStdout(true)
.withAttachStderr(true).withCmd("touch", "/marker").exec();
LOG.info("Created exec {}", touchFileExec.toString());
assertThat(touchFileExec.getId(), not(is(emptyString())));
dockerRule.getClient().execStartCmd(touchFileExec.getId()).withDetach(false)
.exec(new ExecStartResultCallback(System.out, System.err)).awaitCompletion();
InspectExecResponse second = dockerRule.getClient().inspectExecCmd(touchFileExec.getId()).exec();
assertThat(second.isRunning(), is(false));
assertThat(second.getExitCode(), is(0));
// Check that file does exist now
ExecCreateCmdResponse checkFileExec2 = dockerRule.getClient().execCreateCmd(container.getId()).withAttachStdout(true)
.withAttachStderr(true).withCmd("test", "-e", "/marker").exec();
LOG.info("Created exec {}", checkFileExec2.toString());
assertThat(checkFileExec2.getId(), not(is(emptyString())));
dockerRule.getClient().execStartCmd(checkFileExec2.getId()).withDetach(false)
.exec(new ExecStartResultCallback(System.out, System.err)).awaitCompletion();
InspectExecResponse third = dockerRule.getClient().inspectExecCmd(checkFileExec2.getId()).exec();
assertThat(third.isRunning(), is(false));
assertThat(third.getExitCode(), is(0));
// Get container info and check its roundtrip to ensure the consistency
InspectContainerResponse containerInfo = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();
assertEquals(containerInfo.getId(), container.getId());
JSONTestHelper.testRoundTrip(containerInfo);
}