Java Code Examples for com.github.dockerjava.api.command.CreateContainerResponse#getId()

The following examples show how to use com.github.dockerjava.api.command.CreateContainerResponse#getId() . 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: DockerManager.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
public String createAndStartContainer(Option option) {
    StringVars defaultEnv = new StringVars(4);
    defaultEnv.put(Variables.App.Url, serverUrl);
    defaultEnv.put(Variables.Agent.Token, ApiAuth.LocalTaskToken);
    defaultEnv.put(Variables.Agent.Workspace, "/ws/");
    defaultEnv.put(Variables.Agent.PluginDir, "/ws/.plugins");

    CreateContainerCmd createContainerCmd = client.createContainerCmd(option.image)
            .withEnv(defaultEnv.merge(option.inputs).toList())
            .withCmd("/bin/bash", "-c", option.script);

    if (option.hasPlugin()) {
        createContainerCmd.withBinds(
                new Bind(option.pluginDir, new Volume("/ws/.plugins/" + option.plugin)));
    }

    CreateContainerResponse container = createContainerCmd.exec();
    String containerId = container.getId();
    client.startContainerCmd(container.getId()).exec();
    log.debug("Container {} been started", containerId);
    return containerId;
}
 
Example 2
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createContainerWithNetworkID() {
    assumeThat("API version should be >= 1.23", dockerRule, isGreaterOrEqual(VERSION_1_24));

    String networkName = "net-" + UUID.randomUUID().toString();
    Map<String, String> labels = new HashMap<>();
    labels.put("com.example.label", "test");
    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd().withName(networkName)
            .withLabels(labels).withAttachable(true).exec();
    String networkId = createNetworkResponse.getId();
    CreateContainerResponse createContainerResponse = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE).withLabels(labels).withCmd("true").exec();
    String containerId = createContainerResponse.getId();
    dockerRule.getClient().connectToNetworkCmd().withContainerId(containerId).withNetworkId(networkId).exec();
    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(containerId).exec();
    ContainerNetwork containerNetwork = inspectContainerResponse.getNetworkSettings().getNetworks().get(networkName);
    if (containerNetwork == null) {
        // swarm node used network id
        containerNetwork = inspectContainerResponse.getNetworkSettings().getNetworks().get(networkId);
    }
    assertThat(containerNetwork, notNullValue());
}
 
Example 3
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 4
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 5
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();
}
 
Example 6
Source File: DockerConnector.java    From cloudml with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String createContainer(String image, String... command){
    CreateContainerResponse container = dockerClient
            .createContainerCmd(image)
            .withCmd(command)
            .exec();
    return container.getId();
}
 
Example 7
Source File: BesuNode.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
private String createBesuContainer(final NodeConfiguration config) {
  final String genesisFilePath = genesisFilePath(config.getGenesisFilePath());
  LOG.info("Path to Genesis file: {}", genesisFilePath);
  final Volume genesisVolume = new Volume("/etc/besu/genesis.json");
  final Bind genesisBinding = new Bind(genesisFilePath, genesisVolume);
  final Bind privacyBinding = privacyVolumeBinding("enclave_key.pub");
  final List<Bind> bindings = Lists.newArrayList(genesisBinding, privacyBinding);

  try {
    final List<String> commandLineItems =
        Lists.newArrayList(
            "--genesis-file",
            genesisVolume.getPath(),
            "--logging",
            "DEBUG",
            "--miner-enabled",
            "--miner-coinbase",
            "1b23ba34ca45bb56aa67bc78be89ac00ca00da00",
            "--host-whitelist",
            "*",
            "--rpc-http-enabled",
            "--rpc-ws-enabled",
            "--rpc-http-apis",
            "ETH,NET,WEB3,EEA",
            "--privacy-enabled",
            "--privacy-public-key-file",
            privacyBinding.getVolume().getPath());

    config
        .getCors()
        .ifPresent(
            cors -> commandLineItems.addAll(Lists.newArrayList("--rpc-http-cors-origins", cors)));

    LOG.debug("besu command line {}", config);

    final HostConfig hostConfig =
        HostConfig.newHostConfig()
            .withPortBindings(httpRpcPortBinding(), wsRpcPortBinding())
            .withBinds(bindings);
    final CreateContainerCmd createBesu =
        docker
            .createContainerCmd(BESU_IMAGE)
            .withHostConfig(hostConfig)
            .withVolumes(genesisVolume)
            .withCmd(commandLineItems);

    LOG.info("Creating the Besu Docker container...");
    final CreateContainerResponse besu = createBesu.exec();
    LOG.info("Created Besu Docker container, id: " + besu.getId());
    return besu.getId();
  } catch (final NotFoundException e) {
    throw new RuntimeException(
        "Before you run the acceptance tests, execute 'docker pull hyperledger/besu:latest'", e);
  }
}
 
Example 8
Source File: CreateContainerWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    Map<String, Object> results = new HashMap<String, Object>();

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String containerName = (String) workItem.getParameter("ContainerName");
        String containerImageName = (String) workItem.getParameter("ContainerImageName");
        String containerCommand = (String) workItem.getParameter("ContainerCommand");
        String containerHostName = (String) workItem.getParameter("ContainerHostName");
        String containerEnv = (String) workItem.getParameter("ContainerEnv");
        String containerPortBindings = (String) workItem.getParameter("ContainerPortBindings");
        String containerBinds = (String) workItem.getParameter("ContainerBinds");

        if (dockerClient == null) {
            DockerClientConnector connector = new DockerClientConnector();
            dockerClient = connector.getDockerClient();
        }

        CreateContainerCmd createContainerCmd = dockerClient.createContainerCmd(containerImageName).withName(containerName);

        if (containerCommand != null) {
            createContainerCmd = createContainerCmd.withCmd(containerCommand);
        }

        if (containerHostName != null) {
            createContainerCmd = createContainerCmd.withHostName(containerHostName);
        }

        if (containerEnv != null) {
            createContainerCmd = createContainerCmd.withEnv(containerEnv);
        }

        if (containerPortBindings != null) {
            createContainerCmd = createContainerCmd.withPortBindings(PortBinding.parse(containerPortBindings));
        }

        if (containerBinds != null) {
            createContainerCmd = createContainerCmd.withBinds(Bind.parse(containerBinds));
        }

        CreateContainerResponse container = createContainerCmd.exec();

        if (container != null && container.getId() != null) {
            results.put(RESULTS_DOCUMENT,
                        container.getId());
        }

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Unable to create container: " + e.getMessage());
        handleException(e);
    }
}
 
Example 9
Source File: SchedulerMainSystemTest.java    From elasticsearch with Apache License 2.0 4 votes vote down vote up
private String startContainer(CreateContainerCmd createCommand) {
    CreateContainerResponse r = createCommand.exec();
    String containerId = r.getId();
    getDockerClient().startContainerCmd(containerId).exec();
    return containerId;
}
 
Example 10
Source File: DockerHandler.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public void startContainer( String imageName, String volumePath ) throws Exception {
        if (hasImage(imageName) == null) {
            throw new ModelsRuntimeException(
                    "The image " + imageName + " could not be found your system. Please run the GdalInstaller command first.",
                    this);
        }

//      List<Container> containers = dockerClient.listContainersCmd()
//              .withShowSize(true)
//              .withShowAll(true)
//              .withStatusFilter("exited").exec()

        String ts = DateTime.now().toString(HMConstants.dateTimeFormatterYYYYMMDDHHMMSScompact);

        String name = imageName.replace('/', '_').replace(':', '_');

        CreateContainerResponse container;
        if (volumePath != null) {
            Volume v = new Volume(WORKSPACE);
            container = dockerClient.createContainerCmd(imageName)//
                    .withCmd(keepAliveCmd)//
                    .withName(name + ts)//
                    .withWorkingDir(WORKSPACE)//
                    .withBinds(new Bind(volumePath, v))//
                    .exec();
        } else {
            container = dockerClient.createContainerCmd(imageName)//
                    .withCmd(keepAliveCmd)//
                    .withName(name + ts)//
                    .exec();
        }

        containerId = container.getId();
        dockerClient.startContainerCmd(containerId).exec();

        InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(containerId).exec();

        if (!inspectContainerResponse.getState().getRunning()) {
            throw new ModelsRuntimeException("Container not running.", this);
        }
    }
 
Example 11
Source File: PrivateRegistryRule.java    From docker-java with Apache License 2.0 4 votes vote down vote up
/**
 * Starts a local test registry when it is not already started and returns the auth configuration for it
 * This method is synchronized so that only the first invocation starts the registry
 */
@Override
protected void before() throws Throwable {

    int port = 5050;

    String imageName = "private-registry-image";

    File baseDir = new File(DockerRule.class.getResource("/privateRegistry").getFile());

    String registryImageId = dockerClient.buildImageCmd(baseDir)
            .withNoCache(true)
            .start()
            .awaitImageId();

    InspectImageResponse inspectImageResponse = dockerClient.inspectImageCmd(registryImageId).exec();
    assertThat(inspectImageResponse, not(nullValue()));
    DockerRule.LOG.info("Image Inspect: {}", inspectImageResponse.toString());

    dockerClient.tagImageCmd(registryImageId, imageName, "2")
            .withForce().exec();

    // see https://github.com/docker/distribution/blob/master/docs/deploying.md#native-basic-auth
    CreateContainerResponse testregistry = dockerClient
            .createContainerCmd(imageName + ":2")
            .withHostConfig(newHostConfig()
                    .withPortBindings(new PortBinding(Ports.Binding.bindPort(port), ExposedPort.tcp(5000))))
            .withEnv("REGISTRY_AUTH=htpasswd", "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm",
                    "REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd", "REGISTRY_LOG_LEVEL=debug",
                    "REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt", "REGISTRY_HTTP_TLS_KEY=/certs/domain.key")
            .exec();

    containerId = testregistry.getId();
    dockerClient.startContainerCmd(containerId).exec();

    // wait for registry to boot
    Thread.sleep(3000);

    // credentials as configured in /auth/htpasswd
    authConfig = new AuthConfig()
            .withUsername("testuser")
            .withPassword("testpassword")
            .withRegistryAddress("localhost:" + port);
}
 
Example 12
Source File: UpdateContainerCmdIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
    public void updateContainer() throws DockerException, IOException {
        assumeThat("API version should be >= 1.22", dockerRule, isGreaterOrEqual(VERSION_1_22));

        CreateContainerResponse response = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
                .withCmd("sleep", "9999")
                .exec();

        String containerId = response.getId();
        dockerRule.getClient().startContainerCmd(containerId).exec();

        InspectContainerResponse inspectBefore = dockerRule.getClient().inspectContainerCmd(containerId).exec();
        LOG.debug("Inspect: {}", inspectBefore);
        final Long memory = inspectBefore.getHostConfig().getMemory();

        dockerRule.getClient().updateContainerCmd(containerId)
                .withBlkioWeight(300)
                .withCpuShares(512)
                .withCpuPeriod(100000)
                .withCpuQuota(50000)
//                .withCpusetCpus("0") // depends on env
                .withCpusetMems("0")
//                .withMemory(209715200L + 2L)
//                .withMemorySwap(514288000L) Your kernel does not support swap limit capabilities, memory limited without swap.
//                .withMemoryReservation(209715200L)
//                .withKernelMemory(52428800) Can not update kernel memory to a running container, please stop it first.
                .exec();

        // true only on docker toolbox (1.10.1)
//        assertThat(updateResponse.getWarnings(), hasSize(1));
//        assertThat(updateResponse.getWarnings().get(0),
//                is("Your kernel does not support Block I/O weight. Weight discarded."));

        InspectContainerResponse inspectAfter = dockerRule.getClient().inspectContainerCmd(containerId).exec();
        final HostConfig afterHostConfig = inspectAfter.getHostConfig();

//        assertThat(afterHostConfig.getMemory(), is(209715200L + 2L));

//        assertThat(afterHostConfig.getBlkioWeight(), is(300));
        assertThat(afterHostConfig.getCpuShares(), is(512));
        assertThat(afterHostConfig.getCpuPeriod(), is(100000L));
        assertThat(afterHostConfig.getCpuQuota(), is(50000L));
        assertThat(afterHostConfig.getCpusetMems(), is("0"));

//        assertThat(afterHostConfig.getMemoryReservation(), is(209715200L));
//       assertThat(afterHostConfig.getMemorySwap(), is(514288000L));

    }