com.spotify.docker.client.messages.ExecCreation Java Examples
The following examples show how to use
com.spotify.docker.client.messages.ExecCreation.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DockerInterpreterProcess.java From zeppelin with Apache License 2.0 | 6 votes |
private void execInContainer(String containerId, String execCommand, boolean logout) throws DockerException, InterruptedException { LOGGER.info("exec container commmand: " + execCommand); final String[] command = {"sh", "-c", execCommand}; final ExecCreation execCreation = docker.execCreate( containerId, command, DockerClient.ExecCreateParam.attachStdout(), DockerClient.ExecCreateParam.attachStderr()); LogStream logStream = docker.execStart(execCreation.id()); while (logStream.hasNext() && logout) { final String log = UTF_8.decode(logStream.next().content()).toString(); LOGGER.info(log); } }
Example #2
Source File: ContainerExecWSHandler.java From java-docker-exec with MIT License | 5 votes |
/** * 创建bash. * @param ip 宿主机ip地址 * @param containerId 容器id * @return 命令id * @throws Exception */ private String createExec(String ip, String containerId) throws Exception { return DockerHelper.query(ip, docker->{ ExecCreation execCreation=docker.execCreate(containerId,new String[]{"/bin/bash"}, DockerClient.ExecCreateParam.attachStdin(), DockerClient.ExecCreateParam.attachStdout(), DockerClient.ExecCreateParam.attachStderr(), DockerClient.ExecCreateParam.tty(true)); return execCreation.id(); }); }
Example #3
Source File: DockerContainerClient.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
private boolean exec(final ContainerInfo container, final String commands, final OutputStream outputStream) { String containerId = container.id(); String shortId = left(containerId, SHORT_ID_LENGTH); log.info("Attempting to exec commands '{}' in container '{}' for image '{}'", commands, shortId, image); try { // attach stdin as well as stdout/stderr to workaround https://github.com/spotify/docker-client/issues/513 final ExecCreation execCreation = dockerClient .execCreate(containerId, cmd(commands), attachStdin(), attachStdout(), attachStderr()); try (final LogStream stream = dockerClient.execStart(execCreation.id())) { // pretend to be a command line, by printing command to run log.debug("$ " + commands); // Why read each, instead attaching to out and err stream? Mostly because // Logstream preserves order of written out and err if/when they get written. stream.forEachRemaining(logMessage -> write(outputStream, logMessage)); } log.info("Successfully exec commands '{}' in container '{}' for image '{}'", commands, shortId, image); return true; } catch (DockerException | InterruptedException e) { log.error("Failed to exec commands '{}' in container '{}' for image '{}'", commands, shortId, image, e); } return false; }
Example #4
Source File: ExecHealthCheckerTest.java From helios with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { final ExecHealthCheck healthCheck = ExecHealthCheck.of("exit 0"); final Info info = mock(Info.class); when(info.executionDriver()).thenReturn("native-0.2"); final Version version = mock(Version.class); when(version.apiVersion()).thenReturn("1.18"); final ExecState execState = mock(ExecState.class); when(execState.exitCode()).thenReturn(0L); final LogStream log = mock(LogStream.class); when(log.readFully()).thenReturn(""); docker = mock(DockerClient.class); when(docker.info()).thenReturn(info); when(docker.version()).thenReturn(version); when(docker.execCreate(eq(CONTAINER_ID), any(String[].class), (DockerClient.ExecCreateParam) anyVararg())) .thenReturn(ExecCreation.create(EXEC_ID, emptyList())); when(docker.execStart(eq(EXEC_ID), (ExecStartParameter) anyVararg())).thenReturn(log); when(docker.execInspect(EXEC_ID)).thenReturn(execState); checker = new ExecHealthChecker(healthCheck, docker); }
Example #5
Source File: MongoTestRunner.java From aion with MIT License | 4 votes |
/** * Helper method to run some initialization command on Mongo with some retry logic if the * command fails. Since it's not determinate how long starting the database will take, we need * this retry logic. * * @param initializationCommands The command to actually run * @param retriesRemaining How many more times to retry the command if it fails * @param pauseTimeMillis How long to pause between retries * @throws InterruptedException Thrown when the thread gets interrupted trying to sleep. */ private void tryInitializeDb( String[] initializationCommands, int retriesRemaining, long pauseTimeMillis) throws InterruptedException { Exception exception = null; String execOutput = ""; try { final ExecCreation execCreation = dockerClient.execCreate( this.runningDockerContainerId, initializationCommands, DockerClient.ExecCreateParam.attachStdout(), DockerClient.ExecCreateParam.attachStderr(), DockerClient.ExecCreateParam.detach(false)); final LogStream output = dockerClient.execStart(execCreation.id()); execOutput = output.readFully(); } catch (Exception e) { exception = e; } // We can't get the exit code, but look for an expected message in the output to determine // success if (exception != null || !execOutput.contains("Using a default configuration for the set")) { // This is the case that the command didn't work if (retriesRemaining == 0) { // We're out of retries, we should fail if (exception != null) { exception.printStackTrace(); } fail( "Failed to initialize MongoDB, no retries remaining. Output was: " + execOutput); } else { Thread.sleep(pauseTimeMillis); tryInitializeDb(initializationCommands, retriesRemaining - 1, pauseTimeMillis); } } }
Example #6
Source File: Docker.java From james-project with Apache License 2.0 | 4 votes |
public void createUser(ContainerCreation container, String user, String password) throws DockerException, InterruptedException { String createUserCommand = String.format("echo %s | saslpasswd2 -u test -c %s -p", password, user); ExecCreation execCreation = dockerClient.execCreate(container.id(), new String[]{"/bin/bash", "-c", createUserCommand}); dockerClient.execStart(execCreation.id()); }
Example #7
Source File: HealthCheckTest.java From helios with Apache License 2.0 | 4 votes |
@Test public void testExec() throws Exception { // CircleCI uses lxc which doesn't support exec - https://circleci.com/docs/docker/#docker-exec assumeFalse(isCircleCi()); final DockerClient dockerClient = getNewDockerClient(); assumeThat(dockerClient.version(), is(execCompatibleDockerVersion())); startDefaultMaster(); final HeliosClient client = defaultClient(); startDefaultAgent(testHost(), "--service-registry=" + registryAddress); awaitHostStatus(client, testHost(), UP, LONG_WAIT_SECONDS, SECONDS); // check if "file" exists in the root directory as a healthcheck final HealthCheck healthCheck = ExecHealthCheck.of("test", "-e", "file"); // start a container that listens on the service port final String portName = "service"; final String serviceName = "foo_service"; final String serviceProtocol = "foo_proto"; final Job job = Job.newBuilder() .setName(testJobName) .setVersion(testJobVersion) .setImage(BUSYBOX) .setCommand(asList("sh", "-c", "nc -l -p 4711")) .addPort(portName, PortMapping.of(4711)) .addRegistration(ServiceEndpoint.of(serviceName, serviceProtocol), ServicePorts.of(portName)) .setHealthCheck(healthCheck) .build(); final JobId jobId = createJob(job); deployJob(jobId, testHost()); final TaskStatus jobState = awaitTaskState(jobId, testHost(), HEALTHCHECKING); // wait a few seconds to see if the service gets registered Thread.sleep(3000); // shouldn't be registered, since we haven't created the file yet verify(registrar, never()).register(any(ServiceRegistration.class)); // create the file in the container to make the healthcheck succeed final String[] makeFileCmd = new String[]{ "touch", "file" }; final ExecCreation execCreation = dockerClient.execCreate( jobState.getContainerId(), makeFileCmd); final String execId = execCreation.id(); dockerClient.execStart(execId); awaitTaskState(jobId, testHost(), RUNNING); dockerClient.close(); verify(registrar, timeout((int) SECONDS.toMillis(LONG_WAIT_SECONDS))) .register(registrationCaptor.capture()); final ServiceRegistration serviceRegistration = registrationCaptor.getValue(); assertEquals(1, serviceRegistration.getEndpoints().size()); final Endpoint registeredEndpoint = serviceRegistration.getEndpoints().get(0); assertEquals("wrong service", serviceName, registeredEndpoint.getName()); assertEquals("wrong protocol", serviceProtocol, registeredEndpoint.getProtocol()); }
Example #8
Source File: ContainerExecWSHandler.java From paas with Apache License 2.0 | 3 votes |
/** * 创建Bash * * @param ip 宿主机ip地址 * @param port 宿主机Remote端口 * @param containerId 容器id * @return 命令ID * @author jitwxs * @since 2018/7/1 14:13 */ private String createExec(String ip, String port, String containerId) throws Exception { return DockerHelper.query(ip, port, docker -> { ExecCreation execCreation = docker.execCreate(containerId, new String[]{"/bin/bash"}, DockerClient.ExecCreateParam.attachStdin(), DockerClient.ExecCreateParam.attachStdout(), DockerClient.ExecCreateParam.attachStderr(), DockerClient.ExecCreateParam.tty(true)); return execCreation.id(); }); }
Example #9
Source File: DockerClient.java From docker-client with Apache License 2.0 | 2 votes |
/** * Sets up an exec instance in a running container id. * * @param containerId The id of the container * @param cmd shell command * @param params Exec params * @return {@link ExecCreation} * @throws DockerException if a server error occurred (500) * @throws InterruptedException If the thread is interrupted */ ExecCreation execCreate(String containerId, String[] cmd, ExecCreateParam... params) throws DockerException, InterruptedException;