com.github.dockerjava.api.command.CreateContainerResponse Java Examples

The following examples show how to use com.github.dockerjava.api.command.CreateContainerResponse. 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: DockerBridgeTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithAContainerWithAPort() throws InterruptedException {
  CreateContainerResponse container = client.createContainerCmd("nginx")
      .withExposedPorts(ExposedPort.tcp(80), ExposedPort.tcp(443))
      .withPortBindings(PortBinding.parse("80"))
      .exec();

  AtomicBoolean done = new AtomicBoolean();
  Promise<Void> promise = Promise.promise();
  promise.future().onComplete(ar -> done.set(ar.succeeded()));
  bridge.scan(promise);
  await().untilAtomic(done, is(true));
  assertThat(bridge.getServices()).hasSize(0);

  done.set(false);
  client.startContainerCmd(container.getId()).exec();
  Promise<Void> promise2 = Promise.promise();
  promise2.future().onComplete(ar -> done.set(ar.succeeded()));
  bridge.scan(promise2);
  await().untilAtomic(done, is(true));

  assertThat(bridge.getServices()).hasSize(1);
  DockerService service = bridge.getServices().get(0);
  assertThat(service.records()).hasSize(1);
}
 
Example #3
Source File: RemoveImageCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void removeImage() throws DockerException, InterruptedException {

    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("Committing container {}", container.toString());
    String imageId = dockerRule.getClient().commitCmd(container.getId()).exec();

    dockerRule.getClient().stopContainerCmd(container.getId()).exec();
    dockerRule.getClient().removeContainerCmd(container.getId()).exec();

    LOG.info("Removing image: {}", imageId);
    dockerRule.getClient().removeImageCmd(imageId).exec();

    List<Container> containers = dockerRule.getClient().listContainersCmd().withShowAll(true).exec();

    Matcher matcher = not(hasItem(hasField("id", startsWith(imageId))));
    assertThat(containers, matcher);
}
 
Example #4
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 #5
Source File: DockerCloud.java    From docker-plugin with MIT License 6 votes vote down vote up
/**
 * for publishers/builders. Simply runs container in docker cloud
 */
public static String runContainer(DockerTemplateBase dockerTemplateBase,
                                  DockerClient dockerClient) {
    CreateContainerCmd containerConfig = dockerClient.createContainerCmd(dockerTemplateBase.getImage());

    dockerTemplateBase.fillContainerConfig(containerConfig);

    // create
    CreateContainerResponse response = containerConfig.exec();
    String containerId = response.getId();

    // start
    StartContainerCmd startCommand = dockerClient.startContainerCmd(containerId);
    startCommand.exec();

    return containerId;
}
 
Example #6
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = ConflictException.class)
public void createContainerWithName() throws DockerException {
    String containerName = "container_" + dockerRule.getKind();

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withName(containerName)
            .withCmd("env").exec();

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

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

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

    assertThat(inspectContainerResponse.getName(), equalTo("/" + containerName));

    dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withName(containerName)
            .withCmd("env")
            .exec();
}
 
Example #7
Source File: DockerJavaUtil.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * 创建容器
 *
 * @param client
 * @return
 */
public static CreateContainerResponse createContainers(DockerClient client, String containerName, String imageName, Map<Integer, Integer> ports) {//TODO 优化
    CreateContainerCmd createContainerCmd = client.createContainerCmd(imageName).withName(containerName);
    //TODO 处理端口映射
    if(!CollectionUtils.isEmpty(ports)){
        List<ExposedPort> exposedPorts = new ArrayList<>();
        Ports portBindings = new Ports();
        for (Map.Entry<Integer, Integer> entry : ports.entrySet()) {
            Integer key = entry.getKey();
            Integer value = entry.getValue();
            ExposedPort exposedPort = ExposedPort.tcp(key);
            exposedPorts.add(exposedPort);
            portBindings.bind(exposedPort, Ports.Binding.bindPort(value));
        }
        HostConfig hostConfig = newHostConfig().withPortBindings(portBindings);
        createContainerCmd .withHostConfig(hostConfig).withExposedPorts(exposedPorts);
    }
    return createContainerCmd.exec();
}
 
Example #8
Source File: StatsCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testStatsStreaming() throws InterruptedException, IOException {
    CountDownLatch countDownLatch = new CountDownLatch(NUM_STATS);

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("top").exec();

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

    boolean gotStats = false;
    try (StatsCallbackTest statsCallback = dockerRule.getClient()
        .statsCmd(container.getId())
        .exec(new StatsCallbackTest(countDownLatch))) {

        assertTrue(countDownLatch.await(10, TimeUnit.SECONDS));
        gotStats = statsCallback.gotStats();

        LOG.info("Stop stats collection");
    }

    LOG.info("Stopping container");
    dockerRule.getClient().stopContainerCmd(container.getId()).exec();
    dockerRule.getClient().removeContainerCmd(container.getId()).exec();

    LOG.info("Completed test");
    assertTrue("Expected true", gotStats);
}
 
Example #9
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 #10
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createContainerWithEnvAsMap() throws Exception {
    final String[] testVariables = {"VARIABLE1=success1", "VARIABLE2=success2"};

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withEnv(testVariables)
            .withCmd("env")
            .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.getConfig().getEnv()), hasItem(testVariables[0]));
    assertThat(Arrays.asList(inspectContainerResponse.getConfig().getEnv()), hasItem(testVariables[1]));

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

    assertThat(dockerRule.containerLog(container.getId()), containsString(testVariables[0]));
    assertThat(dockerRule.containerLog(container.getId()), containsString(testVariables[1]));
}
 
Example #11
Source File: StartContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = InternalServerErrorException.class)
public void startContainerWithConflictingPortBindings() throws DockerException {

    ExposedPort tcp22 = ExposedPort.tcp(22);
    ExposedPort tcp23 = ExposedPort.tcp(23);

    Ports portBindings = new Ports();
    portBindings.bind(tcp22, Binding.bindPort(11022));
    portBindings.bind(tcp23, Binding.bindPort(11022));

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("true")
            .withExposedPorts(tcp22, tcp23).withHostConfig(newHostConfig()
                    .withPortBindings(portBindings))
            .exec();

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

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

    dockerRule.getClient().startContainerCmd(container.getId()).exec();
}
 
Example #12
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 #13
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createContainerWithLabels() throws DockerException {

    Map<String, String> labels = new HashMap<>();
    labels.put("com.github.dockerjava.null", null);
    labels.put("com.github.dockerjava.Boolean", "true");

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE).withCmd("sleep", "9999")
            .withLabels(labels).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
    labels.put("com.github.dockerjava.null", "");

    // swarm adds 3d label
    assertThat(inspectContainerResponse.getConfig().getLabels(), allOf(
            hasEntry("com.github.dockerjava.null", ""),
            hasEntry("com.github.dockerjava.Boolean", "true")
    ));
}
 
Example #14
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 #15
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 #16
Source File: CopyArchiveToContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void copyDirWithLastAddedTarEntryEmptyDir() throws Exception{
    // create a temp dir
    Path localDir = Files.createTempDirectory(null);
    localDir.toFile().deleteOnExit();
    // create empty sub-dir with name b
    Files.createDirectory(localDir.resolve("b"));
    // create sub-dir with name a
    Path dirWithFile = Files.createDirectory(localDir.resolve("a"));
    // create file in sub-dir b, name or conter are irrelevant
    Files.createFile(dirWithFile.resolve("file"));

    // create a test container
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox")
            .withCmd("sleep", "9999")
            .exec();
    // start the container
    dockerRule.getClient().startContainerCmd(container.getId()).exec();
    // copy data from local dir to container
    dockerRule.getClient().copyArchiveToContainerCmd(container.getId())
            .withHostResource(localDir.toString())
            .exec();

    // cleanup dir
    FileUtils.deleteDirectory(localDir.toFile());
}
 
Example #17
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 #18
Source File: EventsCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
/**
 * This method generates some events and returns the number of events being generated
 */
private int generateEvents() throws Exception {
    String testImage = "busybox:latest";

    dockerRule.getClient().pullImageCmd(testImage).start().awaitCompletion();
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(testImage).withCmd("sleep", "9999").exec();
    dockerRule.getClient().startContainerCmd(container.getId()).exec();
    dockerRule.getClient().stopContainerCmd(container.getId()).withTimeout(1).exec();

    // generates 5 events with remote api 1.24:

    // Event[status=pull,id=busybox:latest,from=<null>,node=<null>,type=IMAGE,action=pull,actor=com.github.dockerjava.api.model.EventActor@417db6d7[id=busybox:latest,attributes={name=busybox}],time=1473455186,timeNano=1473455186436681587]
    // Event[status=create,id=6ec10182cde227040bfead8547b63105e6bbc4e94b99f6098bfad6e158ce0d3c,from=busybox:latest,node=<null>,type=CONTAINER,action=create,actor=com.github.dockerjava.api.model.EventActor@40bcec[id=6ec10182cde227040bfead8547b63105e6bbc4e94b99f6098bfad6e158ce0d3c,attributes={image=busybox:latest, name=sick_lamport}],time=1473455186,timeNano=1473455186470713257]
    // Event[status=<null>,id=<null>,from=<null>,node=<null>,type=NETWORK,action=connect,actor=com.github.dockerjava.api.model.EventActor@318a1b01[id=10870ceb13abb7cf841ea68868472da881b33c8ed08d2cde7dbb39d7c24d1d27,attributes={container=6ec10182cde227040bfead8547b63105e6bbc4e94b99f6098bfad6e158ce0d3c, name=bridge, type=bridge}],time=1473455186,timeNano=1473455186544318466]
    // Event[status=start,id=6ec10182cde227040bfead8547b63105e6bbc4e94b99f6098bfad6e158ce0d3c,from=busybox:latest,node=<null>,type=CONTAINER,action=start,actor=com.github.dockerjava.api.model.EventActor@606f43a3[id=6ec10182cde227040bfead8547b63105e6bbc4e94b99f6098bfad6e158ce0d3c,attributes={image=busybox:latest, name=sick_lamport}],time=1473455186,timeNano=1473455186786163819]
    // Event[status=kill,id=6ec10182cde227040bfead8547b63105e6bbc4e94b99f6098bfad6e158ce0d3c,from=busybox:latest,node=<null>,type=CONTAINER,action=kill,actor=com.github.dockerjava.api.model.EventActor@72a9ffcf[id=6ec10182cde227040bfead8547b63105e6bbc4e94b99f6098bfad6e158ce0d3c,attributes={image=busybox:latest, name=sick_lamport, signal=15}],time=1473455186,timeNano=1473455186792963392]

    return 5;
}
 
Example #19
Source File: WaitContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testWaitContainerTimeout() throws Exception {

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("sleep", "10").exec();

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

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

    WaitContainerResultCallback callback = dockerRule.getClient().waitContainerCmd(container.getId()).exec(
            new WaitContainerResultCallback());
    try {
        callback.awaitStatusCode(100, TimeUnit.MILLISECONDS);
        throw new AssertionError("Should throw exception on timeout.");
    } catch (DockerClientException e) {
        LOG.info(e.getMessage());
    }
}
 
Example #20
Source File: StatsCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testStatsNoStreaming() throws InterruptedException, IOException {
    CountDownLatch countDownLatch = new CountDownLatch(NUM_STATS);

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("top").exec();

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

    try (StatsCallbackTest statsCallback = dockerRule.getClient().statsCmd(container.getId())
        .withNoStream(true)
        .exec(new StatsCallbackTest(countDownLatch))) {
        countDownLatch.await(5, TimeUnit.SECONDS);

        LOG.info("Stop stats collection");
    }

    LOG.info("Stopping container");
    dockerRule.getClient().stopContainerCmd(container.getId()).exec();
    dockerRule.getClient().removeContainerCmd(container.getId()).exec();

    LOG.info("Completed test");
    assertEquals("Expected stats called only once", countDownLatch.getCount(), NUM_STATS - 1);
}
 
Example #21
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createContainerFromPrivateRegistryWithValidAuth() throws Exception {
    DockerAssume.assumeSwarm(dockerRule.getClient());

    AuthConfig authConfig = REGISTRY.getAuthConfig();

    String imgName = REGISTRY.createPrivateImage("create-container-with-valid-auth");

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(imgName)
            .withAuthConfig(authConfig)
            .exec();

    assertThat(container.getId(), is(notNullValue()));
}
 
Example #22
Source File: CopyArchiveToContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
private CreateContainerResponse prepareContainerForCopy(String method) {
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox")
            .withName("docker-java-itest-copyToContainer" + method + dockerRule.getKind())
            .exec();
    LOG.info("Created container: {}", container);
    assertThat(container.getId(), not(isEmptyOrNullString()));
    dockerRule.getClient().startContainerCmd(container.getId()).exec();
    // Copy a folder to the container
    return container;
}
 
Example #23
Source File: CopyArchiveToContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void copyStreamToContainerTwice() throws Exception {
    CreateContainerResponse container = prepareContainerForCopy("rerun");
    CopyArchiveToContainerCmd copyArchiveToContainerCmd=dockerRule.getClient().copyArchiveToContainerCmd(container.getId())
            .withHostResource("src/test/resources/testReadFile");
    copyArchiveToContainerCmd.exec();
    assertFileCopied(container);
    //run again to make sure no DockerClientException
    copyArchiveToContainerCmd.exec();
}
 
Example #24
Source File: CommitCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void commitWithLabels() throws DockerException {

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox")
            .withCmd("touch", "/test")
            .exec();

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

    Integer status = dockerRule.getClient().waitContainerCmd(container.getId())
            .start()
            .awaitStatusCode();

    assertThat(status, is(0));

    LOG.info("Committing container: {}", container.toString());
    Map<String, String> labels = ImmutableMap.of("label1", "abc", "label2", "123");
    String imageId = dockerRule.getClient().commitCmd(container.getId())
            .withLabels(labels)
            .exec();

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

    //use config here since containerConfig contains the configuration of the container which was
    //committed to the container
    //https://stackoverflow.com/questions/36216220/what-is-different-of-config-and-containerconfig-of-docker-inspect
    Map<String, String> responseLabels = inspectImageResponse.getConfig().getLabels();
    //swarm will attach additional labels here
    assertThat(responseLabels.size(), greaterThanOrEqualTo(2));
    assertThat(responseLabels.get("label1"), equalTo("abc"));
    assertThat(responseLabels.get("label2"), equalTo("123"));
}
 
Example #25
Source File: CopyArchiveToContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void copyStreamToContainer() throws Exception {
    CreateContainerResponse container = prepareContainerForCopy("2");
    dockerRule.getClient().copyArchiveToContainerCmd(container.getId())
            .withHostResource("src/test/resources/testReadFile")
            .exec();
    assertFileCopied(container);
}
 
Example #26
Source File: CopyArchiveToContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void copyFileToContainer() throws Exception {
    CreateContainerResponse container = prepareContainerForCopy("1");
    Path temp = Files.createTempFile("", ".tar.gz");
    CompressArchiveUtil.tar(Paths.get("src/test/resources/testReadFile"), temp, true, false);
    try (InputStream uploadStream = Files.newInputStream(temp)) {
        dockerRule.getClient()
                .copyArchiveToContainerCmd(container.getId())
                .withTarInputStream(uploadStream)
                .exec();
        assertFileCopied(container);
    }
}
 
Example #27
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 * https://github.com/calavera/docker/blob/3781cde61ff10b1d9114ae5b4c5c1d1b2c20a1ee/integration-cli/docker_cli_run_unix_test.go#L319-L333
 */
@Test
public void testWithStopSignal() throws Exception {
    Integer signal = 10; // SIGUSR1 in busybox

    CreateContainerResponse resp = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withCmd("/bin/sh", "-c", "trap 'echo \"exit trapped 10\"; exit 10' USR1; while true; do sleep 1; done")
            .withAttachStdin(true)
            .withTty(true)
            .withStopSignal(signal.toString())
            .exec();
    final String containerId = resp.getId();
    assertThat(containerId, not(is(emptyString())));
    dockerRule.getClient().startContainerCmd(containerId).exec();

    InspectContainerResponse inspect = dockerRule.getClient().inspectContainerCmd(containerId).exec();
    assertThat(inspect.getState().getRunning(), is(true));

    dockerRule.getClient().stopContainerCmd(containerId).exec();
    Thread.sleep(TimeUnit.SECONDS.toMillis(3));

    inspect = dockerRule.getClient().inspectContainerCmd(containerId).exec();
    assertThat(inspect.getState().getRunning(), is(false));
    assertThat(inspect.getState().getExitCode(), is(signal));

    StringBuilder stringBuilder = new StringBuilder();
    final StringBuilderLogReader callback = new StringBuilderLogReader(stringBuilder);
    dockerRule.getClient().logContainerCmd(containerId)
            .withStdErr(true)
            .withStdOut(true)
            .withTailAll()
            .exec(callback)
            .awaitCompletion();

    String log = callback.builder.toString();
    assertThat(log.trim(), is("exit trapped 10"));
}
 
Example #28
Source File: ListImagesCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
private String createDanglingImage() {
    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("Committing container {}", container.toString());
    String imageId = dockerRule.getClient().commitCmd(container.getId()).exec();

    dockerRule.getClient().stopContainerCmd(container.getId()).exec();
    dockerRule.getClient().removeContainerCmd(container.getId()).exec();
    return imageId;
}
 
Example #29
Source File: CopyArchiveFromContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void copyFromContainerBinaryFile() throws Exception {
    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withName("copyFromContainerBinaryFile" + dockerRule.getKind())
            .exec();

    LOG.info("Created container: {}", container);
    assertThat(container.getId(), not(isEmptyOrNullString()));

    Path temp = Files.createTempFile("", ".tar.gz");
    Path binaryFile = Paths.get("src/test/resources/testCopyFromArchive/binary.dat");
    CompressArchiveUtil.tar(binaryFile, temp, true, false);

    try (InputStream uploadStream = Files.newInputStream(temp)) {
        dockerRule.getClient().copyArchiveToContainerCmd(container.getId()).withTarInputStream(uploadStream).exec();
    }

    InputStream response = dockerRule.getClient().copyArchiveFromContainerCmd(container.getId(), "/binary.dat").exec();

    try (TarArchiveInputStream tarInputStream = new TarArchiveInputStream(response)) {
        TarArchiveEntry nextTarEntry = tarInputStream.getNextTarEntry();

        assertEquals(nextTarEntry.getName(), "binary.dat");
        try (InputStream binaryFileInputStream = Files.newInputStream(binaryFile, StandardOpenOption.READ)) {
            assertTrue(IOUtils.contentEquals(binaryFileInputStream, tarInputStream));
        }

        assertNull("Nothing except binary.dat is expected to be copied.", tarInputStream.getNextTarEntry());
    }
}
 
Example #30
Source File: DockerConnector.java    From cloudml with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String createContainerWithPorts(String image, int[] ports, String... command){
    ExposedPort[] exposedPorts=new ExposedPort[ports.length];
    for(int i=0;i < ports.length;i++){
        exposedPorts[i]=ExposedPort.tcp(ports[i]);
    }

    CreateContainerResponse container = dockerClient.createContainerCmd(image)
            .withCmd(command)
            .withExposedPorts(exposedPorts)
            .exec();
    return container.getId();
}