com.github.dockerjava.api.exception.DockerException Java Examples

The following examples show how to use com.github.dockerjava.api.exception.DockerException. 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: SocketPoolManager.java    From flow-platform-x with Apache License 2.0 8 votes vote down vote up
@Override
public void start(StartContext context) throws DockerPoolException {
    try {
        final String name = name(context.getAgentName());
        final Path srcDirOnHost = UnixHelper.replacePathWithEnv(context.getDirOnHost());

        CreateContainerResponse container = client.createContainerCmd(AgentContainer.Image).withName(name)
                .withEnv(String.format("%s=%s", SERVER_URL, context.getServerUrl()),
                        String.format("%s=%s", AGENT_TOKEN, context.getToken()),
                        String.format("%s=%s", AGENT_LOG_LEVEL, context.getLogLevel()))
                .withBinds(
                        new Bind(srcDirOnHost.toString(), new Volume("/root/.flow.ci.agent")),
                        new Bind("/var/run/docker.sock", new Volume("/var/run/docker.sock")))
                .exec();

        client.startContainerCmd(container.getId()).exec();
    } catch (DockerException e) {
        throw new DockerPoolException(e);
    }
}
 
Example #2
Source File: CreateVolumeCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createVolumeWithExistingName() throws DockerException {

    String volumeName = "volume1";

    CreateVolumeResponse createVolumeResponse1 = dockerRule.getClient().createVolumeCmd().withName(volumeName)
            .withDriver("local").withLabels(Collections.singletonMap("is-timelord", "yes")).exec();

    assertThat(createVolumeResponse1.getName(), equalTo(volumeName));
    assertThat(createVolumeResponse1.getDriver(), equalTo("local"));
    assertThat(createVolumeResponse1.getLabels(), equalTo(Collections.singletonMap("is-timelord", "yes")));
    assertThat(createVolumeResponse1.getMountpoint(), containsString("/volume1/"));

    CreateVolumeResponse createVolumeResponse2 = dockerRule.getClient().createVolumeCmd().withName(volumeName)
            .withDriver("local").withLabels(Collections.singletonMap("is-timelord", "yes")).exec();

    assertThat(createVolumeResponse2.getName(), equalTo(volumeName));
    assertThat(createVolumeResponse2.getDriver(), equalTo("local"));
    assertThat(createVolumeResponse2.getLabels(), equalTo(Collections.singletonMap("is-timelord", "yes")));
    assertThat(createVolumeResponse2.getMountpoint(), equalTo(createVolumeResponse1.getMountpoint()));
}
 
Example #3
Source File: PullImageCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testPullImageWithNoAuth() throws Exception {
    AuthConfig authConfig = REGISTRY.getAuthConfig();

    String imgName = REGISTRY.createPrivateImage("pull-image-with-no-auth");

    if (isNotSwarm(dockerRule.getClient()) && getVersion(dockerRule.getClient())
            .isGreaterOrEqual(RemoteApiVersion.VERSION_1_30)) {
        exception.expect(DockerException.class);
    } else {
        exception.expect(DockerClientException.class);
    }

    // stream needs to be fully read in order to close the underlying connection
    dockerRule.getClient().pullImageCmd(imgName)
            .start()
            .awaitCompletion(30, TimeUnit.SECONDS);
}
 
Example #4
Source File: SocketPoolManager.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Override
public void start(StartContext context) throws DockerPoolException {
    try {
        final String name = name(context.getAgentName());
        final Path srcDirOnHost = UnixHelper.replacePathWithEnv(context.getDirOnHost());

        CreateContainerResponse container = client.createContainerCmd(AgentContainer.Image).withName(name)
                .withEnv(String.format("%s=%s", SERVER_URL, context.getServerUrl()),
                        String.format("%s=%s", AGENT_TOKEN, context.getToken()),
                        String.format("%s=%s", AGENT_LOG_LEVEL, context.getLogLevel()),
                        String.format("%s=%s", AGENT_WORKSPACE, "/ws"),
                        String.format("%s=%s", AGENT_VOLUMES, System.getenv(AGENT_VOLUMES)))
                .withBinds(
                        new Bind(srcDirOnHost.toString(), new Volume("/ws")),
                        new Bind("/var/run/docker.sock", new Volume("/var/run/docker.sock")))
                .exec();

        client.startContainerCmd(container.getId()).exec();
    } catch (DockerException e) {
        throw new DockerPoolException(e);
    }
}
 
Example #5
Source File: ContainerDiffCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testContainerDiff() throws DockerException {
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE).withCmd("touch", "/test").exec();
    LOG.info("Created container: {}", container.toString());
    assertThat(container.getId(), not(is(emptyString())));
    dockerRule.getClient().startContainerCmd(container.getId()).exec();

    int exitCode = dockerRule.getClient().waitContainerCmd(container.getId()).start()
            .awaitStatusCode();
    assertThat(exitCode, equalTo(0));

    List<ChangeLog> filesystemDiff = dockerRule.getClient().containerDiffCmd(container.getId()).exec();
    LOG.info("Container DIFF: {}", filesystemDiff.toString());

    assertThat(filesystemDiff.size(), equalTo(1));
    ChangeLog testChangeLog = selectUnique(filesystemDiff, hasField("path", equalTo("/test")));

    assertThat(testChangeLog, hasField("path", equalTo("/test")));
    assertThat(testChangeLog, hasField("kind", equalTo(1)));
}
 
Example #6
Source File: KillContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void killContainer() throws DockerException {

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("sleep", "9999").exec();
    LOG.info("Created container: {}", container.toString());
    assertThat(container.getId(), not(is(emptyString())));
    dockerRule.getClient().startContainerCmd(container.getId()).exec();

    LOG.info("Killing container: {}", container.getId());
    dockerRule.getClient().killContainerCmd(container.getId()).exec();

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();
    LOG.info("Container Inspect: {}", inspectContainerResponse.toString());

    assertThat(inspectContainerResponse.getState().getRunning(), is(equalTo(false)));
    assertThat(inspectContainerResponse.getState().getExitCode(), not(equalTo(0)));

}
 
Example #7
Source File: JerseyDockerHttpClient.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
public Response execute(Request request) {
    if (request.hijackedInput() != null) {
        throw new UnsupportedOperationException("Does not support hijacking");
    }
    String url = sanitizeUrl(originalUri).toString();
    if (url.endsWith("/") && request.path().startsWith("/")) {
        url = url.substring(0, url.length() - 1);
    }

    Invocation.Builder builder = client.target(url + request.path()).request();

    request.headers().forEach(builder::header);

    try {
        return new JerseyResponse(
            builder.build(request.method(), toEntity(request)).invoke()
        );
    } catch (ProcessingException e) {
        if (e.getCause() instanceof DockerException) {
            throw (DockerException) e.getCause();
        }
        throw e;
    }
}
 
Example #8
Source File: InspectContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test()
public void inspectContainerWithSize() throws DockerException {

    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())));

    InspectContainerCmd command = dockerRule.getClient().inspectContainerCmd(container.getId()).withSize(true);
    assertTrue(command.getSize());
    InspectContainerResponse containerInfo = command.exec();
    assertEquals(containerInfo.getId(), container.getId());

    // TODO check swarm
    if (isNotSwarm(dockerRule.getClient())) {
        assertNotNull(containerInfo.getSizeRootFs());
        assertTrue(containerInfo.getSizeRootFs().intValue() > 0);
    }
}
 
Example #9
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createContainerWithMemorySwappiness() throws DockerException {
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withCmd("sleep", "9999")
            .withHostConfig(newHostConfig()
                    .withMemorySwappiness(42L))
            .exec();
    assertThat(container.getId(), not(is(emptyString())));
    LOG.info("Created container {}", container.toString());

    dockerRule.getClient().startContainerCmd(container.getId()).exec();
    LOG.info("Started container {}", container.toString());

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient()
            .inspectContainerCmd(container.getId())
            .exec();
    LOG.info("Container Inspect: {}", inspectContainerResponse.toString());
    assertSame(42L, inspectContainerResponse.getHostConfig().getMemorySwappiness());
}
 
Example #10
Source File: DockerBuilderControlOptionRun.java    From docker-plugin with MIT License 6 votes vote down vote up
private void executePullOnDocker(Run<?, ?> build, PrintStream llog, String xImage, DockerClient client)
        throws DockerException {
    PullImageResultCallback resultCallback = new PullImageResultCallback() {
        @Override
        public void onNext(PullResponseItem item) {
            if (item.getStatus() != null && item.getProgress() == null) {
                llog.print(item.getId() + ":" + item.getStatus());
                LOG.info("{} : {}", item.getId(), item.getStatus());
            }
            super.onNext(item);
        }
    };

    PullImageCmd cmd = client.pullImageCmd(xImage);
    DockerCloud.setRegistryAuthentication(cmd, getRegistry(), build.getParent().getParent());
    try {
        cmd.exec(resultCallback).awaitCompletion();
    } catch (InterruptedException e) {
        throw new DockerClientException("Interrupted while pulling image", e);
    }
}
 
Example #11
Source File: InspectNetworkCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void inspectNetwork() throws DockerException {
    assumeNotSwarm("no network in swarm", dockerRule);

    List<Network> networks = dockerRule.getClient().listNetworksCmd().exec();

    Network expected = findNetwork(networks, "bridge");

    Network network = dockerRule.getClient().inspectNetworkCmd().withNetworkId(expected.getId()).exec();

    assertThat(network.getName(), equalTo(expected.getName()));
    assertThat(network.getScope(), equalTo(expected.getScope()));
    assertThat(network.getDriver(), equalTo(expected.getDriver()));
    assertThat(network.getIpam().getConfig().get(0).getSubnet(), equalTo(expected.getIpam().getConfig().get(0).getSubnet()));
    assertThat(network.getIpam().getDriver(), equalTo(expected.getIpam().getDriver()));
}
 
Example #12
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createContainerWithLogConfig() throws DockerException {

    LogConfig logConfig = new LogConfig(LogConfig.LoggingType.NONE, null);
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withHostConfig(newHostConfig()
                    .withLogConfig(logConfig))
            .exec();

    LOG.info("Created container {}", container.toString());

    assertThat(container.getId(), not(is(emptyString())));

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();

    // null becomes empty string
    assertThat(inspectContainerResponse.getHostConfig().getLogConfig().type, is(logConfig.type));
}
 
Example #13
Source File: DockerBuilderControlOptionRun.java    From docker-plugin with MIT License 6 votes vote down vote up
private void executeOnDocker(Run<?, ?> build, PrintStream llog, String xImage, String xCommand, String xHostname, String xUser, DockerClient client)
        throws DockerException {
    try {
        client.inspectImageCmd(xImage).exec();
    } catch (NotFoundException e) {
        throw new DockerClientException("Failed to pull image: " + image, e);
    }

    DockerTemplateBase template = new DockerSimpleTemplate(
            xImage, pullCredentialsId, dnsString, network, xCommand, volumesString, volumesFrom,
            environmentsString, xHostname, xUser, extraGroupsString, memoryLimit, memorySwap, cpuShares,
            shmSize, bindPorts, bindAllPorts, privileged, tty, macAddress, null);

    LOG.info("Starting container for image {}", xImage);
    llog.println("Starting container for image " + xImage);
    String containerId = DockerCloud.runContainer(template, client);

    LOG.info("Started container {}", containerId);
    llog.println("Started container " + containerId);

    getLaunchAction(build).started(client, containerId);
}
 
Example #14
Source File: LeaveSwarmCmdExecIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void leaveSwarmAsMaster() throws DockerException {
    DockerClient dockerClient = startSwarm();

    Info info = dockerClient.infoCmd().exec();
    LOG.info("Inspected docker: {}", info.toString());

    assertThat(info.getSwarm().getLocalNodeState(), is(LocalNodeState.ACTIVE));

    dockerClient.leaveSwarmCmd()
            .withForceEnabled(true)
            .exec();
    LOG.info("Left swarm");

    info = dockerClient.infoCmd().exec();
    LOG.info("Inspected docker: {}", info.toString());

    assertThat(info.getSwarm().getLocalNodeState(), is(LocalNodeState.INACTIVE));

}
 
Example #15
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
/**
 * This tests support for --net option for the docker run command: --net="bridge" Set the Network mode for the container 'bridge':
 * creates a new network stack for the container on the docker bridge 'none': no networking for this container 'container:': reuses
 * another container network stack 'host': use the host network stack inside the container. Note: the host mode gives the container full
 * access to local system services such as D-bus and is therefore considered insecure.
 */
@Test
public void createContainerWithNetworkMode() throws DockerException {

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE).withCmd("true")
            .withHostConfig(newHostConfig()
                    .withNetworkMode("host"))
            .exec();

    LOG.info("Created container {}", container.toString());

    assertThat(container.getId(), not(is(emptyString())));

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();

    assertThat(inspectContainerResponse.getHostConfig().getNetworkMode(), is(equalTo("host")));
}
 
Example #16
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createContainerWithNanoCPUs() throws DockerException {
    Long nanoCPUs = 1000000000L;

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
        .withCmd("sleep", "9999")
        .withHostConfig(newHostConfig()
            .withNanoCPUs(nanoCPUs))
        .exec();

    LOG.info("Created container {}", container.toString());

    assertThat(container.getId(), not(is(emptyString())));

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();

    assertThat(inspectContainerResponse.getHostConfig().getNanoCPUs(), is(nanoCPUs));
}
 
Example #17
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createContainerWithDns() throws DockerException {

    String aDnsServer = "8.8.8.8";
    String anotherDnsServer = "8.8.4.4";

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE).withCmd("true")
            .withHostConfig(newHostConfig()
                    .withDns(aDnsServer, anotherDnsServer))
            .exec();

    LOG.info("Created container {}", container.toString());

    assertThat(container.getId(), not(is(emptyString())));

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();

    assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDns()),
            contains(aDnsServer, anotherDnsServer));
}
 
Example #18
Source File: CreateServiceCmdExecIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateServiceWithValidAuth() throws DockerException {
    dockerClient.createServiceCmd(new ServiceSpec()
            .withName(SERVICE_NAME)
            .withTaskTemplate(new TaskSpec()
                    .withContainerSpec(new ContainerSpec()
                            .withImage(DEFAULT_IMAGE))))
            .withAuthConfig(authConfig)
            .exec();

    List<Service> services = dockerClient.listServicesCmd()
            .withNameFilter(Lists.newArrayList(SERVICE_NAME))
            .exec();

    assertThat(services, hasSize(1));

    dockerClient.removeServiceCmd(SERVICE_NAME).exec();
}
 
Example #19
Source File: CreateServiceCmdExecIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateService() throws DockerException {
    dockerClient.createServiceCmd(new ServiceSpec()
            .withName(SERVICE_NAME)
            .withTaskTemplate(new TaskSpec()
                    .withContainerSpec(new ContainerSpec()
                            .withImage(DEFAULT_IMAGE))))
            .exec();

    List<Service> services = dockerClient.listServicesCmd()
            .withNameFilter(Lists.newArrayList(SERVICE_NAME))
            .exec();

    assertThat(services, hasSize(1));

    dockerClient.removeServiceCmd(SERVICE_NAME).exec();
}
 
Example #20
Source File: StartContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void existingHostConfigIsPreservedByBlankStartCmd() throws DockerException {

    String dnsServer = "8.8.8.8";

    // prepare a container with custom DNS
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox")
            .withHostConfig(newHostConfig()
                    .withDns(dnsServer))
            .withCmd("true").exec();

    LOG.info("Created container {}", container.toString());

    assertThat(container.getId(), not(is(emptyString())));

    // start container _without_any_customization_ (important!)
    dockerRule.getClient().startContainerCmd(container.getId()).exec();

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();

    // The DNS setting survived.
    assertThat(inspectContainerResponse.getHostConfig().getDns(), is(notNullValue()));
    assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDns()), contains(dnsServer));
}
 
Example #21
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createContainerWithIntegerBoundsExceedingULimit() throws DockerException {
    String containerName = "containercoreulimit" + dockerRule.getKind();
    Ulimit[] ulimits = {new Ulimit("core", 99999999998L, 99999999999L)};

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withName(containerName)
            .withHostConfig(newHostConfig()
                    .withUlimits(ulimits))
            .exec();

    LOG.info("Created container {}", container.toString());

    assertThat(container.getId(), not(is(emptyString())));

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();

    assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getUlimits()),
            contains(new Ulimit("core", 99999999998L, 99999999999L)));

}
 
Example #22
Source File: DockerPublisherControl.java    From docker-plugin with MIT License 5 votes vote down vote up
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    try {
        new DockerBuilderControlOptionStopAll(remove).execute(build, launcher, listener);
    } catch (DockerException e) {
        throw new RuntimeException(e);
    }
    return true;
}
 
Example #23
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createContainerWithTmpFs() throws DockerException {
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE).withCmd("sleep", "9999")
            .withHostConfig(new HostConfig().withTmpFs(Collections.singletonMap("/tmp", "rw,noexec,nosuid,size=50m"))).exec();

    assertThat(container.getId(), not(is(emptyString())));

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();
    assertThat(inspectContainerResponse.getHostConfig().getTmpFs().get("/tmp"), equalTo("rw,noexec,nosuid,size=50m"));
}
 
Example #24
Source File: SocketPoolManager.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String name) throws DockerPoolException {
    try {
        client.removeContainerCmd(findContainer(name).getId()).withForce(true).exec();
    } catch (DockerException e) {
        throw new DockerPoolException(e);
    }
}
 
Example #25
Source File: DockerBuilderControlOptionStop.java    From docker-plugin with MIT License 5 votes vote down vote up
@Override
public void execute(Run<?, ?> build, Launcher launcher, TaskListener listener)
        throws DockerException {
    final PrintStream llog = listener.getLogger();
    LOG.info("Stopping container " + containerId);
    llog.println("Stopping container " + containerId);

    final DockerCloud cloud = getCloud(build, launcher);
    final DockerAPI dockerApi = cloud.getDockerApi();
    try(final DockerClient client = dockerApi.getClient()) {
        executeOnDocker(build, llog, client);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #26
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("Duplicates")
@Test
public void createContainerWithShmSize() throws DockerException {
    HostConfig hostConfig = new HostConfig().withShmSize(96 * FileUtils.ONE_MB);
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withHostConfig(hostConfig).withCmd("true").exec();

    LOG.info("Created container {}", container.toString());

    assertThat(container.getId(), not(is(emptyString())));

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();

    assertThat(inspectContainerResponse.getHostConfig().getShmSize(), is(hostConfig.getShmSize()));
}
 
Example #27
Source File: DockerBuilderPublisher.java    From docker-plugin with MIT License 5 votes vote down vote up
private void pushImages() throws IOException {
    for (String tagToUse : tagsToUse) {
        Identifier identifier = Identifier.fromCompoundString(tagToUse);
        PushImageResultCallback resultCallback = new PushImageResultCallback() {
            @Override
            public void onNext(PushResponseItem item) {
                if (item == null) {
                    // docker-java not happy if you pass it nulls.
                    log("Received NULL Push Response. Ignoring");
                    return;
                }
                printResponseItemToListener(listener, item);
                super.onNext(item);
            }
        };
        try(final DockerClient client = getClientWithNoTimeout()) {
            PushImageCmd cmd = client.pushImageCmd(identifier);

            int i = identifier.repository.name.indexOf('/');
            String regName = i >= 0 ?
                    identifier.repository.name.substring(0,i) : null;

            DockerCloud.setRegistryAuthentication(cmd,
                    new DockerRegistryEndpoint(regName, getPushCredentialsId()),
                    run.getParent().getParent());
            cmd.exec(resultCallback).awaitSuccess();
        } catch (DockerException ex) {
            // Private Docker registries fall over regularly. Tell the user so they
            // have some clue as to what to do as the exception gives no hint.
            log("Exception pushing docker image. Check that the destination registry is running.");
            throw ex;
        }
    }
}
 
Example #28
Source File: UpdateSwarmCmdExecIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void updateSwarm() throws DockerException {
    DockerClient dockerClient = startSwarm();

    SwarmSpec newSpec = new SwarmSpec()
            .withName("default")
            .withDispatcher(new SwarmDispatcherConfig()
                    .withHeartbeatPeriod(10000000L)
            ).withOrchestration(new SwarmOrchestration()
                    .withTaskHistoryRententionLimit(100)
            ).withCaConfig(new SwarmCAConfig()
                    .withNodeCertExpiry(60 * 60 * 1000000000L /*ns */))
            .withRaft(new SwarmRaftConfig()
                    .withElectionTick(8)
                    .withSnapshotInterval(20000)
                    .withHeartbeatTick(5)
                    .withLogEntriesForSlowFollowers(200)
            ).withTaskDefaults(new TaskDefaults());

    Swarm swarm = dockerClient.inspectSwarmCmd().exec();
    LOG.info("Inspected swarm: {}", swarm.toString());
    assertThat(swarm.getSpec(), is(not(equalTo(newSpec))));

    dockerClient.updateSwarmCmd(newSpec)
            .withVersion(swarm.getVersion().getIndex())
            .exec();
    LOG.info("Updated swarm: {}", newSpec.toString());

    swarm = dockerClient.inspectSwarmCmd().exec();
    LOG.info("Inspected swarm: {}", swarm.toString());
    assertThat(swarm.getSpec(), is(equalTo(newSpec)));
}
 
Example #29
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createContainerWithCustomIp() throws DockerException {
    String containerName1 = "containerCustomIplink_" + dockerRule.getKind();
    String networkName = "customIpNet" + dockerRule.getKind();
    String subnetPrefix = getFactoryType().getSubnetPrefix() + "101";

    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd()
            .withIpam(new Network.Ipam()
                    .withConfig(new Network.Ipam.Config()
                            .withSubnet(subnetPrefix + ".0/24")))
            .withDriver("bridge")
            .withName(networkName)
            .exec();

    assertNotNull(createNetworkResponse.getId());

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withHostConfig(newHostConfig()
                    .withNetworkMode(networkName))
            .withCmd("sleep", "9999")
            .withName(containerName1)
            .withIpv4Address(subnetPrefix + ".100")
            .exec();

    assertThat(container.getId(), not(is(emptyString())));

    dockerRule.getClient().startContainerCmd(container.getId()).exec();

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient()
            .inspectContainerCmd(container.getId())
            .exec();

    ContainerNetwork customIpNet = inspectContainerResponse.getNetworkSettings().getNetworks().get(networkName);
    assertNotNull(customIpNet);
    assertThat(customIpNet.getGateway(), is(subnetPrefix + ".1"));
    assertThat(customIpNet.getIpAddress(), is(subnetPrefix + ".100"));
}
 
Example #30
Source File: CommitCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void commit() throws DockerException, InterruptedException {
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withCmd("touch", "/test")
            .exec();

    LOG.info("Created container: {}", container.toString());
    assertThat(container.getId(), not(is(emptyString())));
    dockerRule.getClient().startContainerCmd(container.getId()).exec();

    LOG.info("Committing container: {}", container.toString());
    String imageId = dockerRule.getClient().commitCmd(container.getId()).exec();

    //swarm needs some time to reflect new images
    synchronized (this) {
        wait(5000);
    }

    InspectImageResponse inspectImageResponse = dockerRule.getClient().inspectImageCmd(imageId).exec();
    LOG.info("Image Inspect: {}", inspectImageResponse.toString());

    assertThat(inspectImageResponse, hasField("container", startsWith(container.getId())));
    assertThat(inspectImageResponse.getContainerConfig().getImage(), equalTo(DEFAULT_IMAGE));

    InspectImageResponse busyboxImg = dockerRule.getClient().inspectImageCmd("busybox").exec();

    assertThat(inspectImageResponse.getParent(), equalTo(busyboxImg.getId()));
}