Java源码示例:com.github.dockerjava.api.command.ExecCreateCmd

示例1
private TestExecStartResultCallback executeCommandInDocker(String containerName, String[] command,
    boolean expectedToSucceed) throws Exception {
  Container sparkWorkerContainer = runningContainers.get(containerName);
  ExecCreateCmd cmd = dockerClient.execCreateCmd(sparkWorkerContainer.getId()).withCmd(command).withAttachStdout(true)
      .withAttachStderr(true);

  ExecCreateCmdResponse createCmdResponse = cmd.exec();
  TestExecStartResultCallback callback =
      new TestExecStartResultCallback(new ByteArrayOutputStream(), new ByteArrayOutputStream());
  dockerClient.execStartCmd(createCmdResponse.getId()).withDetach(false).withTty(false).exec(callback)
      .awaitCompletion();
  int exitCode = dockerClient.inspectExecCmd(createCmdResponse.getId()).exec().getExitCode();
  LOG.info("Exit code for command : " + exitCode);
  LOG.error("\n\n ###### Stdout #######\n" + callback.getStdout().toString());
  LOG.error("\n\n ###### Stderr #######\n" + callback.getStderr().toString());

  if (expectedToSucceed) {
    assertEquals(0, exitCode, "Command (" + Arrays.toString(command) + ") expected to succeed. Exit (" + exitCode + ")");
  } else {
    assertNotEquals(0, exitCode, "Command (" + Arrays.toString(command) + ") expected to fail. Exit (" + exitCode + ")");
  }
  cmd.close();
  return callback;
}
 
示例2
@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));
}
 
示例3
@Override
protected ExecCreateCmdResponse execute(ExecCreateCmd command) {
    WebTarget webResource = getBaseResource().path("/containers/{id}/exec").resolveTemplate("id",
            command.getContainerId());

    LOGGER.trace("POST: {}", webResource);

    return webResource.request().accept(MediaType.APPLICATION_JSON)
            .post(command, new TypeReference<ExecCreateCmdResponse>() {
            });
}
 
示例4
@Override
public ExecCreateCmd execCreateCmd(String containerId) {
    return new ExecCreateCmdImpl(getDockerCmdExecFactory().createExecCmdExec(), containerId);
}
 
示例5
@Override
public ExecCreateCmd.Exec createExecCmdExec() {
    return new ExecCreateCmdExec(getBaseResource(), getDockerClientConfig());
}
 
示例6
public ExecCreateCmdImpl(ExecCreateCmd.Exec exec, String containerId) {
    super(exec);
    withContainerId(containerId);
}
 
示例7
@Override
public ExecCreateCmd withContainerId(String containerId) {
    checkNotNull(containerId, "containerId was not specified");
    this.containerId = containerId;
    return this;
}
 
示例8
@Override
public ExecCreateCmd withAttachStdin(Boolean attachStdin) {
    this.attachStdin = attachStdin;
    return this;
}
 
示例9
@Override
public ExecCreateCmd withAttachStdout(Boolean attachStdout) {
    this.attachStdout = attachStdout;
    return this;
}
 
示例10
@Override
public ExecCreateCmd withAttachStderr(Boolean attachStderr) {
    this.attachStderr = attachStderr;
    return this;
}
 
示例11
@Override
public ExecCreateCmd withTty(Boolean tty) {
    this.tty = tty;
    return this;
}
 
示例12
@Override
public ExecCreateCmd withUser(String user) {
    this.user = user;
    return this;
}
 
示例13
@Override
public ExecCreateCmd withCmd(String... cmd) {
    this.cmd = cmd;
    return this;
}
 
示例14
@Override
public ExecCreateCmd withEnv(List<String> env) {
    this.env = env;
    return this;
}
 
示例15
@Override
public ExecCreateCmd withPrivileged(Boolean privileged) {
    this.privileged = privileged;
    return this;
}
 
示例16
@Override
public ExecCreateCmd withWorkingDir(String workingDir) {
    this.workingDir = workingDir;
    return this;
}
 
示例17
@Override
public void launch(final SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException {
    final PrintStream logger = computer.getListener().getLogger();
    final String jenkinsUrl = Jenkins.getInstance().getRootUrl();
    final String effectiveJavaExe = StringUtils.isNotBlank(javaExeOrNull) ? javaExeOrNull : DEFAULT_JAVA_EXE;
    final String effectiveJvmArgs = StringUtils.isNotBlank(jvmArgsOrEmpty) ? jvmArgsOrEmpty : DEFAULT_JVM_ARGS ;
    final EnvVars knownVariables = calculateVariablesForVariableSubstitution(effectiveJavaExe, effectiveJvmArgs, remoting.getName(), remoteFs, jenkinsUrl);
    final String effectiveEntryPointCmdString = StringUtils.isNotBlank(entryPointCmdOrEmpty) ? entryPointCmdOrEmpty : DEFAULT_ENTRY_POINT_CMD_STRING;
    final String resolvedEntryPointCmdString = Util.replaceMacro(effectiveEntryPointCmdString, knownVariables);
    final String[] resolvedEntryPointCmd = splitAndFilterEmpty(resolvedEntryPointCmdString, "\n");
    logger.println("Connecting to docker container " + containerId + ", running command " + Joiner.on(" ").join(resolvedEntryPointCmd));

    final String execId;
    try(final DockerClient client = api.getClient()) {
        final ExecCreateCmd cmd = client.execCreateCmd(containerId)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withAttachStderr(true)
                .withTty(false)
                .withCmd(resolvedEntryPointCmd);
        if (StringUtils.isNotBlank(userOrNull)) {
            cmd.withUser(userOrNull);
        }
        final ExecCreateCmdResponse exec = cmd.exec();
        execId = exec.getId();
    }
    final String js = "{ \"Detach\": false, \"Tty\": false }";
    final Socket socket = api.getSocket();
    final OutputStream out = socket.getOutputStream();
    final InputStream in = socket.getInputStream();
    final PrintWriter w = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.US_ASCII));
    w.println("POST /v1.32/exec/" + execId + "/start HTTP/1.1");
    w.println("Host: docker.sock");
    w.println("Content-Type: application/json");
    w.println("Upgrade: tcp");
    w.println("Connection: Upgrade");
    w.println("Content-Length: " + js.length());
    w.println();
    w.println(js);
    w.flush();

    // read HTTP response headers
    String line = readLine(in);
    logger.println(line);
    if (! line.startsWith("HTTP/1.1 101 ")) {   // Switching Protocols
        throw new IOException("Unexpected HTTP response status line " + line);
    }

    // Skip HTTP header
    while ((line = readLine(in)).length() > 0) {
        if (line.length() == 0) break; // end of header
        logger.println(line);
    }

    final InputStream demux = new DockerMultiplexedInputStream(in);

    computer.setChannel(demux, out, listener, new Channel.Listener() {
        @Override
        public void onClosed(Channel channel, IOException cause) {
            // Bye!
        }
    });

}
 
示例18
@Override
public ExecCreateCmd execCreateCmd(String arg0) {
    return getDelegate().execCreateCmd(arg0);
}
 
示例19
ExecCreateCmd execCreateCmd(@Nonnull String containerId);