com.github.dockerjava.api.model.Bind Java Examples

The following examples show how to use com.github.dockerjava.api.model.Bind. 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: 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 #3
Source File: CustomSettingsDockerSystemTest.java    From elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected CreateContainerCmd dockerCommand() {
    return dockerClient
            .createContainerCmd(TEST_CONFIG.getSchedulerImageName())
            .withName(TEST_CONFIG.getSchedulerName() + "_" + clusterId + "_" + new SecureRandom().nextInt())
            .withBinds(new Bind(CUSTOM_CONFIG_PATH, new Volume(CUSTOM_CONFIG_PATH), AccessMode.ro))
            .withEnv("JAVA_OPTS=-Xms128m -Xmx256m")
            .withCmd(
                    ElasticsearchCLIParameter.ELASTICSEARCH_SETTINGS_LOCATION, configPath,
                    ZookeeperCLIParameter.ZOOKEEPER_MESOS_URL, getZookeeperMesosUrl(),
                    ELASTICSEARCH_CPU, "0.25",
                    ELASTICSEARCH_RAM, "256",
                    ELASTICSEARCH_DISK, "10",
                    USE_IP_ADDRESS, "true"
            );
}
 
Example #4
Source File: ElasticsearchAuthSystemTest.java    From elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Use an alpine image to write files to the VM/docker host. Then all the containers can mount that DIR and get access to the passwd files.
 */
private void writePasswordFileToVM() {
    // Mesos password
    CreateContainerResponse exec = dockerClient.createContainerCmd(ALPINE)
            .withBinds(new Bind(SECRET_FOLDER, new Volume(SECRET_FOLDER), AccessMode.rw))
            .withCmd("rm", "-r", SECRET_FOLDER)
            .exec();
    dockerClient.startContainerCmd(exec.getId()).exec();
    exec = dockerClient.createContainerCmd(ALPINE)
            .withBinds(new Bind(SECRET_FOLDER, new Volume(SECRET_FOLDER), AccessMode.rw))
            .withCmd("sh", "-c", "echo -n testRole secret | tee -a " + SECRET_FOLDER + SECRET)
            .exec();
    dockerClient.startContainerCmd(exec.getId()).exec();

    // Framework password
    // Note that the definition is slightly different. There is no username specified in the file. Just the password.
    exec = dockerClient.createContainerCmd(ALPINE)
            .withBinds(new Bind(SECRET_FOLDER, new Volume(SECRET_FOLDER), AccessMode.rw))
            .withCmd("sh", "-c", "echo -n secret | tee -a " + SECRET_FOLDER + FRAMEWORKPASSWD)
            .exec();
    dockerClient.startContainerCmd(exec.getId()).exec();
}
 
Example #5
Source File: ElasticsearchAuthSystemTest.java    From elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected CreateContainerCmd dockerCommand() {
    CreateContainerCmd createContainerCmd = super.dockerCommand();
    createContainerCmd.withBinds(new Bind(SECRET_FOLDER, new Volume(SECRET_FOLDER)));
    createContainerCmd.withCmd(
            ZookeeperCLIParameter.ZOOKEEPER_MESOS_URL, getZookeeperMesosUrl(),
            ElasticsearchCLIParameter.ELASTICSEARCH_NODES, Integer.toString(TEST_CONFIG.getElasticsearchNodesCount()),
            org.apache.mesos.elasticsearch.scheduler.Configuration.ELASTICSEARCH_RAM, "256",
            org.apache.mesos.elasticsearch.scheduler.Configuration.ELASTICSEARCH_DISK, "10",
            org.apache.mesos.elasticsearch.scheduler.Configuration.USE_IP_ADDRESS, "true",
            org.apache.mesos.elasticsearch.scheduler.Configuration.FRAMEWORK_ROLE, "testRole",
            org.apache.mesos.elasticsearch.scheduler.Configuration.FRAMEWORK_PRINCIPAL, "testRole",
            org.apache.mesos.elasticsearch.scheduler.Configuration.FRAMEWORK_SECRET_PATH, SECRET_FOLDER + FRAMEWORKPASSWD,
            org.apache.mesos.elasticsearch.scheduler.Configuration.ELASTICSEARCH_CPU, "0.2"
    );
    return createContainerCmd;
}
 
Example #6
Source File: CreateContainerCmd.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @deprecated see {@link #getHostConfig()}
 */
@Deprecated
@CheckForNull
@JsonIgnore
default Bind[] getBinds() {
    return getHostConfig().getBinds();
}
 
Example #7
Source File: ListContainersCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testVolumeFilter() throws Exception {
    String id;
    dockerRule.getClient().createVolumeCmd()
            .withName("TestFilterVolume")
            .withDriver("local")
            .exec();

    id = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withLabels(testLabel)
            .withHostConfig(newHostConfig()
                    .withBinds(new Bind("TestFilterVolume", new Volume("/test"))))
            .exec()
            .getId();

    dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withLabels(testLabel)
            .exec();

    List<Container> filteredContainers = dockerRule.getClient().listContainersCmd()
            .withShowAll(true)
            .withLabelFilter(testLabel)
            .withVolumeFilter(singletonList("TestFilterVolume"))
            .exec();

    assertThat(filteredContainers.size(), is(1));
    assertThat(filteredContainers.get(0).getId(), is(id));
}
 
Example #8
Source File: StartContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void startContainerWithVolumesFrom() throws DockerException {

    Volume volume1 = new Volume("/opt/webapp1");
    Volume volume2 = new Volume("/opt/webapp2");

    String container1Name = UUID.randomUUID().toString();

    CreateContainerResponse container1 = dockerRule.getClient().createContainerCmd("busybox").withCmd("sleep", "9999")
            .withName(container1Name)
            .withHostConfig(newHostConfig()
                    .withBinds(new Bind("/tmp/webapp1", volume1), new Bind("/tmp/webapp2", volume2)))
            .exec();
    LOG.info("Created container1 {}", container1.toString());

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

    InspectContainerResponse inspectContainerResponse1 = dockerRule.getClient().inspectContainerCmd(container1.getId())
            .exec();

    assertThat(inspectContainerResponse1, mountedVolumes(containsInAnyOrder(volume1, volume2)));

    CreateContainerResponse container2 = dockerRule.getClient().createContainerCmd("busybox").withCmd("sleep", "9999")
            .withHostConfig(newHostConfig()
                    .withVolumesFrom(new VolumesFrom(container1Name)))
            .exec();
    LOG.info("Created container2 {}", container2.toString());

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

    InspectContainerResponse inspectContainerResponse2 = dockerRule.getClient().inspectContainerCmd(container2.getId())
            .exec();

    assertThat(inspectContainerResponse2, mountedVolumes(containsInAnyOrder(volume1, volume2)));
}
 
Example #9
Source File: CreateContainerCmd.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @deprecated see {@link #getHostConfig()}
 */
@Deprecated
default CreateContainerCmd withBinds(Bind... binds) {
    Objects.requireNonNull(binds, "binds was not specified");
    getHostConfig().setBinds(binds);
    return this;
}
 
Example #10
Source File: DockerMachineConfiguratorTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateContainer_loggedWarnings() throws Exception {

	CreateContainerCmd ccc = Mockito.mock( CreateContainerCmd.class );
	Mockito.when( ccc.withEnv( Mockito.anyListOf( String.class ))).thenReturn( ccc );
	Mockito.when( ccc.withBinds( Mockito.anyListOf( Bind.class ))).thenReturn( ccc );
	Mockito.when( ccc.withVolumes( Mockito.anyListOf( Volume.class ))).thenReturn( ccc );
	Mockito.when( ccc.withName( Mockito.anyString())).thenReturn( ccc );

	CreateContainerResponse containerResponse = Mockito.mock( CreateContainerResponse.class );
	Mockito.when( this.dockerClient.createContainerCmd( Mockito.anyString())).thenReturn( ccc );
	Mockito.when( ccc.exec()).thenReturn( containerResponse );
	Mockito.when( containerResponse.getId()).thenReturn( "cid" );

	StartContainerCmd scc = Mockito.mock( StartContainerCmd.class );
	Mockito.when( this.dockerClient.startContainerCmd( Mockito.anyString())).thenReturn( scc );

	this.configurator.logger = Mockito.mock( Logger.class );
	Mockito.when( this.configurator.logger.isLoggable( Level.FINE )).thenReturn( true );
	Mockito.when( containerResponse.getWarnings()).thenReturn( new String[]{ "Not good.", "Stay well." });

	// Create the container (mock)
	final String imageId = "toto";
	this.configurator.createContainer( imageId );

	// Check the client
	Mockito.verify( this.dockerClient ).createContainerCmd( imageId );
	Mockito.verify( this.dockerClient ).startContainerCmd( "cid" );
	Mockito.verifyNoMoreInteractions( this.dockerClient );

	// Check the logs were correctly handled
	Mockito.verify( containerResponse, Mockito.times( 3 )).getWarnings();
	Mockito.verify( this.configurator.logger ).fine( "The following warnings have been found.\nNot good.\nStay well." );
}
 
Example #11
Source File: LogstashSchedulerContainer.java    From logstash with Apache License 2.0 5 votes vote down vote up
@Override
protected CreateContainerCmd dockerCommand() {
    final String[] cmd = asList(
            "--mesos.master=" + mesosMasterIpAddress + ":5050",
            "--mesos.zookeeper.server=" + zookeeperIpAddress + ":2181",
            mesosRole.map(role -> "--mesos-role=" + role).orElse(null),
            "--enable.failover=false",
            elasticsearchHost.map(host -> "--logstash.elasticsearch-host=" + host).orElse(null),
            "--executor.heap-size=64",
            "--logstash.heap-size=256",
            "--enable.docker=" + useDocker,
            logstashConfig.map(file -> "--logstash.config-file=/config/" + file.getName()).orElse(null),
            withSyslog ? "--enable.syslog=true" : null
    ).stream().filter(StringUtils::isNotEmpty).toArray(String[]::new);

    final CreateContainerCmd containerCmd = dockerClient.createContainerCmd(SCHEDULER_IMAGE);
    logstashConfig.ifPresent(file -> {
        try {
            containerCmd.withBinds(new Bind(file.getParentFile().getCanonicalPath(), new Volume("/config"), AccessMode.ro));
        } catch (IOException e) {
            throw new IllegalStateException("Path error", e);
        }
    });
    return containerCmd
            .withName(SCHEDULER_NAME + "_" + new SecureRandom().nextInt())
            .withExposedPorts(ExposedPort.tcp(9092))
            .withCmd(cmd);
}
 
Example #12
Source File: GenericContainer.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void addFileSystemBind(final String hostPath, final String containerPath, final BindMode mode, final SelinuxContext selinuxContext) {

    final MountableFile mountableFile = MountableFile.forHostPath(hostPath);
    binds.add(new Bind(mountableFile.getResolvedPath(), new Volume(containerPath), mode.accessMode, selinuxContext.selContext));
}
 
Example #13
Source File: AlpineContainer.java    From elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected CreateContainerCmd dockerCommand() {
    return dockerClient
            .createContainerCmd(ALPINE_IMAGE_NAME)
            .withName("Alpine" + "_" + new SecureRandom().nextInt())
            .withBinds(new Bind(hostVolume, new Volume(containerVolume)))
            .withAttachStdout(true)
            .withAttachStderr(true)
            .withCmd(cmd);
}
 
Example #14
Source File: RegistratorContainer.java    From minimesos with Apache License 2.0 5 votes vote down vote up
@Override
protected CreateContainerCmd dockerCommand() {
     return DockerClientFactory.build().createContainerCmd(config.getImageName() + ":" + config.getImageTag())
            .withNetworkMode("host")
            .withBinds(Bind.parse("/var/run/docker.sock:/tmp/docker.sock"))
            .withCmd("-internal", String.format("consul://%s:%d", consul.getIpAddress(), ConsulConfig.CONSUL_HTTP_PORT))
            .withName(getName());
}
 
Example #15
Source File: MesosAgentContainer.java    From minimesos with Apache License 2.0 5 votes vote down vote up
private CreateContainerCmd getBaseCommand() {
    String hostDir = MesosCluster.getClusterHostDir().getAbsolutePath();
    List<Bind> binds = new ArrayList<>();
    binds.add(Bind.parse("/var/run/docker.sock:/var/run/docker.sock:rw"));
    binds.add(Bind.parse("/sys/fs/cgroup:/sys/fs/cgroup"));
    binds.add(Bind.parse(hostDir + ":" + hostDir));
    if (getCluster().getMapAgentSandboxVolume()) {
        binds.add(Bind.parse(String.format("%s:%s:rw", hostDir + "/.minimesos/sandbox-" + getClusterId() + "/" + hostName, MESOS_AGENT_WORK_DIR + hostName + "/slaves")));
    }
    CreateContainerCmd cmd = DockerClientFactory.build().createContainerCmd(getImageName() + ":" + getImageTag())
        .withName(getName())
        .withHostName(hostName)
        .withPrivileged(true)
        .withVolumes(new Volume(MESOS_AGENT_WORK_DIR + hostName))
        .withEnv(newEnvironment()
            .withValues(getMesosAgentEnvVars())
            .withValues(getSharedEnvVars())
            .createEnvironment())
        .withPidMode("host")
        .withLinks(new Link(getZooKeeper().getContainerId(), "minimesos-zookeeper"))
        .withBinds(binds.stream().toArray(Bind[]::new));

    MesosDns mesosDns = getCluster().getMesosDns();
    if (mesosDns != null) {
        cmd.withDns(mesosDns.getIpAddress());
    }

    return cmd;
}
 
Example #16
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 #17
Source File: BindVolumeCreateContainerPostProcessor.java    From Dolphin with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeCreateContainer(CreateContainerContext createContainerContext) {
    CreateContainerCmd createContainerCmd = createContainerContext.getCreateContainerCmd();

    Bind bind = createBind(createContainerContext.getInstanceStartRequest());
    createContainerCmd.withBinds(bind);
}
 
Example #18
Source File: CreateContainerCommandImpl.java    From vespa with Apache License 2.0 5 votes vote down vote up
private CreateContainerCmd createCreateContainerCmd() {
    List<Bind> volumeBinds = volumeBindSpecs.stream().map(Bind::parse).collect(Collectors.toList());

    final HostConfig hostConfig = new HostConfig()
            .withSecurityOpts(new ArrayList<>(securityOpts))
            .withBinds(volumeBinds)
            .withUlimits(ulimits)
            // Docker version 1.13.1 patch 94 changed default pids.max for the Docker container's cgroup
            // from max to 4096. -1L reinstates "max". File: /sys/fs/cgroup/pids/docker/CONTAINERID/pids.max.
            .withPidsLimit(-1L)
            .withCapAdd(addCapabilities.toArray(new Capability[0]))
            .withCapDrop(dropCapabilities.toArray(new Capability[0]))
            .withDnsOptions(dnsOptions)
            .withPrivileged(privileged);

    containerResources.ifPresent(cr -> hostConfig
            .withCpuShares(cr.cpuShares())
            .withMemory(cr.memoryBytes())
            // MemorySwap is the total amount of memory and swap, if MemorySwap == Memory, then container has no access swap
            .withMemorySwap(cr.memoryBytes())
            .withCpuPeriod(cr.cpuQuota() > 0 ? (long) cr.cpuPeriod() : null)
            .withCpuQuota(cr.cpuQuota() > 0 ? (long) cr.cpuQuota() : null));

    final CreateContainerCmd containerCmd = docker
            .createContainerCmd(dockerImage.asString())
            .withHostConfig(hostConfig)
            .withName(containerName.asString())
            .withLabels(labels)
            .withEnv(environmentAssignments);

    hostName.ifPresent(containerCmd::withHostName);
    networkMode.ifPresent(hostConfig::withNetworkMode);
    ipv4Address.ifPresent(containerCmd::withIpv4Address);
    ipv6Address.ifPresent(containerCmd::withIpv6Address);
    entrypoint.ifPresent(containerCmd::withEntrypoint);

    return containerCmd;
}
 
Example #19
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 #20
Source File: CreateContainerCmd.java    From docker-java with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @deprecated see {@link #getHostConfig()}
 */
@Deprecated
default CreateContainerCmd withBinds(List<Bind> binds) {
    Objects.requireNonNull(binds, "binds was not specified");
    return withBinds(binds.toArray(new Bind[binds.size()]));
}
 
Example #21
Source File: BindVolumeCreateContainerPostProcessor.java    From Dolphin with Apache License 2.0 4 votes vote down vote up
private Bind createBind(InstanceStartRequest request) {
    String outer = configManager.getOuterWebPackageRootDir(request.getAppId(), request.getInstanceIndex());
    Volume inner = new Volume(configManager.getInnerWebPackageRootDir());

    return new Bind(outer, inner, AccessMode.rw);
}
 
Example #22
Source File: Docker.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public void mountFiles(CreateContainerCmd createContainerCmd) {
  String videoFilesDiskPath = "/var/lib/jenkins/test-files";
  Volume configVol = new Volume(KurentoTest.getTestFilesDiskPath());
  createContainerCmd.withVolumes(configVol).withBinds(new Bind(videoFilesDiskPath, configVol));
}
 
Example #23
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 #24
Source File: DockerMachineConfiguratorTest.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testCreateContainer_success() throws Exception {

	CreateContainerCmd ccc = Mockito.mock( CreateContainerCmd.class );
	Mockito.when( ccc.withEnv( Mockito.anyListOf( String.class ))).thenReturn( ccc );
	Mockito.when( ccc.withBinds( Mockito.anyListOf( Bind.class ))).thenReturn( ccc );
	Mockito.when( ccc.withVolumes( Mockito.anyListOf( Volume.class ))).thenReturn( ccc );
	Mockito.when( ccc.withName( Mockito.anyString())).thenReturn( ccc );

	Mockito.when( this.dockerClient.createContainerCmd( Mockito.anyString())).thenReturn( ccc );
	CreateContainerResponse containerResponse = Mockito.mock( CreateContainerResponse.class );
	Mockito.when( ccc.exec()).thenReturn( containerResponse );
	Mockito.when( containerResponse.getId()).thenReturn( "cid" );

	StartContainerCmd scc = Mockito.mock( StartContainerCmd.class );
	Mockito.when( this.dockerClient.startContainerCmd( Mockito.anyString())).thenReturn( scc );

	// Create the container (mock)
	final String imageId = "toto";
	this.configurator.createContainer( imageId );

	// Check the client
	Mockito.verify( this.dockerClient ).createContainerCmd( imageId );
	Mockito.verify( this.dockerClient ).startContainerCmd( "cid" );
	Mockito.verifyNoMoreInteractions( this.dockerClient );

	// Check the user data
	Assert.assertEquals( 1, this.containerIdToVolume.size());
	File dir = this.containerIdToVolume.values().iterator().next();
	Assert.assertTrue( dir.isDirectory());
	Assert.assertTrue( new File( dir, USER_DATA_FILE ).isFile());

	// Check the creation request
	Mockito.verify( ccc ).withName( Mockito.anyString());

	ArgumentCaptor<List> env = ArgumentCaptor.forClass( List.class );
	Mockito.verify( ccc ).withEnv( env.capture());

	List<String> effectiveEnv = env.getValue();
	Assert.assertEquals( 2, effectiveEnv.size());
	Assert.assertEquals( "RBCF_VERSION=latest", effectiveEnv.get( 0 ));
	Assert.assertEquals( "AGENT_PARAMETERS=file:" + USER_DATA_DIR + USER_DATA_FILE, effectiveEnv.get( 1 ));

	// Volumes
	ArgumentCaptor<List> volumes = ArgumentCaptor.forClass( List.class );
	Mockito.verify( ccc ).withVolumes( volumes.capture());

	List<Volume> effectiveVolumes = volumes.getValue();
	Assert.assertNotNull( effectiveVolumes );
	Assert.assertEquals( 1, effectiveVolumes.size());

	Volume effectiveVolume = effectiveVolumes.get( 0 );
	Assert.assertNotNull( effectiveVolume );
	Assert.assertEquals( USER_DATA_DIR, effectiveVolume.getPath());

	// Bounds
	ArgumentCaptor<List> bounds = ArgumentCaptor.forClass( List.class );
	Mockito.verify( ccc ).withBinds( bounds.capture());

	List<Bind> effectiveBounds = bounds.getValue();
	Assert.assertNotNull( effectiveBounds );
	Assert.assertEquals( 1, effectiveBounds.size());

	Bind effectiveBind = effectiveBounds.get( 0 );
	Assert.assertNotNull( effectiveBind );
	Assert.assertEquals( dir.getAbsolutePath(), effectiveBind.getPath());
	Assert.assertEquals( effectiveVolume, effectiveBind.getVolume());
}
 
Example #25
Source File: DockerMachineConfiguratorTest.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testCreateContainer_withEnv() throws Exception {

	CreateContainerCmd ccc = Mockito.mock( CreateContainerCmd.class );
	Mockito.when( ccc.withEnv( Mockito.anyListOf( String.class ))).thenReturn( ccc );
	Mockito.when( ccc.withBinds( Mockito.anyListOf( Bind.class ))).thenReturn( ccc );
	Mockito.when( ccc.withVolumes( Mockito.anyListOf( Volume.class ))).thenReturn( ccc );
	Mockito.when( ccc.withName( Mockito.anyString())).thenReturn( ccc );

	Mockito.when( this.dockerClient.createContainerCmd( Mockito.anyString())).thenReturn( ccc );
	CreateContainerResponse containerResponse = Mockito.mock( CreateContainerResponse.class );
	Mockito.when( ccc.exec()).thenReturn( containerResponse );
	Mockito.when( containerResponse.getId()).thenReturn( "cid" );

	StartContainerCmd scc = Mockito.mock( StartContainerCmd.class );
	Mockito.when( this.dockerClient.startContainerCmd( Mockito.anyString())).thenReturn( scc );

	// Prepare the parameters
	final String imageId = "toto";
	this.configurator.getParameters().getMessagingProperties().put( MessagingConstants.MESSAGING_TYPE_PROPERTY, "bird" );

	this.configurator.getParameters().getTargetProperties().put( OPTION_PREFIX_ENV + "t1", "v1" );
	this.configurator.getParameters().getTargetProperties().put( OPTION_PREFIX_ENV + "t2", "<application-name>" );
	this.configurator.getParameters().getTargetProperties().put( OPTION_PREFIX_ENV + "t3", "<application-name>_2" );
	this.configurator.getParameters().getTargetProperties().put( OPTION_PREFIX_ENV + "t4", "<scoped-instance-path>" );
	this.configurator.getParameters().getTargetProperties().put( OPTION_PREFIX_ENV + "t5", "<scoped-messaging_type>" );

	// Create the container (mock)
	this.configurator.createContainer( imageId );

	// Check the client
	Mockito.verify( this.dockerClient ).createContainerCmd( imageId );
	Mockito.verify( this.dockerClient ).startContainerCmd( "cid" );
	Mockito.verifyNoMoreInteractions( this.dockerClient );

	// Check the user data
	Assert.assertEquals( 1, this.containerIdToVolume.size());
	File dir = this.containerIdToVolume.values().iterator().next();
	Assert.assertTrue( dir.isDirectory());
	Assert.assertTrue( new File( dir, USER_DATA_FILE ).isFile());

	// Check the creation request
	Mockito.verify( ccc ).withName( Mockito.anyString());

	ArgumentCaptor<List> env = ArgumentCaptor.forClass( List.class );
	Mockito.verify( ccc ).withEnv( env.capture());

	List<String> effectiveEnv = env.getValue();
	Assert.assertEquals( 7, effectiveEnv.size());
	Assert.assertEquals( "t1=v1", effectiveEnv.get( 0 ));
	Assert.assertEquals( "t2=applicationName", effectiveEnv.get( 1 ));
	Assert.assertEquals( "t3=applicationName_2", effectiveEnv.get( 2 ));
	Assert.assertEquals( "t4=/vm", effectiveEnv.get( 3 ));
	Assert.assertEquals( "t5=bird", effectiveEnv.get( 4 ));
	Assert.assertEquals( "RBCF_VERSION=latest", effectiveEnv.get( 5 ));
	Assert.assertEquals( "AGENT_PARAMETERS=file:" + USER_DATA_DIR + USER_DATA_FILE, effectiveEnv.get( 6 ));

	// Volumes
	ArgumentCaptor<List> volumes = ArgumentCaptor.forClass( List.class );
	Mockito.verify( ccc ).withVolumes( volumes.capture());

	List<Volume> effectiveVolumes = volumes.getValue();
	Assert.assertNotNull( effectiveVolumes );
	Assert.assertEquals( 1, effectiveVolumes.size());

	Volume effectiveVolume = effectiveVolumes.get( 0 );
	Assert.assertNotNull( effectiveVolume );
	Assert.assertEquals( USER_DATA_DIR, effectiveVolume.getPath());

	// Bounds
	ArgumentCaptor<List> bounds = ArgumentCaptor.forClass( List.class );
	Mockito.verify( ccc ).withBinds( bounds.capture());

	List<Bind> effectiveBounds = bounds.getValue();
	Assert.assertNotNull( effectiveBounds );
	Assert.assertEquals( 1, effectiveBounds.size());

	Bind effectiveBind = effectiveBounds.get( 0 );
	Assert.assertNotNull( effectiveBind );
	Assert.assertEquals( dir.getAbsolutePath(), effectiveBind.getPath());
	Assert.assertEquals( effectiveVolume, effectiveBind.getVolume());
}
 
Example #26
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 #27
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
public void createContainerWithVolumesFrom() throws DockerException {
    String container1Name = UUID.randomUUID().toString();
    CreateVolumeResponse volume1Info = dockerRule.getClient().createVolumeCmd().exec();
    CreateVolumeResponse volume2Info = dockerRule.getClient().createVolumeCmd().exec();

    Volume volume1 = new Volume("/src/webapp1");
    Volume volume2 = new Volume("/src/webapp2");
    Bind bind1 = new Bind(volume1Info.getName(), volume1);
    Bind bind2 = new Bind(volume2Info.getName(), volume2);

    // create a running container with bind mounts
    CreateContainerResponse container1 = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withCmd("sleep", "9999")
            .withName(container1Name)
            .withHostConfig(newHostConfig()
                    .withBinds(bind1, bind2))
            .exec();

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

    InspectContainerResponse inspectContainerResponse1 = dockerRule.getClient().inspectContainerCmd(container1.getId())
            .exec();

    assertThat(Arrays.asList(inspectContainerResponse1.getHostConfig().getBinds()), containsInAnyOrder(bind1, bind2));

    assertThat(inspectContainerResponse1, mountedVolumes(containsInAnyOrder(volume1, volume2)));

    // create a second container with volumes from first container
    CreateContainerResponse container2 = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withCmd("sleep", "9999")
            .withHostConfig(newHostConfig()
                    .withVolumesFrom(new VolumesFrom(container1Name)))
            .exec();

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

    InspectContainerResponse inspectContainerResponse2 = dockerRule.getClient().inspectContainerCmd(container2.getId())
            .exec();

    // No volumes are created, the information is just stored in .HostConfig.VolumesFrom
    assertThat(inspectContainerResponse2.getHostConfig().getVolumesFrom(),
            hasItemInArray(new VolumesFrom(container1Name)));
    assertThat(inspectContainerResponse1, mountedVolumes(containsInAnyOrder(volume1, volume2)));

    // To ensure that the information stored in VolumesFrom really is considered
    // when starting the container, we start it and verify that it has the same
    // bind mounts as the first container.
    // This is somehow out of scope here, but it helped me to understand how the
    // VolumesFrom feature really works.
    dockerRule.getClient().startContainerCmd(container2.getId()).exec();
    LOG.info("Started container2 {}", container2.toString());

    inspectContainerResponse2 = dockerRule.getClient().inspectContainerCmd(container2.getId()).exec();

    assertThat(inspectContainerResponse2.getHostConfig().getVolumesFrom(), hasItemInArray(new VolumesFrom(
            container1Name)));

    assertThat(inspectContainerResponse2, mountedVolumes(containsInAnyOrder(volume1, volume2)));
}
 
Example #28
Source File: BesuNode.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
private Bind privacyVolumeBinding(final String privacyPublicKey) {
  final String privacyPublicKeyFile = privacyPublicKeyFilePath(privacyPublicKey);
  final Volume privacyPublicKeyVolume = new Volume("/etc/besu/privacy_public_key");
  return new Bind(privacyPublicKeyFile, privacyPublicKeyVolume);
}
 
Example #29
Source File: DockerTemplateBase.java    From docker-plugin with MIT License 2 votes vote down vote up
/**
 * Parses a given volumesString value, appending any {@link Volume}s and {@link Bind}s to the specified lists.
 * @param volumes The strings to be parsed.
 * @param volumeListResult List to which any {@link Volume}s should be stored in.
 * @param bindListResult List to which any {@link Bind}s should be stored in.
 * @throws IllegalArgumentException if anything is invalid.
 */
private static void parseVolumesStrings(final String[] volumes, List<Volume> volumeListResult, List<Bind> bindListResult) {
    for (String vol : volumes) {
        parseVolumesString(vol, volumeListResult, bindListResult);
    }
}
 
Example #30
Source File: StartContainerCmdIT.java    From docker-java with Apache License 2.0 2 votes vote down vote up
@Test
public void startContainerWithVolumes() throws Exception {

    // see http://docs.docker.io/use/working_with_volumes/
    Volume volume1 = new Volume("/opt/webapp1");

    Volume volume2 = new Volume("/opt/webapp2");

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withVolumes(volume1, volume2)
            .withCmd("true")
            .withHostConfig(newHostConfig()
                    .withBinds(new Bind("/tmp/webapp1", volume1, ro), new Bind("/tmp/webapp2", volume2)))
            .exec();

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

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

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

    assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/opt/webapp1", "/opt/webapp2"));

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

    dockerRule.getClient().waitContainerCmd(container.getId()).start().awaitStatusCode();

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

    assertThat(inspectContainerResponse, mountedVolumes(containsInAnyOrder(volume1, volume2)));

    final List<InspectContainerResponse.Mount> mounts = inspectContainerResponse.getMounts();

    assertThat(mounts, hasSize(2));

    final InspectContainerResponse.Mount mount1 = new InspectContainerResponse.Mount()
            .withRw(false).withMode("ro").withDestination(volume1).withSource("/tmp/webapp1");
    final InspectContainerResponse.Mount mount2 = new InspectContainerResponse.Mount()
            .withRw(true).withMode("rw").withDestination(volume2).withSource("/tmp/webapp2");

    assertThat(mounts, containsInAnyOrder(mount1, mount2));
}