Search in sources :

Example 56 with ContainerInfo

use of com.spotify.docker.client.messages.ContainerInfo in project hale by halestudio.

the class HaleDockerClient method startContainer.

/**
 * start a container. Container can be started in the privileged mode if the
 * 'isPrivileged' key in the configuration is set as true.
 *
 * @throws DockerException docker exception
 * @throws InterruptedException interrupted exception
 */
public void startContainer() throws DockerException, InterruptedException {
    try {
        dc.inspectImage(containerConf.image());
    } catch (ImageNotFoundException e) {
        // pull image if it is not present
        LOGGER.info(MessageFormat.format("Docker image not found, attempting to pull image {0}...", containerConf.image()));
        dc.pull(containerConf.image());
    }
    // TODO also add a setting to pull the image always?
    LOGGER.info(MessageFormat.format("Preparing container for image {0}...", containerConf.image()));
    creation = dc.createContainer(containerConf);
    containerId = creation.id();
    LOGGER.info(MessageFormat.format("Created container with ID {0}, now starting...", containerId));
    final HostConfig hostConfig;
    if (getHostName() == null) {
        // don't publish ports (probably unix socket connection)
        hostConfig = HostConfig.builder().publishAllPorts(false).privileged(dbc.isPrivileged()).build();
    } else {
        // XXX publishing all ports can be very bad if the host is
        // accessible externally
        hostConfig = HostConfig.builder().publishAllPorts(dbc.isExposeAllPorts()).privileged(dbc.isPrivileged()).build();
    }
    dc.startContainer(containerId, hostConfig);
    final ContainerInfo info = dc.inspectContainer(containerId);
    portMapper = info.networkSettings().ports();
    containerIp = info.networkSettings().ipAddress();
}
Also used : HostConfig(com.spotify.docker.client.messages.HostConfig) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) ImageNotFoundException(com.spotify.docker.client.ImageNotFoundException)

Example 57 with ContainerInfo

use of com.spotify.docker.client.messages.ContainerInfo in project helios by spotify.

the class TaskRunnerTest method testContainerNotRunningVariation.

@Test
public void testContainerNotRunningVariation() throws Throwable {
    final TaskRunner.NopListener mockListener = mock(TaskRunner.NopListener.class);
    final ImageInfo mockImageInfo = mock(ImageInfo.class);
    final ContainerCreation mockCreation = mock(ContainerCreation.class);
    final HealthChecker mockHealthChecker = mock(HealthChecker.class);
    final ContainerState stoppedState = mock(ContainerState.class);
    when(stoppedState.running()).thenReturn(false);
    when(stoppedState.error()).thenReturn("container is a potato");
    final ContainerInfo stopped = mock(ContainerInfo.class);
    when(stopped.state()).thenReturn(stoppedState);
    when(mockCreation.id()).thenReturn("potato");
    when(mockDocker.inspectContainer(anyString())).thenReturn(stopped);
    when(mockDocker.inspectImage(IMAGE)).thenReturn(mockImageInfo);
    when(mockDocker.createContainer(any(ContainerConfig.class), anyString())).thenReturn(mockCreation);
    when(mockHealthChecker.check(anyString())).thenReturn(false);
    final TaskRunner tr = TaskRunner.builder().delayMillis(0).config(TaskConfig.builder().namespace("test").host(HOST).job(JOB).containerDecorators(ImmutableList.of(containerDecorator)).build()).docker(mockDocker).listener(mockListener).healthChecker(mockHealthChecker).build();
    tr.run();
    try {
        tr.resultFuture().get();
        fail("this should throw");
    } catch (Exception t) {
        assertTrue(t instanceof ExecutionException);
        assertEquals(RuntimeException.class, t.getCause().getClass());
        verify(mockListener).failed(t.getCause(), "container is a potato");
    }
}
Also used : ContainerConfig(com.spotify.docker.client.messages.ContainerConfig) ContainerCreation(com.spotify.docker.client.messages.ContainerCreation) HeliosRuntimeException(com.spotify.helios.common.HeliosRuntimeException) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) ImageInfo(com.spotify.docker.client.messages.ImageInfo) ExecutionException(java.util.concurrent.ExecutionException) ContainerState(com.spotify.docker.client.messages.ContainerState) HeliosRuntimeException(com.spotify.helios.common.HeliosRuntimeException) DockerException(com.spotify.docker.client.exceptions.DockerException) ImageNotFoundException(com.spotify.docker.client.exceptions.ImageNotFoundException) DockerTimeoutException(com.spotify.docker.client.exceptions.DockerTimeoutException) ExecutionException(java.util.concurrent.ExecutionException) ImagePullFailedException(com.spotify.docker.client.exceptions.ImagePullFailedException) Test(org.junit.Test)

Example 58 with ContainerInfo

use of com.spotify.docker.client.messages.ContainerInfo in project helios by spotify.

the class SystemTestBase method assertDockerReachable.

private void assertDockerReachable(final int probePort) throws Exception {
    try (final DockerClient docker = getNewDockerClient()) {
        // Pull our base images
        try {
            docker.inspectImage(BUSYBOX);
        } catch (ImageNotFoundException e) {
            docker.pull(BUSYBOX);
        }
        try {
            docker.inspectImage(ALPINE);
        } catch (ImageNotFoundException e) {
            docker.pull(ALPINE);
        }
        // Start a container with an exposed port
        final HostConfig hostConfig = HostConfig.builder().portBindings(ImmutableMap.of("4711/tcp", singletonList(PortBinding.of("0.0.0.0", probePort)))).build();
        final ContainerConfig config = ContainerConfig.builder().image(BUSYBOX).cmd("nc", "-p", "4711", "-lle", "cat").exposedPorts(ImmutableSet.of("4711/tcp")).hostConfig(hostConfig).build();
        final ContainerCreation creation = docker.createContainer(config, testTag + "-probe");
        final String containerId = creation.id();
        docker.startContainer(containerId);
        // Wait for container to come up
        Polling.await(5, SECONDS, new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                final ContainerInfo info = docker.inspectContainer(containerId);
                return info.state().running() ? true : null;
            }
        });
        log.info("Verifying that docker containers are reachable");
        try {
            Polling.awaitUnchecked(5, SECONDS, new Callable<Object>() {

                @Override
                public Object call() throws Exception {
                    log.info("Probing: {}:{}", DOCKER_HOST.address(), probePort);
                    try (final Socket ignored = new Socket(DOCKER_HOST.address(), probePort)) {
                        return true;
                    } catch (IOException e) {
                        return false;
                    }
                }
            });
        } catch (TimeoutException e) {
            fail("Please ensure that DOCKER_HOST is set to an address that where containers can " + "be reached. If docker is running in a local VM, DOCKER_HOST must be set to the " + "address of that VM. If docker can only be reached on a limited port range, " + "set the environment variable DOCKER_PORT_RANGE=start:end");
        }
        docker.killContainer(containerId);
    }
}
Also used : DockerClient(com.spotify.docker.client.DockerClient) DefaultDockerClient(com.spotify.docker.client.DefaultDockerClient) Matchers.containsString(org.hamcrest.Matchers.containsString) Integer.toHexString(java.lang.Integer.toHexString) IOException(java.io.IOException) DockerRequestException(com.spotify.docker.client.exceptions.DockerRequestException) DockerException(com.spotify.docker.client.exceptions.DockerException) ContainerNotFoundException(com.spotify.docker.client.exceptions.ContainerNotFoundException) ImageNotFoundException(com.spotify.docker.client.exceptions.ImageNotFoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) ExpectedException(org.junit.rules.ExpectedException) ContainerConfig(com.spotify.docker.client.messages.ContainerConfig) ContainerCreation(com.spotify.docker.client.messages.ContainerCreation) HostConfig(com.spotify.docker.client.messages.HostConfig) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) ImageNotFoundException(com.spotify.docker.client.exceptions.ImageNotFoundException) Socket(java.net.Socket) TimeoutException(java.util.concurrent.TimeoutException)

Example 59 with ContainerInfo

use of com.spotify.docker.client.messages.ContainerInfo in project helios by spotify.

the class HeliosSoloDeploymentTest method setup.

@Before
public void setup() throws Exception {
    this.dockerClient = mock(DockerClient.class);
    this.heliosClient = mock(HeliosClient.class);
    // the anonymous classes to override a method are to workaround the docker-client "messages"
    // having no mutators, fun
    final Info info = mock(Info.class);
    when(info.operatingSystem()).thenReturn("foo");
    when(this.dockerClient.info()).thenReturn(info);
    // mock the call to dockerClient.createContainer so we can test the arguments passed to it
    this.containerConfig = ArgumentCaptor.forClass(ContainerConfig.class);
    final ContainerCreation creation = mock(ContainerCreation.class);
    when(creation.id()).thenReturn(CONTAINER_ID);
    when(this.dockerClient.createContainer(this.containerConfig.capture(), anyString())).thenReturn(creation);
    // we have to mock out several other calls to get the HeliosSoloDeployment ctor
    // to return non-exceptionally. the anonymous classes to override a method are to workaround
    // the docker-client "messages" having no mutators, fun
    when(this.dockerClient.info()).thenReturn(info);
    final PortBinding binding = PortBinding.of("192.168.1.1", 5801);
    final ImmutableMap<String, List<PortBinding>> ports = ImmutableMap.<String, List<PortBinding>>of("5801/tcp", ImmutableList.of(binding));
    final ContainerInfo containerInfo = mock(ContainerInfo.class);
    final NetworkSettings networkSettings = mock(NetworkSettings.class);
    when(networkSettings.gateway()).thenReturn("a-gate-way");
    when(networkSettings.ports()).thenReturn(ports);
    when(containerInfo.networkSettings()).thenReturn(networkSettings);
    when(this.dockerClient.inspectContainer(CONTAINER_ID)).thenReturn(containerInfo);
    when(this.dockerClient.waitContainer(CONTAINER_ID)).thenReturn(ContainerExit.create(0L));
}
Also used : ContainerConfig(com.spotify.docker.client.messages.ContainerConfig) ContainerCreation(com.spotify.docker.client.messages.ContainerCreation) PortBinding(com.spotify.docker.client.messages.PortBinding) NetworkSettings(com.spotify.docker.client.messages.NetworkSettings) DockerClient(com.spotify.docker.client.DockerClient) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) ImmutableList(com.spotify.docker.client.shaded.com.google.common.collect.ImmutableList) List(java.util.List) Matchers.anyString(org.mockito.Matchers.anyString) HeliosClient(com.spotify.helios.client.HeliosClient) Info(com.spotify.docker.client.messages.Info) ImageInfo(com.spotify.docker.client.messages.ImageInfo) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) Before(org.junit.Before)

Example 60 with ContainerInfo

use of com.spotify.docker.client.messages.ContainerInfo in project helios by spotify.

the class PollingDockerClient method waitContainer.

@Override
public ContainerExit waitContainer(final String containerId) throws DockerException, InterruptedException {
    // and restarting docker would not close the socket. ¯\_(ツ)_/¯
    while (true) {
        final ContainerInfo info = inspectContainer(containerId);
        if (!info.state().running()) {
            return ContainerExit.create(info.state().exitCode());
        }
        Thread.sleep(WAIT_INSPECT_INTERVAL_MILLIS);
    }
}
Also used : ContainerInfo(com.spotify.docker.client.messages.ContainerInfo)

Aggregations

ContainerInfo (com.spotify.docker.client.messages.ContainerInfo)68 ContainerConfig (com.spotify.docker.client.messages.ContainerConfig)45 Test (org.junit.Test)41 ContainerCreation (com.spotify.docker.client.messages.ContainerCreation)35 Matchers.containsString (org.hamcrest.Matchers.containsString)33 Long.toHexString (java.lang.Long.toHexString)31 Matchers.isEmptyOrNullString (org.hamcrest.Matchers.isEmptyOrNullString)31 DockerException (com.spotify.docker.client.exceptions.DockerException)15 HostConfig (com.spotify.docker.client.messages.HostConfig)15 IOException (java.io.IOException)9 DockerClient (com.spotify.docker.client.DockerClient)8 ContainerNotFoundException (com.spotify.docker.client.exceptions.ContainerNotFoundException)7 DockerRequestException (com.spotify.docker.client.exceptions.DockerRequestException)5 Container (com.spotify.docker.client.messages.Container)5 ImageInfo (com.spotify.docker.client.messages.ImageInfo)5 LogStream (com.spotify.docker.client.LogStream)4 ImageNotFoundException (com.spotify.docker.client.exceptions.ImageNotFoundException)4 AttachedNetwork (com.spotify.docker.client.messages.AttachedNetwork)4 Path (java.nio.file.Path)4 ContainerMount (com.spotify.docker.client.messages.ContainerMount)3