Java Code Examples for com.github.dockerjava.api.command.CreateContainerCmd#exec()

The following examples show how to use com.github.dockerjava.api.command.CreateContainerCmd#exec() . 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: 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 2
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 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: DockerImageExecutor.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> run(TestEnvironment testEnvironment) {
    String hostOsMountDir = System.getProperties().getProperty("buildDirectory");


    CreateContainerCmd containerBuilder = dockerClient.createContainerCmd(testEnvironment.getImage())
            .withBinds(new Bind(hostOsMountDir, new Volume(Constants.HAWKULAR_APM_AGENT_DIRECTORY),
                            AccessMode.ro, SELContext.shared),
                new Bind(scenarioDirectory, new Volume(Constants.HAWKULAR_APM_TEST_DIRECTORY),
                        AccessMode.ro, SELContext.shared))
            .withExtraHosts(Constants.HOST_ADDED_TO_ETC_HOSTS + ":" + apmBindAddress);

    if (userDefinedNetwork) {
        if (network == null) {
            throw new IllegalStateException("Create network before running environment");
        }
        containerBuilder.withNetworkMode(network.getName());
    }

    containerBuilder.withEnv(apmEnvVariables(testEnvironment.getType()));

    if (testEnvironment.isPull()) {
        log.info("Pulling image...");
        dockerClient.pullImageCmd(testEnvironment.getImage()).exec(new PullImageResultCallback()).awaitSuccess();
    }

    CreateContainerResponse containerResponse = containerBuilder.exec();
    log.info(String.format("Starting docker container: %s", containerResponse));

    try {
        dockerClient.startContainerCmd(containerResponse.getId()).exec();
    } catch (DockerException ex) {
        log.severe(String.format("Could not create or start docker container: %s", containerResponse));
        throw new EnvironmentException("Could not create or start docker container.", ex);
    }

    return Arrays.asList(containerResponse.getId());
}
 
Example 5
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 6
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 7
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 8
Source File: Docker.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public void createContainer(String imageId, String containerName, boolean mountFolders,
    String... env) {

  pullImageIfNecessary(imageId, false);

  log.debug("Creating container {}", containerName);

  CreateContainerCmd createContainerCmd =
      getClient().createContainerCmd(imageId).withName(containerName).withEnv(env)
      .withVolumes(new Volume("/var/run/docker.sock"));

  if (mountFolders) {
    mountDefaultFolders(createContainerCmd);
  }

  createContainerCmd.exec();

  log.debug("Container {} started...", containerName);

}
 
Example 9
Source File: Docker.java    From kurento-java with Apache License 2.0 3 votes vote down vote up
public void startNode(String id, BrowserType browserType, String nodeName, String imageId,
    boolean record) {
  // Create node
  pullImageIfNecessary(imageId, true);

  log.debug("Creating container for browser '{}'", id);

  CreateContainerCmd createContainerCmd =
      getClient().createContainerCmd(imageId).withPrivileged(true).withCapAdd(SYS_ADMIN).withName(nodeName);
  mountDefaultFolders(createContainerCmd);
  mountFiles(createContainerCmd);

  if (isRunningInContainer()) {
    createContainerCmd.withNetworkMode("bridge");
  }

  createContainerCmd.exec();
  log.debug("Container {} started...", nodeName);


  // Start node if stopped
  startContainer(nodeName);

  startRecordingIfNeeded(id, nodeName, record);

  logMounts(nodeName);

  logNetworks(nodeName);

  listFolderInContainer(nodeName, KurentoTest.getTestFilesDiskPath());
}
 
Example 10
Source File: Docker.java    From kurento-java with Apache License 2.0 3 votes vote down vote up
public void startNode(String id, BrowserType browserType, String nodeName, String imageId,
    boolean record, String containerIp) {
  // Create node
  pullImageIfNecessary(imageId, true);

  log.debug("Creating container for browser '{}'", id);

  CreateContainerCmd createContainerCmd =
      getClient().createContainerCmd(imageId).withPrivileged(true).withCapAdd(SYS_ADMIN).withName(nodeName);
  mountDefaultFolders(createContainerCmd);
  mountFiles(createContainerCmd);

  createContainerCmd.withNetworkMode("none");

  Map<String, String> labels = new HashMap<>();
  labels.put("KurentoDnat", "true");
  labels.put("Transport", getProperty(TEST_SELENIUM_TRANSPORT));
  labels.put("IpAddress", containerIp);

  createContainerCmd.withLabels(labels);

  createContainerCmd.exec();

  log.debug("Container {} started...", nodeName);

  // Start node if stopped
  startContainer(nodeName);

  startRecordingIfNeeded(id, nodeName, record);

  logMounts(nodeName);

  logNetworks(nodeName);
}