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

The following examples show how to use com.github.dockerjava.api.model.Volume. 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: 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 #4
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 #5
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 #6
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 #7
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 #8
Source File: InspectContainerResponseTest.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void roundTrip_1_26b_full() throws IOException {
    InspectContainerResponse[] responses = testRoundTrip(CommandJSONSamples.inspectContainerResponse_full_1_26b,
        InspectContainerResponse[].class);

    assertEquals(1, responses.length);
    final InspectContainerResponse response = responses[0];

    final List<InspectContainerResponse.Mount> mounts = response.getMounts();
    assertEquals(mounts.size(), 1);

    final InspectContainerResponse.Mount mount = mounts.get(0);
    final Volume volume = mount.getDestination();
    assertEquals(volume.getPath(), "/srv/test");
}
 
Example #9
Source File: InspectContainerResponseTest.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void roundTrip_1_26a_full() throws IOException {
    InspectContainerResponse[] responses = testRoundTrip(CommandJSONSamples.inspectContainerResponse_full_1_26a,
        InspectContainerResponse[].class);

    assertEquals(1, responses.length);
    final InspectContainerResponse response = responses[0];

    final List<InspectContainerResponse.Mount> mounts = response.getMounts();
    assertEquals(mounts.size(), 1);

    final InspectContainerResponse.Mount mount = mounts.get(0);
    final Volume volume = mount.getDestination();
    assertEquals(volume.getPath(), "/var/lib/postgresql/data");
}
 
Example #10
Source File: DockerMatchers.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public List<Volume> featureValueOf(InspectContainerResponse item) {
    List<Volume> volumes = new ArrayList<>();
    for (InspectContainerResponse.Mount mount : item.getMounts()) {
        volumes.add(mount.getDestination());
    }
    return volumes;
}
 
Example #11
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 #12
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 #13
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 #14
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 #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: 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 #18
Source File: CreateContainerCmd.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@CheckForNull
Volume[] getVolumes();
 
Example #19
Source File: InspectContainerResponse.java    From docker-java with Apache License 2.0 4 votes vote down vote up
/**
 * @see #destination
 */
public Mount withDestination(Volume destination) {
    this.destination = destination;
    return this;
}
 
Example #20
Source File: InspectContainerResponse.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@CheckForNull
public Volume getDestination() {
    return destination;
}
 
Example #21
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 #22
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
public void createContainerWithReadOnlyVolume() throws DockerException {

    Volume volume = new Volume("/srv/test");

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE).withVolumes(volume)
            .withCmd("true").exec();

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

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

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

    LOG.info("Inspect container {}", inspectContainerResponse.getConfig().getVolumes());

    assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/srv/test"));

    assertThat(inspectContainerResponse.getMounts().get(0).getDestination(), equalTo(volume));
    // TODO: Create a read-only volume and test like this
    // assertFalse(inspectContainerResponse.getMounts().get(0).getRW());
}
 
Example #23
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
public void createContainerWithVolume() throws DockerException {

    Volume volume = new Volume("/var/log");

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withVolumes(volume)
            .withCmd("true").exec();

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

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

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

    LOG.info("Inspect container {}", inspectContainerResponse.getConfig().getVolumes());

    assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/var/log"));

    assertThat(inspectContainerResponse.getMounts().get(0).getDestination(), equalTo(volume));
    assertThat(inspectContainerResponse.getMounts().get(0).getMode(), equalTo(""));
    assertThat(inspectContainerResponse.getMounts().get(0).getRW(), equalTo(true));
}
 
Example #24
Source File: CreateContainerCmdImpl.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Override
@JsonIgnore
public Volume[] getVolumes() {
    return volumes.getVolumes();
}
 
Example #25
Source File: CreateContainerCmdImpl.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Override
public CreateContainerCmd withVolumes(Volume... volumes) {
    checkNotNull(volumes, "volumes was not specified");
    this.volumes = new Volumes(volumes);
    return this;
}
 
Example #26
Source File: CreateContainerCmdImpl.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Override
public CreateContainerCmd withVolumes(List<Volume> volumes) {
    checkNotNull(volumes, "volumes was not specified");
    return withVolumes(volumes.toArray(new Volume[0]));
}
 
Example #27
Source File: DockerMatchers.java    From docker-java with Apache License 2.0 4 votes vote down vote up
public MountedVolumes(Matcher<? super List<Volume>> subMatcher, String featureDescription, String featureName) {
    super(subMatcher, featureDescription, featureName);
}
 
Example #28
Source File: DockerMatchers.java    From docker-java with Apache License 2.0 4 votes vote down vote up
public static MountedVolumes mountedVolumes(Matcher<? super List<Volume>> subMatcher) {
    return new MountedVolumes(subMatcher, "Mounted volumes", "mountedVolumes");
}
 
Example #29
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 #30
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());
}