Search in sources :

Example 36 with ContainerInfo

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

the class DefaultDockerClient method execCreate.

@Override
public ExecCreation execCreate(final String containerId, final String[] cmd, final ExecCreateParam... params) throws DockerException, InterruptedException {
    final ContainerInfo containerInfo = inspectContainer(containerId);
    if (!containerInfo.state().running()) {
        throw new IllegalStateException("Container " + containerId + " is not running.");
    }
    final WebTarget resource = resource().path("containers").path(containerId).path("exec");
    final StringWriter writer = new StringWriter();
    try {
        final JsonGenerator generator = objectMapper().getFactory().createGenerator(writer);
        generator.writeStartObject();
        for (final ExecCreateParam param : params) {
            if (param.value().equals("true") || param.value().equals("false")) {
                generator.writeBooleanField(param.name(), Boolean.valueOf(param.value()));
            } else {
                generator.writeStringField(param.name(), param.value());
            }
        }
        generator.writeArrayFieldStart("Cmd");
        for (final String s : cmd) {
            generator.writeString(s);
        }
        generator.writeEndArray();
        generator.writeEndObject();
        generator.close();
    } catch (IOException e) {
        throw new DockerException(e);
    }
    try {
        return request(POST, ExecCreation.class, resource, resource.request(APPLICATION_JSON_TYPE), Entity.json(writer.toString()));
    } catch (DockerRequestException e) {
        switch(e.status()) {
            case 404:
                throw new ContainerNotFoundException(containerId, e);
            case 409:
                throw new ExecCreateConflictException(containerId, e);
            default:
                throw e;
        }
    }
}
Also used : DockerException(com.spotify.docker.client.exceptions.DockerException) StringWriter(java.io.StringWriter) DockerRequestException(com.spotify.docker.client.exceptions.DockerRequestException) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) WebTarget(javax.ws.rs.client.WebTarget) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ContainerNotFoundException(com.spotify.docker.client.exceptions.ContainerNotFoundException) ExecCreateConflictException(com.spotify.docker.client.exceptions.ExecCreateConflictException)

Example 37 with ContainerInfo

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

the class DefaultDockerClientTest method testSsl.

@SuppressWarnings("EmptyCatchBlock")
@Test
public void testSsl() throws Exception {
    assumeFalse(TRAVIS);
    // Build a run a container that contains a Docker instance configured with our SSL cert/key
    final String imageName = "test-docker-ssl";
    final String expose = "2376/tcp";
    final Path dockerDirectory = getResource("dockerSslDirectory");
    sut.build(dockerDirectory, imageName);
    final HostConfig hostConfig = HostConfig.builder().privileged(true).publishAllPorts(true).build();
    final ContainerConfig containerConfig = ContainerConfig.builder().image(imageName).exposedPorts(expose).hostConfig(hostConfig).build();
    final String containerName = randomName();
    final ContainerCreation containerCreation = sut.createContainer(containerConfig, containerName);
    final String containerId = containerCreation.id();
    sut.startContainer(containerId);
    // Determine where the Docker instance inside the container we just started is exposed
    final String host;
    if (dockerEndpoint.getScheme().equalsIgnoreCase("unix")) {
        host = "localhost";
    } else {
        host = dockerEndpoint.getHost();
    }
    final ContainerInfo containerInfo = sut.inspectContainer(containerId);
    assertThat(containerInfo.state().running(), equalTo(true));
    final String port = containerInfo.networkSettings().ports().get(expose).get(0).hostPort();
    // Try to connect using SSL and our known cert/key
    final DockerCertificates certs = new DockerCertificates(dockerDirectory);
    final DockerClient c = new DefaultDockerClient(URI.create(format("https://%s:%s", host, port)), certs);
    // We need to wait for the docker process inside the docker container to be ready to accept
    // connections on the port. Otherwise, this test will fail.
    // Even though we've checked that the container is running, this doesn't mean the process
    // inside the container is ready.
    final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(TimeUnit.MINUTES.toMillis(1));
    while (System.nanoTime() < deadline) {
        try (final Socket ignored = new Socket(host, Integer.parseInt(port))) {
            break;
        } catch (IOException ignored) {
        }
        Thread.sleep(500);
    }
    assertThat(c.ping(), equalTo("OK"));
    sut.stopContainer(containerId, 10);
}
Also used : Path(java.nio.file.Path) 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) Long.toHexString(java.lang.Long.toHexString) Matchers.isEmptyOrNullString(org.hamcrest.Matchers.isEmptyOrNullString) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Test(org.junit.Test)

Example 38 with ContainerInfo

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

the class DefaultDockerClientTest method testStorageOpt.

@Test
public void testStorageOpt() throws Exception {
    requireDockerApiVersionAtLeast("1.24", "StorageOpt");
    requireStorageDriverNotAufs();
    // Doesn't work on Travis with Docker API v1.32 because storage driver doesn't have pquota
    // mount option enabled.
    assumeFalse(dockerApiVersionEquals("1.32") && TRAVIS);
    // Pull image
    sut.pull(BUSYBOX_LATEST);
    final ImmutableMap<String, String> storageOpt = ImmutableMap.of("size", "20G");
    final ContainerConfig config = ContainerConfig.builder().image(BUSYBOX_LATEST).hostConfig(HostConfig.builder().storageOpt(storageOpt).build()).build();
    final ContainerCreation container = sut.createContainer(config, randomName());
    final ContainerInfo info = sut.inspectContainer(container.id());
    assertThat(info.hostConfig().storageOpt().size(), is(1));
    assertThat(info.hostConfig().storageOpt().get("size"), is("20G"));
}
Also used : ContainerConfig(com.spotify.docker.client.messages.ContainerConfig) ContainerCreation(com.spotify.docker.client.messages.ContainerCreation) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) Long.toHexString(java.lang.Long.toHexString) Matchers.isEmptyOrNullString(org.hamcrest.Matchers.isEmptyOrNullString) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.Test)

Example 39 with ContainerInfo

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

the class DefaultDockerClientTest method testNetworksConnectContainerWithEndpointConfig.

@Test
public void testNetworksConnectContainerWithEndpointConfig() throws Exception {
    requireDockerApiVersionAtLeast("1.22", "createNetwork and listNetworks");
    assumeFalse(CIRCLECI);
    final String networkName = randomName();
    final String containerName = randomName();
    final String subnet = "172.20.0.0/16";
    final String ipRange = "172.20.10.0/24";
    final String gateway = "172.20.10.11";
    final IpamConfig ipamConfigToCreate = IpamConfig.create(subnet, ipRange, gateway);
    final Ipam ipamToCreate = Ipam.builder().driver("default").config(Lists.newArrayList(ipamConfigToCreate)).build();
    final NetworkConfig networkingConfig = NetworkConfig.builder().name(networkName).ipam(ipamToCreate).build();
    final NetworkCreation networkCreation = sut.createNetwork(networkingConfig);
    assertThat(networkCreation.id(), is(notNullValue()));
    final ContainerConfig containerConfig = ContainerConfig.builder().image(BUSYBOX_LATEST).cmd("sh", "-c", "while :; do sleep 1; done").build();
    final ContainerCreation containerCreation = sut.createContainer(containerConfig, containerName);
    assertThat(containerCreation.id(), is(notNullValue()));
    sut.startContainer(containerCreation.id());
    // Those are some of the extra parameters that can be set along with the network connection
    final String ip = "172.20.10.1";
    final String dummyAlias = "value-does-not-matter";
    final EndpointConfig endpointConfig = EndpointConfig.builder().ipamConfig(EndpointIpamConfig.builder().ipv4Address(ip).build()).aliases(ImmutableList.<String>of(dummyAlias)).build();
    final NetworkConnection networkConnection = NetworkConnection.builder().containerId(containerCreation.id()).endpointConfig(endpointConfig).build();
    sut.connectToNetwork(networkCreation.id(), networkConnection);
    Network network = sut.inspectNetwork(networkCreation.id());
    Network.Container networkContainer = network.containers().get(containerCreation.id());
    assertThat(network.containers().size(), equalTo(1));
    assertThat(networkContainer, notNullValue());
    final ContainerInfo containerInfo = sut.inspectContainer(containerCreation.id());
    assertThat(containerInfo.networkSettings().networks(), is(notNullValue()));
    assertThat(containerInfo.networkSettings().networks().size(), is(2));
    assertThat(containerInfo.networkSettings().networks(), hasKey(networkName));
    final AttachedNetwork attachedNetwork = containerInfo.networkSettings().networks().get(networkName);
    assertThat(attachedNetwork, is(notNullValue()));
    assertThat(attachedNetwork.networkId(), is(equalTo(networkCreation.id())));
    assertThat(attachedNetwork.endpointId(), is(notNullValue()));
    assertThat(attachedNetwork.gateway(), is(equalTo(gateway)));
    assertThat(attachedNetwork.ipAddress(), is(equalTo(ip)));
    assertThat(attachedNetwork.ipPrefixLen(), is(notNullValue()));
    assertThat(attachedNetwork.macAddress(), is(notNullValue()));
    assertThat(attachedNetwork.ipv6Gateway(), is(notNullValue()));
    assertThat(attachedNetwork.globalIPv6Address(), is(notNullValue()));
    assertThat(attachedNetwork.globalIPv6PrefixLen(), greaterThanOrEqualTo(0));
    assertThat(attachedNetwork.aliases(), is(notNullValue()));
    assertThat(dummyAlias, isIn(attachedNetwork.aliases()));
    sut.disconnectFromNetwork(containerCreation.id(), networkCreation.id());
    network = sut.inspectNetwork(networkCreation.id());
    assertThat(network.containers().size(), equalTo(0));
    sut.stopContainer(containerCreation.id(), 1);
    sut.removeContainer(containerCreation.id());
    sut.removeNetwork(networkCreation.id());
}
Also used : NetworkConnection(com.spotify.docker.client.messages.NetworkConnection) NetworkConfig(com.spotify.docker.client.messages.NetworkConfig) IpamConfig(com.spotify.docker.client.messages.IpamConfig) EndpointIpamConfig(com.spotify.docker.client.messages.EndpointConfig.EndpointIpamConfig) Long.toHexString(java.lang.Long.toHexString) Matchers.isEmptyOrNullString(org.hamcrest.Matchers.isEmptyOrNullString) Matchers.containsString(org.hamcrest.Matchers.containsString) NetworkCreation(com.spotify.docker.client.messages.NetworkCreation) ContainerConfig(com.spotify.docker.client.messages.ContainerConfig) AttachedNetwork(com.spotify.docker.client.messages.AttachedNetwork) Ipam(com.spotify.docker.client.messages.Ipam) ContainerCreation(com.spotify.docker.client.messages.ContainerCreation) AttachedNetwork(com.spotify.docker.client.messages.AttachedNetwork) Network(com.spotify.docker.client.messages.Network) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) EndpointConfig(com.spotify.docker.client.messages.EndpointConfig) Test(org.junit.Test)

Example 40 with ContainerInfo

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

the class DefaultDockerClientTest method testPidsLimit.

@Test
public void testPidsLimit() throws Exception {
    if (OsUtils.isLinux()) {
        assumeTrue("Linux kernel must be at least 4.3.", compareVersion(System.getProperty("os.version"), "4.3") >= 0);
    }
    requireDockerApiVersionAtLeast("1.23", "PidsLimit");
    // Pull image
    sut.pull(BUSYBOX_LATEST);
    final ContainerConfig config = ContainerConfig.builder().image(BUSYBOX_LATEST).hostConfig(HostConfig.builder().pidsLimit(// Defaults to -1
    100).build()).build();
    final ContainerCreation container = sut.createContainer(config, randomName());
    final ContainerInfo info = sut.inspectContainer(container.id());
    assertThat(info.hostConfig().pidsLimit(), is(100));
}
Also used : ContainerConfig(com.spotify.docker.client.messages.ContainerConfig) ContainerCreation(com.spotify.docker.client.messages.ContainerCreation) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) Test(org.junit.Test)

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